@capxul/observability 4.20.0-beta.1 → 4.20.0-beta.11

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,3327 @@
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
+ preparePaymentExecution: "moneyExecution.preparePaymentExecution",
592
+ preparePaymentLifecycleExecution: "moneyExecution.preparePaymentLifecycleExecution",
593
+ prepareInvitationConfiguration: "moneyExecution.prepareInvitationConfiguration",
594
+ preparePermissionExecution: "moneyExecution.preparePermissionExecution",
595
+ recoverSubmissionClaims: "moneyExecution.recoverSubmissionClaims",
596
+ submit: "moneyExecution.submit",
597
+ submitPaymentCommandExecution: "moneyExecution.submitPaymentCommandExecution",
598
+ submitInvitationConfigurationExecution: "moneyExecution.submitInvitationConfigurationExecution",
599
+ submitPaymentExecution: "moneyExecution.submitPaymentExecution",
600
+ submitPermissionExecution: "moneyExecution.submitPermissionExecution"
601
+ },
602
+ movement: {
603
+ emitDepositSettled: "movement.emitDepositSettled",
604
+ scan: "movement.scan"
605
+ },
606
+ inbox: {
607
+ approve: "inbox.approve",
608
+ decline: "inbox.decline",
609
+ list: "inbox.list"
610
+ },
611
+ offramp: {
612
+ quote: "offramp.quote",
613
+ status: "offramp.status"
614
+ },
615
+ onboarding: {
616
+ completeOrganization: "onboarding.completeOrganization",
617
+ completePerson: "onboarding.completePerson"
618
+ },
619
+ org: {
620
+ account: { get: "org.account.get" },
621
+ auditLog: "org.auditLog",
622
+ confirmBootstrap: "org.confirmBootstrap",
623
+ createOrg: "org.createOrg",
624
+ create: "org.create",
625
+ /**
626
+ * §11: the consent mutation reports `org_invite_accepted` through its own
627
+ * scheduled emitter. It is named for the emit, not the acceptance, because
628
+ * the interactive acceptance itself owns `org.invitations.accept`.
629
+ */
630
+ emitInviteAccepted: "org.emitInviteAccepted",
631
+ emitInviteProgressed: "org.emitInviteProgressed",
632
+ expireInvitations: "org.expireInvitations",
633
+ getLifecycle: "org.getLifecycle",
634
+ getProofReceipt: "org.getProofReceipt",
635
+ invite: "org.invite",
636
+ /** D8 invitation lifecycle: preview, own list, read, and the four transitions. */
637
+ invitations: {
638
+ /** The exact grantee's consent commit (§8): one accepted digest, once. */
639
+ accept: "org.invitations.accept",
640
+ /**
641
+ * The authoring write. It is named `authorize`, not `invite`, because the
642
+ * backend already uses `org.invitations.invite` as a refusal label and
643
+ * `lint:telemetry-spine` refuses a label that collides with an operation.
644
+ */
645
+ authorize: "org.invitations.authorize",
646
+ cancel: "org.invitations.cancel",
647
+ decline: "org.invitations.decline",
648
+ get: "org.invitations.get",
649
+ list: "org.invitations.list",
650
+ /**
651
+ * The Admin-scoped Organization list. It is named `listScoped`, not
652
+ * `list`, because the own-offer list already owns `org.invitations.list`.
653
+ */
654
+ listScoped: "org.invitations.listScoped",
655
+ /**
656
+ * The authoring write's inner hops: the SDK drives the backend's existing
657
+ * prepare/submit pair, and these names label the two Convex calls. The
658
+ * owning `capxul_sdk_operation` record stays `org.invitations.authorize`.
659
+ */
660
+ prepareConfiguration: "org.invitations.prepareConfiguration",
661
+ preview: "org.invitations.preview",
662
+ resend: "org.invitations.resend",
663
+ retry: "org.invitations.retry",
664
+ submitConfiguration: "org.invitations.submitConfiguration"
665
+ },
666
+ list: "org.list",
667
+ load: "org.load",
668
+ me: "org.me",
669
+ members: "org.members",
670
+ orgs: "org.orgs",
671
+ payment: "org.payment",
672
+ permissions: {
673
+ assign: "org.permissions.assign",
674
+ change: "org.permissions.change",
675
+ create: "org.permissions.create",
676
+ get: "org.permissions.get",
677
+ list: "org.permissions.list",
678
+ replace: "org.permissions.replace",
679
+ revoke: "org.permissions.revoke"
680
+ },
681
+ payments: {
682
+ pay: "org.payments.pay",
683
+ payBatch: "org.payments.payBatch"
684
+ },
685
+ payroll: {
686
+ authorizeRun: "org.payroll.authorizeRun",
687
+ groups: {
688
+ list: "org.payroll.groups.list",
689
+ remove: "org.payroll.groups.remove",
690
+ save: "org.payroll.groups.save"
691
+ },
692
+ runs: "org.payroll.runs",
693
+ terms: "org.payroll.terms"
694
+ },
695
+ addressBook: {
696
+ add: "org.addressBook.add",
697
+ get: "org.addressBook.get",
698
+ hide: "org.addressBook.hide",
699
+ label: "org.addressBook.label",
700
+ list: "org.addressBook.list",
701
+ unhide: "org.addressBook.unhide"
702
+ },
703
+ inbox: {
704
+ approve: "org.inbox.approve",
705
+ decline: "org.inbox.decline",
706
+ list: "org.inbox.list"
707
+ },
708
+ lifecycle: { startOrResume: "org.lifecycle.startOrResume" },
709
+ prepareBootstrap: "org.prepareBootstrap",
710
+ prepareFounderAccount: "org.prepareFounderAccount",
711
+ profile: {
712
+ depositInstructions: "org.profile.depositInstructions",
713
+ get: "org.profile.get"
714
+ },
715
+ readTreasury: "org.readTreasury",
716
+ requests: {
717
+ cancel: "org.requests.cancel",
718
+ get: "org.requests.get",
719
+ issue: "org.requests.issue",
720
+ list: "org.requests.list"
721
+ },
722
+ recordFailure: "org.recordFailure",
723
+ recordProgress: "org.recordProgress",
724
+ resumeBootstrapSubmission: "org.resumeBootstrapSubmission",
725
+ retry: "org.retry",
726
+ retrySetup: "org.retrySetup",
727
+ roles: "org.roles",
728
+ startOrResume: "org.startOrResume",
729
+ submitBootstrap: "org.submitBootstrap",
730
+ treasury: "org.treasury"
731
+ },
732
+ organization: { setup: "organization.setup" },
733
+ organizationPayments: {
734
+ pay: "organizationPayments.pay",
735
+ payBatch: "organizationPayments.payBatch",
736
+ prepareExecution: "organizationPayments.prepareExecution",
737
+ retry: "organizationPayments.retry"
738
+ },
739
+ organizationSetup: { getProofReceipt: "organizationSetup.getProofReceipt" },
740
+ payments: {
741
+ cancel: "payments.cancel",
742
+ claim: "payments.claim",
743
+ createCommitment: "payments.createCommitment",
744
+ get: "payments.get",
745
+ ledger: "payments",
746
+ list: "payments.list",
747
+ pay: "payments.pay",
748
+ prepareExecution: "payments.prepareExecution",
749
+ prepareLifecycleExecution: "payments.prepareLifecycleExecution",
750
+ redirect: "payments.redirect",
751
+ retry: "payments.retry",
752
+ submitCommandExecution: "payments.submitCommandExecution",
753
+ submitExecution: "payments.submitExecution"
754
+ },
755
+ paymentDocuments: {
756
+ get: "paymentDocuments.get",
757
+ render: "paymentDocuments.render",
758
+ verify: "paymentDocuments.verify"
759
+ },
760
+ recipient: { resolve: "recipient.resolve" },
761
+ payroll: {
762
+ authorizeRun: "payroll.authorizeRun",
763
+ emitGroupChanged: "payroll.emitGroupChanged",
764
+ emitRunTransitioned: "payroll.emitRunTransitioned",
765
+ groups: {
766
+ access: "payroll.groups",
767
+ list: "payroll.groups.list",
768
+ remove: "payroll.groups.remove",
769
+ save: "payroll.groups.save"
770
+ },
771
+ removeGroup: "payroll.removeGroup",
772
+ runs: "payroll.runs",
773
+ saveGroup: "payroll.saveGroup",
774
+ terms: "payroll.terms"
775
+ },
776
+ permission: {
777
+ verifyInvitationConfiguration: "permission.verifyInvitationConfiguration",
778
+ command: "permission.command",
779
+ retryVerification: "permission.retryVerification",
780
+ verify: "permission.verify",
781
+ verifySubmitted: "permission.verifySubmitted"
782
+ },
783
+ permissions: {
784
+ assign: "permissions.assign",
785
+ change: "permissions.change",
786
+ create: "permissions.create",
787
+ get: "permissions.get",
788
+ list: "permissions.list",
789
+ prepareExecution: "permissions.prepareExecution",
790
+ replace: "permissions.replace",
791
+ revoke: "permissions.revoke",
792
+ submitExecution: "permissions.submitExecution"
793
+ },
794
+ publishableKeys: {
795
+ mint: "publishableKeys.mint",
796
+ revoke: "publishableKeys.revoke",
797
+ rotate: "publishableKeys.rotate"
798
+ },
799
+ requests: {
800
+ cancel: "requests.cancel",
801
+ get: "requests.get",
802
+ issue: "requests.issue",
803
+ list: "requests.list"
804
+ },
805
+ runtime: {
806
+ assign: "assign",
807
+ canSendOtp: "canSendOtp",
808
+ cancelCommitment: "cancel_commitment",
809
+ change: "change",
810
+ claimCommitment: "claim_commitment",
811
+ create: "create",
812
+ createCapxulClient: "createCapxulClient",
813
+ createCapxulClientWithOrgDeploymentSeams: "createCapxulClientWithOrgDeploymentSeams",
814
+ createCommitment: "create_commitment",
815
+ getConvexJwt: "getConvexJwt",
816
+ getSession: "getSession",
817
+ initialize: "initialize",
818
+ mutation: "mutation",
819
+ now: "now",
820
+ port: "port",
821
+ query: "query",
822
+ redirectCommitment: "redirect_commitment",
823
+ replace: "replace",
824
+ resolve: "resolve",
825
+ revoke: "revoke",
826
+ send: "send",
827
+ sendOtp: "sendOtp",
828
+ signIn: "signIn",
829
+ signOut: "signOut",
830
+ sleep: "sleep",
831
+ verifyOtp: "verifyOtp",
832
+ wallet: "wallet"
833
+ },
834
+ smartAccount: {
835
+ claim: "smartAccount.claim",
836
+ confirmDeployment: "smartAccount.confirmDeployment",
837
+ loadByAuthUserId: "smartAccount.loadByAuthUserId",
838
+ loadCurrent: "smartAccount.loadCurrent",
839
+ provision: "smartAccount.provision"
840
+ },
841
+ system: {
842
+ health: "system.health",
843
+ ping: "system.ping",
844
+ runtimeChain: "system.runtimeChain"
845
+ },
846
+ testUsdc: { mint: "TestUSDC.mint" },
847
+ _internal: {
848
+ accounts: { fund: "_internal.accounts.fund" },
849
+ close: "_internal.close",
850
+ identity: {
851
+ completeProfile: "_internal.identity.completeProfile",
852
+ runFacade: "_internal.identity.runFacade",
853
+ send: "_internal.identity.send"
854
+ },
855
+ organizationSetup: { getProofReceipt: "_internal.organizationSetup.getProofReceipt" }
856
+ },
857
+ tenancy: {
858
+ revokeBackendTenancyConsent: "tenancy.revokeBackendTenancyConsent",
859
+ seedBackendTenancy: "tenancy.seedBackendTenancy"
860
+ }
861
+ };
862
+ function collectOperations(tree) {
863
+ return Object.values(tree).flatMap((value) => typeof value === "string" ? [value] : collectOperations(value));
864
+ }
865
+ const operations = new Set(collectOperations(CAPXUL_OPERATIONS));
866
+ function isCapxulOperation(value) {
867
+ return typeof value === "string" && operations.has(value);
868
+ }
869
+ function normalizeCapxulOperation(value) {
870
+ return isCapxulOperation(value) ? value : "unknown";
871
+ }
872
+ //#endregion
873
+ //#region src/index.ts
874
+ const TELEMETRY_EVENT_NAMES = [
875
+ "auth_otp_requested",
876
+ "auth_otp_delivered",
877
+ "auth_otp_expired",
878
+ "auth_verified",
879
+ "auth_failed",
880
+ "identity_refused",
881
+ "auth_signed_out",
882
+ "native_authorization_started",
883
+ "native_authorization_reviewed",
884
+ "native_authorization_accepted",
885
+ "native_authorization_denied",
886
+ "native_authorization_connected",
887
+ "native_authorization_failed",
888
+ "onboarding_intent_selected",
889
+ "onboarding_profile_submitted",
890
+ "onboarding_organization_submitted",
891
+ "onboarding_dashboard_reached",
892
+ "provisioning_safe_created",
893
+ "provisioning_safe_confirmed",
894
+ "bootstrap_resolved",
895
+ "bootstrap_failed",
896
+ "member_activation_started",
897
+ "member_activation_ready",
898
+ "member_activation_failed",
899
+ "organization_creation_started",
900
+ "organization_creation_ready",
901
+ "organization_creation_failed",
902
+ "chain_upstream_fallback",
903
+ "bundler_error",
904
+ "receipt_pending",
905
+ "operation_retried",
906
+ "account_balance_read",
907
+ "account_balance_failed",
908
+ "faucet_requested",
909
+ "faucet_confirmed",
910
+ "faucet_failed",
911
+ "org_create_started",
912
+ "org_safe_created",
913
+ "org_safe_confirmed",
914
+ "org_roles_seeded",
915
+ "org_created",
916
+ "org_create_failed",
917
+ "org_invite_sent",
918
+ "org_invite_accepted",
919
+ "org_invite_expired",
920
+ "payment_initiated",
921
+ "payment_settled",
922
+ "payment_failed",
923
+ "payment_verification_retry",
924
+ "payment_lifecycle_transition",
925
+ "quick_pay_external_address_acknowledged",
926
+ "deposit_initiated",
927
+ "deposit_settled",
928
+ "permission_mirror_verification",
929
+ "movement_scan_window",
930
+ "movement_scan_checkpoint",
931
+ "movement_scan_incident",
932
+ "indexer_drift_corrected",
933
+ "activity_annotation_saved",
934
+ "ui_activity_action_completed",
935
+ "contact_relationship_changed",
936
+ "ui_contact_action_completed",
937
+ "access_recovery_completed",
938
+ "ui_access_step_completed",
939
+ "org_invite_progressed",
940
+ "invoice_issued",
941
+ "invoice_request_transitioned",
942
+ "ui_invoice_step_completed",
943
+ "ui_treasury_step_completed",
944
+ "ui_receive_step_completed",
945
+ "payroll_group_changed",
946
+ "payroll_run_transitioned",
947
+ "ui_payroll_action_completed",
948
+ "cli_diagnostic_completed",
949
+ "cli_first_used",
950
+ "cli_command_started",
951
+ "cli_command_completed"
952
+ ];
953
+ const TELEMETRY_JOURNEYS = {
954
+ returning_user_login: {
955
+ type: "funnel",
956
+ steps: [
957
+ "auth_otp_requested",
958
+ "auth_otp_delivered",
959
+ "auth_verified"
960
+ ],
961
+ drops_on: ["auth_otp_expired", "auth_failed"]
962
+ },
963
+ new_user_first_signin: {
964
+ type: "funnel",
965
+ steps: [
966
+ "auth_otp_requested",
967
+ "auth_otp_delivered",
968
+ "auth_verified",
969
+ "provisioning_safe_created",
970
+ "provisioning_safe_confirmed"
971
+ ],
972
+ drops_on: ["auth_otp_expired", "auth_failed"]
973
+ },
974
+ sign_out_session_close: {
975
+ type: "point_event",
976
+ point_event: "auth_signed_out"
977
+ },
978
+ member_activation: {
979
+ type: "funnel",
980
+ steps: ["member_activation_started", "member_activation_ready"],
981
+ drops_on: ["member_activation_failed"]
982
+ },
983
+ organization_creation_lifecycle: {
984
+ type: "funnel",
985
+ steps: ["organization_creation_started", "organization_creation_ready"],
986
+ drops_on: ["organization_creation_failed"]
987
+ },
988
+ new_member_personal_dashboard: {
989
+ type: "funnel",
990
+ steps: [
991
+ "auth_verified",
992
+ "onboarding_intent_selected",
993
+ "onboarding_profile_submitted",
994
+ "member_activation_ready",
995
+ "onboarding_dashboard_reached"
996
+ ],
997
+ step_filters: {
998
+ onboarding_intent_selected: [{
999
+ key: "intent",
1000
+ value: ["personal"],
1001
+ operator: "exact",
1002
+ type: "event"
1003
+ }, {
1004
+ key: "entry_point",
1005
+ value: ["signup"],
1006
+ operator: "exact",
1007
+ type: "event"
1008
+ }],
1009
+ onboarding_profile_submitted: [{
1010
+ key: "intent",
1011
+ value: ["personal"],
1012
+ operator: "exact",
1013
+ type: "event"
1014
+ }],
1015
+ onboarding_dashboard_reached: [{
1016
+ key: "intent",
1017
+ value: ["personal"],
1018
+ operator: "exact",
1019
+ type: "event"
1020
+ }]
1021
+ }
1022
+ },
1023
+ new_member_organization_dashboard: {
1024
+ type: "funnel",
1025
+ steps: [
1026
+ "auth_verified",
1027
+ "onboarding_intent_selected",
1028
+ "onboarding_profile_submitted",
1029
+ "onboarding_organization_submitted",
1030
+ "member_activation_started",
1031
+ "member_activation_ready",
1032
+ "organization_creation_started",
1033
+ "organization_creation_ready",
1034
+ "onboarding_dashboard_reached"
1035
+ ],
1036
+ step_filters: {
1037
+ onboarding_intent_selected: [{
1038
+ key: "intent",
1039
+ value: ["organization"],
1040
+ operator: "exact",
1041
+ type: "event"
1042
+ }, {
1043
+ key: "entry_point",
1044
+ value: ["signup"],
1045
+ operator: "exact",
1046
+ type: "event"
1047
+ }],
1048
+ onboarding_profile_submitted: [{
1049
+ key: "intent",
1050
+ value: ["organization"],
1051
+ operator: "exact",
1052
+ type: "event"
1053
+ }],
1054
+ onboarding_dashboard_reached: [{
1055
+ key: "intent",
1056
+ value: ["organization"],
1057
+ operator: "exact",
1058
+ type: "event"
1059
+ }]
1060
+ }
1061
+ },
1062
+ existing_member_organization_dashboard: {
1063
+ type: "funnel",
1064
+ steps: [
1065
+ "onboarding_intent_selected",
1066
+ "onboarding_organization_submitted",
1067
+ "organization_creation_started",
1068
+ "organization_creation_ready",
1069
+ "onboarding_dashboard_reached"
1070
+ ],
1071
+ step_filters: {
1072
+ onboarding_intent_selected: [{
1073
+ key: "intent",
1074
+ value: ["organization"],
1075
+ operator: "exact",
1076
+ type: "event"
1077
+ }, {
1078
+ key: "entry_point",
1079
+ value: ["dashboard"],
1080
+ operator: "exact",
1081
+ type: "event"
1082
+ }],
1083
+ onboarding_dashboard_reached: [{
1084
+ key: "intent",
1085
+ value: ["organization"],
1086
+ operator: "exact",
1087
+ type: "event"
1088
+ }]
1089
+ }
1090
+ },
1091
+ money_on_screen: {
1092
+ type: "point_event",
1093
+ point_event: "account_balance_read"
1094
+ },
1095
+ fund_account: {
1096
+ type: "funnel",
1097
+ steps: ["faucet_requested", "faucet_confirmed"],
1098
+ drops_on: ["faucet_failed"]
1099
+ },
1100
+ org_creation: {
1101
+ type: "funnel",
1102
+ steps: [
1103
+ "org_create_started",
1104
+ "org_safe_created",
1105
+ "org_safe_confirmed",
1106
+ "org_roles_seeded",
1107
+ "org_created"
1108
+ ],
1109
+ drops_on: ["org_create_failed"]
1110
+ },
1111
+ org_member_onboarding: {
1112
+ type: "funnel",
1113
+ steps: ["org_invite_sent", "org_invite_accepted"],
1114
+ drops_on: ["org_invite_expired"]
1115
+ },
1116
+ direct_payment: {
1117
+ type: "funnel",
1118
+ steps: ["payment_initiated", "payment_settled"],
1119
+ drops_on: ["payment_failed"]
1120
+ },
1121
+ deposit: {
1122
+ type: "funnel",
1123
+ steps: ["deposit_initiated", "deposit_settled"]
1124
+ }
1125
+ };
1126
+ const PII = Schema.String.pipe(Schema.brand("PII"));
1127
+ const OptionalString = Schema.optional(Schema.String);
1128
+ const AddressSchema = Schema.String.pipe(Schema.decodeTo(Schema.String, {
1129
+ decode: SchemaGetter.transform((value) => value.toLowerCase()),
1130
+ encode: SchemaGetter.transform((value) => value)
1131
+ }), Schema.refine((value) => EVM_ADDRESS_RE.test(value), { message: "must be 0x + 40 hex chars" }));
1132
+ const AppIdSchema = Schema.String.pipe(Schema.refine((value) => APP_ID_RE.test(value), { message: "must be app_ plus a ULID" }));
1133
+ const BlockNumberSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" }));
1134
+ const ChainIdSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value > 0, { message: "must be a positive safe integer" }));
1135
+ const DurationMsSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" }));
1136
+ const EpochMsSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" }));
1137
+ const PublishableKeyIdSchema = Schema.String.pipe(Schema.refine((value) => value.length > 0, { message: "must be a non-empty string" }));
1138
+ const TxHashSchema = Schema.String.pipe(Schema.refine((value) => BYTES32_RE.test(value), { message: "must be 0x + 64 hex chars" }));
1139
+ const ACCOUNT_ID_TELEMETRY_RE = /^account_[0-9A-Za-z]+$/;
1140
+ const WEI_AMOUNT_TELEMETRY_RE = /^[0-9]+$/;
1141
+ const AccountIdSchema = Schema.String.pipe(Schema.refine((value) => ACCOUNT_ID_TELEMETRY_RE.test(value), { message: "must be account_ plus an alphanumeric id" }));
1142
+ const WeiAmountSchema = Schema.String.pipe(Schema.refine((value) => WEI_AMOUNT_TELEMETRY_RE.test(value), { message: "must be a non-negative integer string" }));
1143
+ const CurrencyCodeSchema = Schema.String.pipe(Schema.refine((value) => value.length > 0, { message: "must be a non-empty currency code" }));
1144
+ const BalanceBucketSchema = Schema.Literals(["zero", "nonzero"]);
1145
+ const OptionalAccountId = Schema.optional(AccountIdSchema);
1146
+ const OptionalWeiAmount = Schema.optional(WeiAmountSchema);
1147
+ const OptionalCurrencyCode = Schema.optional(CurrencyCodeSchema);
1148
+ const OptionalBalanceBucket = Schema.optional(BalanceBucketSchema);
1149
+ /** Which Safe a money record is about. Declared here so the money-domain
1150
+ * props below can name it as well as the UI-step props further down. */
1151
+ const AccountKindSchema = Schema.Literals(["personalSafe", "orgTreasury"]);
1152
+ const OptionalAccountKind = Schema.optional(AccountKindSchema);
1153
+ const OptionalAddress = Schema.optional(AddressSchema);
1154
+ const OptionalAppId = Schema.optional(AppIdSchema);
1155
+ const OptionalBlockNumber = Schema.optional(BlockNumberSchema);
1156
+ const OptionalChainId = Schema.optional(ChainIdSchema);
1157
+ const OptionalDurationMs = Schema.optional(DurationMsSchema);
1158
+ const OptionalEpochMs = Schema.optional(EpochMsSchema);
1159
+ const OptionalPublishableKeyId = Schema.optional(PublishableKeyIdSchema);
1160
+ const OptionalTxHash = Schema.optional(TxHashSchema);
1161
+ /**
1162
+ * Environment discriminator (ADR-0020 A1 amendment, 2026-08-07). PostHog
1163
+ * project 368736 is the SINGLE sink for every environment, so `capxul_env` —
1164
+ * not project isolation — is what keeps a production surface from reading dev
1165
+ * traffic. It is REQUIRED on every catalog event and every synced artifact
1166
+ * filters on it.
1167
+ *
1168
+ * `unknown` is a defect marker, not an environment: it means a producer
1169
+ * reached the transport without declaring where it runs. It is in the union so
1170
+ * the property is never ABSENT (an absent property is invisible to a filter,
1171
+ * a present `unknown` is loud), and sync v2 never synthesizes an artifact for
1172
+ * it.
1173
+ */
1174
+ const CAPXUL_ENVS = [
1175
+ "development",
1176
+ "staging",
1177
+ "production",
1178
+ "unknown",
1179
+ "local"
1180
+ ];
1181
+ /**
1182
+ * Environments a synced product surface may be built for. `unknown` and
1183
+ * `local` cannot. This list is deliberately narrower than `CAPXUL_ENVS`.
1184
+ */
1185
+ const SYNCABLE_CAPXUL_ENVS = [
1186
+ "development",
1187
+ "staging",
1188
+ "production"
1189
+ ];
1190
+ /**
1191
+ * Which half of the system emitted the event. REQUIRED alongside `capxul_env`
1192
+ * so a name that two halves can produce (settlement, auth) stays attributable.
1193
+ */
1194
+ const TELEMETRY_PRODUCERS = [
1195
+ "server",
1196
+ "browser",
1197
+ "sdk",
1198
+ "mcp",
1199
+ "e2e"
1200
+ ];
1201
+ /**
1202
+ * The canonical envelope (ADR-0020 A4): snake_case ONLY. `capxul_env` and
1203
+ * `producer` are REQUIRED — a boundary that forgets to stamp them fails schema
1204
+ * decode instead of silently shipping an unattributable event. Call sites do
1205
+ * not pass them: `stampTelemetryEnvelope` injects them at the emit boundary,
1206
+ * which is the only place that knows where the process runs.
1207
+ */
1208
+ const TelemetryEnvelopeProps = {
1209
+ capxul_env: Schema.Literals(CAPXUL_ENVS),
1210
+ producer: Schema.Literals(TELEMETRY_PRODUCERS),
1211
+ journey_id: OptionalString,
1212
+ correlation_id: OptionalString,
1213
+ sdk_version: OptionalString
1214
+ };
1215
+ /**
1216
+ * The cause of a failure, flat (ADR-0023 R7–R8). `failure_mode` is the one
1217
+ * word from `@capxul/errors`; the `chain_*` keys are the `ChainCause` when the
1218
+ * failure came from the chain path. Spread into every failure event and posted
1219
+ * on `$exception`, so one PostHog filter finds a cause wherever it was seen.
1220
+ */
1221
+ const FailureModeSchema = Schema.Literals(FAILURE_MODES);
1222
+ const ChainUpstreamSchema = Schema.Literals(CHAIN_UPSTREAMS);
1223
+ /**
1224
+ * The refusing upstream's response headers (#1818): exactly the names in
1225
+ * `RESPONSE_HEADER_ALLOWLIST`, each optional, so the catalog itself refuses a
1226
+ * `set-cookie` or `authorization` that a producer let through.
1227
+ */
1228
+ const ResponseHeadersSchema = Schema.Struct({
1229
+ "retry-after": OptionalString,
1230
+ "www-authenticate": OptionalString,
1231
+ "content-type": OptionalString,
1232
+ "x-request-id": OptionalString,
1233
+ "cf-ray": OptionalString,
1234
+ "x-ratelimit-remaining": OptionalString,
1235
+ "x-ratelimit-reset": OptionalString,
1236
+ server: OptionalString
1237
+ });
1238
+ /** One upstream tried, flat (#1818): the `chain_attempts` entry on every producer's row. */
1239
+ const ChainAttemptSchema = Schema.Struct({
1240
+ upstream: ChainUpstreamSchema,
1241
+ failure_mode: FailureModeSchema,
1242
+ http_status: Schema.optional(Schema.Number),
1243
+ rpc_code: Schema.optional(Schema.Number),
1244
+ duration_ms: Schema.Number
1245
+ });
1246
+ const ChainCauseTelemetryProps = {
1247
+ failure_mode: Schema.optional(FailureModeSchema),
1248
+ chain_upstream: Schema.optional(ChainUpstreamSchema),
1249
+ chain_method: OptionalString,
1250
+ chain_retryable: Schema.optional(Schema.Boolean),
1251
+ chain_http_status: Schema.optional(Schema.Number),
1252
+ chain_rpc_code: Schema.optional(Schema.Number),
1253
+ chain_revert_name: OptionalString,
1254
+ chain_revert_selector: OptionalString,
1255
+ chain_revert_args: Schema.optional(Schema.Record(Schema.String, Schema.String)),
1256
+ chain_provider_message: OptionalString,
1257
+ chain_attempts: Schema.optional(Schema.Array(ChainAttemptSchema)),
1258
+ chain_response_headers: Schema.optional(ResponseHeadersSchema)
1259
+ };
1260
+ /**
1261
+ * Stamp the required envelope onto an event at its emit boundary. Call-site
1262
+ * props win on conflict: a relay that already knows the true producer (the
1263
+ * browser-failure relay stamps `browser` while running on the server) must not
1264
+ * be overwritten by the transport's own default.
1265
+ */
1266
+ function stampTelemetryEnvelope(event, defaults) {
1267
+ return {
1268
+ name: event.name,
1269
+ props: {
1270
+ ...defaults,
1271
+ ...event.props
1272
+ }
1273
+ };
1274
+ }
1275
+ const AuthOtpRequestedProps = Schema.Struct({
1276
+ ...TelemetryEnvelopeProps,
1277
+ email: Schema.optional(PII),
1278
+ email_domain: OptionalString
1279
+ });
1280
+ const AuthOtpDeliveredProps = Schema.Struct({
1281
+ ...TelemetryEnvelopeProps,
1282
+ durationMs: OptionalDurationMs,
1283
+ email: Schema.optional(PII),
1284
+ email_domain: OptionalString,
1285
+ resendMessageId: OptionalString
1286
+ });
1287
+ const AuthOtpExpiredProps = Schema.Struct({
1288
+ ...TelemetryEnvelopeProps,
1289
+ email: Schema.optional(PII),
1290
+ email_domain: OptionalString
1291
+ });
1292
+ const AuthVerifiedProps = Schema.Struct({
1293
+ ...TelemetryEnvelopeProps,
1294
+ auth_type: OptionalString
1295
+ });
1296
+ const AuthFailedProps = Schema.Struct({
1297
+ ...TelemetryEnvelopeProps,
1298
+ ...ChainCauseTelemetryProps,
1299
+ email: Schema.optional(PII),
1300
+ auth_type: OptionalString,
1301
+ reason: OptionalString
1302
+ });
1303
+ const IdentityRefusedProps = Schema.Struct({
1304
+ ...TelemetryEnvelopeProps,
1305
+ /** The refused identity event tag, for example CreateOrganization. */
1306
+ event: OptionalString,
1307
+ /** The machine's refusal code: WRONG_STATE, SUPERSEDED or STALE_EPOCH. */
1308
+ refusal_code: OptionalString,
1309
+ /** The machine slot the request targeted, for example identity:org. */
1310
+ slot: OptionalString,
1311
+ /** The machine state at refusal, for example authenticated:claiming. */
1312
+ state: OptionalString
1313
+ });
1314
+ const AuthSignedOutProps = Schema.Struct(TelemetryEnvelopeProps);
1315
+ const NativeAuthorizationMode = Schema.Literals(["login", "signup"]);
1316
+ const NativeAuthorizationStartedProps = Schema.Struct({
1317
+ ...TelemetryEnvelopeProps,
1318
+ mode: NativeAuthorizationMode
1319
+ });
1320
+ const NativeAuthorizationReviewedProps = Schema.Struct({
1321
+ ...TelemetryEnvelopeProps,
1322
+ mode: NativeAuthorizationMode
1323
+ });
1324
+ const NativeAuthorizationAcceptedProps = Schema.Struct({
1325
+ ...TelemetryEnvelopeProps,
1326
+ mode: NativeAuthorizationMode,
1327
+ /** Whether consent also had to finish account setup first. */
1328
+ setup_state: Schema.optional(Schema.Literals([
1329
+ "not_required",
1330
+ "new",
1331
+ "resumable"
1332
+ ]))
1333
+ });
1334
+ const NativeAuthorizationDeniedProps = Schema.Struct({
1335
+ ...TelemetryEnvelopeProps,
1336
+ mode: NativeAuthorizationMode
1337
+ });
1338
+ const NativeAuthorizationConnectedProps = Schema.Struct({
1339
+ ...TelemetryEnvelopeProps,
1340
+ mode: NativeAuthorizationMode
1341
+ });
1342
+ const NativeAuthorizationFailedProps = Schema.Struct({
1343
+ ...TelemetryEnvelopeProps,
1344
+ mode: Schema.optional(NativeAuthorizationMode),
1345
+ /** The refusal word the store returned, for example `identity_mismatch` or
1346
+ * `request_expired`. These are the closed `CLIENT_AUTHORIZATION_REFUSALS` from
1347
+ * `@capxul/wire` plus the store-internal `fresh_session_required` (ruling R3),
1348
+ * which the continuation maps to `identity_mismatch` on the wire but reports
1349
+ * truthfully here. Kept as `OptionalString` rather than an imported literal
1350
+ * set: this package must not depend on the transport contract. */
1351
+ reason: OptionalString
1352
+ });
1353
+ const ProvisioningSafeCreatedProps = Schema.Struct({
1354
+ ...TelemetryEnvelopeProps,
1355
+ safe_address: OptionalAddress
1356
+ });
1357
+ const ProvisioningSafeConfirmedProps = Schema.Struct({
1358
+ ...TelemetryEnvelopeProps,
1359
+ chainId: OptionalChainId,
1360
+ deployedAt: OptionalEpochMs,
1361
+ deployedAtBlock: OptionalBlockNumber,
1362
+ deployTxHash: OptionalTxHash,
1363
+ durationMs: OptionalDurationMs,
1364
+ safe_address: OptionalAddress,
1365
+ userOpHash: OptionalTxHash
1366
+ });
1367
+ const BootstrapResolvedProps = Schema.Struct({
1368
+ ...TelemetryEnvelopeProps,
1369
+ applicationId: OptionalAppId,
1370
+ durationMs: OptionalDurationMs,
1371
+ env: OptionalString,
1372
+ keyId: OptionalPublishableKeyId,
1373
+ origin: OptionalString
1374
+ });
1375
+ const BootstrapFailedProps = Schema.Struct({
1376
+ ...TelemetryEnvelopeProps,
1377
+ ...ChainCauseTelemetryProps,
1378
+ applicationId: OptionalAppId,
1379
+ durationMs: OptionalDurationMs,
1380
+ origin: OptionalString,
1381
+ provider: OptionalString,
1382
+ provider_operation: OptionalString,
1383
+ reason: OptionalString,
1384
+ target_host: OptionalString
1385
+ });
1386
+ /**
1387
+ * R08 (#1966): which Safe was read, on which chain, of which token. `currency`
1388
+ * is the DISPLAY code the surface shows ("USD"); it never says which ERC-20 the
1389
+ * `balanceOf` actually hit, so a reader could not tell a treasury read from a
1390
+ * personal one, nor one token from another with the same fiat peg. The producer
1391
+ * takes each of these from the authority that already decided it — the verified
1392
+ * Organization row's chain, the configured token address — never from a label.
1393
+ * The verified `organization_id` and its group arrive from the backend
1394
+ * attribution, so they are not repeated here.
1395
+ *
1396
+ * D1 (2026-09-10): `asset_id` carries the canonical branded identity the read
1397
+ * resolved, `eip155:<chainId>/erc20:<lowercase-address>`, from the registry
1398
+ * row. `token_address`/`chain_id` are its parts; `currency` is the peg and a
1399
+ * display code. The producer emits the branded id so the live read can be
1400
+ * grouped by ASSET, never by symbol or peg.
1401
+ */
1402
+ const AccountBalanceReadProps = Schema.Struct({
1403
+ ...TelemetryEnvelopeProps,
1404
+ account_id: OptionalAccountId,
1405
+ account_kind: OptionalAccountKind,
1406
+ chain_id: OptionalChainId,
1407
+ token_address: OptionalAddress,
1408
+ asset_id: OptionalString,
1409
+ currency: OptionalCurrencyCode,
1410
+ balance_bucket: OptionalBalanceBucket,
1411
+ durationMs: OptionalDurationMs
1412
+ });
1413
+ const AccountBalanceFailedProps = Schema.Struct({
1414
+ ...TelemetryEnvelopeProps,
1415
+ ...ChainCauseTelemetryProps,
1416
+ reason: OptionalString
1417
+ });
1418
+ const FaucetRequestedProps = Schema.Struct({
1419
+ ...TelemetryEnvelopeProps,
1420
+ amount: OptionalWeiAmount,
1421
+ chainId: OptionalChainId,
1422
+ asset_id: OptionalString
1423
+ });
1424
+ const FaucetConfirmedProps = Schema.Struct({
1425
+ ...TelemetryEnvelopeProps,
1426
+ amount: OptionalWeiAmount,
1427
+ chainId: OptionalChainId,
1428
+ txHash: OptionalTxHash,
1429
+ asset_id: OptionalString,
1430
+ token_address: OptionalAddress,
1431
+ durationMs: OptionalDurationMs
1432
+ });
1433
+ const FaucetFailedProps = Schema.Struct({
1434
+ ...TelemetryEnvelopeProps,
1435
+ ...ChainCauseTelemetryProps,
1436
+ reason: OptionalString,
1437
+ amount: OptionalWeiAmount,
1438
+ chainId: OptionalChainId,
1439
+ asset_id: OptionalString,
1440
+ token_address: OptionalAddress
1441
+ });
1442
+ const ChainServiceSchema = Schema.Literals(["aa-gateway", "backend"]);
1443
+ const ChainUpstreamFallbackProps = Schema.Struct({
1444
+ ...TelemetryEnvelopeProps,
1445
+ service: ChainServiceSchema,
1446
+ method: Schema.String,
1447
+ from_upstream: ChainUpstreamSchema,
1448
+ to_upstream: Schema.optional(ChainUpstreamSchema),
1449
+ failure_mode: FailureModeSchema,
1450
+ exhausted: Schema.Boolean,
1451
+ http_status: Schema.optional(Schema.Number),
1452
+ rpc_code: Schema.optional(Schema.Number),
1453
+ response_headers: Schema.optional(ResponseHeadersSchema)
1454
+ });
1455
+ const BundlerErrorProps = Schema.Struct({
1456
+ ...TelemetryEnvelopeProps,
1457
+ method: Schema.String,
1458
+ failure_mode: FailureModeSchema,
1459
+ chain_upstream: ChainUpstreamSchema,
1460
+ chain_retryable: Schema.Boolean,
1461
+ http_status: Schema.optional(Schema.Number),
1462
+ rpc_code: Schema.optional(Schema.Number),
1463
+ chain_revert_name: OptionalString,
1464
+ chain_provider_message: OptionalString
1465
+ });
1466
+ const ReceiptPendingProps = Schema.Struct({
1467
+ ...TelemetryEnvelopeProps,
1468
+ service: ChainServiceSchema,
1469
+ method: Schema.String,
1470
+ chain_upstream: ChainUpstreamSchema,
1471
+ reason: Schema.Literals(["zero_block_hash", "no_receipt"])
1472
+ });
1473
+ const OperationRetriedProps = Schema.Struct({
1474
+ ...TelemetryEnvelopeProps,
1475
+ operation: Schema.String,
1476
+ failure_mode: FailureModeSchema,
1477
+ reason: Schema.optional(Schema.Literal("connection-lost-in-flight")),
1478
+ connection_id: OptionalString,
1479
+ connection_count: Schema.optional(Schema.Number),
1480
+ attempt: Schema.Number,
1481
+ delay_ms: DurationMsSchema
1482
+ });
1483
+ const ORG_ID_TELEMETRY_RE = /^org_[0-9A-Za-z]+$/;
1484
+ const OrgIdTelemetrySchema = Schema.String.pipe(Schema.refine((value) => ORG_ID_TELEMETRY_RE.test(value), { message: "must be org_ plus an alphanumeric id" }));
1485
+ const OptionalOrgId = Schema.optional(OrgIdTelemetrySchema);
1486
+ const AttemptNumberSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value > 0, { message: "must be a positive safe integer" }));
1487
+ const OnboardingStageSchema = Schema.Literals([
1488
+ "profile",
1489
+ "accountProvisioning",
1490
+ "accountClaim",
1491
+ "preparingFounderAccount",
1492
+ "awaitingFounderAuthorization",
1493
+ "submittingBootstrap",
1494
+ "confirmingBootstrap"
1495
+ ]);
1496
+ const MemberActivationStartedProps = Schema.Struct({
1497
+ ...TelemetryEnvelopeProps,
1498
+ $insert_id: Schema.String
1499
+ });
1500
+ const MemberActivationReadyProps = Schema.Struct({
1501
+ ...TelemetryEnvelopeProps,
1502
+ $insert_id: Schema.String,
1503
+ duration_ms: DurationMsSchema
1504
+ });
1505
+ const MemberActivationFailedProps = Schema.Struct({
1506
+ ...TelemetryEnvelopeProps,
1507
+ ...ChainCauseTelemetryProps,
1508
+ $insert_id: Schema.String,
1509
+ stage: OnboardingStageSchema,
1510
+ error_code: Schema.String,
1511
+ retryable: Schema.Boolean
1512
+ });
1513
+ const OrganizationCreationStartedProps = Schema.Struct({
1514
+ ...TelemetryEnvelopeProps,
1515
+ $insert_id: Schema.String,
1516
+ organization_id: OrgIdTelemetrySchema,
1517
+ attempt_number: AttemptNumberSchema,
1518
+ release: Schema.optional(Schema.String.check(Schema.isPattern(/^[0-9a-f]{40}$/u)))
1519
+ });
1520
+ const OrganizationCreationReadyProps = Schema.Struct({
1521
+ ...TelemetryEnvelopeProps,
1522
+ $insert_id: Schema.String,
1523
+ organization_id: OrgIdTelemetrySchema,
1524
+ attempt_number: AttemptNumberSchema,
1525
+ duration_ms: DurationMsSchema,
1526
+ release: Schema.optional(Schema.String.check(Schema.isPattern(/^[0-9a-f]{40}$/u)))
1527
+ });
1528
+ const OrganizationCreationFailedProps = Schema.Struct({
1529
+ ...TelemetryEnvelopeProps,
1530
+ ...ChainCauseTelemetryProps,
1531
+ $insert_id: Schema.String,
1532
+ organization_id: OrgIdTelemetrySchema,
1533
+ attempt_number: AttemptNumberSchema,
1534
+ stage: OnboardingStageSchema,
1535
+ error_code: Schema.String,
1536
+ retryable: Schema.Boolean,
1537
+ release: Schema.optional(Schema.String.check(Schema.isPattern(/^[0-9a-f]{40}$/u))),
1538
+ /** #1655: the SDK's backoff before this attempt. Absent on the first attempt. */
1539
+ backoff_ms: Schema.optional(DurationMsSchema),
1540
+ failure_reason: Schema.optional(Schema.Literals([
1541
+ "receipt_provider_unavailable",
1542
+ "block_provider_unavailable",
1543
+ ...ORGANIZATION_SETUP_REASONS
1544
+ ]))
1545
+ });
1546
+ const OnboardingIntentSchema = Schema.Literals(["personal", "organization"]);
1547
+ const OnboardingIntentSelectedProps = Schema.Struct({
1548
+ ...TelemetryEnvelopeProps,
1549
+ journey_id: Schema.String,
1550
+ intent: OnboardingIntentSchema,
1551
+ entry_point: Schema.String
1552
+ });
1553
+ const OnboardingProfileSubmittedProps = Schema.Struct({
1554
+ ...TelemetryEnvelopeProps,
1555
+ journey_id: Schema.String,
1556
+ intent: OnboardingIntentSchema
1557
+ });
1558
+ const OnboardingOrganizationSubmittedProps = Schema.Struct({
1559
+ ...TelemetryEnvelopeProps,
1560
+ journey_id: Schema.String
1561
+ });
1562
+ const OnboardingDashboardReachedProps = Schema.Struct({
1563
+ ...TelemetryEnvelopeProps,
1564
+ journey_id: Schema.String,
1565
+ intent: OnboardingIntentSchema,
1566
+ organization_id: Schema.optional(OrgIdTelemetrySchema)
1567
+ });
1568
+ const OrgCreateStartedProps = Schema.Struct({
1569
+ ...TelemetryEnvelopeProps,
1570
+ org_id: OptionalOrgId,
1571
+ email_domain: OptionalString,
1572
+ template: OptionalString
1573
+ });
1574
+ const OrgSafeCreatedProps = Schema.Struct({
1575
+ ...TelemetryEnvelopeProps,
1576
+ org_id: OptionalOrgId,
1577
+ chainId: OptionalChainId,
1578
+ safe_address: OptionalAddress
1579
+ });
1580
+ const OrgSafeConfirmedProps = Schema.Struct({
1581
+ ...TelemetryEnvelopeProps,
1582
+ org_id: OptionalOrgId,
1583
+ chainId: OptionalChainId,
1584
+ safe_address: OptionalAddress,
1585
+ durationMs: OptionalDurationMs
1586
+ });
1587
+ const OrgRolesSeededProps = Schema.Struct({
1588
+ ...TelemetryEnvelopeProps,
1589
+ org_id: OptionalOrgId,
1590
+ chainId: OptionalChainId,
1591
+ role: OptionalString,
1592
+ txHash: OptionalTxHash
1593
+ });
1594
+ const OrgCreatedProps = Schema.Struct({
1595
+ ...TelemetryEnvelopeProps,
1596
+ org_id: OptionalOrgId,
1597
+ chainId: OptionalChainId,
1598
+ safe_address: OptionalAddress,
1599
+ durationMs: OptionalDurationMs
1600
+ });
1601
+ const OrgCreateFailedProps = Schema.Struct({
1602
+ ...TelemetryEnvelopeProps,
1603
+ ...ChainCauseTelemetryProps,
1604
+ org_id: OptionalOrgId,
1605
+ reason: OptionalString
1606
+ });
1607
+ const OrgInviteSentProps = Schema.Struct({
1608
+ ...TelemetryEnvelopeProps,
1609
+ org_id: OptionalOrgId,
1610
+ invitation_id: OptionalString,
1611
+ generation: OptionalString,
1612
+ command_id: OptionalString,
1613
+ subject_party_id: OptionalString,
1614
+ persisted_at: OptionalEpochMs,
1615
+ email_domain: OptionalString,
1616
+ role: OptionalString,
1617
+ status: OptionalString
1618
+ });
1619
+ const OrgInviteAcceptedProps = Schema.Struct({
1620
+ ...TelemetryEnvelopeProps,
1621
+ org_id: OptionalOrgId,
1622
+ invitation_id: OptionalString,
1623
+ accepted_at: OptionalEpochMs,
1624
+ generation: OptionalString,
1625
+ command_id: OptionalString,
1626
+ subject_party_id: OptionalString,
1627
+ role: OptionalString,
1628
+ status: OptionalString
1629
+ });
1630
+ const OrgInviteExpiredProps = Schema.Struct({
1631
+ ...TelemetryEnvelopeProps,
1632
+ org_id: OptionalOrgId,
1633
+ email_domain: OptionalString,
1634
+ invitation_id: OptionalString,
1635
+ reason: OptionalString,
1636
+ role: OptionalString,
1637
+ status: OptionalString
1638
+ });
1639
+ const RecipientLocatorKindSchema = Schema.Literals([
1640
+ "handle",
1641
+ "email",
1642
+ "address",
1643
+ "party"
1644
+ ]);
1645
+ const RecipientResolutionStatusSchema = Schema.Literals([
1646
+ "known_party",
1647
+ "new_email",
1648
+ "external_address"
1649
+ ]);
1650
+ const RecipientPartyKindSchema = Schema.Literals([
1651
+ "person",
1652
+ "organization",
1653
+ "unresolved"
1654
+ ]);
1655
+ const RecipientTelemetryProps = {
1656
+ recipient_locator_kind: Schema.optional(RecipientLocatorKindSchema),
1657
+ recipient_resolution_status: Schema.optional(RecipientResolutionStatusSchema),
1658
+ recipient_party_id: OptionalString,
1659
+ recipient_party_kind: Schema.optional(RecipientPartyKindSchema),
1660
+ recipient_is_capxul_account: Schema.optional(Schema.Boolean),
1661
+ recipient_handle: OptionalString,
1662
+ recipient_address: OptionalAddress,
1663
+ external_address_acknowledged: Schema.optional(Schema.Boolean)
1664
+ };
1665
+ const PaymentInitiatedProps = Schema.Struct({
1666
+ command_id: OptionalString,
1667
+ execution_id: OptionalString,
1668
+ payment_lifecycle_id: OptionalString,
1669
+ ...TelemetryEnvelopeProps,
1670
+ ...RecipientTelemetryProps,
1671
+ kind: Schema.String,
1672
+ payment_id: Schema.String
1673
+ });
1674
+ const PaymentLifecycleProps = {
1675
+ payment_state: OptionalString,
1676
+ execution_state: OptionalString,
1677
+ occurred_at: Schema.optional(Schema.Number),
1678
+ causal_sequence: Schema.optional(Schema.Number),
1679
+ sponsorship_valid_until: Schema.optional(Schema.Number),
1680
+ terminal_event_id: OptionalString
1681
+ };
1682
+ const PaymentSettledL2Props = Schema.Struct({
1683
+ ...PaymentLifecycleProps,
1684
+ ...TelemetryEnvelopeProps,
1685
+ ...RecipientTelemetryProps,
1686
+ kind: Schema.String,
1687
+ chain_id: Schema.Number,
1688
+ settlement_id: Schema.String,
1689
+ payment_id: OptionalString,
1690
+ payment_ids: OptionalString,
1691
+ command_id: OptionalString,
1692
+ payment_lifecycle_id: OptionalString,
1693
+ execution_id: OptionalString,
1694
+ user_op_hash: OptionalString,
1695
+ transaction_hash: OptionalString
1696
+ });
1697
+ const PaymentFailedL2Props = Schema.Struct({
1698
+ ...PaymentLifecycleProps,
1699
+ ...TelemetryEnvelopeProps,
1700
+ ...ChainCauseTelemetryProps,
1701
+ ...RecipientTelemetryProps,
1702
+ kind: Schema.String,
1703
+ payment_id: Schema.String,
1704
+ payment_ids: OptionalString,
1705
+ reason_code: Schema.String,
1706
+ command_id: OptionalString,
1707
+ payment_lifecycle_id: OptionalString,
1708
+ execution_id: OptionalString,
1709
+ user_op_hash: OptionalString
1710
+ });
1711
+ const PaymentVerificationRetryProps = Schema.Struct({
1712
+ ...PaymentLifecycleProps,
1713
+ ...TelemetryEnvelopeProps,
1714
+ ...RecipientTelemetryProps,
1715
+ command_id: Schema.String,
1716
+ payment_lifecycle_id: Schema.String,
1717
+ attempt: Schema.Number,
1718
+ reason_code: Schema.String,
1719
+ chain_id: Schema.Number,
1720
+ delay_ms: DurationMsSchema,
1721
+ outcome: Schema.Literals(["scheduled", "unresolved"]),
1722
+ payment_id: OptionalString,
1723
+ payment_ids: OptionalString,
1724
+ execution_id: OptionalString,
1725
+ user_op_hash: OptionalString
1726
+ });
1727
+ const PaymentLifecycleTransitionProps = Schema.Struct({
1728
+ ...TelemetryEnvelopeProps,
1729
+ ...RecipientTelemetryProps,
1730
+ payment_id: Schema.String,
1731
+ payment_lifecycle_id: Schema.String,
1732
+ command_id: Schema.String,
1733
+ payment_state: Schema.String,
1734
+ occurred_at: Schema.Number,
1735
+ causal_sequence: Schema.Number,
1736
+ execution_id: OptionalString,
1737
+ execution_state: OptionalString,
1738
+ user_op_hash: OptionalString,
1739
+ sponsorship_valid_until: Schema.optional(Schema.Number),
1740
+ reason_code: OptionalString
1741
+ });
1742
+ const QuickPayExternalAddressAcknowledgedProps = Schema.Struct({
1743
+ ...TelemetryEnvelopeProps,
1744
+ recipient_locator_kind: Schema.Literal("address"),
1745
+ recipient_resolution_status: Schema.Literal("external_address"),
1746
+ recipient_address: AddressSchema,
1747
+ external_address_acknowledged: Schema.Literal(true),
1748
+ organization_id: OptionalOrgId
1749
+ });
1750
+ const DepositInitiatedProps = Schema.Struct({
1751
+ ...TelemetryEnvelopeProps,
1752
+ scope_kind: Schema.optional(Schema.Literals(["account", "organization"])),
1753
+ account_kind: Schema.optional(Schema.Literals(["personalSafe", "orgTreasury"])),
1754
+ chain_id: Schema.optional(Schema.Number),
1755
+ network: Schema.optional(Schema.Literal("base-sepolia")),
1756
+ organization_id: OptionalOrgId,
1757
+ $groups: Schema.optional(Schema.Struct({ organization: OptionalOrgId })),
1758
+ actor_id: OptionalString,
1759
+ actor_kind: Schema.optional(Schema.Literal("authenticated")),
1760
+ distinct_id: OptionalString,
1761
+ trace_id: OptionalString,
1762
+ span_id: OptionalString
1763
+ });
1764
+ const DepositSettledProps = Schema.Struct({
1765
+ ...TelemetryEnvelopeProps,
1766
+ chain_id: Schema.Number,
1767
+ tx_hash: Schema.String,
1768
+ log_index: Schema.Number
1769
+ });
1770
+ const PermissionMirrorVerificationProps = Schema.Struct({
1771
+ ...TelemetryEnvelopeProps,
1772
+ /** The RECEIPT verification outcome. What the mirror then did is separate. */
1773
+ outcome: Schema.String,
1774
+ reason: Schema.String,
1775
+ chain_id: Schema.Number,
1776
+ retry_count: Schema.Number,
1777
+ /**
1778
+ * #1960 R02, consumed by R03. A verified receipt is not an applied Permission:
1779
+ * these two optional fields let the producer say what the applying mutation
1780
+ * actually returned, and which command it was, without either fact rewriting
1781
+ * the receipt outcome above. Absent when application has not happened yet.
1782
+ */
1783
+ application_result: Schema.optional(Schema.Literals([
1784
+ "applied",
1785
+ "replayed",
1786
+ "conflicting_replay",
1787
+ "revision_mismatch",
1788
+ "cleanup_required",
1789
+ "not_applied",
1790
+ "application_failure",
1791
+ "mismatch",
1792
+ "refused"
1793
+ ])),
1794
+ command_kind: Schema.optional(Schema.Literals(["invitation_configuration", "invitation_eoa"])),
1795
+ command_id: OptionalString,
1796
+ invitation_id: OptionalString,
1797
+ generation: OptionalString,
1798
+ purpose: Schema.optional(Schema.Literals([
1799
+ "configure",
1800
+ "grant",
1801
+ "disable",
1802
+ "compensate"
1803
+ ])),
1804
+ $insert_id: OptionalString,
1805
+ /**
1806
+ * #1961 R03. The authorized stored row names the Permission it changed; the
1807
+ * verified receipt names the chain facts that prove it. Every field is
1808
+ * optional because a pending or provider-failed verification has neither an
1809
+ * application result nor a receipt to report.
1810
+ */
1811
+ permission_id: OptionalString,
1812
+ permission_assignment_id: OptionalString,
1813
+ permission_operation: Schema.optional(Schema.Literals([
1814
+ "create",
1815
+ "change",
1816
+ "assign",
1817
+ "revoke",
1818
+ "replace"
1819
+ ])),
1820
+ revision: Schema.optional(Schema.Number),
1821
+ user_op_hash: OptionalString,
1822
+ transaction_hash: OptionalString,
1823
+ block_number: Schema.optional(Schema.Number),
1824
+ log_index: Schema.optional(Schema.Number)
1825
+ });
1826
+ const MovementScanWindowProps = Schema.Struct({
1827
+ ...TelemetryEnvelopeProps,
1828
+ chain_id: Schema.Number,
1829
+ token_address: Schema.String,
1830
+ from_block: Schema.Number,
1831
+ to_block: Schema.Number,
1832
+ log_count: Schema.Number,
1833
+ request_count: Schema.Number,
1834
+ outcome: Schema.String
1835
+ });
1836
+ const MovementScanCheckpointProps = Schema.Struct({
1837
+ ...TelemetryEnvelopeProps,
1838
+ chain_id: Schema.Number,
1839
+ token_address: Schema.String,
1840
+ next_block: Schema.Number,
1841
+ anchor_block_number: Schema.Number
1842
+ });
1843
+ const MovementScanIncidentProps = Schema.Struct({
1844
+ ...TelemetryEnvelopeProps,
1845
+ chain_id: Schema.Number,
1846
+ token_address: Schema.String,
1847
+ incident_kind: Schema.String,
1848
+ anchor_block_number: Schema.Number
1849
+ });
1850
+ /**
1851
+ * One durable row the reconciliation job corrected against Ponder (SPEC D9).
1852
+ *
1853
+ * Both block fields are optional and for the same reason: a correction INTO
1854
+ * drift (a Payment settled in Convex whose Ponder fact a reorg removed) has no
1855
+ * current block, and a correction that confirms a later fact has one.
1856
+ *
1857
+ * `projection_kind` is closed. A later ticket that reconciles a deploy, a
1858
+ * bootstrap or a grant outcome adds its kind here in the same change; an
1859
+ * unknown kind must not decode.
1860
+ */
1861
+ const IndexerDriftCorrectedProps = Schema.Struct({
1862
+ ...TelemetryEnvelopeProps,
1863
+ projection_kind: Schema.Literals([
1864
+ "member_authority",
1865
+ "payment_settlement",
1866
+ "permission_assignment"
1867
+ ]),
1868
+ previous_state: Schema.String,
1869
+ current_state: Schema.String,
1870
+ previous_block: Schema.optional(Schema.Number),
1871
+ current_block: Schema.optional(Schema.Number),
1872
+ logical_event_id: Schema.optional(Schema.String),
1873
+ scope_kind: Schema.optional(Schema.Literals(["account", "organization"])),
1874
+ account_id: OptionalAccountId,
1875
+ reference_id: OptionalString
1876
+ });
1877
+ const AuthOtpRequestedTelemetryEventSchema = Schema.Struct({
1878
+ name: Schema.Literal("auth_otp_requested"),
1879
+ props: AuthOtpRequestedProps
1880
+ });
1881
+ const AuthOtpDeliveredTelemetryEventSchema = Schema.Struct({
1882
+ name: Schema.Literal("auth_otp_delivered"),
1883
+ props: AuthOtpDeliveredProps
1884
+ });
1885
+ const AuthOtpExpiredTelemetryEventSchema = Schema.Struct({
1886
+ name: Schema.Literal("auth_otp_expired"),
1887
+ props: AuthOtpExpiredProps
1888
+ });
1889
+ const AuthVerifiedTelemetryEventSchema = Schema.Struct({
1890
+ name: Schema.Literal("auth_verified"),
1891
+ props: AuthVerifiedProps
1892
+ });
1893
+ const AuthFailedTelemetryEventSchema = Schema.Struct({
1894
+ name: Schema.Literal("auth_failed"),
1895
+ props: AuthFailedProps
1896
+ });
1897
+ const IdentityRefusedTelemetryEventSchema = Schema.Struct({
1898
+ name: Schema.Literal("identity_refused"),
1899
+ props: IdentityRefusedProps
1900
+ });
1901
+ const AuthSignedOutTelemetryEventSchema = Schema.Struct({
1902
+ name: Schema.Literal("auth_signed_out"),
1903
+ props: AuthSignedOutProps
1904
+ });
1905
+ const NativeAuthorizationStartedTelemetryEventSchema = Schema.Struct({
1906
+ name: Schema.Literal("native_authorization_started"),
1907
+ props: NativeAuthorizationStartedProps
1908
+ });
1909
+ const NativeAuthorizationReviewedTelemetryEventSchema = Schema.Struct({
1910
+ name: Schema.Literal("native_authorization_reviewed"),
1911
+ props: NativeAuthorizationReviewedProps
1912
+ });
1913
+ const NativeAuthorizationAcceptedTelemetryEventSchema = Schema.Struct({
1914
+ name: Schema.Literal("native_authorization_accepted"),
1915
+ props: NativeAuthorizationAcceptedProps
1916
+ });
1917
+ const NativeAuthorizationDeniedTelemetryEventSchema = Schema.Struct({
1918
+ name: Schema.Literal("native_authorization_denied"),
1919
+ props: NativeAuthorizationDeniedProps
1920
+ });
1921
+ const NativeAuthorizationConnectedTelemetryEventSchema = Schema.Struct({
1922
+ name: Schema.Literal("native_authorization_connected"),
1923
+ props: NativeAuthorizationConnectedProps
1924
+ });
1925
+ const NativeAuthorizationFailedTelemetryEventSchema = Schema.Struct({
1926
+ name: Schema.Literal("native_authorization_failed"),
1927
+ props: NativeAuthorizationFailedProps
1928
+ });
1929
+ const OnboardingIntentSelectedTelemetryEventSchema = Schema.Struct({
1930
+ name: Schema.Literal("onboarding_intent_selected"),
1931
+ props: OnboardingIntentSelectedProps
1932
+ });
1933
+ const OnboardingProfileSubmittedTelemetryEventSchema = Schema.Struct({
1934
+ name: Schema.Literal("onboarding_profile_submitted"),
1935
+ props: OnboardingProfileSubmittedProps
1936
+ });
1937
+ const OnboardingOrganizationSubmittedTelemetryEventSchema = Schema.Struct({
1938
+ name: Schema.Literal("onboarding_organization_submitted"),
1939
+ props: OnboardingOrganizationSubmittedProps
1940
+ });
1941
+ const OnboardingDashboardReachedTelemetryEventSchema = Schema.Struct({
1942
+ name: Schema.Literal("onboarding_dashboard_reached"),
1943
+ props: OnboardingDashboardReachedProps
1944
+ });
1945
+ const ProvisioningSafeCreatedTelemetryEventSchema = Schema.Struct({
1946
+ name: Schema.Literal("provisioning_safe_created"),
1947
+ props: ProvisioningSafeCreatedProps
1948
+ });
1949
+ const ProvisioningSafeConfirmedTelemetryEventSchema = Schema.Struct({
1950
+ name: Schema.Literal("provisioning_safe_confirmed"),
1951
+ props: ProvisioningSafeConfirmedProps
1952
+ });
1953
+ const BootstrapResolvedTelemetryEventSchema = Schema.Struct({
1954
+ name: Schema.Literal("bootstrap_resolved"),
1955
+ props: BootstrapResolvedProps
1956
+ });
1957
+ const BootstrapFailedTelemetryEventSchema = Schema.Struct({
1958
+ name: Schema.Literal("bootstrap_failed"),
1959
+ props: BootstrapFailedProps
1960
+ });
1961
+ const MemberActivationStartedTelemetryEventSchema = Schema.Struct({
1962
+ name: Schema.Literal("member_activation_started"),
1963
+ props: MemberActivationStartedProps
1964
+ });
1965
+ const MemberActivationReadyTelemetryEventSchema = Schema.Struct({
1966
+ name: Schema.Literal("member_activation_ready"),
1967
+ props: MemberActivationReadyProps
1968
+ });
1969
+ const MemberActivationFailedTelemetryEventSchema = Schema.Struct({
1970
+ name: Schema.Literal("member_activation_failed"),
1971
+ props: MemberActivationFailedProps
1972
+ });
1973
+ const OrganizationCreationStartedTelemetryEventSchema = Schema.Struct({
1974
+ name: Schema.Literal("organization_creation_started"),
1975
+ props: OrganizationCreationStartedProps
1976
+ });
1977
+ const OrganizationCreationReadyTelemetryEventSchema = Schema.Struct({
1978
+ name: Schema.Literal("organization_creation_ready"),
1979
+ props: OrganizationCreationReadyProps
1980
+ });
1981
+ const OrganizationCreationFailedTelemetryEventSchema = Schema.Struct({
1982
+ name: Schema.Literal("organization_creation_failed"),
1983
+ props: OrganizationCreationFailedProps
1984
+ });
1985
+ const AccountBalanceReadTelemetryEventSchema = Schema.Struct({
1986
+ name: Schema.Literal("account_balance_read"),
1987
+ props: AccountBalanceReadProps
1988
+ });
1989
+ const AccountBalanceFailedTelemetryEventSchema = Schema.Struct({
1990
+ name: Schema.Literal("account_balance_failed"),
1991
+ props: AccountBalanceFailedProps
1992
+ });
1993
+ const FaucetRequestedTelemetryEventSchema = Schema.Struct({
1994
+ name: Schema.Literal("faucet_requested"),
1995
+ props: FaucetRequestedProps
1996
+ });
1997
+ const FaucetConfirmedTelemetryEventSchema = Schema.Struct({
1998
+ name: Schema.Literal("faucet_confirmed"),
1999
+ props: FaucetConfirmedProps
2000
+ });
2001
+ const FaucetFailedTelemetryEventSchema = Schema.Struct({
2002
+ name: Schema.Literal("faucet_failed"),
2003
+ props: FaucetFailedProps
2004
+ });
2005
+ const ChainUpstreamFallbackTelemetryEventSchema = Schema.Struct({
2006
+ name: Schema.Literal("chain_upstream_fallback"),
2007
+ props: ChainUpstreamFallbackProps
2008
+ });
2009
+ const BundlerErrorTelemetryEventSchema = Schema.Struct({
2010
+ name: Schema.Literal("bundler_error"),
2011
+ props: BundlerErrorProps
2012
+ });
2013
+ const ReceiptPendingTelemetryEventSchema = Schema.Struct({
2014
+ name: Schema.Literal("receipt_pending"),
2015
+ props: ReceiptPendingProps
2016
+ });
2017
+ const OperationRetriedTelemetryEventSchema = Schema.Struct({
2018
+ name: Schema.Literal("operation_retried"),
2019
+ props: OperationRetriedProps
2020
+ });
2021
+ const OrgCreateStartedTelemetryEventSchema = Schema.Struct({
2022
+ name: Schema.Literal("org_create_started"),
2023
+ props: OrgCreateStartedProps
2024
+ });
2025
+ const OrgSafeCreatedTelemetryEventSchema = Schema.Struct({
2026
+ name: Schema.Literal("org_safe_created"),
2027
+ props: OrgSafeCreatedProps
2028
+ });
2029
+ const OrgSafeConfirmedTelemetryEventSchema = Schema.Struct({
2030
+ name: Schema.Literal("org_safe_confirmed"),
2031
+ props: OrgSafeConfirmedProps
2032
+ });
2033
+ const OrgRolesSeededTelemetryEventSchema = Schema.Struct({
2034
+ name: Schema.Literal("org_roles_seeded"),
2035
+ props: OrgRolesSeededProps
2036
+ });
2037
+ const OrgCreatedTelemetryEventSchema = Schema.Struct({
2038
+ name: Schema.Literal("org_created"),
2039
+ props: OrgCreatedProps
2040
+ });
2041
+ const OrgCreateFailedTelemetryEventSchema = Schema.Struct({
2042
+ name: Schema.Literal("org_create_failed"),
2043
+ props: OrgCreateFailedProps
2044
+ });
2045
+ const OrgInviteSentTelemetryEventSchema = Schema.Struct({
2046
+ name: Schema.Literal("org_invite_sent"),
2047
+ props: OrgInviteSentProps
2048
+ });
2049
+ const OrgInviteAcceptedTelemetryEventSchema = Schema.Struct({
2050
+ name: Schema.Literal("org_invite_accepted"),
2051
+ props: OrgInviteAcceptedProps
2052
+ });
2053
+ const OrgInviteExpiredTelemetryEventSchema = Schema.Struct({
2054
+ name: Schema.Literal("org_invite_expired"),
2055
+ props: OrgInviteExpiredProps
2056
+ });
2057
+ const PaymentInitiatedTelemetryEventSchema = Schema.Struct({
2058
+ name: Schema.Literal("payment_initiated"),
2059
+ props: PaymentInitiatedProps
2060
+ });
2061
+ const PaymentSettledTelemetryEventSchema = Schema.Struct({
2062
+ name: Schema.Literal("payment_settled"),
2063
+ props: PaymentSettledL2Props
2064
+ });
2065
+ const PaymentFailedTelemetryEventSchema = Schema.Struct({
2066
+ name: Schema.Literal("payment_failed"),
2067
+ props: PaymentFailedL2Props
2068
+ });
2069
+ const PaymentVerificationRetryTelemetryEventSchema = Schema.Struct({
2070
+ name: Schema.Literal("payment_verification_retry"),
2071
+ props: PaymentVerificationRetryProps
2072
+ });
2073
+ const PaymentLifecycleTransitionTelemetryEventSchema = Schema.Struct({
2074
+ name: Schema.Literal("payment_lifecycle_transition"),
2075
+ props: PaymentLifecycleTransitionProps
2076
+ });
2077
+ const QuickPayExternalAddressAcknowledgedTelemetryEventSchema = Schema.Struct({
2078
+ name: Schema.Literal("quick_pay_external_address_acknowledged"),
2079
+ props: QuickPayExternalAddressAcknowledgedProps
2080
+ });
2081
+ const DepositInitiatedTelemetryEventSchema = Schema.Struct({
2082
+ name: Schema.Literal("deposit_initiated"),
2083
+ props: DepositInitiatedProps
2084
+ });
2085
+ const DepositSettledTelemetryEventSchema = Schema.Struct({
2086
+ name: Schema.Literal("deposit_settled"),
2087
+ props: DepositSettledProps
2088
+ });
2089
+ const PermissionMirrorVerificationTelemetryEventSchema = Schema.Struct({
2090
+ name: Schema.Literal("permission_mirror_verification"),
2091
+ props: PermissionMirrorVerificationProps
2092
+ });
2093
+ const MovementScanWindowTelemetryEventSchema = Schema.Struct({
2094
+ name: Schema.Literal("movement_scan_window"),
2095
+ props: MovementScanWindowProps
2096
+ });
2097
+ const MovementScanCheckpointTelemetryEventSchema = Schema.Struct({
2098
+ name: Schema.Literal("movement_scan_checkpoint"),
2099
+ props: MovementScanCheckpointProps
2100
+ });
2101
+ const MovementScanIncidentTelemetryEventSchema = Schema.Struct({
2102
+ name: Schema.Literal("movement_scan_incident"),
2103
+ props: MovementScanIncidentProps
2104
+ });
2105
+ const IndexerDriftCorrectedTelemetryEventSchema = Schema.Struct({
2106
+ name: Schema.Literal("indexer_drift_corrected"),
2107
+ props: IndexerDriftCorrectedProps
2108
+ });
2109
+ /** The one spelling of "whose scope did this happen in" across every surface. */
2110
+ const ScopeKindSchema = Schema.Literals(["account", "organization"]);
2111
+ const OptionalReasonCode = Schema.optional(Schema.Literals(CAPXUL_ERROR_CODES));
2112
+ const ActivityReferenceProps = {
2113
+ reference_kind: Schema.Literals(["payment", "movement"]),
2114
+ reference_id: Schema.String
2115
+ };
2116
+ const ActivityFilterProps = {
2117
+ filter_kind: Schema.optional(Schema.Literals([
2118
+ "all",
2119
+ "payment",
2120
+ "movement"
2121
+ ])),
2122
+ filter_direction: Schema.optional(Schema.Literals([
2123
+ "all",
2124
+ "in",
2125
+ "out",
2126
+ "self"
2127
+ ])),
2128
+ filter_status: Schema.optional(Schema.Array(Schema.Literals([
2129
+ "pending",
2130
+ "settling",
2131
+ "unresolved",
2132
+ "pending_claim",
2133
+ "scheduled",
2134
+ "streaming",
2135
+ "settled",
2136
+ "cancelled",
2137
+ "failed"
2138
+ ])))
2139
+ };
2140
+ const ActivityActionProps = {
2141
+ ...TelemetryEnvelopeProps,
2142
+ scope_kind: ScopeKindSchema,
2143
+ reason_code: OptionalReasonCode
2144
+ };
2145
+ const ContactRelationshipChangedTelemetryEventSchema = Schema.Struct({
2146
+ name: Schema.Literal("contact_relationship_changed"),
2147
+ props: Schema.Struct({
2148
+ ...TelemetryEnvelopeProps,
2149
+ change: Schema.Literals([
2150
+ "added",
2151
+ "renamed",
2152
+ "hidden",
2153
+ "restored"
2154
+ ]),
2155
+ scope_kind: ScopeKindSchema,
2156
+ scope_id: Schema.String,
2157
+ owner_party_id: Schema.String,
2158
+ party_id: Schema.String,
2159
+ hidden: Schema.Boolean,
2160
+ occurred_at: Schema.Number,
2161
+ operation: Schema.Literals([
2162
+ CAPXUL_OPERATIONS.addressBook.add,
2163
+ CAPXUL_OPERATIONS.addressBook.label,
2164
+ CAPXUL_OPERATIONS.addressBook.hide,
2165
+ CAPXUL_OPERATIONS.addressBook.unhide
2166
+ ])
2167
+ })
2168
+ });
2169
+ const ContactActionProps = {
2170
+ ...TelemetryEnvelopeProps,
2171
+ scope_kind: ScopeKindSchema,
2172
+ party_id: OptionalString,
2173
+ reason_code: OptionalReasonCode
2174
+ };
2175
+ /** One completed online CLI diagnostic. No command input or provider text. */
2176
+ const CLI_COMMAND_NAMES = [
2177
+ "capxul",
2178
+ "doctor",
2179
+ "telemetry",
2180
+ "telemetry.status",
2181
+ "telemetry.enable",
2182
+ "telemetry.disable",
2183
+ "auth",
2184
+ "auth.login",
2185
+ "auth.signup",
2186
+ "auth.send",
2187
+ "auth.verify",
2188
+ "auth.profile",
2189
+ "auth.status",
2190
+ "auth.logout",
2191
+ "contact",
2192
+ "contact.list",
2193
+ "contact.get",
2194
+ "contact.add",
2195
+ "contact.label",
2196
+ "contact.hide",
2197
+ "contact.unhide",
2198
+ "org",
2199
+ CAPXUL_OPERATIONS.org.list,
2200
+ "org.use",
2201
+ "org.status",
2202
+ CAPXUL_OPERATIONS.org.me,
2203
+ CAPXUL_OPERATIONS.org.members,
2204
+ "org.member",
2205
+ "org.member.get",
2206
+ "org.member.invite",
2207
+ "org.contact",
2208
+ "org.contact.list",
2209
+ "org.contact.get",
2210
+ "org.contact.add",
2211
+ "org.contact.label",
2212
+ "org.contact.hide",
2213
+ "org.contact.unhide",
2214
+ CAPXUL_OPERATIONS.org.invite,
2215
+ "org.invite.list",
2216
+ "org.invite.get",
2217
+ "org.invite.wait",
2218
+ "org.invite.review",
2219
+ "org.invite.accept",
2220
+ "org.invite.decline",
2221
+ "org.invite.cancel",
2222
+ "org.invite.resend",
2223
+ "org.invite.retry",
2224
+ "org.wait",
2225
+ CAPXUL_OPERATIONS.org.create,
2226
+ CAPXUL_OPERATIONS.org.retry,
2227
+ "unknown"
2228
+ ];
2229
+ const CLI_CAPABILITIES = [
2230
+ "cli",
2231
+ "diagnostics",
2232
+ "collection",
2233
+ "authentication",
2234
+ "organization",
2235
+ "contacts"
2236
+ ];
2237
+ const CLI_INVOCATION_KINDS = [
2238
+ "command",
2239
+ "help",
2240
+ "version",
2241
+ "completion",
2242
+ "parse_refusal",
2243
+ "collection_control"
2244
+ ];
2245
+ const CliRelease = Schema.String.check(Schema.isPattern(/^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/u));
2246
+ const CliInvocationProps = {
2247
+ ...TelemetryEnvelopeProps,
2248
+ schema_version: Schema.Literal(1),
2249
+ command: Schema.Literals(CLI_COMMAND_NAMES),
2250
+ capability: Schema.Literals(CLI_CAPABILITIES),
2251
+ invocation_kind: Schema.Literals(CLI_INVOCATION_KINDS),
2252
+ invocation_id: Schema.String.check(Schema.isPattern(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u)),
2253
+ cli_identity_kind: Schema.optional(Schema.Literals(["anonymous", "identified"])),
2254
+ anonymous_id: Schema.optional(Schema.String.check(Schema.isPattern(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u))),
2255
+ auth_user_id: Schema.optional(Schema.String.check(Schema.isPattern(/^[^\s]{1,256}$/u))),
2256
+ occurred_at: Schema.Number,
2257
+ cli_version: CliRelease,
2258
+ sdk_version: CliRelease,
2259
+ release: CliRelease,
2260
+ platform: Schema.Literals([
2261
+ "darwin",
2262
+ "linux",
2263
+ "unknown"
2264
+ ]),
2265
+ architecture: Schema.Literals([
2266
+ "arm64",
2267
+ "x64",
2268
+ "unknown"
2269
+ ]),
2270
+ ci: Schema.Boolean,
2271
+ tty: Schema.Boolean,
2272
+ output_mode: Schema.Literals(["human", "json"])
2273
+ };
2274
+ const CliFirstUsedTelemetryEventSchema = Schema.Struct({
2275
+ name: Schema.Literal("cli_first_used"),
2276
+ props: Schema.Struct(CliInvocationProps)
2277
+ });
2278
+ const CliCommandStartedTelemetryEventSchema = Schema.Struct({
2279
+ name: Schema.Literal("cli_command_started"),
2280
+ props: Schema.Struct({
2281
+ ...CliInvocationProps,
2282
+ invocation_kind: Schema.Literals([
2283
+ "command",
2284
+ "help",
2285
+ "version"
2286
+ ])
2287
+ })
2288
+ });
2289
+ const CliCommandCompletedTelemetryEventSchema = Schema.Struct({
2290
+ name: Schema.Literal("cli_command_completed"),
2291
+ props: Schema.Struct({
2292
+ ...CliInvocationProps,
2293
+ outcome: Schema.Literals([
2294
+ "succeeded",
2295
+ "refused",
2296
+ "failed",
2297
+ "cancelled"
2298
+ ]),
2299
+ duration_ms: Schema.Number,
2300
+ organization_id: Schema.optional(OrgIdTelemetrySchema),
2301
+ setup_status: Schema.optional(Schema.Literals(ORGANIZATION_SETUP_STATUSES)),
2302
+ setup_reason: Schema.optional(Schema.Literals(ORGANIZATION_SETUP_REASONS)),
2303
+ $groups: Schema.optional(Schema.Struct({ organization: OrgIdTelemetrySchema })),
2304
+ error_code: Schema.optional(Schema.Literals([
2305
+ ...CAPXUL_ERROR_CODES,
2306
+ "CLI_USAGE",
2307
+ "CLI_CONFIG",
2308
+ "CLI_STORAGE",
2309
+ "CLI_DEFECT",
2310
+ "CLI_DEADLINE"
2311
+ ]))
2312
+ })
2313
+ });
2314
+ const CliDiagnosticCompletedTelemetryEventSchema = Schema.Struct({
2315
+ name: Schema.Literal("cli_diagnostic_completed"),
2316
+ props: Schema.Struct({
2317
+ ...TelemetryEnvelopeProps,
2318
+ outcome: Schema.Literals([
2319
+ "succeeded",
2320
+ "refused",
2321
+ "failed",
2322
+ "cancelled"
2323
+ ]),
2324
+ invocation_id: Schema.String.check(Schema.isPattern(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u)),
2325
+ cli_version: Schema.String.check(Schema.isPattern(/^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/u))
2326
+ })
2327
+ });
2328
+ const UiContactActionCompletedTelemetryEventSchema = Schema.Struct({
2329
+ name: Schema.Literal("ui_contact_action_completed"),
2330
+ props: Schema.Union([
2331
+ Schema.Struct({
2332
+ ...ContactActionProps,
2333
+ action: Schema.Literal("add"),
2334
+ outcome: Schema.Literals(["opened", "cancelled"])
2335
+ }),
2336
+ Schema.Struct({
2337
+ ...ContactActionProps,
2338
+ action: Schema.Literal("refusal"),
2339
+ outcome: Schema.Literal("displayed")
2340
+ }),
2341
+ Schema.Struct({
2342
+ ...ContactActionProps,
2343
+ action: Schema.Literal("retry"),
2344
+ outcome: Schema.Literal("requested")
2345
+ })
2346
+ ])
2347
+ });
2348
+ const ActivityAnnotationSavedTelemetryEventSchema = Schema.Struct({
2349
+ name: Schema.Literal("activity_annotation_saved"),
2350
+ props: Schema.Struct({
2351
+ ...TelemetryEnvelopeProps,
2352
+ ...ActivityReferenceProps,
2353
+ scope_kind: ScopeKindSchema,
2354
+ scope_id: Schema.String,
2355
+ occurred_at: Schema.Number
2356
+ })
2357
+ });
2358
+ const UiActivityActionCompletedTelemetryEventSchema = Schema.Struct({
2359
+ name: Schema.Literal("ui_activity_action_completed"),
2360
+ props: Schema.Union([
2361
+ Schema.Struct({
2362
+ ...ActivityActionProps,
2363
+ action: Schema.Literal("read"),
2364
+ outcome: Schema.Literals(["partial_displayed", "recovered"]),
2365
+ surface: Schema.Literals([
2366
+ "transactions",
2367
+ "recent",
2368
+ "summary"
2369
+ ])
2370
+ }),
2371
+ Schema.Struct({
2372
+ ...ActivityActionProps,
2373
+ ...ActivityFilterProps,
2374
+ action: Schema.Literal("filter"),
2375
+ outcome: Schema.Literal("committed")
2376
+ }),
2377
+ Schema.Struct({
2378
+ ...ActivityActionProps,
2379
+ action: Schema.Literal("refusal"),
2380
+ outcome: Schema.Literal("displayed")
2381
+ }),
2382
+ Schema.Struct({
2383
+ ...ActivityActionProps,
2384
+ action: Schema.Literal("retry"),
2385
+ outcome: Schema.Literal("requested")
2386
+ }),
2387
+ Schema.Struct({
2388
+ ...ActivityActionProps,
2389
+ ...ActivityReferenceProps,
2390
+ action: Schema.Literal("detail"),
2391
+ outcome: Schema.Literals(["opened", "failed"])
2392
+ }),
2393
+ Schema.Struct({
2394
+ ...ActivityActionProps,
2395
+ ...ActivityReferenceProps,
2396
+ action: Schema.Literal("receipt"),
2397
+ outcome: Schema.Literals([
2398
+ "document_rendered",
2399
+ "explorer_opened",
2400
+ "popup_blocked",
2401
+ "failed"
2402
+ ])
2403
+ }),
2404
+ Schema.Struct({
2405
+ ...ActivityActionProps,
2406
+ ...ActivityFilterProps,
2407
+ action: Schema.Literal("export"),
2408
+ outcome: Schema.Literals([
2409
+ "completed",
2410
+ "partial",
2411
+ "failed"
2412
+ ]),
2413
+ row_count: Schema.optional(Schema.Number),
2414
+ truncated: Schema.optional(Schema.Boolean)
2415
+ })
2416
+ ])
2417
+ });
2418
+ /**
2419
+ * Reliability closeout (#1960 R02) — the shape every explicit UI observation
2420
+ * below shares. `scope_kind` says whose surface the person was looking at,
2421
+ * `organization_id` is the verified Organization the producer resolved (absent
2422
+ * on a personal action), and `reason_code` is a catalog error code, never copy.
2423
+ */
2424
+ const UiStepProps = {
2425
+ ...TelemetryEnvelopeProps,
2426
+ scope_kind: ScopeKindSchema,
2427
+ organization_id: OptionalOrgId,
2428
+ reason_code: OptionalReasonCode
2429
+ };
2430
+ const AccessRecoveryCompletedProps = Schema.Union([Schema.Struct({
2431
+ ...TelemetryEnvelopeProps,
2432
+ recovery: Schema.Literal("session_restoration"),
2433
+ outcome: Schema.Literals([
2434
+ "restored",
2435
+ "absent",
2436
+ "failed"
2437
+ ]),
2438
+ reason_code: OptionalReasonCode,
2439
+ organization_id: OptionalOrgId
2440
+ }), Schema.Struct({
2441
+ ...TelemetryEnvelopeProps,
2442
+ recovery: Schema.Literal("signer_readiness"),
2443
+ outcome: Schema.Literals(["ready", "unavailable"]),
2444
+ reason_code: OptionalReasonCode,
2445
+ organization_id: OptionalOrgId
2446
+ })]);
2447
+ const AccessRecoveryCompletedTelemetryEventSchema = Schema.Struct({
2448
+ name: Schema.Literal("access_recovery_completed"),
2449
+ props: AccessRecoveryCompletedProps
2450
+ });
2451
+ /**
2452
+ * R05 (#1963) wired three of these steps at the app's dashboard Access
2453
+ * boundary: `dashboard_granted` on the commit of the granted content,
2454
+ * `gate_error_displayed` on the mounted error surface, and `retry_selected` on
2455
+ * the actual selection. `redirect_completed` stays RESERVED and unproduced —
2456
+ * asking for a navigation is not arriving, and the destination page's own
2457
+ * normalized pageview already carries the arrival on the same journey, so a
2458
+ * second event would add no fact. `capability_refusal_displayed` and
2459
+ * `signer_refusal_displayed` belong to the screens that draw those refusals
2460
+ * (Recipients, Invoice, Payroll, Quick Pay); Access publishes the contract and
2461
+ * the `CanReason` those owners report, and produces neither itself.
2462
+ */
2463
+ const UiAccessStepCompletedTelemetryEventSchema = Schema.Struct({
2464
+ name: Schema.Literal("ui_access_step_completed"),
2465
+ props: Schema.Struct({
2466
+ ...UiStepProps,
2467
+ step: Schema.Literals([
2468
+ "dashboard_granted",
2469
+ "redirect_completed",
2470
+ "gate_error_displayed",
2471
+ "retry_selected",
2472
+ "capability_refusal_displayed",
2473
+ "signer_refusal_displayed"
2474
+ ]),
2475
+ capability: Schema.optional(Schema.Literals(["spend", "managePeople"])),
2476
+ probe: Schema.optional(Schema.Literals([
2477
+ "session",
2478
+ "membership",
2479
+ "lifecycle"
2480
+ ])),
2481
+ reason: Schema.optional(Schema.Literals([
2482
+ "loading",
2483
+ "no-permission",
2484
+ "org-unavailable"
2485
+ ]))
2486
+ })
2487
+ });
2488
+ /**
2489
+ * R06 (#1964) wired three of the four progress words to the durable writer that
2490
+ * commits each one. `account_ready` comes from `org/memberLifecycle.ts`, for
2491
+ * every membership row a claimed personal Account actually advanced.
2492
+ * `permission_applied` and `membership_activated` come from
2493
+ * `permission/mirror.ts`: the first only when the mirror wrote a NEW Permission
2494
+ * state, the second only when that call flipped a `pending_grant` row to
2495
+ * `active`. A replay of an applied command writes neither, so it reports
2496
+ * neither. `revoked` stays RESERVED and unproduced — no writer revokes a
2497
+ * membership yet, and #1459 owns that ceremony.
2498
+ */
2499
+ const OrgInviteProgressedTelemetryEventSchema = Schema.Struct({
2500
+ name: Schema.Literal("org_invite_progressed"),
2501
+ props: Schema.Struct({
2502
+ ...TelemetryEnvelopeProps,
2503
+ organization_id: OrgIdTelemetrySchema,
2504
+ progress: Schema.Literals([
2505
+ "configuration_authorized",
2506
+ "account_ready",
2507
+ "permission_applied",
2508
+ "membership_activated",
2509
+ "revoked"
2510
+ ]),
2511
+ /** The invited Party. The initiating actor stays on the envelope's identity. */
2512
+ member_party_id: Schema.String,
2513
+ invitation_id: Schema.optional(Schema.String),
2514
+ generation: Schema.optional(Schema.String),
2515
+ command_id: Schema.optional(Schema.String),
2516
+ occurred_at: Schema.Number
2517
+ })
2518
+ });
2519
+ const InvoiceIssuedTelemetryEventSchema = Schema.Struct({
2520
+ name: Schema.Literal("invoice_issued"),
2521
+ props: Schema.Struct({
2522
+ ...TelemetryEnvelopeProps,
2523
+ request_id: Schema.String,
2524
+ issuer_scope_kind: ScopeKindSchema,
2525
+ issuer_scope_id: Schema.String,
2526
+ payer_party_id: OptionalString,
2527
+ occurred_at: Schema.Number
2528
+ })
2529
+ });
2530
+ const InvoiceRequestTransitionedTelemetryEventSchema = Schema.Struct({
2531
+ name: Schema.Literal("invoice_request_transitioned"),
2532
+ props: Schema.Struct({
2533
+ ...TelemetryEnvelopeProps,
2534
+ request_id: Schema.String,
2535
+ transition: Schema.Literals([
2536
+ "approval_prepared",
2537
+ "declined",
2538
+ "cancelled"
2539
+ ]),
2540
+ actor_scope_kind: ScopeKindSchema,
2541
+ actor_scope_id: Schema.String,
2542
+ occurred_at: Schema.Number
2543
+ })
2544
+ });
2545
+ const UiInvoiceStepCompletedTelemetryEventSchema = Schema.Struct({
2546
+ name: Schema.Literal("ui_invoice_step_completed"),
2547
+ props: Schema.Struct({
2548
+ ...UiStepProps,
2549
+ step: Schema.Literals([
2550
+ "opened",
2551
+ "previewed",
2552
+ "dismissed",
2553
+ "submitted",
2554
+ "result_displayed",
2555
+ "refusal_displayed",
2556
+ "retry_selected"
2557
+ ]),
2558
+ request_id: OptionalString
2559
+ })
2560
+ });
2561
+ const UiTreasuryStepCompletedTelemetryEventSchema = Schema.Struct({
2562
+ name: Schema.Literal("ui_treasury_step_completed"),
2563
+ props: Schema.Struct({
2564
+ ...UiStepProps,
2565
+ step: Schema.Literals([
2566
+ "balance_displayed",
2567
+ "read_refusal_displayed",
2568
+ "retry_selected",
2569
+ "recovery_completed"
2570
+ ]),
2571
+ account_kind: Schema.optional(AccountKindSchema)
2572
+ })
2573
+ });
2574
+ const UiReceiveStepCompletedTelemetryEventSchema = Schema.Struct({
2575
+ name: Schema.Literal("ui_receive_step_completed"),
2576
+ props: Schema.Struct({
2577
+ ...UiStepProps,
2578
+ step: Schema.Literals([
2579
+ "instructions_displayed",
2580
+ "address_copied",
2581
+ "copy_failed",
2582
+ "refusal_displayed",
2583
+ "retry_selected"
2584
+ ]),
2585
+ account_kind: Schema.optional(AccountKindSchema)
2586
+ })
2587
+ });
2588
+ const PayrollGroupChangedTelemetryEventSchema = Schema.Struct({
2589
+ name: Schema.Literal("payroll_group_changed"),
2590
+ props: Schema.Struct({
2591
+ ...TelemetryEnvelopeProps,
2592
+ organization_id: OrgIdTelemetrySchema,
2593
+ change: Schema.Literals([
2594
+ "created",
2595
+ "updated",
2596
+ "deleted"
2597
+ ]),
2598
+ group_id: Schema.String,
2599
+ member_count: Schema.Number,
2600
+ occurred_at: Schema.Number
2601
+ })
2602
+ });
2603
+ const PayrollRunTransitionedTelemetryEventSchema = Schema.Struct({
2604
+ name: Schema.Literal("payroll_run_transitioned"),
2605
+ props: Schema.Struct({
2606
+ ...TelemetryEnvelopeProps,
2607
+ organization_id: OrgIdTelemetrySchema,
2608
+ transition: Schema.Literals([
2609
+ "prepared",
2610
+ "authorized",
2611
+ "settled"
2612
+ ]),
2613
+ run_id: Schema.String,
2614
+ /**
2615
+ * The `paymentCommands` row at `payrollRuns.batchRef` — the durable owner of
2616
+ * this run's Payment membership. `payment_count` counts THAT command's
2617
+ * `paymentIds`, so an unrelated Payment quoting the run id changes neither.
2618
+ */
2619
+ command_id: OptionalString,
2620
+ payment_count: Schema.optional(Schema.Number),
2621
+ occurred_at: Schema.Number
2622
+ })
2623
+ });
2624
+ const UiPayrollActionCompletedTelemetryEventSchema = Schema.Struct({
2625
+ name: Schema.Literal("ui_payroll_action_completed"),
2626
+ props: Schema.Struct({
2627
+ ...UiStepProps,
2628
+ action: Schema.Literals([
2629
+ "opened",
2630
+ "refusal_displayed",
2631
+ "recovery_completed",
2632
+ "cancelled",
2633
+ "submitted_displayed"
2634
+ ]),
2635
+ run_id: OptionalString
2636
+ })
2637
+ });
2638
+ const TELEMETRY_EVENT_SCHEMAS = {
2639
+ contact_relationship_changed: ContactRelationshipChangedTelemetryEventSchema,
2640
+ access_recovery_completed: AccessRecoveryCompletedTelemetryEventSchema,
2641
+ ui_access_step_completed: UiAccessStepCompletedTelemetryEventSchema,
2642
+ org_invite_progressed: OrgInviteProgressedTelemetryEventSchema,
2643
+ invoice_issued: InvoiceIssuedTelemetryEventSchema,
2644
+ invoice_request_transitioned: InvoiceRequestTransitionedTelemetryEventSchema,
2645
+ ui_invoice_step_completed: UiInvoiceStepCompletedTelemetryEventSchema,
2646
+ ui_treasury_step_completed: UiTreasuryStepCompletedTelemetryEventSchema,
2647
+ ui_receive_step_completed: UiReceiveStepCompletedTelemetryEventSchema,
2648
+ payroll_group_changed: PayrollGroupChangedTelemetryEventSchema,
2649
+ payroll_run_transitioned: PayrollRunTransitionedTelemetryEventSchema,
2650
+ ui_payroll_action_completed: UiPayrollActionCompletedTelemetryEventSchema,
2651
+ ui_contact_action_completed: UiContactActionCompletedTelemetryEventSchema,
2652
+ cli_diagnostic_completed: CliDiagnosticCompletedTelemetryEventSchema,
2653
+ cli_first_used: CliFirstUsedTelemetryEventSchema,
2654
+ cli_command_started: CliCommandStartedTelemetryEventSchema,
2655
+ cli_command_completed: CliCommandCompletedTelemetryEventSchema,
2656
+ activity_annotation_saved: ActivityAnnotationSavedTelemetryEventSchema,
2657
+ ui_activity_action_completed: UiActivityActionCompletedTelemetryEventSchema,
2658
+ auth_otp_requested: AuthOtpRequestedTelemetryEventSchema,
2659
+ auth_otp_delivered: AuthOtpDeliveredTelemetryEventSchema,
2660
+ auth_otp_expired: AuthOtpExpiredTelemetryEventSchema,
2661
+ auth_verified: AuthVerifiedTelemetryEventSchema,
2662
+ auth_failed: AuthFailedTelemetryEventSchema,
2663
+ identity_refused: IdentityRefusedTelemetryEventSchema,
2664
+ auth_signed_out: AuthSignedOutTelemetryEventSchema,
2665
+ native_authorization_started: NativeAuthorizationStartedTelemetryEventSchema,
2666
+ native_authorization_reviewed: NativeAuthorizationReviewedTelemetryEventSchema,
2667
+ native_authorization_accepted: NativeAuthorizationAcceptedTelemetryEventSchema,
2668
+ native_authorization_denied: NativeAuthorizationDeniedTelemetryEventSchema,
2669
+ native_authorization_connected: NativeAuthorizationConnectedTelemetryEventSchema,
2670
+ native_authorization_failed: NativeAuthorizationFailedTelemetryEventSchema,
2671
+ onboarding_intent_selected: OnboardingIntentSelectedTelemetryEventSchema,
2672
+ onboarding_profile_submitted: OnboardingProfileSubmittedTelemetryEventSchema,
2673
+ onboarding_organization_submitted: OnboardingOrganizationSubmittedTelemetryEventSchema,
2674
+ onboarding_dashboard_reached: OnboardingDashboardReachedTelemetryEventSchema,
2675
+ provisioning_safe_created: ProvisioningSafeCreatedTelemetryEventSchema,
2676
+ provisioning_safe_confirmed: ProvisioningSafeConfirmedTelemetryEventSchema,
2677
+ bootstrap_resolved: BootstrapResolvedTelemetryEventSchema,
2678
+ bootstrap_failed: BootstrapFailedTelemetryEventSchema,
2679
+ member_activation_started: MemberActivationStartedTelemetryEventSchema,
2680
+ member_activation_ready: MemberActivationReadyTelemetryEventSchema,
2681
+ member_activation_failed: MemberActivationFailedTelemetryEventSchema,
2682
+ organization_creation_started: OrganizationCreationStartedTelemetryEventSchema,
2683
+ organization_creation_ready: OrganizationCreationReadyTelemetryEventSchema,
2684
+ organization_creation_failed: OrganizationCreationFailedTelemetryEventSchema,
2685
+ account_balance_read: AccountBalanceReadTelemetryEventSchema,
2686
+ account_balance_failed: AccountBalanceFailedTelemetryEventSchema,
2687
+ faucet_requested: FaucetRequestedTelemetryEventSchema,
2688
+ faucet_confirmed: FaucetConfirmedTelemetryEventSchema,
2689
+ faucet_failed: FaucetFailedTelemetryEventSchema,
2690
+ chain_upstream_fallback: ChainUpstreamFallbackTelemetryEventSchema,
2691
+ bundler_error: BundlerErrorTelemetryEventSchema,
2692
+ receipt_pending: ReceiptPendingTelemetryEventSchema,
2693
+ operation_retried: OperationRetriedTelemetryEventSchema,
2694
+ org_create_started: OrgCreateStartedTelemetryEventSchema,
2695
+ org_safe_created: OrgSafeCreatedTelemetryEventSchema,
2696
+ org_safe_confirmed: OrgSafeConfirmedTelemetryEventSchema,
2697
+ org_roles_seeded: OrgRolesSeededTelemetryEventSchema,
2698
+ org_created: OrgCreatedTelemetryEventSchema,
2699
+ org_create_failed: OrgCreateFailedTelemetryEventSchema,
2700
+ org_invite_sent: OrgInviteSentTelemetryEventSchema,
2701
+ org_invite_accepted: OrgInviteAcceptedTelemetryEventSchema,
2702
+ org_invite_expired: OrgInviteExpiredTelemetryEventSchema,
2703
+ payment_initiated: PaymentInitiatedTelemetryEventSchema,
2704
+ payment_settled: PaymentSettledTelemetryEventSchema,
2705
+ payment_failed: PaymentFailedTelemetryEventSchema,
2706
+ payment_verification_retry: PaymentVerificationRetryTelemetryEventSchema,
2707
+ payment_lifecycle_transition: PaymentLifecycleTransitionTelemetryEventSchema,
2708
+ quick_pay_external_address_acknowledged: QuickPayExternalAddressAcknowledgedTelemetryEventSchema,
2709
+ deposit_initiated: DepositInitiatedTelemetryEventSchema,
2710
+ deposit_settled: DepositSettledTelemetryEventSchema,
2711
+ permission_mirror_verification: PermissionMirrorVerificationTelemetryEventSchema,
2712
+ movement_scan_window: MovementScanWindowTelemetryEventSchema,
2713
+ movement_scan_checkpoint: MovementScanCheckpointTelemetryEventSchema,
2714
+ movement_scan_incident: MovementScanIncidentTelemetryEventSchema,
2715
+ indexer_drift_corrected: IndexerDriftCorrectedTelemetryEventSchema
2716
+ };
2717
+ const FINANCIAL_OPS_TARGET_TELEMETRY_PRODUCERS = [];
2718
+ /**
2719
+ * Contract-first events whose producer is owned by a later domain node.
2720
+ *
2721
+ * A domain node removes its entry when it adds the producer. The telemetry
2722
+ * gate rejects an entry that has a producer.
2723
+ */
2724
+ const CONTRACT_FIRST_TELEMETRY_EVENTS = [];
2725
+ /**
2726
+ * Catalog events whose product mapper remains gated on the #1150 frontend
2727
+ * adoption. L1 S1 removes their retired SDK-flow producers without inventing
2728
+ * replacements inside the identity actor. The telemetry-spine gate enforces
2729
+ * planned-XOR-wired: a name must leave this list in the same change that adds
2730
+ * its real product-boundary producer.
2731
+ */
2732
+ const PRODUCT_MAPPER_GATED_TELEMETRY_EVENTS = ["auth_otp_expired"];
2733
+ /** Catalogued browser observations whose producers remain owned by app adoption. */
2734
+ const BROWSER_GATED_TELEMETRY_EVENTS = [
2735
+ "onboarding_intent_selected",
2736
+ "onboarding_profile_submitted",
2737
+ "onboarding_organization_submitted",
2738
+ "onboarding_dashboard_reached",
2739
+ "ui_activity_action_completed",
2740
+ "ui_contact_action_completed",
2741
+ "ui_access_step_completed",
2742
+ "ui_invoice_step_completed",
2743
+ "ui_treasury_step_completed",
2744
+ "ui_receive_step_completed",
2745
+ "ui_payroll_action_completed"
2746
+ ];
2747
+ let trackHandler = () => {};
2748
+ function setTrackHandler(handler) {
2749
+ const previous = trackHandler;
2750
+ trackHandler = handler;
2751
+ return previous;
2752
+ }
2753
+ function getTrackHandler() {
2754
+ return trackHandler;
2755
+ }
2756
+ function track(name, props) {
2757
+ trackHandler(name, props);
2758
+ }
2759
+ function redactTelemetryEvent(event, options = {}) {
2760
+ const props = redactTelemetryProps(event.name, event.props, options);
2761
+ return props === void 0 ? { name: event.name } : {
2762
+ name: event.name,
2763
+ props
2764
+ };
2765
+ }
2766
+ function redactTelemetryProps(name, props, options = {}) {
2767
+ if (props === void 0) return void 0;
2768
+ const clone = cloneProps(props);
2769
+ if (options.rawMode === true) return clone;
2770
+ for (const key of PII_PROP_KEYS_BY_EVENT[name] ?? []) redactProperty(clone, key);
2771
+ return clone;
2772
+ }
2773
+ /**
2774
+ * Remove query strings and fragments from every PostHog URL/referrer/path
2775
+ * property before transport. Browser applications may carry emails, draft ids,
2776
+ * or other capabilities in the URL; those values must never leave the origin.
2777
+ *
2778
+ * The callback replaces the event's data with a sanitized copy. Nested values
2779
+ * can refer to live clients or configuration; observation must never mutate them.
2780
+ */
2781
+ function sanitizePostHogBrowserEvent(event, urlPolicy = "path-only") {
2782
+ if (event === null) return event;
2783
+ const transportToken = event.properties.token;
2784
+ const seen = /* @__PURE__ */ new WeakMap();
2785
+ event.properties = sanitizePostHogBrowserValue(event.properties, seen, urlPolicy);
2786
+ if (transportToken !== void 0) event.properties.token = transportToken;
2787
+ if (event.$set !== void 0) event.$set = sanitizePostHogBrowserValue(event.$set, seen, urlPolicy);
2788
+ if (event.$set_once !== void 0) event.$set_once = sanitizePostHogBrowserValue(event.$set_once, seen, urlPolicy);
2789
+ return event;
2790
+ }
2791
+ /**
2792
+ * Drop local events before transport. Sanitize and stamp every other browser
2793
+ * event with `capxul_env` and `producer: "browser"`.
2794
+ */
2795
+ function createCapxulBeforeSend(capxulEnv, urlPolicy = "path-only") {
2796
+ return (event) => {
2797
+ if (capxulEnv === "local") return null;
2798
+ const sanitized = sanitizePostHogBrowserEvent(event, urlPolicy);
2799
+ if (sanitized === null) return sanitized;
2800
+ sanitized.properties.capxul_env = capxulEnv;
2801
+ sanitized.properties.producer ??= "browser";
2802
+ return sanitized;
2803
+ };
2804
+ }
2805
+ function utilityAppAnalytics(input) {
2806
+ return {
2807
+ api_host: input.host,
2808
+ defaults: "2026-01-30",
2809
+ autocapture: false,
2810
+ capture_pageview: false,
2811
+ capture_pageleave: true,
2812
+ disable_session_recording: true,
2813
+ disable_persistence: true,
2814
+ capture_heatmaps: false,
2815
+ capture_exceptions: false,
2816
+ capture_performance: false,
2817
+ disable_surveys: true,
2818
+ disable_web_experiments: true,
2819
+ disable_product_tours: true,
2820
+ disable_conversations: true,
2821
+ disable_external_dependency_loading: true,
2822
+ person_profiles: "identified_only",
2823
+ advanced_disable_flags: true,
2824
+ save_campaign_params: false,
2825
+ save_referrer: false,
2826
+ before_send: createCapxulBeforeSend(input.capxulEnv)
2827
+ };
2828
+ }
2829
+ /** In unstructured bodies, preserve text around explicitly named credentials. */
2830
+ const NETWORK_FIELD = /((?:"?)([A-Za-z_][A-Za-z0-9_.-]*)(?:"?)\s*[:=]\s*)("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^\s,;&}]+)/gu;
2831
+ function maskNetworkText(text, context) {
2832
+ return redactSecrets(text).replace(NETWORK_FIELD, (whole, prefix, name, value) => {
2833
+ if (!isCredentialField(name, context)) return whole;
2834
+ const quote = value.startsWith("\"") ? "\"" : value.startsWith("'") ? "'" : "";
2835
+ return `${prefix}${quote}[REDACTED]${quote}`;
2836
+ });
2837
+ }
2838
+ function maskNetworkHeaders(headers) {
2839
+ if (headers === void 0) return void 0;
2840
+ const masked = {};
2841
+ 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);
2842
+ return masked;
2843
+ }
2844
+ function maskJsonValue(value, depth = 0, context) {
2845
+ if (typeof value === "function" || typeof value === "symbol") return "[UNREADABLE]";
2846
+ if (typeof value === "string") return maskNetworkText(value, context);
2847
+ if (typeof value !== "object" || value === null) return value;
2848
+ if (depth >= 16) return "[REDACTED]";
2849
+ if (Array.isArray(value)) return value.map((item) => maskJsonValue(item, depth + 1, context));
2850
+ const masked = Object.create(null);
2851
+ for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(value))) {
2852
+ if (!descriptor.enumerable) continue;
2853
+ 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);
2854
+ }
2855
+ return masked;
2856
+ }
2857
+ function maskNetworkBody(body, context) {
2858
+ try {
2859
+ if (typeof body !== "string") return maskJsonValue(body, 0, context);
2860
+ let parsed;
2861
+ try {
2862
+ parsed = JSON.parse(body);
2863
+ } catch {
2864
+ 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();
2865
+ return maskNetworkText(body, context);
2866
+ }
2867
+ return JSON.stringify(maskJsonValue(parsed, 0, context));
2868
+ } catch {
2869
+ return "[UNREADABLE]";
2870
+ }
2871
+ }
2872
+ /** Keep request evidence while masking credential values at the browser boundary. */
2873
+ function maskCapturedNetworkRequest(request) {
2874
+ const requestUrl = request.name ?? request.url ?? "";
2875
+ let context;
2876
+ try {
2877
+ const path = new URL(requestUrl, "https://capxul.invalid").pathname;
2878
+ if (/\/(?:auth|oauth|sign-in|signin|login|verify-otp|verify-email)(?:\/|$)/iu.test(path)) context = "authentication";
2879
+ } catch {}
2880
+ return {
2881
+ ...request,
2882
+ ...request.name === void 0 ? {} : { name: redactUrlSecrets(request.name) },
2883
+ ...request.url === void 0 ? {} : { url: redactUrlSecrets(request.url) },
2884
+ requestHeaders: maskNetworkHeaders(request.requestHeaders),
2885
+ responseHeaders: maskNetworkHeaders(request.responseHeaders),
2886
+ requestBody: maskNetworkBody(request.requestBody, context),
2887
+ responseBody: maskNetworkBody(request.responseBody)
2888
+ };
2889
+ }
2890
+ function productAppAnalytics(input) {
2891
+ return {
2892
+ api_host: input.host,
2893
+ defaults: "2026-01-30",
2894
+ autocapture: false,
2895
+ capture_pageview: false,
2896
+ capture_pageleave: true,
2897
+ disable_session_recording: false,
2898
+ disable_persistence: false,
2899
+ capture_heatmaps: false,
2900
+ capture_exceptions: true,
2901
+ capture_performance: {
2902
+ network_timing: true,
2903
+ web_vitals: false
2904
+ },
2905
+ disable_surveys: true,
2906
+ disable_web_experiments: true,
2907
+ disable_product_tours: true,
2908
+ disable_conversations: true,
2909
+ disable_external_dependency_loading: false,
2910
+ person_profiles: "identified_only",
2911
+ advanced_disable_flags: false,
2912
+ save_campaign_params: false,
2913
+ save_referrer: false,
2914
+ session_recording: {
2915
+ maskAllInputs: true,
2916
+ maskInputFn: (text, element) => {
2917
+ const autocomplete = element?.getAttribute("autocomplete")?.toLowerCase().split(/\s+/u) ?? [];
2918
+ return element?.getAttribute("type")?.toLowerCase() === "password" || autocomplete.some((value) => [
2919
+ "one-time-code",
2920
+ "current-password",
2921
+ "new-password"
2922
+ ].includes(value)) || isCredentialField(element?.getAttribute("name") ?? "") || isCredentialField(element?.getAttribute("id") ?? "") ? "*".repeat(text.length) : maskNetworkText(text);
2923
+ },
2924
+ captureCanvas: { recordCanvas: false },
2925
+ recordHeaders: true,
2926
+ recordBody: true,
2927
+ maskCapturedNetworkRequestFn: maskCapturedNetworkRequest
2928
+ },
2929
+ before_send: createCapxulBeforeSend(input.capxulEnv, "diagnostic")
2930
+ };
2931
+ }
2932
+ /**
2933
+ * Apply a named privacy profile before an application-owned PostHog client
2934
+ * initializes. Hosts still own the vendor client and lifecycle; this helper
2935
+ * centralizes the security-relevant options and the missing-key opt-out (no
2936
+ * key ⇒ no client ⇒ no network call).
2937
+ */
2938
+ function initializeCapxulBrowserAnalytics(profile, input, initialize) {
2939
+ const key = input.key?.trim();
2940
+ if (key === void 0 || key.length === 0) return void 0;
2941
+ try {
2942
+ const options = profile(input);
2943
+ const client = initialize(key, options);
2944
+ warnWhenReplayHasNoRecorder(options, client);
2945
+ return client;
2946
+ } catch {
2947
+ return;
2948
+ }
2949
+ }
2950
+ let replayRecorderWarned = false;
2951
+ /**
2952
+ * #1709: `posthog-js/dist/module.slim` never registers the session recording
2953
+ * manager, so a profile that enables replay records nothing with it. The
2954
+ * client exposes the manager as `sessionRecording` once `init` ran on the
2955
+ * standard build. Warn once per page so the missing build is visible.
2956
+ */
2957
+ function warnWhenReplayHasNoRecorder(options, client) {
2958
+ if (replayRecorderWarned) return;
2959
+ const replayEnabled = typeof options === "object" && options !== null && options.disable_session_recording === false;
2960
+ const recorderMissing = typeof client === "object" && client !== null && client.sessionRecording === void 0;
2961
+ if (!replayEnabled || !recorderMissing) return;
2962
+ replayRecorderWarned = true;
2963
+ 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.");
2964
+ }
2965
+ /** The utility profile, pre-bound — the shape ADR-0016's consumers already use. */
2966
+ function initializePostHogBrowserAnalytics(input, initialize) {
2967
+ return initializeCapxulBrowserAnalytics(utilityAppAnalytics, input, initialize);
2968
+ }
2969
+ /**
2970
+ * Build an explicit SPA pageview sink for toolbar-free PostHog clients. The
2971
+ * pathname-only input avoids query capabilities, repeated pathnames are
2972
+ * deduplicated, and vendor failures remain best-effort.
2973
+ */
2974
+ function createPostHogBrowserPageviewTracker(client) {
2975
+ let previousPathname;
2976
+ return (pathname) => {
2977
+ if (client === null || client === void 0) return;
2978
+ const safePathname = stripUrlQueryAndFragment(pathname);
2979
+ if (safePathname === previousPathname) return;
2980
+ try {
2981
+ Promise.resolve(client.capture("$pageview", { $pathname: safePathname })).catch(() => {});
2982
+ previousPathname = safePathname;
2983
+ } catch {}
2984
+ };
2985
+ }
2986
+ function sanitizePostHogBrowserValue(value, seen, urlPolicy) {
2987
+ if (typeof value !== "object" || value === null || value instanceof Date) return value;
2988
+ if (seen.has(value)) return seen.get(value);
2989
+ if (Array.isArray(value)) {
2990
+ const copy = [];
2991
+ seen.set(value, copy);
2992
+ for (let index = 0; index < value.length; index++) {
2993
+ const item = value[index];
2994
+ copy[index] = typeof item === "string" ? maskNetworkText(item) : sanitizePostHogBrowserValue(item, seen, urlPolicy);
2995
+ }
2996
+ return copy;
2997
+ }
2998
+ const properties = Object.create(null);
2999
+ seen.set(value, properties);
3000
+ for (const [key, nestedValue] of Object.entries(value)) {
3001
+ if (isPostHogQueryDerivedProperty(key)) continue;
3002
+ if (isCredentialField(key)) {
3003
+ properties[key] = "[REDACTED]";
3004
+ continue;
3005
+ }
3006
+ if (typeof nestedValue === "string") {
3007
+ properties[key] = isPostHogUrlProperty(key) ? urlPolicy === "path-only" ? stripUrlQueryAndFragment(nestedValue) : redactUrlSecrets(nestedValue) : maskNetworkText(nestedValue);
3008
+ continue;
3009
+ }
3010
+ properties[key] = sanitizePostHogBrowserValue(nestedValue, seen, urlPolicy);
3011
+ }
3012
+ return properties;
3013
+ }
3014
+ const POSTHOG_QUERY_DERIVED_PROPERTY_NAMES = [
3015
+ "utm_source",
3016
+ "utm_medium",
3017
+ "utm_campaign",
3018
+ "utm_content",
3019
+ "utm_term",
3020
+ "gad_source",
3021
+ "mc_cid",
3022
+ "gclid",
3023
+ "gclsrc",
3024
+ "dclid",
3025
+ "gbraid",
3026
+ "wbraid",
3027
+ "fbclid",
3028
+ "msclkid",
3029
+ "twclid",
3030
+ "li_fat_id",
3031
+ "igshid",
3032
+ "ttclid",
3033
+ "rdt_cid",
3034
+ "epik",
3035
+ "qclid",
3036
+ "sccid",
3037
+ "irclid",
3038
+ "_kx",
3039
+ "ph_keyword"
3040
+ ];
3041
+ function isPostHogQueryDerivedProperty(key) {
3042
+ const normalized = key.toLowerCase();
3043
+ return POSTHOG_QUERY_DERIVED_PROPERTY_NAMES.some((propertyName) => normalized === propertyName || normalized.endsWith(`_${propertyName}`) || normalized.endsWith(`$${propertyName}`));
3044
+ }
3045
+ function isPostHogUrlProperty(key) {
3046
+ const normalized = key.toLowerCase();
3047
+ return normalized.includes("url") || normalized.includes("referrer") || normalized.includes("path") || normalized.includes("filename");
3048
+ }
3049
+ function stripUrlQueryAndFragment(value) {
3050
+ const queryIndex = value.indexOf("?");
3051
+ const fragmentIndex = value.indexOf("#");
3052
+ if (queryIndex === -1 && fragmentIndex === -1) return value;
3053
+ if (queryIndex === -1) return value.slice(0, fragmentIndex);
3054
+ if (fragmentIndex === -1) return value.slice(0, queryIndex);
3055
+ return value.slice(0, Math.min(queryIndex, fragmentIndex));
3056
+ }
3057
+ var RecordingTelemetryAdapter = class {
3058
+ #events = [];
3059
+ #rawMode;
3060
+ constructor(options = {}) {
3061
+ this.#rawMode = options.rawMode === true;
3062
+ }
3063
+ get events() {
3064
+ return this.#events.map((event) => cloneEvent(event));
3065
+ }
3066
+ emit(event) {
3067
+ return Effect.sync(() => {
3068
+ this.#events.push(redactTelemetryEvent(event, { rawMode: this.#rawMode }));
3069
+ });
3070
+ }
3071
+ identify(_input) {
3072
+ return Effect.void;
3073
+ }
3074
+ group(_input) {
3075
+ return Effect.void;
3076
+ }
3077
+ reset() {
3078
+ return Effect.void;
3079
+ }
3080
+ reportHandledError(_error, _context) {
3081
+ return Effect.void;
3082
+ }
3083
+ clear() {
3084
+ this.#events.length = 0;
3085
+ }
3086
+ };
3087
+ var PostHogTelemetryAdapter = class {
3088
+ #capture;
3089
+ constructor(deps) {
3090
+ this.#capture = deps.capture;
3091
+ }
3092
+ emit(event) {
3093
+ return Effect.sync(() => {
3094
+ try {
3095
+ Promise.resolve(this.#capture(event.name, redactTelemetryProps(event.name, event.props))).catch(() => {});
3096
+ } catch {}
3097
+ });
3098
+ }
3099
+ identify(_input) {
3100
+ return Effect.void;
3101
+ }
3102
+ group(_input) {
3103
+ return Effect.void;
3104
+ }
3105
+ reset() {
3106
+ return Effect.void;
3107
+ }
3108
+ reportHandledError(_error, _context) {
3109
+ return Effect.void;
3110
+ }
3111
+ };
3112
+ var InMemoryTelemetryBusAdapter = class {
3113
+ #subscribers = /* @__PURE__ */ new Set();
3114
+ #rawMode;
3115
+ constructor(options = {}) {
3116
+ this.#rawMode = options.rawMode === true;
3117
+ }
3118
+ subscribe(handler) {
3119
+ this.#subscribers.add(handler);
3120
+ return () => {
3121
+ this.#subscribers.delete(handler);
3122
+ };
3123
+ }
3124
+ emit(event) {
3125
+ return Effect.sync(() => {
3126
+ const delivered = redactTelemetryEvent(event, { rawMode: this.#rawMode });
3127
+ for (const handler of this.#subscribers) try {
3128
+ handler(cloneEvent(delivered));
3129
+ } catch {}
3130
+ });
3131
+ }
3132
+ identify(_input) {
3133
+ return Effect.void;
3134
+ }
3135
+ group(_input) {
3136
+ return Effect.void;
3137
+ }
3138
+ reset() {
3139
+ return Effect.void;
3140
+ }
3141
+ reportHandledError(_error, _context) {
3142
+ return Effect.void;
3143
+ }
3144
+ };
3145
+ const PII_PROP_KEYS_BY_EVENT = {
3146
+ auth_otp_requested: ["email"],
3147
+ auth_otp_delivered: ["email"],
3148
+ auth_otp_expired: ["email"],
3149
+ auth_failed: ["email"]
3150
+ };
3151
+ function redactProperty(props, key) {
3152
+ const value = props[key];
3153
+ if (typeof value === "string") props[key] = sha256Hex(value).slice(0, 12);
3154
+ }
3155
+ function cloneEvent(event) {
3156
+ if (event.props === void 0) return { name: event.name };
3157
+ return {
3158
+ name: event.name,
3159
+ props: cloneProps(event.props)
3160
+ };
3161
+ }
3162
+ function cloneProps(props) {
3163
+ const cloned = {};
3164
+ for (const [key, value] of Object.entries(props)) cloned[key] = cloneTelemetryValue(value);
3165
+ return cloned;
3166
+ }
3167
+ function cloneTelemetryValue(value) {
3168
+ if (Array.isArray(value)) return value.map(cloneTelemetryValue);
3169
+ if (value === null || typeof value !== "object") return value;
3170
+ if (Object.getPrototypeOf(value) !== Object.prototype) return value;
3171
+ const cloned = {};
3172
+ for (const [key, nested] of Object.entries(value)) cloned[key] = cloneTelemetryValue(nested);
3173
+ return cloned;
3174
+ }
3175
+ const SHA256_INITIAL_HASH = [
3176
+ 1779033703,
3177
+ 3144134277,
3178
+ 1013904242,
3179
+ 2773480762,
3180
+ 1359893119,
3181
+ 2600822924,
3182
+ 528734635,
3183
+ 1541459225
3184
+ ];
3185
+ const SHA256_K = [
3186
+ 1116352408,
3187
+ 1899447441,
3188
+ 3049323471,
3189
+ 3921009573,
3190
+ 961987163,
3191
+ 1508970993,
3192
+ 2453635748,
3193
+ 2870763221,
3194
+ 3624381080,
3195
+ 310598401,
3196
+ 607225278,
3197
+ 1426881987,
3198
+ 1925078388,
3199
+ 2162078206,
3200
+ 2614888103,
3201
+ 3248222580,
3202
+ 3835390401,
3203
+ 4022224774,
3204
+ 264347078,
3205
+ 604807628,
3206
+ 770255983,
3207
+ 1249150122,
3208
+ 1555081692,
3209
+ 1996064986,
3210
+ 2554220882,
3211
+ 2821834349,
3212
+ 2952996808,
3213
+ 3210313671,
3214
+ 3336571891,
3215
+ 3584528711,
3216
+ 113926993,
3217
+ 338241895,
3218
+ 666307205,
3219
+ 773529912,
3220
+ 1294757372,
3221
+ 1396182291,
3222
+ 1695183700,
3223
+ 1986661051,
3224
+ 2177026350,
3225
+ 2456956037,
3226
+ 2730485921,
3227
+ 2820302411,
3228
+ 3259730800,
3229
+ 3345764771,
3230
+ 3516065817,
3231
+ 3600352804,
3232
+ 4094571909,
3233
+ 275423344,
3234
+ 430227734,
3235
+ 506948616,
3236
+ 659060556,
3237
+ 883997877,
3238
+ 958139571,
3239
+ 1322822218,
3240
+ 1537002063,
3241
+ 1747873779,
3242
+ 1955562222,
3243
+ 2024104815,
3244
+ 2227730452,
3245
+ 2361852424,
3246
+ 2428436474,
3247
+ 2756734187,
3248
+ 3204031479,
3249
+ 3329325298
3250
+ ];
3251
+ function sha256Hex(input) {
3252
+ const padded = padSha256Message(new TextEncoder().encode(input));
3253
+ const view = new DataView(padded.buffer, padded.byteOffset, padded.byteLength);
3254
+ const words = /* @__PURE__ */ new Uint32Array(64);
3255
+ let h0 = SHA256_INITIAL_HASH[0];
3256
+ let h1 = SHA256_INITIAL_HASH[1];
3257
+ let h2 = SHA256_INITIAL_HASH[2];
3258
+ let h3 = SHA256_INITIAL_HASH[3];
3259
+ let h4 = SHA256_INITIAL_HASH[4];
3260
+ let h5 = SHA256_INITIAL_HASH[5];
3261
+ let h6 = SHA256_INITIAL_HASH[6];
3262
+ let h7 = SHA256_INITIAL_HASH[7];
3263
+ for (let offset = 0; offset < padded.byteLength; offset += 64) {
3264
+ for (let i = 0; i < 16; i++) words[i] = view.getUint32(offset + i * 4);
3265
+ for (let i = 16; i < 64; i++) {
3266
+ const s0 = rotr(words[i - 15], 7) ^ rotr(words[i - 15], 18) ^ words[i - 15] >>> 3;
3267
+ const s1 = rotr(words[i - 2], 17) ^ rotr(words[i - 2], 19) ^ words[i - 2] >>> 10;
3268
+ words[i] = words[i - 16] + s0 + words[i - 7] + s1 >>> 0;
3269
+ }
3270
+ let a = h0;
3271
+ let b = h1;
3272
+ let c = h2;
3273
+ let d = h3;
3274
+ let e = h4;
3275
+ let f = h5;
3276
+ let g = h6;
3277
+ let h = h7;
3278
+ for (let i = 0; i < 64; i++) {
3279
+ const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
3280
+ const ch = e & f ^ ~e & g;
3281
+ const temp1 = h + s1 + ch + SHA256_K[i] + words[i] >>> 0;
3282
+ const temp2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + (a & b ^ a & c ^ b & c) >>> 0;
3283
+ h = g;
3284
+ g = f;
3285
+ f = e;
3286
+ e = d + temp1 >>> 0;
3287
+ d = c;
3288
+ c = b;
3289
+ b = a;
3290
+ a = temp1 + temp2 >>> 0;
3291
+ }
3292
+ h0 = h0 + a >>> 0;
3293
+ h1 = h1 + b >>> 0;
3294
+ h2 = h2 + c >>> 0;
3295
+ h3 = h3 + d >>> 0;
3296
+ h4 = h4 + e >>> 0;
3297
+ h5 = h5 + f >>> 0;
3298
+ h6 = h6 + g >>> 0;
3299
+ h7 = h7 + h >>> 0;
3300
+ }
3301
+ return [
3302
+ h0,
3303
+ h1,
3304
+ h2,
3305
+ h3,
3306
+ h4,
3307
+ h5,
3308
+ h6,
3309
+ h7
3310
+ ].map((word) => word.toString(16).padStart(8, "0")).join("");
3311
+ }
3312
+ function padSha256Message(bytes) {
3313
+ const bitLength = bytes.byteLength * 8;
3314
+ const zeroPadLength = (64 - (bytes.byteLength + 1 + 8) % 64) % 64;
3315
+ const output = new Uint8Array(bytes.byteLength + 1 + zeroPadLength + 8);
3316
+ output.set(bytes);
3317
+ output[bytes.byteLength] = 128;
3318
+ const view = new DataView(output.buffer);
3319
+ view.setUint32(output.byteLength - 8, Math.floor(bitLength / 4294967296));
3320
+ view.setUint32(output.byteLength - 4, bitLength >>> 0);
3321
+ return output;
3322
+ }
3323
+ function rotr(value, bits) {
3324
+ return value >>> bits | value << 32 - bits;
3325
+ }
3326
+ //#endregion
3327
+ 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 };