@capxul/observability 4.20.0-beta.2 → 4.20.0-beta.20

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.
@@ -0,0 +1,3458 @@
1
+ import { Effect, Schema, SchemaGetter } from "effect";
2
+ //#region ../errors/src/secret-material.ts
3
+ const CREDENTIAL_FIELDS = /* @__PURE__ */ new Set([
4
+ "password",
5
+ "passwd",
6
+ "pwd",
7
+ "pass",
8
+ "passphrase",
9
+ "currentpassword",
10
+ "newpassword",
11
+ "confirmpassword",
12
+ "passwordconfirmation",
13
+ "passwordhash",
14
+ "hashedpassword",
15
+ "pin",
16
+ "privatekey",
17
+ "walletprivatekey",
18
+ "secretkey",
19
+ "signingkey",
20
+ "signingsecret",
21
+ "seed",
22
+ "seedphrase",
23
+ "mnemonic",
24
+ "recoveryphrase",
25
+ "recovery",
26
+ "recoverycode",
27
+ "recoverycodes",
28
+ "keyshare",
29
+ "signingmaterial",
30
+ "recoverymaterial",
31
+ "privatekeybytes",
32
+ "signingprivatekey",
33
+ "encryptionkey",
34
+ "decryptionkey",
35
+ "authtoken",
36
+ "apitoken",
37
+ "bearertoken",
38
+ "oauthtoken",
39
+ "csrftoken",
40
+ "clientassertion",
41
+ "token",
42
+ "accesstoken",
43
+ "refreshtoken",
44
+ "idtoken",
45
+ "sessiontoken",
46
+ "session",
47
+ "sessionkey",
48
+ "sessionsecret",
49
+ "authsessionid",
50
+ "sessioncredential",
51
+ "sessioncredentials",
52
+ "sessioncookie",
53
+ "auth",
54
+ "authentication",
55
+ "authorization",
56
+ "proxyauthorization",
57
+ "cookie",
58
+ "cookies",
59
+ "setcookie",
60
+ "apikey",
61
+ "xapikey",
62
+ "xauthtoken",
63
+ "clientsecret",
64
+ "secret",
65
+ "secrets",
66
+ "credential",
67
+ "credentials",
68
+ "signature",
69
+ "otp",
70
+ "otpcode",
71
+ "totpsecret",
72
+ "onetimecode",
73
+ "onetimepassword",
74
+ "verificationcode",
75
+ "authcode",
76
+ "authorizationcode",
77
+ "oauthcode",
78
+ "codeverifier",
79
+ "devicecode",
80
+ "usercode",
81
+ "continuitytoken",
82
+ "refreshattemptid",
83
+ "revocationtoken"
84
+ ]);
85
+ /** Match credential fields by meaning, without hiding token addresses or replay IDs. */
86
+ function isCredentialField(name, context) {
87
+ const normalized = name.toLowerCase().replace(/[^a-z0-9]/gu, "");
88
+ return CREDENTIAL_FIELDS.has(normalized) || /(?:password(?:hash)?|passwd|passphrase|privatekey|signingkey|apikey|clientsecret|accesstoken|refreshtoken|sessiontoken)$/u.test(normalized) || context === "authentication" && (normalized === "code" || normalized === "sessionid") || context === "header" && /(?:token|secret|apikey|privatekey|signingkey|password|authorization|cookie|session)$/u.test(normalized);
89
+ }
90
+ function decodeUrlComponent(text) {
91
+ try {
92
+ return decodeURIComponent(text);
93
+ } catch {
94
+ return text;
95
+ }
96
+ }
97
+ /** Preserve URL diagnostics while removing credentials from their declared components. */
98
+ function redactUrlSecrets(value, source) {
99
+ try {
100
+ const absolute = /^[a-z][a-z0-9+.-]*:/iu.test(value);
101
+ const protocolRelative = value.startsWith("//");
102
+ const url = new URL(value, "https://redaction.invalid");
103
+ if (url.protocol !== "https:" && url.protocol !== "http:") return maskText(value);
104
+ let changed = url.username.length > 0 || url.password.length > 0;
105
+ const maskParams = (params) => new URLSearchParams(Array.from(params, ([name, entry]) => {
106
+ const safeName = maskText(name);
107
+ const safeEntry = isCredentialField(name) || /^(?:code|draft|__posthog)$/iu.test(name) ? "[REDACTED]" : maskText(entry);
108
+ changed ||= safeName !== name || safeEntry !== entry;
109
+ return [safeName, safeEntry];
110
+ })).toString();
111
+ const provider = source === "alchemy" || source === "infura" || /(?:^|\.)(?:alchemy\.com|alchemyapi\.io|infura\.io)$/iu.test(url.hostname);
112
+ const rawPath = absolute || protocolRelative ? url.pathname : value.split(/[?#]/u)[0] ?? "";
113
+ const segments = rawPath.split("/");
114
+ let path = segments.map((segment, index) => {
115
+ const decoded = decodeUrlComponent(segment);
116
+ const masked = provider && /^v[23]$/u.test(decodeUrlComponent(segments[index - 1] ?? "")) && decoded.length > 0 ? "[REDACTED]" : maskText(decoded);
117
+ changed ||= masked !== decoded;
118
+ return masked === decoded ? segment : encodeURIComponent(masked);
119
+ }).join("/");
120
+ if (source === "gateway" && rawPath.length > 0) {
121
+ path = `${rawPath.startsWith("/") ? "/" : ""}${encodeURIComponent("[REDACTED]")}`;
122
+ changed = true;
123
+ }
124
+ const query = maskParams(url.searchParams);
125
+ const fragment = url.hash.slice(1);
126
+ const decodedFragment = decodeUrlComponent(fragment);
127
+ const maskedFragment = maskText(decodedFragment);
128
+ changed ||= maskedFragment !== decodedFragment;
129
+ const fragmentQuery = fragment.indexOf("?");
130
+ const fragmentPath = fragment.slice(0, fragmentQuery);
131
+ const maskedFragmentPath = maskText(decodeUrlComponent(fragmentPath));
132
+ changed ||= maskedFragmentPath !== decodeUrlComponent(fragmentPath);
133
+ const hash = fragmentQuery >= 0 ? `${maskedFragmentPath === decodeUrlComponent(fragmentPath) ? fragmentPath : encodeURIComponent(maskedFragmentPath)}?${maskParams(new URLSearchParams(fragment.slice(fragmentQuery + 1)))}` : fragment.includes("=") ? maskParams(new URLSearchParams(fragment)) : maskedFragment === decodedFragment ? fragment : encodeURIComponent(maskedFragment);
134
+ const origin = absolute ? url.origin : protocolRelative ? `//${url.host}` : "";
135
+ if (!changed) return value;
136
+ return `${origin}${path}${query ? `?${query}` : ""}${hash ? `#${hash}` : ""}`;
137
+ } catch {
138
+ if (source === "gateway") return "[REDACTED]";
139
+ return maskText(value.replace(/(https?:\/\/)[^/\s@]+@/giu, "$1[REDACTED]@").replace(/([?&#])([^=&#]+)=([^&#]*)/gu, (whole, separator, name) => isCredentialField(decodeUrlComponent(name)) || /^(?:code|draft|__posthog)$/iu.test(decodeUrlComponent(name)) ? `${separator}${name}=[REDACTED]` : whole));
140
+ }
141
+ }
142
+ const JSON_FIELD = /("(?:[^"\\]|\\.)*")(\s*:\s*)("(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)/gu;
143
+ const PROSE_FIELD = /(?=(\b([A-Za-z][A-Za-z0-9_-]*(?:[ \t]+[A-Za-z][A-Za-z0-9_-]*){0,3})\s*[:=]\s*((?:Bearer|Basic)[ \t]+[^\s,;"']+|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^\s,;&"']+)))/gu;
144
+ const EMBEDDED_URL = /(https?:\/\/[^\s"<>]*)/giu;
145
+ function isSecretLabel(name) {
146
+ return isCredentialField(name) || /^request[ _-]?body$/iu.test(name);
147
+ }
148
+ const JSON_ENCODING_MAX = 8;
149
+ const JSON_NESTING_MAX = 64;
150
+ const JSON_KEY = /("(?:[^"\\]|\\.)*")\s*:/gu;
151
+ const JSON_CONTAINER_START = /(?:\{\s*["}]|\[\s*[[\]{}"0-9tfn-])/uy;
152
+ function hasSecretJsonKey(value) {
153
+ for (const match of value.matchAll(JSON_KEY)) try {
154
+ if (match[1] !== void 0 && isSecretLabel(JSON.parse(match[1]))) return true;
155
+ } catch {}
156
+ return false;
157
+ }
158
+ /** Project a complete fragment once. Never retry all of its nested substrings. */
159
+ function projectJsonFragment(value, encodingDepth, overDepth) {
160
+ if (overDepth || encodingDepth >= JSON_ENCODING_MAX) return "[REDACTED]";
161
+ let parsed;
162
+ try {
163
+ parsed = JSON.parse(value);
164
+ } catch {
165
+ return hasSecretJsonKey(value) ? "[REDACTED]" : value;
166
+ }
167
+ try {
168
+ let changed = false;
169
+ const masked = JSON.stringify(parsed, (name, nested) => {
170
+ if (isSecretLabel(name)) {
171
+ changed ||= nested !== "[REDACTED]";
172
+ return "[REDACTED]";
173
+ }
174
+ if (typeof nested === "string") {
175
+ const projected = maskJsonFragments(nested, encodingDepth + 1);
176
+ changed ||= projected !== nested;
177
+ return projected;
178
+ }
179
+ return nested;
180
+ });
181
+ return changed ? masked : value;
182
+ } catch {
183
+ return "[REDACTED]";
184
+ }
185
+ }
186
+ /** Scan balanced object/array fragments once, respecting JSON quotes and escapes. */
187
+ function maskJsonFragments(value, encodingDepth = 0) {
188
+ if (value.trimStart().startsWith("\"")) try {
189
+ const decoded = JSON.parse(value);
190
+ if (typeof decoded === "string") {
191
+ if (encodingDepth >= JSON_ENCODING_MAX) return "\"[REDACTED]\"";
192
+ const masked = maskJsonFragments(decoded, encodingDepth + 1);
193
+ return masked === decoded ? value : JSON.stringify(masked);
194
+ }
195
+ } catch {}
196
+ let output = "";
197
+ let cursor = 0;
198
+ let start = -1;
199
+ let depth = 0;
200
+ let overDepth = false;
201
+ let quoted = false;
202
+ let escaped = false;
203
+ for (let index = 0; index < value.length; index++) {
204
+ const character = value[index];
205
+ if (start < 0) {
206
+ JSON_CONTAINER_START.lastIndex = index;
207
+ if (!JSON_CONTAINER_START.test(value)) continue;
208
+ start = index;
209
+ depth = 1;
210
+ overDepth = false;
211
+ continue;
212
+ }
213
+ if (quoted) {
214
+ if (escaped) escaped = false;
215
+ else if (character === "\\") escaped = true;
216
+ else if (character === "\"") quoted = false;
217
+ continue;
218
+ }
219
+ if (character === "\"") quoted = true;
220
+ else if (character === "{" || character === "[") {
221
+ depth++;
222
+ overDepth ||= depth > JSON_NESTING_MAX;
223
+ } else if (character === "}" || character === "]") {
224
+ depth--;
225
+ if (depth !== 0) continue;
226
+ output += value.slice(cursor, start) + projectJsonFragment(value.slice(start, index + 1), encodingDepth, overDepth);
227
+ cursor = index + 1;
228
+ start = -1;
229
+ }
230
+ }
231
+ if (start >= 0) {
232
+ const fragment = value.slice(start);
233
+ output += value.slice(cursor, start) + (overDepth || hasSecretJsonKey(fragment) ? "[REDACTED]" : fragment);
234
+ cursor = value.length;
235
+ }
236
+ return output + value.slice(cursor);
237
+ }
238
+ function maskLabelledText(value) {
239
+ const jsonMasked = maskJsonFragments(value).replace(JSON_FIELD, (whole, quotedName, separator) => {
240
+ try {
241
+ return isSecretLabel(JSON.parse(quotedName)) ? `${quotedName}${separator}"[REDACTED]"` : whole;
242
+ } catch {
243
+ return whole;
244
+ }
245
+ });
246
+ let output = "";
247
+ let cursor = 0;
248
+ for (const match of jsonMasked.matchAll(PROSE_FIELD)) {
249
+ const [, whole, label, entry] = match;
250
+ if (whole === void 0 || label === void 0 || entry === void 0 || match.index < cursor || /^Bearer[ \t]+/iu.test(entry)) continue;
251
+ const words = label.split(/[ \t]+/u);
252
+ for (let index = 0; index < words.length; index++) {
253
+ const name = words.slice(index).join(" ");
254
+ if (isSecretLabel(name)) {
255
+ const prefix = words.slice(0, index).join(" ");
256
+ output += jsonMasked.slice(cursor, match.index) + `${prefix ? `${prefix} ` : ""}${name}=[REDACTED]`;
257
+ cursor = match.index + whole.length;
258
+ break;
259
+ }
260
+ }
261
+ }
262
+ return output + jsonMasked.slice(cursor);
263
+ }
264
+ const TOKEN_MASKS = [
265
+ [/\bBearer\s+(?!(?:realm|error|error_description|scope|authorization_uri|resource|claims)\s*=)[^\s,;"']+/giu, "Bearer [REDACTED]"],
266
+ [/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/gu, "[REDACTED]"],
267
+ [/(^|[^a-fA-F0-9])(?<!0[xX])[a-fA-F0-9]{64}(?=$|[^a-fA-F0-9])/gu, "$1[REDACTED]"],
268
+ [/(?:(?:sk|pk|rk)_(?:live|test)|(?:phc|phx|ghp|gho|ghu|ghs|ghr|whsec)_|github_pat_|xox[baprs]-|AKIA[0-9A-Z]{16}|AIza)[A-Za-z0-9_-]*/giu, "[REDACTED]"]
269
+ ];
270
+ /** URL components and malformed URLs use this non-recursive masking layer. */
271
+ function maskText(value) {
272
+ let text = maskLabelledText(value);
273
+ for (const [pattern, replacement] of TOKEN_MASKS) text = text.replace(pattern, replacement);
274
+ return text;
275
+ }
276
+ /** Mask credential fields and embedded URLs while preserving surrounding evidence. */
277
+ function redactSecrets(value, source) {
278
+ return maskLabelledText(value).split(EMBEDDED_URL).map((part, index) => index % 2 === 1 ? redactUrlSecrets(part, source).replaceAll("%5BREDACTED%5D", "[REDACTED]") : maskText(part)).join("");
279
+ }
280
+ //#endregion
281
+ //#region ../errors/src/chain-cause.ts
282
+ /**
283
+ * Why an operation failed — the one flat vocabulary. The first four are the
284
+ * auth/provider diagnoses that predate this file. The rest name the chain
285
+ * path. `FailureMode` is derived from this list so a runtime membership check
286
+ * (the SDK's `$exception` projection, the observability schema) and the type
287
+ * can never drift apart.
288
+ */
289
+ const FAILURE_MODES = [
290
+ "auth-origin-mismatch",
291
+ "stale-openfort-cache",
292
+ "app-env-allowlist",
293
+ "no-secure-context",
294
+ "signer-not-ready",
295
+ "rate-limited",
296
+ "timeout",
297
+ "upstream-down",
298
+ "revert",
299
+ "insufficient-balance",
300
+ "insufficient-allowance",
301
+ "rejected",
302
+ "unauthorized",
303
+ "forbidden",
304
+ "bad-request",
305
+ "method-unsupported",
306
+ "unknown"
307
+ ];
308
+ /** Who answered. `alto` is the bundler; `gateway` is the AA gateway's own logic. */
309
+ const CHAIN_UPSTREAMS = [
310
+ "alchemy",
311
+ "infura",
312
+ "public",
313
+ "alto",
314
+ "gateway"
315
+ ];
316
+ //#endregion
317
+ //#region ../errors/src/errors.ts
318
+ const CAPXUL_ERROR_CODES = [
319
+ "NOT_AUTHENTICATED",
320
+ "EMAIL_DELIVERY_FAILED",
321
+ "PROFILE_NOT_FOUND",
322
+ "SMART_ACCOUNT_MISSING",
323
+ "PLAYER_NOT_FOUND",
324
+ "ACCOUNT_NOT_FOUND",
325
+ "ACCOUNT_CLAIMED_BY_OTHER_SIGNER",
326
+ "PROVIDER_ERROR",
327
+ "CAPABILITY_UNAVAILABLE",
328
+ "INVALID_INPUT",
329
+ "ENV_MISSING",
330
+ "NOT_IMPLEMENTED",
331
+ "VERIFICATION_REQUIRED",
332
+ "INSUFFICIENT_BALANCE",
333
+ "INVALID_RECIPIENT",
334
+ "ROLE_PERMISSION_DENIED",
335
+ "TRANSACTION_FAILED",
336
+ "RATE_LIMITED",
337
+ "NETWORK_ERROR",
338
+ "UNKNOWN",
339
+ "OTP_EXPIRED",
340
+ "SIGNER_REJECTED",
341
+ "CANCELLED",
342
+ "WRONG_STATE",
343
+ "STALE_EPOCH",
344
+ "SUPERSEDED",
345
+ "WORK_DIED",
346
+ "ACTOR_STOPPED"
347
+ ];
348
+ new Set(CAPXUL_ERROR_CODES);
349
+ //#endregion
350
+ //#region ../types/src/organization-setup.ts
351
+ /** Backend-owned Organization setup states shared by wire and telemetry. */
352
+ const ORGANIZATION_SETUP_STATUSES = [
353
+ "awaitingAuthorization",
354
+ "processing",
355
+ "needsAttention",
356
+ "ready",
357
+ "rechecking",
358
+ "failed"
359
+ ];
360
+ /** Closed reasons for a stored Organization setup issue. */
361
+ const ORGANIZATION_SETUP_REASONS = [
362
+ "submission_unknown",
363
+ "receipt_unresolved",
364
+ "provider_unavailable",
365
+ "receipt_reverted",
366
+ "deterministic_address_mismatch",
367
+ "receipt_mismatch",
368
+ "block_identity_changed",
369
+ "authority_event_mismatch",
370
+ "allowance_timestamp_mismatch",
371
+ "receipt_identity_unavailable",
372
+ "receipt_identity_mismatch",
373
+ "contract_code_unavailable",
374
+ "contract_state_mismatch",
375
+ "permission_projection_mismatch",
376
+ "bootstrap_reorg",
377
+ "dependent_authority_unresolved",
378
+ "historical_evidence_missing",
379
+ "worker_failed"
380
+ ];
381
+ //#endregion
382
+ //#region ../types/src/index.ts
383
+ const EVM_ADDRESS_RE = /^0x[0-9a-f]{40}$/i;
384
+ const BYTES32_RE = /^0x[0-9a-f]{64}$/i;
385
+ `${"0".repeat(64)}`;
386
+ const SUPPORTED_CURRENCIES = [
387
+ {
388
+ code: "USD",
389
+ symbol: "$",
390
+ name: "US Dollar"
391
+ },
392
+ {
393
+ code: "NGN",
394
+ symbol: "NGN",
395
+ name: "Nigerian Naira"
396
+ },
397
+ {
398
+ code: "GHS",
399
+ symbol: "GHS",
400
+ name: "Ghanaian Cedi"
401
+ },
402
+ {
403
+ code: "KES",
404
+ symbol: "KSh",
405
+ name: "Kenyan Shilling"
406
+ },
407
+ {
408
+ code: "UGX",
409
+ symbol: "USh",
410
+ name: "Ugandan Shilling"
411
+ }
412
+ ];
413
+ SUPPORTED_CURRENCIES.map((currency) => currency.code);
414
+ Object.fromEntries(SUPPORTED_CURRENCIES.map((currency) => [currency.code, currency.symbol]));
415
+ const APP_ID_RE = /^app_[0-7][0-9A-HJKMNP-TV-Z]{25}$/;
416
+ Math.floor(Number.MAX_SAFE_INTEGER / 1e3);
417
+ //#endregion
418
+ //#region src/operations.ts
419
+ const CAPXUL_OPERATIONS = {
420
+ account: {
421
+ addressBook: {
422
+ add: "account.addressBook.add",
423
+ get: "account.addressBook.get",
424
+ hide: "account.addressBook.hide",
425
+ label: "account.addressBook.label",
426
+ list: "account.addressBook.list",
427
+ unhide: "account.addressBook.unhide"
428
+ },
429
+ balance: "account.balance",
430
+ faucetMint: "account.faucetMint",
431
+ getLifecycle: "account.getLifecycle",
432
+ readBalance: "account.readBalance",
433
+ retrySetup: "account.retrySetup",
434
+ status: "account.status",
435
+ profile: {
436
+ depositInstructions: "account.profile.depositInstructions",
437
+ get: "account.profile.get"
438
+ },
439
+ inbox: {
440
+ approve: "account.inbox.approve",
441
+ decline: "account.inbox.decline",
442
+ list: "account.inbox.list"
443
+ },
444
+ requests: {
445
+ cancel: "account.requests.cancel",
446
+ get: "account.requests.get",
447
+ issue: "account.requests.issue",
448
+ list: "account.requests.list"
449
+ }
450
+ },
451
+ accounts: {
452
+ fund: "accounts.fund",
453
+ read: "accounts.read"
454
+ },
455
+ activity: {
456
+ annotate: "activity.annotate",
457
+ emitAnnotationSaved: "activity.emitAnnotationSaved",
458
+ get: "activity.get",
459
+ list: "activity.list",
460
+ /** The SDK's live Activity read over the indexer's SSE stream. */
461
+ subscribe: "activity.subscribe",
462
+ summary: "activity.summary"
463
+ },
464
+ addressBook: {
465
+ add: "addressBook.add",
466
+ emitRelationshipChanged: "addressBook.emitRelationshipChanged",
467
+ get: "addressBook.get",
468
+ hide: "addressBook.hide",
469
+ label: "addressBook.label",
470
+ list: "addressBook.list",
471
+ unhide: "addressBook.unhide"
472
+ },
473
+ applications: { create: "applications.create" },
474
+ auth: {
475
+ canSendOtp: "auth.canSendOtp",
476
+ getSession: "auth.getSession",
477
+ signIn: "auth.signIn",
478
+ signOut: "auth.signOut",
479
+ sendVerificationOtp: "auth.sendVerificationOTP",
480
+ verifyOtp: "auth.verifyOtp"
481
+ },
482
+ client: {
483
+ createOrg: "createOrg",
484
+ orgs: "orgs"
485
+ },
486
+ /** AUTH A3 (#2073): the SDK facade over the native continuation endpoints. */
487
+ clientRequests: {
488
+ decide: "clientRequests.decide",
489
+ read: "clientRequests.read"
490
+ },
491
+ /** AUTH A2 (#2072): the native client authorization issuer and its browser
492
+ * continuation. One name per durable transition the endpoints can fail on. */
493
+ clientAuthorization: {
494
+ acceptRequest: "clientAuthorization.acceptRequest",
495
+ cancelRequest: "clientAuthorization.cancelRequest",
496
+ consumeRequest: "clientAuthorization.consumeRequest",
497
+ denyRequest: "clientAuthorization.denyRequest",
498
+ invalidateContext: "clientAuthorization.invalidateContext",
499
+ markConsented: "clientAuthorization.markConsented",
500
+ readMetadata: "clientAuthorization.readMetadata",
501
+ revokeGrant: "clientAuthorization.revokeGrant",
502
+ rotateGrant: "clientAuthorization.rotateGrant",
503
+ startRequest: "clientAuthorization.startRequest",
504
+ sweepExpired: "clientAuthorization.sweepExpired"
505
+ },
506
+ credentials: {
507
+ bootstrapClient: "credentials.bootstrapClient",
508
+ mintQuickstartKey: "credentials.mintQuickstartKey"
509
+ },
510
+ currentUser: { get: "currentUser.get" },
511
+ devIdentity: { seedFinancialOpsOrg: "devIdentity.seedFinancialOpsOrg" },
512
+ dev: { browserSeed: "dev.browserSeed" },
513
+ destinations: {
514
+ add: "destinations.add",
515
+ list: "destinations.list",
516
+ remove: "destinations.remove"
517
+ },
518
+ faucetSafe: { deploy: "FaucetSafe.deploy" },
519
+ financialOps: {
520
+ addDestination: "financialOps.addDestination",
521
+ approveRequest: "financialOps.approveRequest",
522
+ cancelRequest: "financialOps.cancelRequest",
523
+ createPayee: "financialOps.createPayee",
524
+ declineRequest: "financialOps.declineRequest",
525
+ emitInvoiceIssued: "financialOps.emitInvoiceIssued",
526
+ emitInvoiceRequestTransitioned: "financialOps.emitInvoiceRequestTransitioned",
527
+ emitPaymentWriterTelemetry: "financialOps.emitPaymentWriterTelemetry",
528
+ issueRequest: "financialOps.issueRequest",
529
+ migrateEvidenceIdentity: "financialOps.migrateEvidenceIdentity",
530
+ planEvidenceIdentity: "financialOps.planEvidenceIdentity",
531
+ recoverSettlementVerification: "financialOps.recoverSettlementVerification",
532
+ removeDestination: "financialOps.removeDestination",
533
+ verifySettlement: "financialOps.verifySettlement"
534
+ },
535
+ holdings: { current: "holdings.current" },
536
+ indexer: { reconcile: "indexer.reconcile" },
537
+ identity: {
538
+ accountAt: "identity.AccountAt",
539
+ accountClaimed: "identity.AccountClaimed",
540
+ accountClaiming: "identity.AccountClaiming",
541
+ accountDerived: "identity.AccountDerived",
542
+ accountFailed: "identity.AccountFailed",
543
+ attachOrganization: "identity.AttachOrganization",
544
+ claimAccount: "identity.ClaimAccount",
545
+ completeOnboarding: "identity.completeOnboarding",
546
+ completeProfile: "identity.completeProfile",
547
+ create: "identity.create",
548
+ createOrganization: "identity.CreateOrganization",
549
+ ensureAccount: "identity.EnsureAccount",
550
+ leaveOrganization: "identity.LeaveOrganization",
551
+ loadByAuthUserId: "identity.loadByAuthUserId",
552
+ loadCurrent: "identity.loadCurrent",
553
+ orgAt: "identity.OrgAt",
554
+ orgFailed: "identity.OrgFailed",
555
+ orgReady: "identity.OrgReady",
556
+ otpFailed: "identity.OtpFailed",
557
+ otpSent: "identity.OtpSent",
558
+ readSession: "identity.ReadSession",
559
+ requestOtp: "identity.RequestOtp",
560
+ reset: "identity.Reset",
561
+ restoreSession: "identity.RestoreSession",
562
+ resumeOtpEntry: "identity.ResumeOtpEntry",
563
+ retryAccount: "identity.RetryAccount",
564
+ retryOrganization: "identity.RetryOrganization",
565
+ sessionAbsent: "identity.SessionAbsent",
566
+ sessionRead: "identity.SessionRead",
567
+ sessionReadFailed: "identity.SessionReadFailed",
568
+ sessionRestored: "identity.SessionRestored",
569
+ signedOut: "identity.SignedOut",
570
+ signOut: "identity.SignOut",
571
+ signOutFailed: "identity.SignOutFailed",
572
+ update: "identity.update",
573
+ handleAvailable: "identity.handleAvailable",
574
+ verified: "identity.Verified",
575
+ verifyFailed: "identity.VerifyFailed",
576
+ verifyOtp: "identity.VerifyOtp"
577
+ },
578
+ media: {
579
+ generateUploadUrl: "media.generateUploadUrl",
580
+ setOrgLogo: "media.setOrgLogo",
581
+ setProfileImage: "media.setProfileImage",
582
+ uploadImage: "media.uploadImage"
583
+ },
584
+ me: {
585
+ depositInstructions: "me.depositInstructions",
586
+ get: "me.get"
587
+ },
588
+ moneyExecution: {
589
+ abandonPaymentExecution: "moneyExecution.abandonPaymentExecution",
590
+ prepareOrganizationPaymentExecution: "moneyExecution.prepareOrganizationPaymentExecution",
591
+ prepareRequestPaymentExecution: "moneyExecution.prepareRequestPaymentExecution",
592
+ preparePaymentExecution: "moneyExecution.preparePaymentExecution",
593
+ preparePaymentLifecycleExecution: "moneyExecution.preparePaymentLifecycleExecution",
594
+ prepareInvitationConfiguration: "moneyExecution.prepareInvitationConfiguration",
595
+ preparePermissionExecution: "moneyExecution.preparePermissionExecution",
596
+ recoverSubmissionClaims: "moneyExecution.recoverSubmissionClaims",
597
+ submit: "moneyExecution.submit",
598
+ prepareInvoiceCheckoutExecution: "moneyExecution.prepareInvoiceCheckoutExecution",
599
+ prepareOfferCheckoutExecution: "moneyExecution.prepareOfferCheckoutExecution",
600
+ submitPaymentCommandExecution: "moneyExecution.submitPaymentCommandExecution",
601
+ submitInvitationConfigurationExecution: "moneyExecution.submitInvitationConfigurationExecution",
602
+ submitPaymentExecution: "moneyExecution.submitPaymentExecution",
603
+ submitPermissionExecution: "moneyExecution.submitPermissionExecution"
604
+ },
605
+ movement: {
606
+ emitDepositSettled: "movement.emitDepositSettled",
607
+ scan: "movement.scan"
608
+ },
609
+ inbox: {
610
+ paymentTerms: "inbox.paymentTerms",
611
+ approve: "inbox.approve",
612
+ fulfill: "inbox.fulfill",
613
+ decline: "inbox.decline",
614
+ list: "inbox.list"
615
+ },
616
+ offramp: {
617
+ quote: "offramp.quote",
618
+ status: "offramp.status"
619
+ },
620
+ offers: {
621
+ create: "offers.create",
622
+ get: "offers.get",
623
+ list: "offers.list",
624
+ revise: "offers.revise",
625
+ deactivate: "offers.deactivate"
626
+ },
627
+ checkouts: {
628
+ invoice: "checkouts.invoice",
629
+ prepareInvoice: "checkouts.prepareInvoice",
630
+ invoiceState: "checkouts.invoiceState",
631
+ reconcileInvoice: "checkouts.reconcileInvoice",
632
+ payInvoiceRegistered: "checkouts.payInvoiceRegistered",
633
+ prepareRegistered: "checkouts.prepareRegistered",
634
+ state: "checkouts.state",
635
+ reconcile: "checkouts.reconcile",
636
+ offer: "checkouts.offer",
637
+ create: "checkouts.create",
638
+ get: "checkouts.get",
639
+ prepare: "checkouts.prepare"
640
+ },
641
+ onboarding: {
642
+ completeOrganization: "onboarding.completeOrganization",
643
+ completePerson: "onboarding.completePerson"
644
+ },
645
+ org: {
646
+ account: { get: "org.account.get" },
647
+ auditLog: "org.auditLog",
648
+ confirmBootstrap: "org.confirmBootstrap",
649
+ createOrg: "org.createOrg",
650
+ create: "org.create",
651
+ /**
652
+ * §11: the consent mutation reports `org_invite_accepted` through its own
653
+ * scheduled emitter. It is named for the emit, not the acceptance, because
654
+ * the interactive acceptance itself owns `org.invitations.accept`.
655
+ */
656
+ emitInviteAccepted: "org.emitInviteAccepted",
657
+ emitInviteProgressed: "org.emitInviteProgressed",
658
+ expireInvitations: "org.expireInvitations",
659
+ getLifecycle: "org.getLifecycle",
660
+ getProofReceipt: "org.getProofReceipt",
661
+ invite: "org.invite",
662
+ /** D8 invitation lifecycle: preview, own list, read, and the four transitions. */
663
+ invitations: {
664
+ /** The exact grantee's consent commit (§8): one accepted digest, once. */
665
+ accept: "org.invitations.accept",
666
+ /**
667
+ * The authoring write. It is named `authorize`, not `invite`, because the
668
+ * backend already uses `org.invitations.invite` as a refusal label and
669
+ * `lint:telemetry-spine` refuses a label that collides with an operation.
670
+ */
671
+ authorize: "org.invitations.authorize",
672
+ cancel: "org.invitations.cancel",
673
+ decline: "org.invitations.decline",
674
+ get: "org.invitations.get",
675
+ subscribe: "org.invitations.subscribe",
676
+ list: "org.invitations.list",
677
+ /**
678
+ * The Admin-scoped Organization list. It is named `listScoped`, not
679
+ * `list`, because the own-offer list already owns `org.invitations.list`.
680
+ */
681
+ listScoped: "org.invitations.listScoped",
682
+ /**
683
+ * The authoring write's inner hops: the SDK drives the backend's existing
684
+ * prepare/submit pair, and these names label the two Convex calls. The
685
+ * owning `capxul_sdk_operation` record stays `org.invitations.authorize`.
686
+ */
687
+ prepareConfiguration: "org.invitations.prepareConfiguration",
688
+ preview: "org.invitations.preview",
689
+ resend: "org.invitations.resend",
690
+ retry: "org.invitations.retry",
691
+ submitConfiguration: "org.invitations.submitConfiguration"
692
+ },
693
+ list: "org.list",
694
+ load: "org.load",
695
+ me: "org.me",
696
+ members: "org.members",
697
+ orgs: "org.orgs",
698
+ payment: "org.payment",
699
+ permissions: {
700
+ assign: "org.permissions.assign",
701
+ change: "org.permissions.change",
702
+ create: "org.permissions.create",
703
+ get: "org.permissions.get",
704
+ getCommand: "org.permissions.getCommand",
705
+ subscribeCommand: "org.permissions.subscribeCommand",
706
+ list: "org.permissions.list",
707
+ replace: "org.permissions.replace",
708
+ previewReplacement: "org.permissions.previewReplacement",
709
+ revoke: "org.permissions.revoke"
710
+ },
711
+ payments: {
712
+ get: "org.payments.get",
713
+ list: "org.payments.list",
714
+ pay: "org.payments.pay",
715
+ payBatch: "org.payments.payBatch",
716
+ previewRetry: "org.payments.previewRetry",
717
+ subscribe: "org.payments.subscribe"
718
+ },
719
+ payroll: {
720
+ authorizeRun: "org.payroll.authorizeRun",
721
+ getRun: "org.payroll.getRun",
722
+ subscribeRun: "org.payroll.subscribeRun",
723
+ groups: {
724
+ list: "org.payroll.groups.list",
725
+ remove: "org.payroll.groups.remove",
726
+ save: "org.payroll.groups.save"
727
+ },
728
+ runs: "org.payroll.runs",
729
+ terms: "org.payroll.terms"
730
+ },
731
+ addressBook: {
732
+ add: "org.addressBook.add",
733
+ get: "org.addressBook.get",
734
+ hide: "org.addressBook.hide",
735
+ label: "org.addressBook.label",
736
+ list: "org.addressBook.list",
737
+ unhide: "org.addressBook.unhide"
738
+ },
739
+ inbox: {
740
+ approve: "org.inbox.approve",
741
+ decline: "org.inbox.decline",
742
+ list: "org.inbox.list"
743
+ },
744
+ lifecycle: { startOrResume: "org.lifecycle.startOrResume" },
745
+ prepareBootstrap: "org.prepareBootstrap",
746
+ prepareFounderAccount: "org.prepareFounderAccount",
747
+ profile: {
748
+ depositInstructions: "org.profile.depositInstructions",
749
+ get: "org.profile.get"
750
+ },
751
+ readTreasury: "org.readTreasury",
752
+ requests: {
753
+ cancel: "org.requests.cancel",
754
+ get: "org.requests.get",
755
+ issue: "org.requests.issue",
756
+ list: "org.requests.list"
757
+ },
758
+ recordFailure: "org.recordFailure",
759
+ recordProgress: "org.recordProgress",
760
+ resumeBootstrapSubmission: "org.resumeBootstrapSubmission",
761
+ retry: "org.retry",
762
+ retrySetup: "org.retrySetup",
763
+ roles: "org.roles",
764
+ startOrResume: "org.startOrResume",
765
+ submitBootstrap: "org.submitBootstrap",
766
+ treasury: "org.treasury"
767
+ },
768
+ organization: { setup: "organization.setup" },
769
+ organizationPayments: {
770
+ pay: "organizationPayments.pay",
771
+ payBatch: "organizationPayments.payBatch",
772
+ prepareExecution: "organizationPayments.prepareExecution",
773
+ retry: "organizationPayments.retry"
774
+ },
775
+ organizationSetup: { getProofReceipt: "organizationSetup.getProofReceipt" },
776
+ payments: {
777
+ cancel: "payments.cancel",
778
+ claim: "payments.claim",
779
+ createCommitment: "payments.createCommitment",
780
+ get: "payments.get",
781
+ ledger: "payments",
782
+ list: "payments.list",
783
+ pay: "payments.pay",
784
+ prepareExecution: "payments.prepareExecution",
785
+ prepareLifecycleExecution: "payments.prepareLifecycleExecution",
786
+ redirect: "payments.redirect",
787
+ retry: "payments.retry",
788
+ submitCommandExecution: "payments.submitCommandExecution",
789
+ submitExecution: "payments.submitExecution",
790
+ subscribe: "payments.subscribe"
791
+ },
792
+ paymentDocuments: {
793
+ get: "paymentDocuments.get",
794
+ render: "paymentDocuments.render",
795
+ verify: "paymentDocuments.verify"
796
+ },
797
+ recipient: { resolve: "recipient.resolve" },
798
+ payroll: {
799
+ authorizeRun: "payroll.authorizeRun",
800
+ getRun: "payroll.getRun",
801
+ subscribeRun: "payroll.subscribeRun",
802
+ emitGroupChanged: "payroll.emitGroupChanged",
803
+ emitRunTransitioned: "payroll.emitRunTransitioned",
804
+ groups: {
805
+ access: "payroll.groups",
806
+ list: "payroll.groups.list",
807
+ remove: "payroll.groups.remove",
808
+ save: "payroll.groups.save"
809
+ },
810
+ removeGroup: "payroll.removeGroup",
811
+ runs: "payroll.runs",
812
+ saveGroup: "payroll.saveGroup",
813
+ terms: "payroll.terms"
814
+ },
815
+ permission: {
816
+ getCommand: "permission.getCommand",
817
+ previewReplacement: "permission.previewReplacement",
818
+ verifyInvitationConfiguration: "permission.verifyInvitationConfiguration",
819
+ command: "permission.command",
820
+ retryVerification: "permission.retryVerification",
821
+ verify: "permission.verify",
822
+ verifySubmitted: "permission.verifySubmitted"
823
+ },
824
+ permissions: {
825
+ assign: "permissions.assign",
826
+ change: "permissions.change",
827
+ create: "permissions.create",
828
+ get: "permissions.get",
829
+ getCommand: "permissions.getCommand",
830
+ subscribeCommand: "permissions.subscribeCommand",
831
+ list: "permissions.list",
832
+ prepareExecution: "permissions.prepareExecution",
833
+ previewReplacement: "permissions.previewReplacement",
834
+ replace: "permissions.replace",
835
+ revoke: "permissions.revoke",
836
+ submitExecution: "permissions.submitExecution"
837
+ },
838
+ publishableKeys: {
839
+ mint: "publishableKeys.mint",
840
+ revoke: "publishableKeys.revoke",
841
+ rotate: "publishableKeys.rotate"
842
+ },
843
+ requests: {
844
+ cancel: "requests.cancel",
845
+ get: "requests.get",
846
+ issue: "requests.issue",
847
+ list: "requests.list"
848
+ },
849
+ runtime: {
850
+ assign: "assign",
851
+ canSendOtp: "canSendOtp",
852
+ cancelCommitment: "cancel_commitment",
853
+ change: "change",
854
+ claimCommitment: "claim_commitment",
855
+ create: "create",
856
+ createCapxulClient: "createCapxulClient",
857
+ createCapxulClientWithOrgDeploymentSeams: "createCapxulClientWithOrgDeploymentSeams",
858
+ createCommitment: "create_commitment",
859
+ getConvexJwt: "getConvexJwt",
860
+ getSession: "getSession",
861
+ initialize: "initialize",
862
+ mutation: "mutation",
863
+ now: "now",
864
+ port: "port",
865
+ query: "query",
866
+ redirectCommitment: "redirect_commitment",
867
+ replace: "replace",
868
+ resolve: "resolve",
869
+ revoke: "revoke",
870
+ send: "send",
871
+ sendOtp: "sendOtp",
872
+ signIn: "signIn",
873
+ signOut: "signOut",
874
+ sleep: "sleep",
875
+ verifyOtp: "verifyOtp",
876
+ wallet: "wallet"
877
+ },
878
+ smartAccount: {
879
+ claim: "smartAccount.claim",
880
+ confirmDeployment: "smartAccount.confirmDeployment",
881
+ loadByAuthUserId: "smartAccount.loadByAuthUserId",
882
+ loadCurrent: "smartAccount.loadCurrent",
883
+ provision: "smartAccount.provision"
884
+ },
885
+ system: {
886
+ health: "system.health",
887
+ ping: "system.ping",
888
+ runtimeChain: "system.runtimeChain"
889
+ },
890
+ testUsdc: { mint: "TestUSDC.mint" },
891
+ _internal: {
892
+ accounts: { fund: "_internal.accounts.fund" },
893
+ close: "_internal.close",
894
+ identity: {
895
+ completeProfile: "_internal.identity.completeProfile",
896
+ runFacade: "_internal.identity.runFacade",
897
+ send: "_internal.identity.send"
898
+ },
899
+ organizationSetup: { getProofReceipt: "_internal.organizationSetup.getProofReceipt" }
900
+ },
901
+ tenancy: {
902
+ revokeBackendTenancyConsent: "tenancy.revokeBackendTenancyConsent",
903
+ seedBackendTenancy: "tenancy.seedBackendTenancy"
904
+ }
905
+ };
906
+ function collectOperations(tree) {
907
+ return Object.values(tree).flatMap((value) => typeof value === "string" ? [value] : collectOperations(value));
908
+ }
909
+ const operations = new Set(collectOperations(CAPXUL_OPERATIONS));
910
+ function isCapxulOperation(value) {
911
+ return typeof value === "string" && operations.has(value);
912
+ }
913
+ function normalizeCapxulOperation(value) {
914
+ return isCapxulOperation(value) ? value : "unknown";
915
+ }
916
+ //#endregion
917
+ //#region src/index.ts
918
+ const TELEMETRY_EVENT_NAMES = [
919
+ "auth_otp_requested",
920
+ "auth_otp_delivered",
921
+ "auth_otp_expired",
922
+ "auth_verified",
923
+ "auth_failed",
924
+ "identity_refused",
925
+ "auth_signed_out",
926
+ "native_authorization_started",
927
+ "native_authorization_reviewed",
928
+ "native_authorization_accepted",
929
+ "native_authorization_denied",
930
+ "native_authorization_connected",
931
+ "native_authorization_failed",
932
+ "onboarding_intent_selected",
933
+ "onboarding_profile_submitted",
934
+ "onboarding_organization_submitted",
935
+ "onboarding_dashboard_reached",
936
+ "provisioning_safe_created",
937
+ "provisioning_safe_confirmed",
938
+ "bootstrap_resolved",
939
+ "bootstrap_failed",
940
+ "member_activation_started",
941
+ "member_activation_ready",
942
+ "member_activation_failed",
943
+ "organization_creation_started",
944
+ "organization_creation_ready",
945
+ "organization_creation_failed",
946
+ "chain_upstream_fallback",
947
+ "bundler_error",
948
+ "receipt_pending",
949
+ "operation_retried",
950
+ "account_balance_read",
951
+ "account_balance_failed",
952
+ "faucet_requested",
953
+ "faucet_confirmed",
954
+ "faucet_failed",
955
+ "org_create_started",
956
+ "org_safe_created",
957
+ "org_safe_confirmed",
958
+ "org_roles_seeded",
959
+ "org_created",
960
+ "org_create_failed",
961
+ "org_invite_sent",
962
+ "org_invite_accepted",
963
+ "org_invite_expired",
964
+ "payment_initiated",
965
+ "payment_settled",
966
+ "payment_failed",
967
+ "payment_verification_retry",
968
+ "payment_lifecycle_transition",
969
+ "quick_pay_external_address_acknowledged",
970
+ "deposit_initiated",
971
+ "deposit_settled",
972
+ "permission_mirror_verification",
973
+ "movement_scan_window",
974
+ "movement_scan_checkpoint",
975
+ "movement_scan_incident",
976
+ "indexer_drift_corrected",
977
+ "activity_annotation_saved",
978
+ "ui_activity_action_completed",
979
+ "contact_relationship_changed",
980
+ "ui_contact_action_completed",
981
+ "access_recovery_completed",
982
+ "ui_access_step_completed",
983
+ "org_invite_progressed",
984
+ "invoice_issued",
985
+ "invoice_request_transitioned",
986
+ "ui_invoice_step_completed",
987
+ "ui_treasury_step_completed",
988
+ "ui_receive_step_completed",
989
+ "payroll_group_changed",
990
+ "payroll_run_transitioned",
991
+ "ui_payroll_action_completed",
992
+ "cli_diagnostic_completed",
993
+ "cli_first_used",
994
+ "cli_command_started",
995
+ "cli_command_completed"
996
+ ];
997
+ const TELEMETRY_JOURNEYS = {
998
+ returning_user_login: {
999
+ type: "funnel",
1000
+ steps: [
1001
+ "auth_otp_requested",
1002
+ "auth_otp_delivered",
1003
+ "auth_verified"
1004
+ ],
1005
+ drops_on: ["auth_otp_expired", "auth_failed"]
1006
+ },
1007
+ new_user_first_signin: {
1008
+ type: "funnel",
1009
+ steps: [
1010
+ "auth_otp_requested",
1011
+ "auth_otp_delivered",
1012
+ "auth_verified",
1013
+ "provisioning_safe_created",
1014
+ "provisioning_safe_confirmed"
1015
+ ],
1016
+ drops_on: ["auth_otp_expired", "auth_failed"]
1017
+ },
1018
+ sign_out_session_close: {
1019
+ type: "point_event",
1020
+ point_event: "auth_signed_out"
1021
+ },
1022
+ member_activation: {
1023
+ type: "funnel",
1024
+ steps: ["member_activation_started", "member_activation_ready"],
1025
+ drops_on: ["member_activation_failed"]
1026
+ },
1027
+ organization_creation_lifecycle: {
1028
+ type: "funnel",
1029
+ steps: ["organization_creation_started", "organization_creation_ready"],
1030
+ drops_on: ["organization_creation_failed"]
1031
+ },
1032
+ new_member_personal_dashboard: {
1033
+ type: "funnel",
1034
+ steps: [
1035
+ "auth_verified",
1036
+ "onboarding_intent_selected",
1037
+ "onboarding_profile_submitted",
1038
+ "member_activation_ready",
1039
+ "onboarding_dashboard_reached"
1040
+ ],
1041
+ step_filters: {
1042
+ onboarding_intent_selected: [{
1043
+ key: "intent",
1044
+ value: ["personal"],
1045
+ operator: "exact",
1046
+ type: "event"
1047
+ }, {
1048
+ key: "entry_point",
1049
+ value: ["signup"],
1050
+ operator: "exact",
1051
+ type: "event"
1052
+ }],
1053
+ onboarding_profile_submitted: [{
1054
+ key: "intent",
1055
+ value: ["personal"],
1056
+ operator: "exact",
1057
+ type: "event"
1058
+ }],
1059
+ onboarding_dashboard_reached: [{
1060
+ key: "intent",
1061
+ value: ["personal"],
1062
+ operator: "exact",
1063
+ type: "event"
1064
+ }]
1065
+ }
1066
+ },
1067
+ new_member_organization_dashboard: {
1068
+ type: "funnel",
1069
+ steps: [
1070
+ "auth_verified",
1071
+ "onboarding_intent_selected",
1072
+ "onboarding_profile_submitted",
1073
+ "onboarding_organization_submitted",
1074
+ "member_activation_started",
1075
+ "member_activation_ready",
1076
+ "organization_creation_started",
1077
+ "organization_creation_ready",
1078
+ "onboarding_dashboard_reached"
1079
+ ],
1080
+ step_filters: {
1081
+ onboarding_intent_selected: [{
1082
+ key: "intent",
1083
+ value: ["organization"],
1084
+ operator: "exact",
1085
+ type: "event"
1086
+ }, {
1087
+ key: "entry_point",
1088
+ value: ["signup"],
1089
+ operator: "exact",
1090
+ type: "event"
1091
+ }],
1092
+ onboarding_profile_submitted: [{
1093
+ key: "intent",
1094
+ value: ["organization"],
1095
+ operator: "exact",
1096
+ type: "event"
1097
+ }],
1098
+ onboarding_dashboard_reached: [{
1099
+ key: "intent",
1100
+ value: ["organization"],
1101
+ operator: "exact",
1102
+ type: "event"
1103
+ }]
1104
+ }
1105
+ },
1106
+ existing_member_organization_dashboard: {
1107
+ type: "funnel",
1108
+ steps: [
1109
+ "onboarding_intent_selected",
1110
+ "onboarding_organization_submitted",
1111
+ "organization_creation_started",
1112
+ "organization_creation_ready",
1113
+ "onboarding_dashboard_reached"
1114
+ ],
1115
+ step_filters: {
1116
+ onboarding_intent_selected: [{
1117
+ key: "intent",
1118
+ value: ["organization"],
1119
+ operator: "exact",
1120
+ type: "event"
1121
+ }, {
1122
+ key: "entry_point",
1123
+ value: ["dashboard"],
1124
+ operator: "exact",
1125
+ type: "event"
1126
+ }],
1127
+ onboarding_dashboard_reached: [{
1128
+ key: "intent",
1129
+ value: ["organization"],
1130
+ operator: "exact",
1131
+ type: "event"
1132
+ }]
1133
+ }
1134
+ },
1135
+ money_on_screen: {
1136
+ type: "point_event",
1137
+ point_event: "account_balance_read"
1138
+ },
1139
+ fund_account: {
1140
+ type: "funnel",
1141
+ steps: ["faucet_requested", "faucet_confirmed"],
1142
+ drops_on: ["faucet_failed"]
1143
+ },
1144
+ org_creation: {
1145
+ type: "funnel",
1146
+ steps: [
1147
+ "org_create_started",
1148
+ "org_safe_created",
1149
+ "org_safe_confirmed",
1150
+ "org_roles_seeded",
1151
+ "org_created"
1152
+ ],
1153
+ drops_on: ["org_create_failed"]
1154
+ },
1155
+ org_member_onboarding: {
1156
+ type: "funnel",
1157
+ steps: ["org_invite_sent", "org_invite_accepted"],
1158
+ drops_on: ["org_invite_expired"]
1159
+ },
1160
+ direct_payment: {
1161
+ type: "funnel",
1162
+ steps: ["payment_initiated", "payment_settled"],
1163
+ drops_on: ["payment_failed"]
1164
+ },
1165
+ deposit: {
1166
+ type: "funnel",
1167
+ steps: ["deposit_initiated", "deposit_settled"]
1168
+ }
1169
+ };
1170
+ const PII = Schema.String.pipe(Schema.brand("PII"));
1171
+ const OptionalString = Schema.optional(Schema.String);
1172
+ const AddressSchema = Schema.String.pipe(Schema.decodeTo(Schema.String, {
1173
+ decode: SchemaGetter.transform((value) => value.toLowerCase()),
1174
+ encode: SchemaGetter.transform((value) => value)
1175
+ }), Schema.refine((value) => EVM_ADDRESS_RE.test(value), { message: "must be 0x + 40 hex chars" }));
1176
+ const AppIdSchema = Schema.String.pipe(Schema.refine((value) => APP_ID_RE.test(value), { message: "must be app_ plus a ULID" }));
1177
+ const BlockNumberSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" }));
1178
+ const ChainIdSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value > 0, { message: "must be a positive safe integer" }));
1179
+ const DurationMsSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" }));
1180
+ const EpochMsSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" }));
1181
+ const PublishableKeyIdSchema = Schema.String.pipe(Schema.refine((value) => value.length > 0, { message: "must be a non-empty string" }));
1182
+ const TxHashSchema = Schema.String.pipe(Schema.refine((value) => BYTES32_RE.test(value), { message: "must be 0x + 64 hex chars" }));
1183
+ const ACCOUNT_ID_TELEMETRY_RE = /^account_[0-9A-Za-z]+$/;
1184
+ const WEI_AMOUNT_TELEMETRY_RE = /^[0-9]+$/;
1185
+ const AccountIdSchema = Schema.String.pipe(Schema.refine((value) => ACCOUNT_ID_TELEMETRY_RE.test(value), { message: "must be account_ plus an alphanumeric id" }));
1186
+ const WeiAmountSchema = Schema.String.pipe(Schema.refine((value) => WEI_AMOUNT_TELEMETRY_RE.test(value), { message: "must be a non-negative integer string" }));
1187
+ const CurrencyCodeSchema = Schema.String.pipe(Schema.refine((value) => value.length > 0, { message: "must be a non-empty currency code" }));
1188
+ const BalanceBucketSchema = Schema.Literals(["zero", "nonzero"]);
1189
+ const OptionalAccountId = Schema.optional(AccountIdSchema);
1190
+ const OptionalWeiAmount = Schema.optional(WeiAmountSchema);
1191
+ const OptionalCurrencyCode = Schema.optional(CurrencyCodeSchema);
1192
+ const OptionalBalanceBucket = Schema.optional(BalanceBucketSchema);
1193
+ /** Which Safe a money record is about. Declared here so the money-domain
1194
+ * props below can name it as well as the UI-step props further down. */
1195
+ const AccountKindSchema = Schema.Literals(["personalSafe", "orgTreasury"]);
1196
+ const OptionalAccountKind = Schema.optional(AccountKindSchema);
1197
+ const OptionalAddress = Schema.optional(AddressSchema);
1198
+ const OptionalAppId = Schema.optional(AppIdSchema);
1199
+ const OptionalBlockNumber = Schema.optional(BlockNumberSchema);
1200
+ const OptionalChainId = Schema.optional(ChainIdSchema);
1201
+ const OptionalDurationMs = Schema.optional(DurationMsSchema);
1202
+ const OptionalEpochMs = Schema.optional(EpochMsSchema);
1203
+ const OptionalPublishableKeyId = Schema.optional(PublishableKeyIdSchema);
1204
+ const OptionalTxHash = Schema.optional(TxHashSchema);
1205
+ /**
1206
+ * Environment discriminator (ADR-0020 A1 amendment, 2026-08-07). PostHog
1207
+ * project 368736 is the SINGLE sink for every environment, so `capxul_env` —
1208
+ * not project isolation — is what keeps a production surface from reading dev
1209
+ * traffic. It is REQUIRED on every catalog event and every synced artifact
1210
+ * filters on it.
1211
+ *
1212
+ * `unknown` is a defect marker, not an environment: it means a producer
1213
+ * reached the transport without declaring where it runs. It is in the union so
1214
+ * the property is never ABSENT (an absent property is invisible to a filter,
1215
+ * a present `unknown` is loud), and sync v2 never synthesizes an artifact for
1216
+ * it.
1217
+ */
1218
+ const CAPXUL_ENVS = [
1219
+ "development",
1220
+ "staging",
1221
+ "production",
1222
+ "unknown",
1223
+ "local"
1224
+ ];
1225
+ /**
1226
+ * Environments a synced product surface may be built for. `unknown` and
1227
+ * `local` cannot. This list is deliberately narrower than `CAPXUL_ENVS`.
1228
+ */
1229
+ const SYNCABLE_CAPXUL_ENVS = [
1230
+ "development",
1231
+ "staging",
1232
+ "production"
1233
+ ];
1234
+ /**
1235
+ * Which half of the system emitted the event. REQUIRED alongside `capxul_env`
1236
+ * so a name that two halves can produce (settlement, auth) stays attributable.
1237
+ */
1238
+ const TELEMETRY_PRODUCERS = [
1239
+ "server",
1240
+ "browser",
1241
+ "sdk",
1242
+ "mcp",
1243
+ "e2e"
1244
+ ];
1245
+ /**
1246
+ * The canonical envelope (ADR-0020 A4): snake_case ONLY. `capxul_env` and
1247
+ * `producer` are REQUIRED — a boundary that forgets to stamp them fails schema
1248
+ * decode instead of silently shipping an unattributable event. Call sites do
1249
+ * not pass them: `stampTelemetryEnvelope` injects them at the emit boundary,
1250
+ * which is the only place that knows where the process runs.
1251
+ */
1252
+ const TelemetryEnvelopeProps = {
1253
+ capxul_env: Schema.Literals(CAPXUL_ENVS),
1254
+ producer: Schema.Literals(TELEMETRY_PRODUCERS),
1255
+ journey_id: OptionalString,
1256
+ correlation_id: OptionalString,
1257
+ sdk_version: OptionalString
1258
+ };
1259
+ /**
1260
+ * The cause of a failure, flat (ADR-0023 R7–R8). `failure_mode` is the one
1261
+ * word from `@capxul/errors`; the `chain_*` keys are the `ChainCause` when the
1262
+ * failure came from the chain path. Spread into every failure event and posted
1263
+ * on `$exception`, so one PostHog filter finds a cause wherever it was seen.
1264
+ */
1265
+ const FailureModeSchema = Schema.Literals(FAILURE_MODES);
1266
+ const ChainUpstreamSchema = Schema.Literals(CHAIN_UPSTREAMS);
1267
+ /**
1268
+ * The refusing upstream's response headers (#1818): exactly the names in
1269
+ * `RESPONSE_HEADER_ALLOWLIST`, each optional, so the catalog itself refuses a
1270
+ * `set-cookie` or `authorization` that a producer let through.
1271
+ */
1272
+ const ResponseHeadersSchema = Schema.Struct({
1273
+ "retry-after": OptionalString,
1274
+ "www-authenticate": OptionalString,
1275
+ "content-type": OptionalString,
1276
+ "x-request-id": OptionalString,
1277
+ "cf-ray": OptionalString,
1278
+ "x-ratelimit-remaining": OptionalString,
1279
+ "x-ratelimit-reset": OptionalString,
1280
+ server: OptionalString
1281
+ });
1282
+ /** One upstream tried, flat (#1818): the `chain_attempts` entry on every producer's row. */
1283
+ const ChainAttemptSchema = Schema.Struct({
1284
+ upstream: ChainUpstreamSchema,
1285
+ failure_mode: FailureModeSchema,
1286
+ http_status: Schema.optional(Schema.Number),
1287
+ rpc_code: Schema.optional(Schema.Number),
1288
+ duration_ms: Schema.Number
1289
+ });
1290
+ const ChainCauseTelemetryProps = {
1291
+ failure_mode: Schema.optional(FailureModeSchema),
1292
+ chain_upstream: Schema.optional(ChainUpstreamSchema),
1293
+ chain_method: OptionalString,
1294
+ chain_retryable: Schema.optional(Schema.Boolean),
1295
+ chain_http_status: Schema.optional(Schema.Number),
1296
+ chain_rpc_code: Schema.optional(Schema.Number),
1297
+ chain_revert_name: OptionalString,
1298
+ chain_revert_selector: OptionalString,
1299
+ chain_revert_args: Schema.optional(Schema.Record(Schema.String, Schema.String)),
1300
+ chain_provider_message: OptionalString,
1301
+ chain_attempts: Schema.optional(Schema.Array(ChainAttemptSchema)),
1302
+ chain_response_headers: Schema.optional(ResponseHeadersSchema)
1303
+ };
1304
+ /**
1305
+ * Stamp the required envelope onto an event at its emit boundary. Call-site
1306
+ * props win on conflict: a relay that already knows the true producer (the
1307
+ * browser-failure relay stamps `browser` while running on the server) must not
1308
+ * be overwritten by the transport's own default.
1309
+ */
1310
+ function stampTelemetryEnvelope(event, defaults) {
1311
+ return {
1312
+ name: event.name,
1313
+ props: {
1314
+ ...defaults,
1315
+ ...event.props
1316
+ }
1317
+ };
1318
+ }
1319
+ const AuthOtpRequestedProps = Schema.Struct({
1320
+ ...TelemetryEnvelopeProps,
1321
+ email: Schema.optional(PII),
1322
+ email_domain: OptionalString
1323
+ });
1324
+ const AuthOtpDeliveredProps = Schema.Struct({
1325
+ ...TelemetryEnvelopeProps,
1326
+ durationMs: OptionalDurationMs,
1327
+ email: Schema.optional(PII),
1328
+ email_domain: OptionalString,
1329
+ resendMessageId: OptionalString
1330
+ });
1331
+ const AuthOtpExpiredProps = Schema.Struct({
1332
+ ...TelemetryEnvelopeProps,
1333
+ email: Schema.optional(PII),
1334
+ email_domain: OptionalString
1335
+ });
1336
+ const AuthVerifiedProps = Schema.Struct({
1337
+ ...TelemetryEnvelopeProps,
1338
+ auth_type: OptionalString
1339
+ });
1340
+ const AuthFailedProps = Schema.Struct({
1341
+ ...TelemetryEnvelopeProps,
1342
+ ...ChainCauseTelemetryProps,
1343
+ email: Schema.optional(PII),
1344
+ auth_type: OptionalString,
1345
+ reason: OptionalString
1346
+ });
1347
+ const IdentityRefusedProps = Schema.Struct({
1348
+ ...TelemetryEnvelopeProps,
1349
+ /** The refused identity event tag, for example CreateOrganization. */
1350
+ event: OptionalString,
1351
+ /** The machine's refusal code: WRONG_STATE, SUPERSEDED or STALE_EPOCH. */
1352
+ refusal_code: OptionalString,
1353
+ /** The machine slot the request targeted, for example identity:org. */
1354
+ slot: OptionalString,
1355
+ /** The machine state at refusal, for example authenticated:claiming. */
1356
+ state: OptionalString
1357
+ });
1358
+ const AuthSignedOutProps = Schema.Struct(TelemetryEnvelopeProps);
1359
+ const NativeAuthorizationMode = Schema.Literals(["login", "signup"]);
1360
+ const NativeAuthorizationStartedProps = Schema.Struct({
1361
+ ...TelemetryEnvelopeProps,
1362
+ mode: NativeAuthorizationMode
1363
+ });
1364
+ const NativeAuthorizationReviewedProps = Schema.Struct({
1365
+ ...TelemetryEnvelopeProps,
1366
+ mode: NativeAuthorizationMode
1367
+ });
1368
+ const NativeAuthorizationAcceptedProps = Schema.Struct({
1369
+ ...TelemetryEnvelopeProps,
1370
+ mode: NativeAuthorizationMode,
1371
+ /** Whether consent also had to finish account setup first. */
1372
+ setup_state: Schema.optional(Schema.Literals([
1373
+ "not_required",
1374
+ "new",
1375
+ "resumable"
1376
+ ]))
1377
+ });
1378
+ const NativeAuthorizationDeniedProps = Schema.Struct({
1379
+ ...TelemetryEnvelopeProps,
1380
+ mode: NativeAuthorizationMode
1381
+ });
1382
+ const NativeAuthorizationConnectedProps = Schema.Struct({
1383
+ ...TelemetryEnvelopeProps,
1384
+ mode: NativeAuthorizationMode
1385
+ });
1386
+ const NativeAuthorizationFailedProps = Schema.Struct({
1387
+ ...TelemetryEnvelopeProps,
1388
+ mode: Schema.optional(NativeAuthorizationMode),
1389
+ /** The refusal word the store returned, for example `identity_mismatch` or
1390
+ * `request_expired`. These are the closed `CLIENT_AUTHORIZATION_REFUSALS` from
1391
+ * `@capxul/wire` plus the store-internal `fresh_session_required` (ruling R3),
1392
+ * which the continuation maps to `identity_mismatch` on the wire but reports
1393
+ * truthfully here. Kept as `OptionalString` rather than an imported literal
1394
+ * set: this package must not depend on the transport contract. */
1395
+ reason: OptionalString
1396
+ });
1397
+ const ProvisioningSafeCreatedProps = Schema.Struct({
1398
+ ...TelemetryEnvelopeProps,
1399
+ safe_address: OptionalAddress
1400
+ });
1401
+ const ProvisioningSafeConfirmedProps = Schema.Struct({
1402
+ ...TelemetryEnvelopeProps,
1403
+ chainId: OptionalChainId,
1404
+ deployedAt: OptionalEpochMs,
1405
+ deployedAtBlock: OptionalBlockNumber,
1406
+ deployTxHash: OptionalTxHash,
1407
+ durationMs: OptionalDurationMs,
1408
+ safe_address: OptionalAddress,
1409
+ userOpHash: OptionalTxHash
1410
+ });
1411
+ const BootstrapResolvedProps = Schema.Struct({
1412
+ ...TelemetryEnvelopeProps,
1413
+ applicationId: OptionalAppId,
1414
+ durationMs: OptionalDurationMs,
1415
+ env: OptionalString,
1416
+ keyId: OptionalPublishableKeyId,
1417
+ origin: OptionalString
1418
+ });
1419
+ const BootstrapFailedProps = Schema.Struct({
1420
+ ...TelemetryEnvelopeProps,
1421
+ ...ChainCauseTelemetryProps,
1422
+ applicationId: OptionalAppId,
1423
+ durationMs: OptionalDurationMs,
1424
+ origin: OptionalString,
1425
+ provider: OptionalString,
1426
+ provider_operation: OptionalString,
1427
+ reason: OptionalString,
1428
+ target_host: OptionalString
1429
+ });
1430
+ /**
1431
+ * R08 (#1966): which Safe was read, on which chain, of which token. `currency`
1432
+ * is the DISPLAY code the surface shows ("USD"); it never says which ERC-20 the
1433
+ * `balanceOf` actually hit, so a reader could not tell a treasury read from a
1434
+ * personal one, nor one token from another with the same fiat peg. The producer
1435
+ * takes each of these from the authority that already decided it — the verified
1436
+ * Organization row's chain, the configured token address — never from a label.
1437
+ * The verified `organization_id` and its group arrive from the backend
1438
+ * attribution, so they are not repeated here.
1439
+ *
1440
+ * D1 (2026-09-10): `asset_id` carries the canonical branded identity the read
1441
+ * resolved, `eip155:<chainId>/erc20:<lowercase-address>`, from the registry
1442
+ * row. `token_address`/`chain_id` are its parts; `currency` is the peg and a
1443
+ * display code. The producer emits the branded id so the live read can be
1444
+ * grouped by ASSET, never by symbol or peg.
1445
+ */
1446
+ const AccountBalanceReadProps = Schema.Struct({
1447
+ ...TelemetryEnvelopeProps,
1448
+ account_id: OptionalAccountId,
1449
+ account_kind: OptionalAccountKind,
1450
+ chain_id: OptionalChainId,
1451
+ token_address: OptionalAddress,
1452
+ asset_id: OptionalString,
1453
+ currency: OptionalCurrencyCode,
1454
+ balance_bucket: OptionalBalanceBucket,
1455
+ durationMs: OptionalDurationMs
1456
+ });
1457
+ const AccountBalanceFailedProps = Schema.Struct({
1458
+ ...TelemetryEnvelopeProps,
1459
+ ...ChainCauseTelemetryProps,
1460
+ reason: OptionalString
1461
+ });
1462
+ const FaucetRequestedProps = Schema.Struct({
1463
+ ...TelemetryEnvelopeProps,
1464
+ amount: OptionalWeiAmount,
1465
+ chainId: OptionalChainId,
1466
+ asset_id: OptionalString
1467
+ });
1468
+ const FaucetConfirmedProps = Schema.Struct({
1469
+ ...TelemetryEnvelopeProps,
1470
+ amount: OptionalWeiAmount,
1471
+ chainId: OptionalChainId,
1472
+ txHash: OptionalTxHash,
1473
+ asset_id: OptionalString,
1474
+ token_address: OptionalAddress,
1475
+ durationMs: OptionalDurationMs
1476
+ });
1477
+ const FaucetFailedProps = Schema.Struct({
1478
+ ...TelemetryEnvelopeProps,
1479
+ ...ChainCauseTelemetryProps,
1480
+ reason: OptionalString,
1481
+ amount: OptionalWeiAmount,
1482
+ chainId: OptionalChainId,
1483
+ asset_id: OptionalString,
1484
+ token_address: OptionalAddress
1485
+ });
1486
+ const ChainServiceSchema = Schema.Literals(["aa-gateway", "backend"]);
1487
+ const ChainUpstreamFallbackProps = Schema.Struct({
1488
+ ...TelemetryEnvelopeProps,
1489
+ service: ChainServiceSchema,
1490
+ method: Schema.String,
1491
+ from_upstream: ChainUpstreamSchema,
1492
+ to_upstream: Schema.optional(ChainUpstreamSchema),
1493
+ failure_mode: FailureModeSchema,
1494
+ exhausted: Schema.Boolean,
1495
+ http_status: Schema.optional(Schema.Number),
1496
+ rpc_code: Schema.optional(Schema.Number),
1497
+ response_headers: Schema.optional(ResponseHeadersSchema)
1498
+ });
1499
+ const BundlerErrorProps = Schema.Struct({
1500
+ ...TelemetryEnvelopeProps,
1501
+ method: Schema.String,
1502
+ failure_mode: FailureModeSchema,
1503
+ chain_upstream: ChainUpstreamSchema,
1504
+ chain_retryable: Schema.Boolean,
1505
+ http_status: Schema.optional(Schema.Number),
1506
+ rpc_code: Schema.optional(Schema.Number),
1507
+ chain_revert_name: OptionalString,
1508
+ chain_provider_message: OptionalString
1509
+ });
1510
+ const ReceiptPendingProps = Schema.Struct({
1511
+ ...TelemetryEnvelopeProps,
1512
+ service: ChainServiceSchema,
1513
+ method: Schema.String,
1514
+ chain_upstream: ChainUpstreamSchema,
1515
+ reason: Schema.Literals(["zero_block_hash", "no_receipt"])
1516
+ });
1517
+ const OperationRetriedProps = Schema.Struct({
1518
+ ...TelemetryEnvelopeProps,
1519
+ operation: Schema.String,
1520
+ failure_mode: FailureModeSchema,
1521
+ reason: Schema.optional(Schema.Literal("connection-lost-in-flight")),
1522
+ connection_id: OptionalString,
1523
+ connection_count: Schema.optional(Schema.Number),
1524
+ attempt: Schema.Number,
1525
+ delay_ms: DurationMsSchema
1526
+ });
1527
+ const ORG_ID_TELEMETRY_RE = /^org_[0-9A-Za-z]+$/;
1528
+ const OrgIdTelemetrySchema = Schema.String.pipe(Schema.refine((value) => ORG_ID_TELEMETRY_RE.test(value), { message: "must be org_ plus an alphanumeric id" }));
1529
+ const OptionalOrgId = Schema.optional(OrgIdTelemetrySchema);
1530
+ const AttemptNumberSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value > 0, { message: "must be a positive safe integer" }));
1531
+ const OnboardingStageSchema = Schema.Literals([
1532
+ "profile",
1533
+ "accountProvisioning",
1534
+ "accountClaim",
1535
+ "preparingFounderAccount",
1536
+ "awaitingFounderAuthorization",
1537
+ "submittingBootstrap",
1538
+ "confirmingBootstrap"
1539
+ ]);
1540
+ const MemberActivationStartedProps = Schema.Struct({
1541
+ ...TelemetryEnvelopeProps,
1542
+ $insert_id: Schema.String
1543
+ });
1544
+ const MemberActivationReadyProps = Schema.Struct({
1545
+ ...TelemetryEnvelopeProps,
1546
+ $insert_id: Schema.String,
1547
+ duration_ms: DurationMsSchema
1548
+ });
1549
+ const MemberActivationFailedProps = Schema.Struct({
1550
+ ...TelemetryEnvelopeProps,
1551
+ ...ChainCauseTelemetryProps,
1552
+ $insert_id: Schema.String,
1553
+ stage: OnboardingStageSchema,
1554
+ error_code: Schema.String,
1555
+ retryable: Schema.Boolean
1556
+ });
1557
+ const OrganizationCreationStartedProps = Schema.Struct({
1558
+ ...TelemetryEnvelopeProps,
1559
+ $insert_id: Schema.String,
1560
+ organization_id: OrgIdTelemetrySchema,
1561
+ attempt_number: AttemptNumberSchema,
1562
+ release: Schema.optional(Schema.String.check(Schema.isPattern(/^[0-9a-f]{40}$/u)))
1563
+ });
1564
+ const OrganizationCreationReadyProps = Schema.Struct({
1565
+ ...TelemetryEnvelopeProps,
1566
+ $insert_id: Schema.String,
1567
+ organization_id: OrgIdTelemetrySchema,
1568
+ attempt_number: AttemptNumberSchema,
1569
+ duration_ms: DurationMsSchema,
1570
+ release: Schema.optional(Schema.String.check(Schema.isPattern(/^[0-9a-f]{40}$/u)))
1571
+ });
1572
+ const OrganizationCreationFailedProps = Schema.Struct({
1573
+ ...TelemetryEnvelopeProps,
1574
+ ...ChainCauseTelemetryProps,
1575
+ $insert_id: Schema.String,
1576
+ organization_id: OrgIdTelemetrySchema,
1577
+ attempt_number: AttemptNumberSchema,
1578
+ stage: OnboardingStageSchema,
1579
+ error_code: Schema.String,
1580
+ retryable: Schema.Boolean,
1581
+ release: Schema.optional(Schema.String.check(Schema.isPattern(/^[0-9a-f]{40}$/u))),
1582
+ /** #1655: the SDK's backoff before this attempt. Absent on the first attempt. */
1583
+ backoff_ms: Schema.optional(DurationMsSchema),
1584
+ failure_reason: Schema.optional(Schema.Literals([
1585
+ "receipt_provider_unavailable",
1586
+ "block_provider_unavailable",
1587
+ ...ORGANIZATION_SETUP_REASONS
1588
+ ]))
1589
+ });
1590
+ const OnboardingIntentSchema = Schema.Literals(["personal", "organization"]);
1591
+ const OnboardingIntentSelectedProps = Schema.Struct({
1592
+ ...TelemetryEnvelopeProps,
1593
+ journey_id: Schema.String,
1594
+ intent: OnboardingIntentSchema,
1595
+ entry_point: Schema.String
1596
+ });
1597
+ const OnboardingProfileSubmittedProps = Schema.Struct({
1598
+ ...TelemetryEnvelopeProps,
1599
+ journey_id: Schema.String,
1600
+ intent: OnboardingIntentSchema
1601
+ });
1602
+ const OnboardingOrganizationSubmittedProps = Schema.Struct({
1603
+ ...TelemetryEnvelopeProps,
1604
+ journey_id: Schema.String
1605
+ });
1606
+ const OnboardingDashboardReachedProps = Schema.Struct({
1607
+ ...TelemetryEnvelopeProps,
1608
+ journey_id: Schema.String,
1609
+ intent: OnboardingIntentSchema,
1610
+ organization_id: Schema.optional(OrgIdTelemetrySchema)
1611
+ });
1612
+ const OrgCreateStartedProps = Schema.Struct({
1613
+ ...TelemetryEnvelopeProps,
1614
+ org_id: OptionalOrgId,
1615
+ email_domain: OptionalString,
1616
+ template: OptionalString
1617
+ });
1618
+ const OrgSafeCreatedProps = Schema.Struct({
1619
+ ...TelemetryEnvelopeProps,
1620
+ org_id: OptionalOrgId,
1621
+ chainId: OptionalChainId,
1622
+ safe_address: OptionalAddress
1623
+ });
1624
+ const OrgSafeConfirmedProps = Schema.Struct({
1625
+ ...TelemetryEnvelopeProps,
1626
+ org_id: OptionalOrgId,
1627
+ chainId: OptionalChainId,
1628
+ safe_address: OptionalAddress,
1629
+ durationMs: OptionalDurationMs
1630
+ });
1631
+ const OrgRolesSeededProps = Schema.Struct({
1632
+ ...TelemetryEnvelopeProps,
1633
+ org_id: OptionalOrgId,
1634
+ chainId: OptionalChainId,
1635
+ role: OptionalString,
1636
+ txHash: OptionalTxHash
1637
+ });
1638
+ const OrgCreatedProps = Schema.Struct({
1639
+ ...TelemetryEnvelopeProps,
1640
+ org_id: OptionalOrgId,
1641
+ chainId: OptionalChainId,
1642
+ safe_address: OptionalAddress,
1643
+ durationMs: OptionalDurationMs
1644
+ });
1645
+ const OrgCreateFailedProps = Schema.Struct({
1646
+ ...TelemetryEnvelopeProps,
1647
+ ...ChainCauseTelemetryProps,
1648
+ org_id: OptionalOrgId,
1649
+ reason: OptionalString
1650
+ });
1651
+ const OrgInviteSentProps = Schema.Struct({
1652
+ ...TelemetryEnvelopeProps,
1653
+ org_id: OptionalOrgId,
1654
+ invitation_id: OptionalString,
1655
+ generation: OptionalString,
1656
+ command_id: OptionalString,
1657
+ subject_party_id: OptionalString,
1658
+ persisted_at: OptionalEpochMs,
1659
+ email_domain: OptionalString,
1660
+ role: OptionalString,
1661
+ status: OptionalString
1662
+ });
1663
+ const OrgInviteAcceptedProps = Schema.Struct({
1664
+ ...TelemetryEnvelopeProps,
1665
+ org_id: OptionalOrgId,
1666
+ invitation_id: OptionalString,
1667
+ accepted_at: OptionalEpochMs,
1668
+ generation: OptionalString,
1669
+ command_id: OptionalString,
1670
+ subject_party_id: OptionalString,
1671
+ role: OptionalString,
1672
+ status: OptionalString
1673
+ });
1674
+ const OrgInviteExpiredProps = Schema.Struct({
1675
+ ...TelemetryEnvelopeProps,
1676
+ org_id: OptionalOrgId,
1677
+ email_domain: OptionalString,
1678
+ invitation_id: OptionalString,
1679
+ reason: OptionalString,
1680
+ role: OptionalString,
1681
+ status: OptionalString
1682
+ });
1683
+ const RecipientLocatorKindSchema = Schema.Literals([
1684
+ "handle",
1685
+ "email",
1686
+ "address",
1687
+ "party"
1688
+ ]);
1689
+ const RecipientResolutionStatusSchema = Schema.Literals([
1690
+ "known_party",
1691
+ "new_email",
1692
+ "external_address"
1693
+ ]);
1694
+ const RecipientPartyKindSchema = Schema.Literals([
1695
+ "person",
1696
+ "organization",
1697
+ "unresolved"
1698
+ ]);
1699
+ const RecipientTelemetryProps = {
1700
+ recipient_locator_kind: Schema.optional(RecipientLocatorKindSchema),
1701
+ recipient_resolution_status: Schema.optional(RecipientResolutionStatusSchema),
1702
+ recipient_party_id: OptionalString,
1703
+ recipient_party_kind: Schema.optional(RecipientPartyKindSchema),
1704
+ recipient_is_capxul_account: Schema.optional(Schema.Boolean),
1705
+ recipient_handle: OptionalString,
1706
+ recipient_address: OptionalAddress,
1707
+ external_address_acknowledged: Schema.optional(Schema.Boolean)
1708
+ };
1709
+ const PaymentInitiatedProps = Schema.Struct({
1710
+ command_id: OptionalString,
1711
+ execution_id: OptionalString,
1712
+ payment_lifecycle_id: OptionalString,
1713
+ ...TelemetryEnvelopeProps,
1714
+ ...RecipientTelemetryProps,
1715
+ kind: Schema.String,
1716
+ payment_id: Schema.String
1717
+ });
1718
+ const PaymentLifecycleProps = {
1719
+ payment_state: OptionalString,
1720
+ execution_state: OptionalString,
1721
+ occurred_at: Schema.optional(Schema.Number),
1722
+ causal_sequence: Schema.optional(Schema.Number),
1723
+ sponsorship_valid_until: Schema.optional(Schema.Number),
1724
+ terminal_event_id: OptionalString
1725
+ };
1726
+ const PaymentSettledL2Props = Schema.Struct({
1727
+ ...PaymentLifecycleProps,
1728
+ ...TelemetryEnvelopeProps,
1729
+ ...RecipientTelemetryProps,
1730
+ kind: Schema.String,
1731
+ chain_id: Schema.Number,
1732
+ settlement_id: Schema.String,
1733
+ payment_id: OptionalString,
1734
+ payment_ids: OptionalString,
1735
+ command_id: OptionalString,
1736
+ payment_lifecycle_id: OptionalString,
1737
+ execution_id: OptionalString,
1738
+ user_op_hash: OptionalString,
1739
+ transaction_hash: OptionalString
1740
+ });
1741
+ const PaymentFailedL2Props = Schema.Struct({
1742
+ ...PaymentLifecycleProps,
1743
+ ...TelemetryEnvelopeProps,
1744
+ ...ChainCauseTelemetryProps,
1745
+ ...RecipientTelemetryProps,
1746
+ kind: Schema.String,
1747
+ payment_id: Schema.String,
1748
+ payment_ids: OptionalString,
1749
+ reason_code: Schema.String,
1750
+ command_id: OptionalString,
1751
+ payment_lifecycle_id: OptionalString,
1752
+ execution_id: OptionalString,
1753
+ user_op_hash: OptionalString
1754
+ });
1755
+ const PaymentVerificationRetryProps = Schema.Struct({
1756
+ ...PaymentLifecycleProps,
1757
+ ...TelemetryEnvelopeProps,
1758
+ ...RecipientTelemetryProps,
1759
+ command_id: Schema.String,
1760
+ payment_lifecycle_id: Schema.String,
1761
+ attempt: Schema.Number,
1762
+ reason_code: Schema.String,
1763
+ chain_id: Schema.Number,
1764
+ delay_ms: DurationMsSchema,
1765
+ outcome: Schema.Literals(["scheduled", "unresolved"]),
1766
+ payment_id: OptionalString,
1767
+ payment_ids: OptionalString,
1768
+ execution_id: OptionalString,
1769
+ user_op_hash: OptionalString
1770
+ });
1771
+ const PaymentLifecycleTransitionProps = Schema.Struct({
1772
+ ...TelemetryEnvelopeProps,
1773
+ ...RecipientTelemetryProps,
1774
+ payment_id: Schema.String,
1775
+ payment_lifecycle_id: Schema.String,
1776
+ command_id: Schema.String,
1777
+ payment_state: Schema.String,
1778
+ occurred_at: Schema.Number,
1779
+ causal_sequence: Schema.Number,
1780
+ execution_id: OptionalString,
1781
+ execution_state: OptionalString,
1782
+ user_op_hash: OptionalString,
1783
+ sponsorship_valid_until: Schema.optional(Schema.Number),
1784
+ reason_code: OptionalString
1785
+ });
1786
+ const QuickPayExternalAddressAcknowledgedProps = Schema.Struct({
1787
+ ...TelemetryEnvelopeProps,
1788
+ recipient_locator_kind: Schema.Literal("address"),
1789
+ recipient_resolution_status: Schema.Literal("external_address"),
1790
+ recipient_address: AddressSchema,
1791
+ external_address_acknowledged: Schema.Literal(true),
1792
+ organization_id: OptionalOrgId
1793
+ });
1794
+ const DepositInitiatedProps = Schema.Struct({
1795
+ ...TelemetryEnvelopeProps,
1796
+ scope_kind: Schema.optional(Schema.Literals(["account", "organization"])),
1797
+ account_kind: Schema.optional(Schema.Literals(["personalSafe", "orgTreasury"])),
1798
+ chain_id: Schema.optional(Schema.Number),
1799
+ network: Schema.optional(Schema.Literal("base-sepolia")),
1800
+ organization_id: OptionalOrgId,
1801
+ $groups: Schema.optional(Schema.Struct({ organization: OptionalOrgId })),
1802
+ actor_id: OptionalString,
1803
+ actor_kind: Schema.optional(Schema.Literal("authenticated")),
1804
+ distinct_id: OptionalString,
1805
+ trace_id: OptionalString,
1806
+ span_id: OptionalString
1807
+ });
1808
+ const DepositSettledProps = Schema.Struct({
1809
+ ...TelemetryEnvelopeProps,
1810
+ chain_id: Schema.Number,
1811
+ tx_hash: Schema.String,
1812
+ log_index: Schema.Number
1813
+ });
1814
+ const PermissionMirrorVerificationProps = Schema.Struct({
1815
+ ...TelemetryEnvelopeProps,
1816
+ /** The RECEIPT verification outcome. What the mirror then did is separate. */
1817
+ outcome: Schema.String,
1818
+ reason: Schema.String,
1819
+ chain_id: Schema.Number,
1820
+ retry_count: Schema.Number,
1821
+ /**
1822
+ * #1960 R02, consumed by R03. A verified receipt is not an applied Permission:
1823
+ * these two optional fields let the producer say what the applying mutation
1824
+ * actually returned, and which command it was, without either fact rewriting
1825
+ * the receipt outcome above. Absent when application has not happened yet.
1826
+ */
1827
+ application_result: Schema.optional(Schema.Literals([
1828
+ "applied",
1829
+ "replayed",
1830
+ "conflicting_replay",
1831
+ "revision_mismatch",
1832
+ "cleanup_required",
1833
+ "not_applied",
1834
+ "application_failure",
1835
+ "mismatch",
1836
+ "refused"
1837
+ ])),
1838
+ command_kind: Schema.optional(Schema.Literals(["invitation_configuration", "invitation_eoa"])),
1839
+ command_id: OptionalString,
1840
+ invitation_id: OptionalString,
1841
+ generation: OptionalString,
1842
+ purpose: Schema.optional(Schema.Literals([
1843
+ "configure",
1844
+ "grant",
1845
+ "disable",
1846
+ "compensate"
1847
+ ])),
1848
+ $insert_id: OptionalString,
1849
+ /**
1850
+ * #1961 R03. The authorized stored row names the Permission it changed; the
1851
+ * verified receipt names the chain facts that prove it. Every field is
1852
+ * optional because a pending or provider-failed verification has neither an
1853
+ * application result nor a receipt to report.
1854
+ */
1855
+ permission_id: OptionalString,
1856
+ permission_assignment_id: OptionalString,
1857
+ permission_operation: Schema.optional(Schema.Literals([
1858
+ "create",
1859
+ "change",
1860
+ "assign",
1861
+ "revoke",
1862
+ "replace"
1863
+ ])),
1864
+ revision: Schema.optional(Schema.Number),
1865
+ user_op_hash: OptionalString,
1866
+ transaction_hash: OptionalString,
1867
+ block_number: Schema.optional(Schema.Number),
1868
+ log_index: Schema.optional(Schema.Number)
1869
+ });
1870
+ const MovementScanWindowProps = Schema.Struct({
1871
+ ...TelemetryEnvelopeProps,
1872
+ chain_id: Schema.Number,
1873
+ token_address: Schema.String,
1874
+ from_block: Schema.Number,
1875
+ to_block: Schema.Number,
1876
+ log_count: Schema.Number,
1877
+ request_count: Schema.Number,
1878
+ outcome: Schema.String
1879
+ });
1880
+ const MovementScanCheckpointProps = Schema.Struct({
1881
+ ...TelemetryEnvelopeProps,
1882
+ chain_id: Schema.Number,
1883
+ token_address: Schema.String,
1884
+ next_block: Schema.Number,
1885
+ anchor_block_number: Schema.Number
1886
+ });
1887
+ const MovementScanIncidentProps = Schema.Struct({
1888
+ ...TelemetryEnvelopeProps,
1889
+ chain_id: Schema.Number,
1890
+ token_address: Schema.String,
1891
+ incident_kind: Schema.String,
1892
+ anchor_block_number: Schema.Number
1893
+ });
1894
+ /**
1895
+ * One durable row the reconciliation job corrected against Ponder (SPEC D9).
1896
+ *
1897
+ * Both block fields are optional and for the same reason: a correction INTO
1898
+ * drift (a Payment settled in Convex whose Ponder fact a reorg removed) has no
1899
+ * current block, and a correction that confirms a later fact has one.
1900
+ *
1901
+ * `projection_kind` is closed. A later ticket that reconciles a deploy, a
1902
+ * bootstrap or a grant outcome adds its kind here in the same change; an
1903
+ * unknown kind must not decode.
1904
+ */
1905
+ const IndexerDriftCorrectedProps = Schema.Struct({
1906
+ ...TelemetryEnvelopeProps,
1907
+ projection_kind: Schema.Literals([
1908
+ "member_authority",
1909
+ "payment_settlement",
1910
+ "permission_assignment"
1911
+ ]),
1912
+ previous_state: Schema.String,
1913
+ current_state: Schema.String,
1914
+ previous_block: Schema.optional(Schema.Number),
1915
+ current_block: Schema.optional(Schema.Number),
1916
+ logical_event_id: Schema.optional(Schema.String),
1917
+ scope_kind: Schema.optional(Schema.Literals(["account", "organization"])),
1918
+ account_id: OptionalAccountId,
1919
+ reference_id: OptionalString
1920
+ });
1921
+ const AuthOtpRequestedTelemetryEventSchema = Schema.Struct({
1922
+ name: Schema.Literal("auth_otp_requested"),
1923
+ props: AuthOtpRequestedProps
1924
+ });
1925
+ const AuthOtpDeliveredTelemetryEventSchema = Schema.Struct({
1926
+ name: Schema.Literal("auth_otp_delivered"),
1927
+ props: AuthOtpDeliveredProps
1928
+ });
1929
+ const AuthOtpExpiredTelemetryEventSchema = Schema.Struct({
1930
+ name: Schema.Literal("auth_otp_expired"),
1931
+ props: AuthOtpExpiredProps
1932
+ });
1933
+ const AuthVerifiedTelemetryEventSchema = Schema.Struct({
1934
+ name: Schema.Literal("auth_verified"),
1935
+ props: AuthVerifiedProps
1936
+ });
1937
+ const AuthFailedTelemetryEventSchema = Schema.Struct({
1938
+ name: Schema.Literal("auth_failed"),
1939
+ props: AuthFailedProps
1940
+ });
1941
+ const IdentityRefusedTelemetryEventSchema = Schema.Struct({
1942
+ name: Schema.Literal("identity_refused"),
1943
+ props: IdentityRefusedProps
1944
+ });
1945
+ const AuthSignedOutTelemetryEventSchema = Schema.Struct({
1946
+ name: Schema.Literal("auth_signed_out"),
1947
+ props: AuthSignedOutProps
1948
+ });
1949
+ const NativeAuthorizationStartedTelemetryEventSchema = Schema.Struct({
1950
+ name: Schema.Literal("native_authorization_started"),
1951
+ props: NativeAuthorizationStartedProps
1952
+ });
1953
+ const NativeAuthorizationReviewedTelemetryEventSchema = Schema.Struct({
1954
+ name: Schema.Literal("native_authorization_reviewed"),
1955
+ props: NativeAuthorizationReviewedProps
1956
+ });
1957
+ const NativeAuthorizationAcceptedTelemetryEventSchema = Schema.Struct({
1958
+ name: Schema.Literal("native_authorization_accepted"),
1959
+ props: NativeAuthorizationAcceptedProps
1960
+ });
1961
+ const NativeAuthorizationDeniedTelemetryEventSchema = Schema.Struct({
1962
+ name: Schema.Literal("native_authorization_denied"),
1963
+ props: NativeAuthorizationDeniedProps
1964
+ });
1965
+ const NativeAuthorizationConnectedTelemetryEventSchema = Schema.Struct({
1966
+ name: Schema.Literal("native_authorization_connected"),
1967
+ props: NativeAuthorizationConnectedProps
1968
+ });
1969
+ const NativeAuthorizationFailedTelemetryEventSchema = Schema.Struct({
1970
+ name: Schema.Literal("native_authorization_failed"),
1971
+ props: NativeAuthorizationFailedProps
1972
+ });
1973
+ const OnboardingIntentSelectedTelemetryEventSchema = Schema.Struct({
1974
+ name: Schema.Literal("onboarding_intent_selected"),
1975
+ props: OnboardingIntentSelectedProps
1976
+ });
1977
+ const OnboardingProfileSubmittedTelemetryEventSchema = Schema.Struct({
1978
+ name: Schema.Literal("onboarding_profile_submitted"),
1979
+ props: OnboardingProfileSubmittedProps
1980
+ });
1981
+ const OnboardingOrganizationSubmittedTelemetryEventSchema = Schema.Struct({
1982
+ name: Schema.Literal("onboarding_organization_submitted"),
1983
+ props: OnboardingOrganizationSubmittedProps
1984
+ });
1985
+ const OnboardingDashboardReachedTelemetryEventSchema = Schema.Struct({
1986
+ name: Schema.Literal("onboarding_dashboard_reached"),
1987
+ props: OnboardingDashboardReachedProps
1988
+ });
1989
+ const ProvisioningSafeCreatedTelemetryEventSchema = Schema.Struct({
1990
+ name: Schema.Literal("provisioning_safe_created"),
1991
+ props: ProvisioningSafeCreatedProps
1992
+ });
1993
+ const ProvisioningSafeConfirmedTelemetryEventSchema = Schema.Struct({
1994
+ name: Schema.Literal("provisioning_safe_confirmed"),
1995
+ props: ProvisioningSafeConfirmedProps
1996
+ });
1997
+ const BootstrapResolvedTelemetryEventSchema = Schema.Struct({
1998
+ name: Schema.Literal("bootstrap_resolved"),
1999
+ props: BootstrapResolvedProps
2000
+ });
2001
+ const BootstrapFailedTelemetryEventSchema = Schema.Struct({
2002
+ name: Schema.Literal("bootstrap_failed"),
2003
+ props: BootstrapFailedProps
2004
+ });
2005
+ const MemberActivationStartedTelemetryEventSchema = Schema.Struct({
2006
+ name: Schema.Literal("member_activation_started"),
2007
+ props: MemberActivationStartedProps
2008
+ });
2009
+ const MemberActivationReadyTelemetryEventSchema = Schema.Struct({
2010
+ name: Schema.Literal("member_activation_ready"),
2011
+ props: MemberActivationReadyProps
2012
+ });
2013
+ const MemberActivationFailedTelemetryEventSchema = Schema.Struct({
2014
+ name: Schema.Literal("member_activation_failed"),
2015
+ props: MemberActivationFailedProps
2016
+ });
2017
+ const OrganizationCreationStartedTelemetryEventSchema = Schema.Struct({
2018
+ name: Schema.Literal("organization_creation_started"),
2019
+ props: OrganizationCreationStartedProps
2020
+ });
2021
+ const OrganizationCreationReadyTelemetryEventSchema = Schema.Struct({
2022
+ name: Schema.Literal("organization_creation_ready"),
2023
+ props: OrganizationCreationReadyProps
2024
+ });
2025
+ const OrganizationCreationFailedTelemetryEventSchema = Schema.Struct({
2026
+ name: Schema.Literal("organization_creation_failed"),
2027
+ props: OrganizationCreationFailedProps
2028
+ });
2029
+ const AccountBalanceReadTelemetryEventSchema = Schema.Struct({
2030
+ name: Schema.Literal("account_balance_read"),
2031
+ props: AccountBalanceReadProps
2032
+ });
2033
+ const AccountBalanceFailedTelemetryEventSchema = Schema.Struct({
2034
+ name: Schema.Literal("account_balance_failed"),
2035
+ props: AccountBalanceFailedProps
2036
+ });
2037
+ const FaucetRequestedTelemetryEventSchema = Schema.Struct({
2038
+ name: Schema.Literal("faucet_requested"),
2039
+ props: FaucetRequestedProps
2040
+ });
2041
+ const FaucetConfirmedTelemetryEventSchema = Schema.Struct({
2042
+ name: Schema.Literal("faucet_confirmed"),
2043
+ props: FaucetConfirmedProps
2044
+ });
2045
+ const FaucetFailedTelemetryEventSchema = Schema.Struct({
2046
+ name: Schema.Literal("faucet_failed"),
2047
+ props: FaucetFailedProps
2048
+ });
2049
+ const ChainUpstreamFallbackTelemetryEventSchema = Schema.Struct({
2050
+ name: Schema.Literal("chain_upstream_fallback"),
2051
+ props: ChainUpstreamFallbackProps
2052
+ });
2053
+ const BundlerErrorTelemetryEventSchema = Schema.Struct({
2054
+ name: Schema.Literal("bundler_error"),
2055
+ props: BundlerErrorProps
2056
+ });
2057
+ const ReceiptPendingTelemetryEventSchema = Schema.Struct({
2058
+ name: Schema.Literal("receipt_pending"),
2059
+ props: ReceiptPendingProps
2060
+ });
2061
+ const OperationRetriedTelemetryEventSchema = Schema.Struct({
2062
+ name: Schema.Literal("operation_retried"),
2063
+ props: OperationRetriedProps
2064
+ });
2065
+ const OrgCreateStartedTelemetryEventSchema = Schema.Struct({
2066
+ name: Schema.Literal("org_create_started"),
2067
+ props: OrgCreateStartedProps
2068
+ });
2069
+ const OrgSafeCreatedTelemetryEventSchema = Schema.Struct({
2070
+ name: Schema.Literal("org_safe_created"),
2071
+ props: OrgSafeCreatedProps
2072
+ });
2073
+ const OrgSafeConfirmedTelemetryEventSchema = Schema.Struct({
2074
+ name: Schema.Literal("org_safe_confirmed"),
2075
+ props: OrgSafeConfirmedProps
2076
+ });
2077
+ const OrgRolesSeededTelemetryEventSchema = Schema.Struct({
2078
+ name: Schema.Literal("org_roles_seeded"),
2079
+ props: OrgRolesSeededProps
2080
+ });
2081
+ const OrgCreatedTelemetryEventSchema = Schema.Struct({
2082
+ name: Schema.Literal("org_created"),
2083
+ props: OrgCreatedProps
2084
+ });
2085
+ const OrgCreateFailedTelemetryEventSchema = Schema.Struct({
2086
+ name: Schema.Literal("org_create_failed"),
2087
+ props: OrgCreateFailedProps
2088
+ });
2089
+ const OrgInviteSentTelemetryEventSchema = Schema.Struct({
2090
+ name: Schema.Literal("org_invite_sent"),
2091
+ props: OrgInviteSentProps
2092
+ });
2093
+ const OrgInviteAcceptedTelemetryEventSchema = Schema.Struct({
2094
+ name: Schema.Literal("org_invite_accepted"),
2095
+ props: OrgInviteAcceptedProps
2096
+ });
2097
+ const OrgInviteExpiredTelemetryEventSchema = Schema.Struct({
2098
+ name: Schema.Literal("org_invite_expired"),
2099
+ props: OrgInviteExpiredProps
2100
+ });
2101
+ const PaymentInitiatedTelemetryEventSchema = Schema.Struct({
2102
+ name: Schema.Literal("payment_initiated"),
2103
+ props: PaymentInitiatedProps
2104
+ });
2105
+ const PaymentSettledTelemetryEventSchema = Schema.Struct({
2106
+ name: Schema.Literal("payment_settled"),
2107
+ props: PaymentSettledL2Props
2108
+ });
2109
+ const PaymentFailedTelemetryEventSchema = Schema.Struct({
2110
+ name: Schema.Literal("payment_failed"),
2111
+ props: PaymentFailedL2Props
2112
+ });
2113
+ const PaymentVerificationRetryTelemetryEventSchema = Schema.Struct({
2114
+ name: Schema.Literal("payment_verification_retry"),
2115
+ props: PaymentVerificationRetryProps
2116
+ });
2117
+ const PaymentLifecycleTransitionTelemetryEventSchema = Schema.Struct({
2118
+ name: Schema.Literal("payment_lifecycle_transition"),
2119
+ props: PaymentLifecycleTransitionProps
2120
+ });
2121
+ const QuickPayExternalAddressAcknowledgedTelemetryEventSchema = Schema.Struct({
2122
+ name: Schema.Literal("quick_pay_external_address_acknowledged"),
2123
+ props: QuickPayExternalAddressAcknowledgedProps
2124
+ });
2125
+ const DepositInitiatedTelemetryEventSchema = Schema.Struct({
2126
+ name: Schema.Literal("deposit_initiated"),
2127
+ props: DepositInitiatedProps
2128
+ });
2129
+ const DepositSettledTelemetryEventSchema = Schema.Struct({
2130
+ name: Schema.Literal("deposit_settled"),
2131
+ props: DepositSettledProps
2132
+ });
2133
+ const PermissionMirrorVerificationTelemetryEventSchema = Schema.Struct({
2134
+ name: Schema.Literal("permission_mirror_verification"),
2135
+ props: PermissionMirrorVerificationProps
2136
+ });
2137
+ const MovementScanWindowTelemetryEventSchema = Schema.Struct({
2138
+ name: Schema.Literal("movement_scan_window"),
2139
+ props: MovementScanWindowProps
2140
+ });
2141
+ const MovementScanCheckpointTelemetryEventSchema = Schema.Struct({
2142
+ name: Schema.Literal("movement_scan_checkpoint"),
2143
+ props: MovementScanCheckpointProps
2144
+ });
2145
+ const MovementScanIncidentTelemetryEventSchema = Schema.Struct({
2146
+ name: Schema.Literal("movement_scan_incident"),
2147
+ props: MovementScanIncidentProps
2148
+ });
2149
+ const IndexerDriftCorrectedTelemetryEventSchema = Schema.Struct({
2150
+ name: Schema.Literal("indexer_drift_corrected"),
2151
+ props: IndexerDriftCorrectedProps
2152
+ });
2153
+ /** The one spelling of "whose scope did this happen in" across every surface. */
2154
+ const ScopeKindSchema = Schema.Literals(["account", "organization"]);
2155
+ const OptionalReasonCode = Schema.optional(Schema.Literals(CAPXUL_ERROR_CODES));
2156
+ const ActivityReferenceProps = {
2157
+ reference_kind: Schema.Literals(["payment", "movement"]),
2158
+ reference_id: Schema.String
2159
+ };
2160
+ const ActivityFilterProps = {
2161
+ filter_kind: Schema.optional(Schema.Literals([
2162
+ "all",
2163
+ "payment",
2164
+ "movement"
2165
+ ])),
2166
+ filter_direction: Schema.optional(Schema.Literals([
2167
+ "all",
2168
+ "in",
2169
+ "out",
2170
+ "self"
2171
+ ])),
2172
+ filter_status: Schema.optional(Schema.Array(Schema.Literals([
2173
+ "pending",
2174
+ "settling",
2175
+ "unresolved",
2176
+ "pending_claim",
2177
+ "scheduled",
2178
+ "streaming",
2179
+ "settled",
2180
+ "cancelled",
2181
+ "failed"
2182
+ ])))
2183
+ };
2184
+ const ActivityActionProps = {
2185
+ ...TelemetryEnvelopeProps,
2186
+ scope_kind: ScopeKindSchema,
2187
+ reason_code: OptionalReasonCode
2188
+ };
2189
+ const ContactRelationshipChangedTelemetryEventSchema = Schema.Struct({
2190
+ name: Schema.Literal("contact_relationship_changed"),
2191
+ props: Schema.Struct({
2192
+ ...TelemetryEnvelopeProps,
2193
+ change: Schema.Literals([
2194
+ "added",
2195
+ "renamed",
2196
+ "hidden",
2197
+ "restored"
2198
+ ]),
2199
+ scope_kind: ScopeKindSchema,
2200
+ scope_id: Schema.String,
2201
+ owner_party_id: Schema.String,
2202
+ party_id: Schema.String,
2203
+ hidden: Schema.Boolean,
2204
+ occurred_at: Schema.Number,
2205
+ operation: Schema.Literals([
2206
+ CAPXUL_OPERATIONS.addressBook.add,
2207
+ CAPXUL_OPERATIONS.addressBook.label,
2208
+ CAPXUL_OPERATIONS.addressBook.hide,
2209
+ CAPXUL_OPERATIONS.addressBook.unhide
2210
+ ])
2211
+ })
2212
+ });
2213
+ const ContactActionProps = {
2214
+ ...TelemetryEnvelopeProps,
2215
+ scope_kind: ScopeKindSchema,
2216
+ party_id: OptionalString,
2217
+ reason_code: OptionalReasonCode
2218
+ };
2219
+ /** One completed online CLI diagnostic. No command input or provider text. */
2220
+ const CLI_COMMAND_NAMES = [
2221
+ "status",
2222
+ "request",
2223
+ "request.list",
2224
+ "request.get",
2225
+ "request.cancel",
2226
+ "offer",
2227
+ "offer.create",
2228
+ "offer.list",
2229
+ "offer.get",
2230
+ "offer.revise",
2231
+ "offer.deactivate",
2232
+ "org.offer",
2233
+ "org.offer.create",
2234
+ "org.offer.list",
2235
+ "org.offer.get",
2236
+ "org.offer.revise",
2237
+ "org.offer.deactivate",
2238
+ "request.issue",
2239
+ "inbox",
2240
+ CAPXUL_OPERATIONS.inbox.list,
2241
+ "inbox.get",
2242
+ "inbox.pay",
2243
+ CAPXUL_OPERATIONS.inbox.decline,
2244
+ "org.request",
2245
+ "org.request.list",
2246
+ "org.request.get",
2247
+ "org.request.cancel",
2248
+ "org.request.issue",
2249
+ "org.inbox",
2250
+ CAPXUL_OPERATIONS.org.inbox.list,
2251
+ "org.inbox.get",
2252
+ "org.inbox.pay",
2253
+ CAPXUL_OPERATIONS.org.inbox.decline,
2254
+ "capxul",
2255
+ "doctor",
2256
+ "telemetry",
2257
+ "telemetry.status",
2258
+ "telemetry.enable",
2259
+ "telemetry.disable",
2260
+ "auth",
2261
+ "auth.login",
2262
+ "auth.signup",
2263
+ "auth.send",
2264
+ "auth.verify",
2265
+ "auth.profile",
2266
+ "auth.status",
2267
+ "auth.logout",
2268
+ "account",
2269
+ CAPXUL_OPERATIONS.account.status,
2270
+ CAPXUL_OPERATIONS.account.balance,
2271
+ "account.deposit",
2272
+ "account.retry",
2273
+ "document",
2274
+ "document.get",
2275
+ "document.verify",
2276
+ "document.render",
2277
+ "document.export",
2278
+ "payment",
2279
+ "payment.list",
2280
+ "payment.get",
2281
+ "payment.wait",
2282
+ "payment.send",
2283
+ "payment.retry",
2284
+ "activity",
2285
+ CAPXUL_OPERATIONS.activity.list,
2286
+ CAPXUL_OPERATIONS.activity.get,
2287
+ CAPXUL_OPERATIONS.activity.summary,
2288
+ CAPXUL_OPERATIONS.activity.annotate,
2289
+ "contact",
2290
+ "contact.list",
2291
+ "contact.get",
2292
+ "contact.add",
2293
+ "contact.label",
2294
+ "contact.hide",
2295
+ "contact.unhide",
2296
+ "org",
2297
+ CAPXUL_OPERATIONS.org.list,
2298
+ "org.use",
2299
+ "org.status",
2300
+ CAPXUL_OPERATIONS.org.me,
2301
+ "org.balance",
2302
+ "org.deposit",
2303
+ "org.permission",
2304
+ "org.permission.list",
2305
+ "org.permission.get",
2306
+ "org.permission.create",
2307
+ "org.permission.change",
2308
+ "org.permission.assign",
2309
+ "org.permission.revoke",
2310
+ "org.permission.replace",
2311
+ "org.permission.command",
2312
+ "org.permission.command.get",
2313
+ "org.permission.command.wait",
2314
+ CAPXUL_OPERATIONS.org.payment,
2315
+ "org.payment.list",
2316
+ "org.payment.get",
2317
+ "org.payment.wait",
2318
+ "org.payment.retry",
2319
+ "org.payment.send",
2320
+ "org.payroll",
2321
+ "org.payroll.groups",
2322
+ CAPXUL_OPERATIONS.org.payroll.groups.list,
2323
+ CAPXUL_OPERATIONS.org.payroll.groups.save,
2324
+ CAPXUL_OPERATIONS.org.payroll.groups.remove,
2325
+ CAPXUL_OPERATIONS.org.payroll.terms,
2326
+ "org.payroll.list",
2327
+ "org.payroll.run",
2328
+ "org.payroll.get",
2329
+ "org.payroll.wait",
2330
+ CAPXUL_OPERATIONS.org.members,
2331
+ "org.member",
2332
+ "org.member.get",
2333
+ "org.member.invite",
2334
+ "org.contact",
2335
+ "org.contact.list",
2336
+ "org.contact.get",
2337
+ "org.contact.add",
2338
+ "org.contact.label",
2339
+ "org.contact.hide",
2340
+ "org.contact.unhide",
2341
+ CAPXUL_OPERATIONS.org.invite,
2342
+ "org.invite.list",
2343
+ "org.invite.get",
2344
+ "org.invite.wait",
2345
+ "org.invite.review",
2346
+ "org.invite.accept",
2347
+ "org.invite.decline",
2348
+ "org.invite.cancel",
2349
+ "org.invite.resend",
2350
+ "org.invite.retry",
2351
+ "org.wait",
2352
+ CAPXUL_OPERATIONS.org.create,
2353
+ CAPXUL_OPERATIONS.org.retry,
2354
+ "unknown"
2355
+ ];
2356
+ const CLI_CAPABILITIES = [
2357
+ "cli",
2358
+ "diagnostics",
2359
+ "collection",
2360
+ "authentication",
2361
+ "account",
2362
+ "organization",
2363
+ "contacts",
2364
+ "documents",
2365
+ "payments",
2366
+ "activity"
2367
+ ];
2368
+ const CLI_INVOCATION_KINDS = [
2369
+ "command",
2370
+ "help",
2371
+ "version",
2372
+ "completion",
2373
+ "parse_refusal",
2374
+ "collection_control"
2375
+ ];
2376
+ const CliRelease = Schema.String.check(Schema.isPattern(/^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/u));
2377
+ const CliInvocationProps = {
2378
+ ...TelemetryEnvelopeProps,
2379
+ schema_version: Schema.Literal(1),
2380
+ command: Schema.Literals(CLI_COMMAND_NAMES),
2381
+ capability: Schema.Literals(CLI_CAPABILITIES),
2382
+ invocation_kind: Schema.Literals(CLI_INVOCATION_KINDS),
2383
+ invocation_id: Schema.String.check(Schema.isPattern(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u)),
2384
+ cli_identity_kind: Schema.optional(Schema.Literals(["anonymous", "identified"])),
2385
+ anonymous_id: Schema.optional(Schema.String.check(Schema.isPattern(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u))),
2386
+ auth_user_id: Schema.optional(Schema.String.check(Schema.isPattern(/^[^\s]{1,256}$/u))),
2387
+ occurred_at: Schema.Number,
2388
+ cli_version: CliRelease,
2389
+ sdk_version: CliRelease,
2390
+ release: CliRelease,
2391
+ platform: Schema.Literals([
2392
+ "darwin",
2393
+ "linux",
2394
+ "unknown"
2395
+ ]),
2396
+ architecture: Schema.Literals([
2397
+ "arm64",
2398
+ "x64",
2399
+ "unknown"
2400
+ ]),
2401
+ ci: Schema.Boolean,
2402
+ tty: Schema.Boolean,
2403
+ output_mode: Schema.Literals(["human", "json"])
2404
+ };
2405
+ const CliFirstUsedTelemetryEventSchema = Schema.Struct({
2406
+ name: Schema.Literal("cli_first_used"),
2407
+ props: Schema.Struct(CliInvocationProps)
2408
+ });
2409
+ const CliCommandStartedTelemetryEventSchema = Schema.Struct({
2410
+ name: Schema.Literal("cli_command_started"),
2411
+ props: Schema.Struct({
2412
+ ...CliInvocationProps,
2413
+ invocation_kind: Schema.Literals([
2414
+ "command",
2415
+ "help",
2416
+ "version"
2417
+ ])
2418
+ })
2419
+ });
2420
+ const CliCommandCompletedTelemetryEventSchema = Schema.Struct({
2421
+ name: Schema.Literal("cli_command_completed"),
2422
+ props: Schema.Struct({
2423
+ ...CliInvocationProps,
2424
+ outcome: Schema.Literals([
2425
+ "succeeded",
2426
+ "refused",
2427
+ "failed",
2428
+ "cancelled"
2429
+ ]),
2430
+ duration_ms: Schema.Number,
2431
+ organization_id: Schema.optional(OrgIdTelemetrySchema),
2432
+ setup_status: Schema.optional(Schema.Literals(ORGANIZATION_SETUP_STATUSES)),
2433
+ setup_reason: Schema.optional(Schema.Literals(ORGANIZATION_SETUP_REASONS)),
2434
+ $groups: Schema.optional(Schema.Struct({ organization: OrgIdTelemetrySchema })),
2435
+ error_code: Schema.optional(Schema.Literals([
2436
+ ...CAPXUL_ERROR_CODES,
2437
+ "CLI_USAGE",
2438
+ "CLI_CONFIG",
2439
+ "CLI_STORAGE",
2440
+ "CLI_DEFECT",
2441
+ "CLI_DEADLINE"
2442
+ ]))
2443
+ })
2444
+ });
2445
+ const CliDiagnosticCompletedTelemetryEventSchema = Schema.Struct({
2446
+ name: Schema.Literal("cli_diagnostic_completed"),
2447
+ props: Schema.Struct({
2448
+ ...TelemetryEnvelopeProps,
2449
+ outcome: Schema.Literals([
2450
+ "succeeded",
2451
+ "refused",
2452
+ "failed",
2453
+ "cancelled"
2454
+ ]),
2455
+ invocation_id: Schema.String.check(Schema.isPattern(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u)),
2456
+ cli_version: Schema.String.check(Schema.isPattern(/^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/u))
2457
+ })
2458
+ });
2459
+ const UiContactActionCompletedTelemetryEventSchema = Schema.Struct({
2460
+ name: Schema.Literal("ui_contact_action_completed"),
2461
+ props: Schema.Union([
2462
+ Schema.Struct({
2463
+ ...ContactActionProps,
2464
+ action: Schema.Literal("add"),
2465
+ outcome: Schema.Literals(["opened", "cancelled"])
2466
+ }),
2467
+ Schema.Struct({
2468
+ ...ContactActionProps,
2469
+ action: Schema.Literal("refusal"),
2470
+ outcome: Schema.Literal("displayed")
2471
+ }),
2472
+ Schema.Struct({
2473
+ ...ContactActionProps,
2474
+ action: Schema.Literal("retry"),
2475
+ outcome: Schema.Literal("requested")
2476
+ })
2477
+ ])
2478
+ });
2479
+ const ActivityAnnotationSavedTelemetryEventSchema = Schema.Struct({
2480
+ name: Schema.Literal("activity_annotation_saved"),
2481
+ props: Schema.Struct({
2482
+ ...TelemetryEnvelopeProps,
2483
+ ...ActivityReferenceProps,
2484
+ scope_kind: ScopeKindSchema,
2485
+ scope_id: Schema.String,
2486
+ occurred_at: Schema.Number
2487
+ })
2488
+ });
2489
+ const UiActivityActionCompletedTelemetryEventSchema = Schema.Struct({
2490
+ name: Schema.Literal("ui_activity_action_completed"),
2491
+ props: Schema.Union([
2492
+ Schema.Struct({
2493
+ ...ActivityActionProps,
2494
+ action: Schema.Literal("read"),
2495
+ outcome: Schema.Literals(["partial_displayed", "recovered"]),
2496
+ surface: Schema.Literals([
2497
+ "transactions",
2498
+ "recent",
2499
+ "summary"
2500
+ ])
2501
+ }),
2502
+ Schema.Struct({
2503
+ ...ActivityActionProps,
2504
+ ...ActivityFilterProps,
2505
+ action: Schema.Literal("filter"),
2506
+ outcome: Schema.Literal("committed")
2507
+ }),
2508
+ Schema.Struct({
2509
+ ...ActivityActionProps,
2510
+ action: Schema.Literal("refusal"),
2511
+ outcome: Schema.Literal("displayed")
2512
+ }),
2513
+ Schema.Struct({
2514
+ ...ActivityActionProps,
2515
+ action: Schema.Literal("retry"),
2516
+ outcome: Schema.Literal("requested")
2517
+ }),
2518
+ Schema.Struct({
2519
+ ...ActivityActionProps,
2520
+ ...ActivityReferenceProps,
2521
+ action: Schema.Literal("detail"),
2522
+ outcome: Schema.Literals(["opened", "failed"])
2523
+ }),
2524
+ Schema.Struct({
2525
+ ...ActivityActionProps,
2526
+ ...ActivityReferenceProps,
2527
+ action: Schema.Literal("receipt"),
2528
+ outcome: Schema.Literals([
2529
+ "document_rendered",
2530
+ "explorer_opened",
2531
+ "popup_blocked",
2532
+ "failed"
2533
+ ])
2534
+ }),
2535
+ Schema.Struct({
2536
+ ...ActivityActionProps,
2537
+ ...ActivityFilterProps,
2538
+ action: Schema.Literal("export"),
2539
+ outcome: Schema.Literals([
2540
+ "completed",
2541
+ "partial",
2542
+ "failed"
2543
+ ]),
2544
+ row_count: Schema.optional(Schema.Number),
2545
+ truncated: Schema.optional(Schema.Boolean)
2546
+ })
2547
+ ])
2548
+ });
2549
+ /**
2550
+ * Reliability closeout (#1960 R02) — the shape every explicit UI observation
2551
+ * below shares. `scope_kind` says whose surface the person was looking at,
2552
+ * `organization_id` is the verified Organization the producer resolved (absent
2553
+ * on a personal action), and `reason_code` is a catalog error code, never copy.
2554
+ */
2555
+ const UiStepProps = {
2556
+ ...TelemetryEnvelopeProps,
2557
+ scope_kind: ScopeKindSchema,
2558
+ organization_id: OptionalOrgId,
2559
+ reason_code: OptionalReasonCode
2560
+ };
2561
+ const AccessRecoveryCompletedProps = Schema.Union([Schema.Struct({
2562
+ ...TelemetryEnvelopeProps,
2563
+ recovery: Schema.Literal("session_restoration"),
2564
+ outcome: Schema.Literals([
2565
+ "restored",
2566
+ "absent",
2567
+ "failed"
2568
+ ]),
2569
+ reason_code: OptionalReasonCode,
2570
+ organization_id: OptionalOrgId
2571
+ }), Schema.Struct({
2572
+ ...TelemetryEnvelopeProps,
2573
+ recovery: Schema.Literal("signer_readiness"),
2574
+ outcome: Schema.Literals(["ready", "unavailable"]),
2575
+ reason_code: OptionalReasonCode,
2576
+ organization_id: OptionalOrgId
2577
+ })]);
2578
+ const AccessRecoveryCompletedTelemetryEventSchema = Schema.Struct({
2579
+ name: Schema.Literal("access_recovery_completed"),
2580
+ props: AccessRecoveryCompletedProps
2581
+ });
2582
+ /**
2583
+ * R05 (#1963) wired three of these steps at the app's dashboard Access
2584
+ * boundary: `dashboard_granted` on the commit of the granted content,
2585
+ * `gate_error_displayed` on the mounted error surface, and `retry_selected` on
2586
+ * the actual selection. `redirect_completed` stays RESERVED and unproduced —
2587
+ * asking for a navigation is not arriving, and the destination page's own
2588
+ * normalized pageview already carries the arrival on the same journey, so a
2589
+ * second event would add no fact. `capability_refusal_displayed` and
2590
+ * `signer_refusal_displayed` belong to the screens that draw those refusals
2591
+ * (Recipients, Invoice, Payroll, Quick Pay); Access publishes the contract and
2592
+ * the `CanReason` those owners report, and produces neither itself.
2593
+ */
2594
+ const UiAccessStepCompletedTelemetryEventSchema = Schema.Struct({
2595
+ name: Schema.Literal("ui_access_step_completed"),
2596
+ props: Schema.Struct({
2597
+ ...UiStepProps,
2598
+ step: Schema.Literals([
2599
+ "dashboard_granted",
2600
+ "redirect_completed",
2601
+ "gate_error_displayed",
2602
+ "retry_selected",
2603
+ "capability_refusal_displayed",
2604
+ "signer_refusal_displayed"
2605
+ ]),
2606
+ capability: Schema.optional(Schema.Literals(["spend", "managePeople"])),
2607
+ probe: Schema.optional(Schema.Literals([
2608
+ "session",
2609
+ "membership",
2610
+ "lifecycle"
2611
+ ])),
2612
+ reason: Schema.optional(Schema.Literals([
2613
+ "loading",
2614
+ "no-permission",
2615
+ "org-unavailable"
2616
+ ]))
2617
+ })
2618
+ });
2619
+ /**
2620
+ * R06 (#1964) wired three of the four progress words to the durable writer that
2621
+ * commits each one. `account_ready` comes from `org/memberLifecycle.ts`, for
2622
+ * every membership row a claimed personal Account actually advanced.
2623
+ * `permission_applied` and `membership_activated` come from
2624
+ * `permission/mirror.ts`: the first only when the mirror wrote a NEW Permission
2625
+ * state, the second only when that call flipped a `pending_grant` row to
2626
+ * `active`. A replay of an applied command writes neither, so it reports
2627
+ * neither. `revoked` stays RESERVED and unproduced — no writer revokes a
2628
+ * membership yet, and #1459 owns that ceremony.
2629
+ */
2630
+ const OrgInviteProgressedTelemetryEventSchema = Schema.Struct({
2631
+ name: Schema.Literal("org_invite_progressed"),
2632
+ props: Schema.Struct({
2633
+ ...TelemetryEnvelopeProps,
2634
+ organization_id: OrgIdTelemetrySchema,
2635
+ progress: Schema.Literals([
2636
+ "configuration_authorized",
2637
+ "account_ready",
2638
+ "permission_applied",
2639
+ "membership_activated",
2640
+ "revoked"
2641
+ ]),
2642
+ /** The invited Party. The initiating actor stays on the envelope's identity. */
2643
+ member_party_id: Schema.String,
2644
+ invitation_id: Schema.optional(Schema.String),
2645
+ generation: Schema.optional(Schema.String),
2646
+ command_id: Schema.optional(Schema.String),
2647
+ occurred_at: Schema.Number
2648
+ })
2649
+ });
2650
+ const InvoiceIssuedTelemetryEventSchema = Schema.Struct({
2651
+ name: Schema.Literal("invoice_issued"),
2652
+ props: Schema.Struct({
2653
+ ...TelemetryEnvelopeProps,
2654
+ request_id: Schema.String,
2655
+ issuer_scope_kind: ScopeKindSchema,
2656
+ issuer_scope_id: Schema.String,
2657
+ payer_party_id: OptionalString,
2658
+ occurred_at: Schema.Number
2659
+ })
2660
+ });
2661
+ const InvoiceRequestTransitionedTelemetryEventSchema = Schema.Struct({
2662
+ name: Schema.Literal("invoice_request_transitioned"),
2663
+ props: Schema.Struct({
2664
+ ...TelemetryEnvelopeProps,
2665
+ request_id: Schema.String,
2666
+ transition: Schema.Literals([
2667
+ "approval_prepared",
2668
+ "declined",
2669
+ "cancelled"
2670
+ ]),
2671
+ actor_scope_kind: ScopeKindSchema,
2672
+ actor_scope_id: Schema.String,
2673
+ occurred_at: Schema.Number
2674
+ })
2675
+ });
2676
+ const UiInvoiceStepCompletedTelemetryEventSchema = Schema.Struct({
2677
+ name: Schema.Literal("ui_invoice_step_completed"),
2678
+ props: Schema.Struct({
2679
+ ...UiStepProps,
2680
+ step: Schema.Literals([
2681
+ "opened",
2682
+ "previewed",
2683
+ "dismissed",
2684
+ "submitted",
2685
+ "result_displayed",
2686
+ "refusal_displayed",
2687
+ "retry_selected"
2688
+ ]),
2689
+ request_id: OptionalString
2690
+ })
2691
+ });
2692
+ const UiTreasuryStepCompletedTelemetryEventSchema = Schema.Struct({
2693
+ name: Schema.Literal("ui_treasury_step_completed"),
2694
+ props: Schema.Struct({
2695
+ ...UiStepProps,
2696
+ step: Schema.Literals([
2697
+ "balance_displayed",
2698
+ "read_refusal_displayed",
2699
+ "retry_selected",
2700
+ "recovery_completed"
2701
+ ]),
2702
+ account_kind: Schema.optional(AccountKindSchema)
2703
+ })
2704
+ });
2705
+ const UiReceiveStepCompletedTelemetryEventSchema = Schema.Struct({
2706
+ name: Schema.Literal("ui_receive_step_completed"),
2707
+ props: Schema.Struct({
2708
+ ...UiStepProps,
2709
+ step: Schema.Literals([
2710
+ "instructions_displayed",
2711
+ "address_copied",
2712
+ "copy_failed",
2713
+ "refusal_displayed",
2714
+ "retry_selected"
2715
+ ]),
2716
+ account_kind: Schema.optional(AccountKindSchema)
2717
+ })
2718
+ });
2719
+ const PayrollGroupChangedTelemetryEventSchema = Schema.Struct({
2720
+ name: Schema.Literal("payroll_group_changed"),
2721
+ props: Schema.Struct({
2722
+ ...TelemetryEnvelopeProps,
2723
+ organization_id: OrgIdTelemetrySchema,
2724
+ change: Schema.Literals([
2725
+ "created",
2726
+ "updated",
2727
+ "deleted"
2728
+ ]),
2729
+ group_id: Schema.String,
2730
+ member_count: Schema.Number,
2731
+ occurred_at: Schema.Number
2732
+ })
2733
+ });
2734
+ const PayrollRunTransitionedTelemetryEventSchema = Schema.Struct({
2735
+ name: Schema.Literal("payroll_run_transitioned"),
2736
+ props: Schema.Struct({
2737
+ ...TelemetryEnvelopeProps,
2738
+ organization_id: OrgIdTelemetrySchema,
2739
+ transition: Schema.Literals([
2740
+ "prepared",
2741
+ "authorized",
2742
+ "settled"
2743
+ ]),
2744
+ run_id: Schema.String,
2745
+ /**
2746
+ * The `paymentCommands` row at `payrollRuns.batchRef` — the durable owner of
2747
+ * this run's Payment membership. `payment_count` counts THAT command's
2748
+ * `paymentIds`, so an unrelated Payment quoting the run id changes neither.
2749
+ */
2750
+ command_id: OptionalString,
2751
+ payment_count: Schema.optional(Schema.Number),
2752
+ occurred_at: Schema.Number
2753
+ })
2754
+ });
2755
+ const UiPayrollActionCompletedTelemetryEventSchema = Schema.Struct({
2756
+ name: Schema.Literal("ui_payroll_action_completed"),
2757
+ props: Schema.Struct({
2758
+ ...UiStepProps,
2759
+ action: Schema.Literals([
2760
+ "opened",
2761
+ "refusal_displayed",
2762
+ "recovery_completed",
2763
+ "cancelled",
2764
+ "submitted_displayed"
2765
+ ]),
2766
+ run_id: OptionalString
2767
+ })
2768
+ });
2769
+ const TELEMETRY_EVENT_SCHEMAS = {
2770
+ contact_relationship_changed: ContactRelationshipChangedTelemetryEventSchema,
2771
+ access_recovery_completed: AccessRecoveryCompletedTelemetryEventSchema,
2772
+ ui_access_step_completed: UiAccessStepCompletedTelemetryEventSchema,
2773
+ org_invite_progressed: OrgInviteProgressedTelemetryEventSchema,
2774
+ invoice_issued: InvoiceIssuedTelemetryEventSchema,
2775
+ invoice_request_transitioned: InvoiceRequestTransitionedTelemetryEventSchema,
2776
+ ui_invoice_step_completed: UiInvoiceStepCompletedTelemetryEventSchema,
2777
+ ui_treasury_step_completed: UiTreasuryStepCompletedTelemetryEventSchema,
2778
+ ui_receive_step_completed: UiReceiveStepCompletedTelemetryEventSchema,
2779
+ payroll_group_changed: PayrollGroupChangedTelemetryEventSchema,
2780
+ payroll_run_transitioned: PayrollRunTransitionedTelemetryEventSchema,
2781
+ ui_payroll_action_completed: UiPayrollActionCompletedTelemetryEventSchema,
2782
+ ui_contact_action_completed: UiContactActionCompletedTelemetryEventSchema,
2783
+ cli_diagnostic_completed: CliDiagnosticCompletedTelemetryEventSchema,
2784
+ cli_first_used: CliFirstUsedTelemetryEventSchema,
2785
+ cli_command_started: CliCommandStartedTelemetryEventSchema,
2786
+ cli_command_completed: CliCommandCompletedTelemetryEventSchema,
2787
+ activity_annotation_saved: ActivityAnnotationSavedTelemetryEventSchema,
2788
+ ui_activity_action_completed: UiActivityActionCompletedTelemetryEventSchema,
2789
+ auth_otp_requested: AuthOtpRequestedTelemetryEventSchema,
2790
+ auth_otp_delivered: AuthOtpDeliveredTelemetryEventSchema,
2791
+ auth_otp_expired: AuthOtpExpiredTelemetryEventSchema,
2792
+ auth_verified: AuthVerifiedTelemetryEventSchema,
2793
+ auth_failed: AuthFailedTelemetryEventSchema,
2794
+ identity_refused: IdentityRefusedTelemetryEventSchema,
2795
+ auth_signed_out: AuthSignedOutTelemetryEventSchema,
2796
+ native_authorization_started: NativeAuthorizationStartedTelemetryEventSchema,
2797
+ native_authorization_reviewed: NativeAuthorizationReviewedTelemetryEventSchema,
2798
+ native_authorization_accepted: NativeAuthorizationAcceptedTelemetryEventSchema,
2799
+ native_authorization_denied: NativeAuthorizationDeniedTelemetryEventSchema,
2800
+ native_authorization_connected: NativeAuthorizationConnectedTelemetryEventSchema,
2801
+ native_authorization_failed: NativeAuthorizationFailedTelemetryEventSchema,
2802
+ onboarding_intent_selected: OnboardingIntentSelectedTelemetryEventSchema,
2803
+ onboarding_profile_submitted: OnboardingProfileSubmittedTelemetryEventSchema,
2804
+ onboarding_organization_submitted: OnboardingOrganizationSubmittedTelemetryEventSchema,
2805
+ onboarding_dashboard_reached: OnboardingDashboardReachedTelemetryEventSchema,
2806
+ provisioning_safe_created: ProvisioningSafeCreatedTelemetryEventSchema,
2807
+ provisioning_safe_confirmed: ProvisioningSafeConfirmedTelemetryEventSchema,
2808
+ bootstrap_resolved: BootstrapResolvedTelemetryEventSchema,
2809
+ bootstrap_failed: BootstrapFailedTelemetryEventSchema,
2810
+ member_activation_started: MemberActivationStartedTelemetryEventSchema,
2811
+ member_activation_ready: MemberActivationReadyTelemetryEventSchema,
2812
+ member_activation_failed: MemberActivationFailedTelemetryEventSchema,
2813
+ organization_creation_started: OrganizationCreationStartedTelemetryEventSchema,
2814
+ organization_creation_ready: OrganizationCreationReadyTelemetryEventSchema,
2815
+ organization_creation_failed: OrganizationCreationFailedTelemetryEventSchema,
2816
+ account_balance_read: AccountBalanceReadTelemetryEventSchema,
2817
+ account_balance_failed: AccountBalanceFailedTelemetryEventSchema,
2818
+ faucet_requested: FaucetRequestedTelemetryEventSchema,
2819
+ faucet_confirmed: FaucetConfirmedTelemetryEventSchema,
2820
+ faucet_failed: FaucetFailedTelemetryEventSchema,
2821
+ chain_upstream_fallback: ChainUpstreamFallbackTelemetryEventSchema,
2822
+ bundler_error: BundlerErrorTelemetryEventSchema,
2823
+ receipt_pending: ReceiptPendingTelemetryEventSchema,
2824
+ operation_retried: OperationRetriedTelemetryEventSchema,
2825
+ org_create_started: OrgCreateStartedTelemetryEventSchema,
2826
+ org_safe_created: OrgSafeCreatedTelemetryEventSchema,
2827
+ org_safe_confirmed: OrgSafeConfirmedTelemetryEventSchema,
2828
+ org_roles_seeded: OrgRolesSeededTelemetryEventSchema,
2829
+ org_created: OrgCreatedTelemetryEventSchema,
2830
+ org_create_failed: OrgCreateFailedTelemetryEventSchema,
2831
+ org_invite_sent: OrgInviteSentTelemetryEventSchema,
2832
+ org_invite_accepted: OrgInviteAcceptedTelemetryEventSchema,
2833
+ org_invite_expired: OrgInviteExpiredTelemetryEventSchema,
2834
+ payment_initiated: PaymentInitiatedTelemetryEventSchema,
2835
+ payment_settled: PaymentSettledTelemetryEventSchema,
2836
+ payment_failed: PaymentFailedTelemetryEventSchema,
2837
+ payment_verification_retry: PaymentVerificationRetryTelemetryEventSchema,
2838
+ payment_lifecycle_transition: PaymentLifecycleTransitionTelemetryEventSchema,
2839
+ quick_pay_external_address_acknowledged: QuickPayExternalAddressAcknowledgedTelemetryEventSchema,
2840
+ deposit_initiated: DepositInitiatedTelemetryEventSchema,
2841
+ deposit_settled: DepositSettledTelemetryEventSchema,
2842
+ permission_mirror_verification: PermissionMirrorVerificationTelemetryEventSchema,
2843
+ movement_scan_window: MovementScanWindowTelemetryEventSchema,
2844
+ movement_scan_checkpoint: MovementScanCheckpointTelemetryEventSchema,
2845
+ movement_scan_incident: MovementScanIncidentTelemetryEventSchema,
2846
+ indexer_drift_corrected: IndexerDriftCorrectedTelemetryEventSchema
2847
+ };
2848
+ const FINANCIAL_OPS_TARGET_TELEMETRY_PRODUCERS = [];
2849
+ /**
2850
+ * Contract-first events whose producer is owned by a later domain node.
2851
+ *
2852
+ * A domain node removes its entry when it adds the producer. The telemetry
2853
+ * gate rejects an entry that has a producer.
2854
+ */
2855
+ const CONTRACT_FIRST_TELEMETRY_EVENTS = [];
2856
+ /**
2857
+ * Catalog events whose product mapper remains gated on the #1150 frontend
2858
+ * adoption. L1 S1 removes their retired SDK-flow producers without inventing
2859
+ * replacements inside the identity actor. The telemetry-spine gate enforces
2860
+ * planned-XOR-wired: a name must leave this list in the same change that adds
2861
+ * its real product-boundary producer.
2862
+ */
2863
+ const PRODUCT_MAPPER_GATED_TELEMETRY_EVENTS = ["auth_otp_expired"];
2864
+ /** Catalogued browser observations whose producers remain owned by app adoption. */
2865
+ const BROWSER_GATED_TELEMETRY_EVENTS = [
2866
+ "onboarding_intent_selected",
2867
+ "onboarding_profile_submitted",
2868
+ "onboarding_organization_submitted",
2869
+ "onboarding_dashboard_reached",
2870
+ "ui_activity_action_completed",
2871
+ "ui_contact_action_completed",
2872
+ "ui_access_step_completed",
2873
+ "ui_invoice_step_completed",
2874
+ "ui_treasury_step_completed",
2875
+ "ui_receive_step_completed",
2876
+ "ui_payroll_action_completed"
2877
+ ];
2878
+ let trackHandler = () => {};
2879
+ function setTrackHandler(handler) {
2880
+ const previous = trackHandler;
2881
+ trackHandler = handler;
2882
+ return previous;
2883
+ }
2884
+ function getTrackHandler() {
2885
+ return trackHandler;
2886
+ }
2887
+ function track(name, props) {
2888
+ trackHandler(name, props);
2889
+ }
2890
+ function redactTelemetryEvent(event, options = {}) {
2891
+ const props = redactTelemetryProps(event.name, event.props, options);
2892
+ return props === void 0 ? { name: event.name } : {
2893
+ name: event.name,
2894
+ props
2895
+ };
2896
+ }
2897
+ function redactTelemetryProps(name, props, options = {}) {
2898
+ if (props === void 0) return void 0;
2899
+ const clone = cloneProps(props);
2900
+ if (options.rawMode === true) return clone;
2901
+ for (const key of PII_PROP_KEYS_BY_EVENT[name] ?? []) redactProperty(clone, key);
2902
+ return clone;
2903
+ }
2904
+ /**
2905
+ * Remove query strings and fragments from every PostHog URL/referrer/path
2906
+ * property before transport. Browser applications may carry emails, draft ids,
2907
+ * or other capabilities in the URL; those values must never leave the origin.
2908
+ *
2909
+ * The callback replaces the event's data with a sanitized copy. Nested values
2910
+ * can refer to live clients or configuration; observation must never mutate them.
2911
+ */
2912
+ function sanitizePostHogBrowserEvent(event, urlPolicy = "path-only") {
2913
+ if (event === null) return event;
2914
+ const transportToken = event.properties.token;
2915
+ const seen = /* @__PURE__ */ new WeakMap();
2916
+ event.properties = sanitizePostHogBrowserValue(event.properties, seen, urlPolicy);
2917
+ if (transportToken !== void 0) event.properties.token = transportToken;
2918
+ if (event.$set !== void 0) event.$set = sanitizePostHogBrowserValue(event.$set, seen, urlPolicy);
2919
+ if (event.$set_once !== void 0) event.$set_once = sanitizePostHogBrowserValue(event.$set_once, seen, urlPolicy);
2920
+ return event;
2921
+ }
2922
+ /**
2923
+ * Drop local events before transport. Sanitize and stamp every other browser
2924
+ * event with `capxul_env` and `producer: "browser"`.
2925
+ */
2926
+ function createCapxulBeforeSend(capxulEnv, urlPolicy = "path-only") {
2927
+ return (event) => {
2928
+ if (capxulEnv === "local") return null;
2929
+ const sanitized = sanitizePostHogBrowserEvent(event, urlPolicy);
2930
+ if (sanitized === null) return sanitized;
2931
+ sanitized.properties.capxul_env = capxulEnv;
2932
+ sanitized.properties.producer ??= "browser";
2933
+ return sanitized;
2934
+ };
2935
+ }
2936
+ function utilityAppAnalytics(input) {
2937
+ return {
2938
+ api_host: input.host,
2939
+ defaults: "2026-01-30",
2940
+ autocapture: false,
2941
+ capture_pageview: false,
2942
+ capture_pageleave: true,
2943
+ disable_session_recording: true,
2944
+ disable_persistence: true,
2945
+ capture_heatmaps: false,
2946
+ capture_exceptions: false,
2947
+ capture_performance: false,
2948
+ disable_surveys: true,
2949
+ disable_web_experiments: true,
2950
+ disable_product_tours: true,
2951
+ disable_conversations: true,
2952
+ disable_external_dependency_loading: true,
2953
+ person_profiles: "identified_only",
2954
+ advanced_disable_flags: true,
2955
+ save_campaign_params: false,
2956
+ save_referrer: false,
2957
+ before_send: createCapxulBeforeSend(input.capxulEnv)
2958
+ };
2959
+ }
2960
+ /** In unstructured bodies, preserve text around explicitly named credentials. */
2961
+ const NETWORK_FIELD = /((?:"?)([A-Za-z_][A-Za-z0-9_.-]*)(?:"?)\s*[:=]\s*)("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^\s,;&}]+)/gu;
2962
+ function maskNetworkText(text, context) {
2963
+ return redactSecrets(text).replace(NETWORK_FIELD, (whole, prefix, name, value) => {
2964
+ if (!isCredentialField(name, context)) return whole;
2965
+ const quote = value.startsWith("\"") ? "\"" : value.startsWith("'") ? "'" : "";
2966
+ return `${prefix}${quote}[REDACTED]${quote}`;
2967
+ });
2968
+ }
2969
+ function maskNetworkHeaders(headers) {
2970
+ if (headers === void 0) return void 0;
2971
+ const masked = {};
2972
+ for (const [name, value] of Object.entries(headers)) masked[name] = isCredentialField(name, "header") ? "[REDACTED]" : /^(?:location|content-location|referer)$/iu.test(name) ? redactUrlSecrets(value) : maskNetworkText(value);
2973
+ return masked;
2974
+ }
2975
+ function maskJsonValue(value, depth = 0, context) {
2976
+ if (typeof value === "function" || typeof value === "symbol") return "[UNREADABLE]";
2977
+ if (typeof value === "string") return maskNetworkText(value, context);
2978
+ if (typeof value !== "object" || value === null) return value;
2979
+ if (depth >= 16) return "[REDACTED]";
2980
+ if (Array.isArray(value)) return value.map((item) => maskJsonValue(item, depth + 1, context));
2981
+ const masked = Object.create(null);
2982
+ for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(value))) {
2983
+ if (!descriptor.enumerable) continue;
2984
+ masked[key] = isCredentialField(key, context) ? "[REDACTED]" : !("value" in descriptor) ? "[UNREADABLE]" : typeof descriptor.value === "string" && isPostHogUrlProperty(key) ? redactUrlSecrets(descriptor.value) : maskJsonValue(descriptor.value, depth + 1, context);
2985
+ }
2986
+ return masked;
2987
+ }
2988
+ function maskNetworkBody(body, context) {
2989
+ try {
2990
+ if (typeof body !== "string") return maskJsonValue(body, 0, context);
2991
+ let parsed;
2992
+ try {
2993
+ parsed = JSON.parse(body);
2994
+ } catch {
2995
+ if (/^[^=&\s]+=[\s\S]*$/u.test(body)) return new URLSearchParams(Array.from(new URLSearchParams(body), ([name, value]) => [name, isCredentialField(name, context) ? "[REDACTED]" : maskNetworkText(value)])).toString();
2996
+ return maskNetworkText(body, context);
2997
+ }
2998
+ return JSON.stringify(maskJsonValue(parsed, 0, context));
2999
+ } catch {
3000
+ return "[UNREADABLE]";
3001
+ }
3002
+ }
3003
+ /** Keep request evidence while masking credential values at the browser boundary. */
3004
+ function maskCapturedNetworkRequest(request) {
3005
+ const requestUrl = request.name ?? request.url ?? "";
3006
+ let context;
3007
+ try {
3008
+ const path = new URL(requestUrl, "https://capxul.invalid").pathname;
3009
+ if (/\/(?:auth|oauth|sign-in|signin|login|verify-otp|verify-email)(?:\/|$)/iu.test(path)) context = "authentication";
3010
+ } catch {}
3011
+ return {
3012
+ ...request,
3013
+ ...request.name === void 0 ? {} : { name: redactUrlSecrets(request.name) },
3014
+ ...request.url === void 0 ? {} : { url: redactUrlSecrets(request.url) },
3015
+ requestHeaders: maskNetworkHeaders(request.requestHeaders),
3016
+ responseHeaders: maskNetworkHeaders(request.responseHeaders),
3017
+ requestBody: maskNetworkBody(request.requestBody, context),
3018
+ responseBody: maskNetworkBody(request.responseBody)
3019
+ };
3020
+ }
3021
+ function productAppAnalytics(input) {
3022
+ return {
3023
+ api_host: input.host,
3024
+ defaults: "2026-01-30",
3025
+ autocapture: false,
3026
+ capture_pageview: false,
3027
+ capture_pageleave: true,
3028
+ disable_session_recording: false,
3029
+ disable_persistence: false,
3030
+ capture_heatmaps: false,
3031
+ capture_exceptions: true,
3032
+ capture_performance: {
3033
+ network_timing: true,
3034
+ web_vitals: false
3035
+ },
3036
+ disable_surveys: true,
3037
+ disable_web_experiments: true,
3038
+ disable_product_tours: true,
3039
+ disable_conversations: true,
3040
+ disable_external_dependency_loading: false,
3041
+ person_profiles: "identified_only",
3042
+ advanced_disable_flags: false,
3043
+ save_campaign_params: false,
3044
+ save_referrer: false,
3045
+ session_recording: {
3046
+ maskAllInputs: true,
3047
+ maskInputFn: (text, element) => {
3048
+ const autocomplete = element?.getAttribute("autocomplete")?.toLowerCase().split(/\s+/u) ?? [];
3049
+ return element?.getAttribute("type")?.toLowerCase() === "password" || autocomplete.some((value) => [
3050
+ "one-time-code",
3051
+ "current-password",
3052
+ "new-password"
3053
+ ].includes(value)) || isCredentialField(element?.getAttribute("name") ?? "") || isCredentialField(element?.getAttribute("id") ?? "") ? "*".repeat(text.length) : maskNetworkText(text);
3054
+ },
3055
+ captureCanvas: { recordCanvas: false },
3056
+ recordHeaders: true,
3057
+ recordBody: true,
3058
+ maskCapturedNetworkRequestFn: maskCapturedNetworkRequest
3059
+ },
3060
+ before_send: createCapxulBeforeSend(input.capxulEnv, "diagnostic")
3061
+ };
3062
+ }
3063
+ /**
3064
+ * Apply a named privacy profile before an application-owned PostHog client
3065
+ * initializes. Hosts still own the vendor client and lifecycle; this helper
3066
+ * centralizes the security-relevant options and the missing-key opt-out (no
3067
+ * key ⇒ no client ⇒ no network call).
3068
+ */
3069
+ function initializeCapxulBrowserAnalytics(profile, input, initialize) {
3070
+ const key = input.key?.trim();
3071
+ if (key === void 0 || key.length === 0) return void 0;
3072
+ try {
3073
+ const options = profile(input);
3074
+ const client = initialize(key, options);
3075
+ warnWhenReplayHasNoRecorder(options, client);
3076
+ return client;
3077
+ } catch {
3078
+ return;
3079
+ }
3080
+ }
3081
+ let replayRecorderWarned = false;
3082
+ /**
3083
+ * #1709: `posthog-js/dist/module.slim` never registers the session recording
3084
+ * manager, so a profile that enables replay records nothing with it. The
3085
+ * client exposes the manager as `sessionRecording` once `init` ran on the
3086
+ * standard build. Warn once per page so the missing build is visible.
3087
+ */
3088
+ function warnWhenReplayHasNoRecorder(options, client) {
3089
+ if (replayRecorderWarned) return;
3090
+ const replayEnabled = typeof options === "object" && options !== null && options.disable_session_recording === false;
3091
+ const recorderMissing = typeof client === "object" && client !== null && client.sessionRecording === void 0;
3092
+ if (!replayEnabled || !recorderMissing) return;
3093
+ replayRecorderWarned = true;
3094
+ console.warn("@capxul/observability: session replay is enabled but the PostHog client has no session recording manager. Import the standard `posthog-js` build; `posthog-js/dist/module.slim` records nothing.");
3095
+ }
3096
+ /** The utility profile, pre-bound — the shape ADR-0016's consumers already use. */
3097
+ function initializePostHogBrowserAnalytics(input, initialize) {
3098
+ return initializeCapxulBrowserAnalytics(utilityAppAnalytics, input, initialize);
3099
+ }
3100
+ /**
3101
+ * Build an explicit SPA pageview sink for toolbar-free PostHog clients. The
3102
+ * pathname-only input avoids query capabilities, repeated pathnames are
3103
+ * deduplicated, and vendor failures remain best-effort.
3104
+ */
3105
+ function createPostHogBrowserPageviewTracker(client) {
3106
+ let previousPathname;
3107
+ return (pathname) => {
3108
+ if (client === null || client === void 0) return;
3109
+ const safePathname = stripUrlQueryAndFragment(pathname);
3110
+ if (safePathname === previousPathname) return;
3111
+ try {
3112
+ Promise.resolve(client.capture("$pageview", { $pathname: safePathname })).catch(() => {});
3113
+ previousPathname = safePathname;
3114
+ } catch {}
3115
+ };
3116
+ }
3117
+ function sanitizePostHogBrowserValue(value, seen, urlPolicy) {
3118
+ if (typeof value !== "object" || value === null || value instanceof Date) return value;
3119
+ if (seen.has(value)) return seen.get(value);
3120
+ if (Array.isArray(value)) {
3121
+ const copy = [];
3122
+ seen.set(value, copy);
3123
+ for (let index = 0; index < value.length; index++) {
3124
+ const item = value[index];
3125
+ copy[index] = typeof item === "string" ? maskNetworkText(item) : sanitizePostHogBrowserValue(item, seen, urlPolicy);
3126
+ }
3127
+ return copy;
3128
+ }
3129
+ const properties = Object.create(null);
3130
+ seen.set(value, properties);
3131
+ for (const [key, nestedValue] of Object.entries(value)) {
3132
+ if (isPostHogQueryDerivedProperty(key)) continue;
3133
+ if (isCredentialField(key)) {
3134
+ properties[key] = "[REDACTED]";
3135
+ continue;
3136
+ }
3137
+ if (typeof nestedValue === "string") {
3138
+ properties[key] = isPostHogUrlProperty(key) ? urlPolicy === "path-only" ? stripUrlQueryAndFragment(nestedValue) : redactUrlSecrets(nestedValue) : maskNetworkText(nestedValue);
3139
+ continue;
3140
+ }
3141
+ properties[key] = sanitizePostHogBrowserValue(nestedValue, seen, urlPolicy);
3142
+ }
3143
+ return properties;
3144
+ }
3145
+ const POSTHOG_QUERY_DERIVED_PROPERTY_NAMES = [
3146
+ "utm_source",
3147
+ "utm_medium",
3148
+ "utm_campaign",
3149
+ "utm_content",
3150
+ "utm_term",
3151
+ "gad_source",
3152
+ "mc_cid",
3153
+ "gclid",
3154
+ "gclsrc",
3155
+ "dclid",
3156
+ "gbraid",
3157
+ "wbraid",
3158
+ "fbclid",
3159
+ "msclkid",
3160
+ "twclid",
3161
+ "li_fat_id",
3162
+ "igshid",
3163
+ "ttclid",
3164
+ "rdt_cid",
3165
+ "epik",
3166
+ "qclid",
3167
+ "sccid",
3168
+ "irclid",
3169
+ "_kx",
3170
+ "ph_keyword"
3171
+ ];
3172
+ function isPostHogQueryDerivedProperty(key) {
3173
+ const normalized = key.toLowerCase();
3174
+ return POSTHOG_QUERY_DERIVED_PROPERTY_NAMES.some((propertyName) => normalized === propertyName || normalized.endsWith(`_${propertyName}`) || normalized.endsWith(`$${propertyName}`));
3175
+ }
3176
+ function isPostHogUrlProperty(key) {
3177
+ const normalized = key.toLowerCase();
3178
+ return normalized.includes("url") || normalized.includes("referrer") || normalized.includes("path") || normalized.includes("filename");
3179
+ }
3180
+ function stripUrlQueryAndFragment(value) {
3181
+ const queryIndex = value.indexOf("?");
3182
+ const fragmentIndex = value.indexOf("#");
3183
+ if (queryIndex === -1 && fragmentIndex === -1) return value;
3184
+ if (queryIndex === -1) return value.slice(0, fragmentIndex);
3185
+ if (fragmentIndex === -1) return value.slice(0, queryIndex);
3186
+ return value.slice(0, Math.min(queryIndex, fragmentIndex));
3187
+ }
3188
+ var RecordingTelemetryAdapter = class {
3189
+ #events = [];
3190
+ #rawMode;
3191
+ constructor(options = {}) {
3192
+ this.#rawMode = options.rawMode === true;
3193
+ }
3194
+ get events() {
3195
+ return this.#events.map((event) => cloneEvent(event));
3196
+ }
3197
+ emit(event) {
3198
+ return Effect.sync(() => {
3199
+ this.#events.push(redactTelemetryEvent(event, { rawMode: this.#rawMode }));
3200
+ });
3201
+ }
3202
+ identify(_input) {
3203
+ return Effect.void;
3204
+ }
3205
+ group(_input) {
3206
+ return Effect.void;
3207
+ }
3208
+ reset() {
3209
+ return Effect.void;
3210
+ }
3211
+ reportHandledError(_error, _context) {
3212
+ return Effect.void;
3213
+ }
3214
+ clear() {
3215
+ this.#events.length = 0;
3216
+ }
3217
+ };
3218
+ var PostHogTelemetryAdapter = class {
3219
+ #capture;
3220
+ constructor(deps) {
3221
+ this.#capture = deps.capture;
3222
+ }
3223
+ emit(event) {
3224
+ return Effect.sync(() => {
3225
+ try {
3226
+ Promise.resolve(this.#capture(event.name, redactTelemetryProps(event.name, event.props))).catch(() => {});
3227
+ } catch {}
3228
+ });
3229
+ }
3230
+ identify(_input) {
3231
+ return Effect.void;
3232
+ }
3233
+ group(_input) {
3234
+ return Effect.void;
3235
+ }
3236
+ reset() {
3237
+ return Effect.void;
3238
+ }
3239
+ reportHandledError(_error, _context) {
3240
+ return Effect.void;
3241
+ }
3242
+ };
3243
+ var InMemoryTelemetryBusAdapter = class {
3244
+ #subscribers = /* @__PURE__ */ new Set();
3245
+ #rawMode;
3246
+ constructor(options = {}) {
3247
+ this.#rawMode = options.rawMode === true;
3248
+ }
3249
+ subscribe(handler) {
3250
+ this.#subscribers.add(handler);
3251
+ return () => {
3252
+ this.#subscribers.delete(handler);
3253
+ };
3254
+ }
3255
+ emit(event) {
3256
+ return Effect.sync(() => {
3257
+ const delivered = redactTelemetryEvent(event, { rawMode: this.#rawMode });
3258
+ for (const handler of this.#subscribers) try {
3259
+ handler(cloneEvent(delivered));
3260
+ } catch {}
3261
+ });
3262
+ }
3263
+ identify(_input) {
3264
+ return Effect.void;
3265
+ }
3266
+ group(_input) {
3267
+ return Effect.void;
3268
+ }
3269
+ reset() {
3270
+ return Effect.void;
3271
+ }
3272
+ reportHandledError(_error, _context) {
3273
+ return Effect.void;
3274
+ }
3275
+ };
3276
+ const PII_PROP_KEYS_BY_EVENT = {
3277
+ auth_otp_requested: ["email"],
3278
+ auth_otp_delivered: ["email"],
3279
+ auth_otp_expired: ["email"],
3280
+ auth_failed: ["email"]
3281
+ };
3282
+ function redactProperty(props, key) {
3283
+ const value = props[key];
3284
+ if (typeof value === "string") props[key] = sha256Hex(value).slice(0, 12);
3285
+ }
3286
+ function cloneEvent(event) {
3287
+ if (event.props === void 0) return { name: event.name };
3288
+ return {
3289
+ name: event.name,
3290
+ props: cloneProps(event.props)
3291
+ };
3292
+ }
3293
+ function cloneProps(props) {
3294
+ const cloned = {};
3295
+ for (const [key, value] of Object.entries(props)) cloned[key] = cloneTelemetryValue(value);
3296
+ return cloned;
3297
+ }
3298
+ function cloneTelemetryValue(value) {
3299
+ if (Array.isArray(value)) return value.map(cloneTelemetryValue);
3300
+ if (value === null || typeof value !== "object") return value;
3301
+ if (Object.getPrototypeOf(value) !== Object.prototype) return value;
3302
+ const cloned = {};
3303
+ for (const [key, nested] of Object.entries(value)) cloned[key] = cloneTelemetryValue(nested);
3304
+ return cloned;
3305
+ }
3306
+ const SHA256_INITIAL_HASH = [
3307
+ 1779033703,
3308
+ 3144134277,
3309
+ 1013904242,
3310
+ 2773480762,
3311
+ 1359893119,
3312
+ 2600822924,
3313
+ 528734635,
3314
+ 1541459225
3315
+ ];
3316
+ const SHA256_K = [
3317
+ 1116352408,
3318
+ 1899447441,
3319
+ 3049323471,
3320
+ 3921009573,
3321
+ 961987163,
3322
+ 1508970993,
3323
+ 2453635748,
3324
+ 2870763221,
3325
+ 3624381080,
3326
+ 310598401,
3327
+ 607225278,
3328
+ 1426881987,
3329
+ 1925078388,
3330
+ 2162078206,
3331
+ 2614888103,
3332
+ 3248222580,
3333
+ 3835390401,
3334
+ 4022224774,
3335
+ 264347078,
3336
+ 604807628,
3337
+ 770255983,
3338
+ 1249150122,
3339
+ 1555081692,
3340
+ 1996064986,
3341
+ 2554220882,
3342
+ 2821834349,
3343
+ 2952996808,
3344
+ 3210313671,
3345
+ 3336571891,
3346
+ 3584528711,
3347
+ 113926993,
3348
+ 338241895,
3349
+ 666307205,
3350
+ 773529912,
3351
+ 1294757372,
3352
+ 1396182291,
3353
+ 1695183700,
3354
+ 1986661051,
3355
+ 2177026350,
3356
+ 2456956037,
3357
+ 2730485921,
3358
+ 2820302411,
3359
+ 3259730800,
3360
+ 3345764771,
3361
+ 3516065817,
3362
+ 3600352804,
3363
+ 4094571909,
3364
+ 275423344,
3365
+ 430227734,
3366
+ 506948616,
3367
+ 659060556,
3368
+ 883997877,
3369
+ 958139571,
3370
+ 1322822218,
3371
+ 1537002063,
3372
+ 1747873779,
3373
+ 1955562222,
3374
+ 2024104815,
3375
+ 2227730452,
3376
+ 2361852424,
3377
+ 2428436474,
3378
+ 2756734187,
3379
+ 3204031479,
3380
+ 3329325298
3381
+ ];
3382
+ function sha256Hex(input) {
3383
+ const padded = padSha256Message(new TextEncoder().encode(input));
3384
+ const view = new DataView(padded.buffer, padded.byteOffset, padded.byteLength);
3385
+ const words = /* @__PURE__ */ new Uint32Array(64);
3386
+ let h0 = SHA256_INITIAL_HASH[0];
3387
+ let h1 = SHA256_INITIAL_HASH[1];
3388
+ let h2 = SHA256_INITIAL_HASH[2];
3389
+ let h3 = SHA256_INITIAL_HASH[3];
3390
+ let h4 = SHA256_INITIAL_HASH[4];
3391
+ let h5 = SHA256_INITIAL_HASH[5];
3392
+ let h6 = SHA256_INITIAL_HASH[6];
3393
+ let h7 = SHA256_INITIAL_HASH[7];
3394
+ for (let offset = 0; offset < padded.byteLength; offset += 64) {
3395
+ for (let i = 0; i < 16; i++) words[i] = view.getUint32(offset + i * 4);
3396
+ for (let i = 16; i < 64; i++) {
3397
+ const s0 = rotr(words[i - 15], 7) ^ rotr(words[i - 15], 18) ^ words[i - 15] >>> 3;
3398
+ const s1 = rotr(words[i - 2], 17) ^ rotr(words[i - 2], 19) ^ words[i - 2] >>> 10;
3399
+ words[i] = words[i - 16] + s0 + words[i - 7] + s1 >>> 0;
3400
+ }
3401
+ let a = h0;
3402
+ let b = h1;
3403
+ let c = h2;
3404
+ let d = h3;
3405
+ let e = h4;
3406
+ let f = h5;
3407
+ let g = h6;
3408
+ let h = h7;
3409
+ for (let i = 0; i < 64; i++) {
3410
+ const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
3411
+ const ch = e & f ^ ~e & g;
3412
+ const temp1 = h + s1 + ch + SHA256_K[i] + words[i] >>> 0;
3413
+ const temp2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + (a & b ^ a & c ^ b & c) >>> 0;
3414
+ h = g;
3415
+ g = f;
3416
+ f = e;
3417
+ e = d + temp1 >>> 0;
3418
+ d = c;
3419
+ c = b;
3420
+ b = a;
3421
+ a = temp1 + temp2 >>> 0;
3422
+ }
3423
+ h0 = h0 + a >>> 0;
3424
+ h1 = h1 + b >>> 0;
3425
+ h2 = h2 + c >>> 0;
3426
+ h3 = h3 + d >>> 0;
3427
+ h4 = h4 + e >>> 0;
3428
+ h5 = h5 + f >>> 0;
3429
+ h6 = h6 + g >>> 0;
3430
+ h7 = h7 + h >>> 0;
3431
+ }
3432
+ return [
3433
+ h0,
3434
+ h1,
3435
+ h2,
3436
+ h3,
3437
+ h4,
3438
+ h5,
3439
+ h6,
3440
+ h7
3441
+ ].map((word) => word.toString(16).padStart(8, "0")).join("");
3442
+ }
3443
+ function padSha256Message(bytes) {
3444
+ const bitLength = bytes.byteLength * 8;
3445
+ const zeroPadLength = (64 - (bytes.byteLength + 1 + 8) % 64) % 64;
3446
+ const output = new Uint8Array(bytes.byteLength + 1 + zeroPadLength + 8);
3447
+ output.set(bytes);
3448
+ output[bytes.byteLength] = 128;
3449
+ const view = new DataView(output.buffer);
3450
+ view.setUint32(output.byteLength - 8, Math.floor(bitLength / 4294967296));
3451
+ view.setUint32(output.byteLength - 4, bitLength >>> 0);
3452
+ return output;
3453
+ }
3454
+ function rotr(value, bits) {
3455
+ return value >>> bits | value << 32 - bits;
3456
+ }
3457
+ //#endregion
3458
+ export { OnboardingIntentSelectedTelemetryEventSchema as $, redactTelemetryProps as $t, FINANCIAL_OPS_TARGET_TELEMETRY_PRODUCERS as A, ReceiptPendingTelemetryEventSchema as At, MemberActivationFailedTelemetryEventSchema as B, UiContactActionCompletedTelemetryEventSchema as Bt, CliCommandCompletedTelemetryEventSchema as C, PayrollGroupChangedTelemetryEventSchema as Ct, ContactRelationshipChangedTelemetryEventSchema as D, ProvisioningSafeConfirmedTelemetryEventSchema as Dt, CliFirstUsedTelemetryEventSchema as E, PostHogTelemetryAdapter as Et, IdentityRefusedTelemetryEventSchema as F, TELEMETRY_EVENT_SCHEMAS as Ft, MovementScanWindowTelemetryEventSchema as G, createCapxulBeforeSend as Gt, MemberActivationStartedTelemetryEventSchema as H, UiPayrollActionCompletedTelemetryEventSchema as Ht, InMemoryTelemetryBusAdapter as I, TELEMETRY_JOURNEYS as It, NativeAuthorizationDeniedTelemetryEventSchema as J, initializeCapxulBrowserAnalytics as Jt, NativeAuthorizationAcceptedTelemetryEventSchema as K, createPostHogBrowserPageviewTracker as Kt, IndexerDriftCorrectedTelemetryEventSchema as L, TELEMETRY_PRODUCERS as Lt, FaucetConfirmedTelemetryEventSchema as M, ResponseHeadersSchema as Mt, FaucetFailedTelemetryEventSchema as N, SYNCABLE_CAPXUL_ENVS as Nt, DepositInitiatedTelemetryEventSchema as O, ProvisioningSafeCreatedTelemetryEventSchema as Ot, FaucetRequestedTelemetryEventSchema as P, TELEMETRY_EVENT_NAMES as Pt, OnboardingDashboardReachedTelemetryEventSchema as Q, redactTelemetryEvent as Qt, InvoiceIssuedTelemetryEventSchema as R, UiAccessStepCompletedTelemetryEventSchema as Rt, ChainUpstreamSchema as S, PaymentVerificationRetryTelemetryEventSchema as St, CliDiagnosticCompletedTelemetryEventSchema as T, PermissionMirrorVerificationTelemetryEventSchema as Tt, MovementScanCheckpointTelemetryEventSchema as U, UiReceiveStepCompletedTelemetryEventSchema as Ut, MemberActivationReadyTelemetryEventSchema as V, UiInvoiceStepCompletedTelemetryEventSchema as Vt, MovementScanIncidentTelemetryEventSchema as W, UiTreasuryStepCompletedTelemetryEventSchema as Wt, NativeAuthorizationReviewedTelemetryEventSchema as X, maskCapturedNetworkRequest as Xt, NativeAuthorizationFailedTelemetryEventSchema as Y, initializePostHogBrowserAnalytics as Yt, NativeAuthorizationStartedTelemetryEventSchema as Z, productAppAnalytics as Zt, CLI_COMMAND_NAMES as _, PRODUCT_MAPPER_GATED_TELEMETRY_EVENTS as _t, AuthFailedTelemetryEventSchema as a, CAPXUL_OPERATIONS as an, OrgCreatedTelemetryEventSchema as at, ChainAttemptSchema as b, PaymentLifecycleTransitionTelemetryEventSchema as bt, AuthOtpRequestedTelemetryEventSchema as c, ORGANIZATION_SETUP_REASONS as cn, OrgInviteProgressedTelemetryEventSchema as ct, BROWSER_GATED_TELEMETRY_EVENTS as d, FAILURE_MODES as dn, OrgSafeConfirmedTelemetryEventSchema as dt, sanitizePostHogBrowserEvent as en, OnboardingOrganizationSubmittedTelemetryEventSchema as et, BootstrapFailedTelemetryEventSchema as f, isCredentialField as fn, OrgSafeCreatedTelemetryEventSchema as ft, CLI_CAPABILITIES as g, PII as gt, CAPXUL_ENVS as h, OrganizationCreationStartedTelemetryEventSchema as ht, ActivityAnnotationSavedTelemetryEventSchema as i, utilityAppAnalytics as in, OrgCreateStartedTelemetryEventSchema as it, FailureModeSchema as j, RecordingTelemetryAdapter as jt, DepositSettledTelemetryEventSchema as k, QuickPayExternalAddressAcknowledgedTelemetryEventSchema as kt, AuthSignedOutTelemetryEventSchema as l, ORGANIZATION_SETUP_STATUSES as ln, OrgInviteSentTelemetryEventSchema as lt, BundlerErrorTelemetryEventSchema as m, redactUrlSecrets as mn, OrganizationCreationReadyTelemetryEventSchema as mt, AccountBalanceFailedTelemetryEventSchema as n, stampTelemetryEnvelope as nn, OperationRetriedTelemetryEventSchema as nt, AuthOtpDeliveredTelemetryEventSchema as o, isCapxulOperation as on, OrgInviteAcceptedTelemetryEventSchema as ot, BootstrapResolvedTelemetryEventSchema as p, redactSecrets as pn, OrganizationCreationFailedTelemetryEventSchema as pt, NativeAuthorizationConnectedTelemetryEventSchema as q, getTrackHandler as qt, AccountBalanceReadTelemetryEventSchema as r, track as rn, OrgCreateFailedTelemetryEventSchema as rt, AuthOtpExpiredTelemetryEventSchema as s, normalizeCapxulOperation as sn, OrgInviteExpiredTelemetryEventSchema as st, AccessRecoveryCompletedTelemetryEventSchema as t, setTrackHandler as tn, OnboardingProfileSubmittedTelemetryEventSchema as tt, AuthVerifiedTelemetryEventSchema as u, CAPXUL_ERROR_CODES as un, OrgRolesSeededTelemetryEventSchema as ut, CLI_INVOCATION_KINDS as v, PaymentFailedTelemetryEventSchema as vt, CliCommandStartedTelemetryEventSchema as w, PayrollRunTransitionedTelemetryEventSchema as wt, ChainUpstreamFallbackTelemetryEventSchema as x, PaymentSettledTelemetryEventSchema as xt, CONTRACT_FIRST_TELEMETRY_EVENTS as y, PaymentInitiatedTelemetryEventSchema as yt, InvoiceRequestTransitionedTelemetryEventSchema as z, UiActivityActionCompletedTelemetryEventSchema as zt };