@capxul/sdk 1.0.0-alpha.9 → 1.2.0
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.
- package/README.md +121 -6
- package/dist/{InMemoryAuthCacheAdapter-v5W-XB5M.mjs → InMemoryAuthCacheAdapter-Dr1sEd9y.mjs} +36 -16
- package/dist/InMemoryAuthCacheAdapter-Dr1sEd9y.mjs.map +1 -0
- package/dist/create-capxul-client-C7H5b68l.d.mts +2764 -0
- package/dist/create-capxul-client-C7H5b68l.d.mts.map +1 -0
- package/dist/create-capxul-client-DiqVIxsV.mjs +6980 -0
- package/dist/create-capxul-client-DiqVIxsV.mjs.map +1 -0
- package/dist/index.d.mts +119 -2020
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2464 -6308
- package/dist/index.mjs.map +1 -1
- package/dist/node/index.d.mts +3 -6
- package/dist/node/index.d.mts.map +1 -1
- package/dist/node/index.mjs +27 -27
- package/dist/node/index.mjs.map +1 -1
- package/dist/signer-CJT0pPiO.d.mts +301 -0
- package/dist/signer-CJT0pPiO.d.mts.map +1 -0
- package/dist/testing/index.d.mts +54 -0
- package/dist/testing/index.d.mts.map +1 -0
- package/dist/testing/index.mjs +1068 -0
- package/dist/testing/index.mjs.map +1 -0
- package/package.json +17 -18
- package/dist/InMemoryAuthCacheAdapter-v5W-XB5M.mjs.map +0 -1
- package/dist/index-CTXgQ_xR.d.mts +0 -158
- package/dist/index-CTXgQ_xR.d.mts.map +0 -1
- package/dist/ports/safe-deployment.d.mts +0 -2
- package/dist/ports/safe-deployment.mjs +0 -38
- package/dist/ports/safe-deployment.mjs.map +0 -1
- package/dist/safe-deployment-D3k9yndM.d.mts +0 -136
- package/dist/safe-deployment-D3k9yndM.d.mts.map +0 -1
- package/dist/signer-DqDtJU1l.d.mts +0 -145
- package/dist/signer-DqDtJU1l.d.mts.map +0 -1
package/README.md
CHANGED
|
@@ -1,9 +1,124 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@capxul/sdk`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The imperative TypeScript client for Capxul. It owns the public
|
|
4
|
+
`createCapxulClient` factory, domain method bundles, production adapter assembly,
|
|
5
|
+
and the internal Effect-based ports and flows that those methods bridge.
|
|
4
6
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
- [Env module](./docs/env.md)
|
|
7
|
+
```ts
|
|
8
|
+
import { createCapxulClient } from "@capxul/sdk";
|
|
8
9
|
|
|
9
|
-
|
|
10
|
+
const created = await createCapxulClient({
|
|
11
|
+
publishableKey: process.env.CAPXUL_PUBLISHABLE_KEY!,
|
|
12
|
+
requirement: "counterfactual",
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
if (!created.ok) throw created.error;
|
|
16
|
+
const client = created.value;
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Every public operation resolves a `Promise<CapxulResult<T>>`. Domain failures
|
|
20
|
+
are values, not thrown exceptions.
|
|
21
|
+
|
|
22
|
+
## Engineering telemetry
|
|
23
|
+
|
|
24
|
+
Production hosts can opt into sanitized Effect logs and traces through the
|
|
25
|
+
public client input:
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
const created = await createCapxulClient({
|
|
29
|
+
publishableKey: "cap_pk_…",
|
|
30
|
+
engineeringTelemetry: {
|
|
31
|
+
host: "https://us.i.posthog.com",
|
|
32
|
+
headers: { Authorization: "Bearer phc_…" },
|
|
33
|
+
capxulEnv: "production",
|
|
34
|
+
serviceName: "capxul-sdk",
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Use the browser-safe PostHog project token (`phc_...`), never a personal API
|
|
40
|
+
key (`phx_...`) or another secret. The host URL must be a credential-free HTTPS
|
|
41
|
+
origin; credentials belong only in the explicit header. The SDK supplies its
|
|
42
|
+
runtime producer and version, permits only closed identity classifications and
|
|
43
|
+
safe correlation identifiers, and excludes email, OTP, auth/session tokens,
|
|
44
|
+
wallet data, request/response bodies, provider messages, raw causes, and
|
|
45
|
+
stacks. Export is best-effort and cannot change the operation result. An OTLP
|
|
46
|
+
HTTP 200 is not delivery proof: verify a live run by querying both PostHog
|
|
47
|
+
`logs` and `posthog.trace_spans` for the same fresh trace.
|
|
48
|
+
|
|
49
|
+
Onboarding uses explicit domain objects. Personal completion accepts
|
|
50
|
+
`{ profile }`; Organization completion accepts independently validated
|
|
51
|
+
`{ profile, organization }`. The latter makes the Member Profile and personal
|
|
52
|
+
Account/Safe ready before the first Organization write, then returns the exact
|
|
53
|
+
`orgId` and its `OrgLifecycle`. A failed lifecycle after creation is returned
|
|
54
|
+
with that `orgId`; Organization-list timing is not a success gate.
|
|
55
|
+
Public Profile reads include the durable `onboarded` flag and optional
|
|
56
|
+
`withdrawalAddress`, and `toEvmAddress` validates form-sourced withdrawal values.
|
|
57
|
+
|
|
58
|
+
## Published entry points
|
|
59
|
+
|
|
60
|
+
The packed npm package exposes only:
|
|
61
|
+
|
|
62
|
+
- `@capxul/sdk` — the client factory, public method and value types, signers,
|
|
63
|
+
and observation helpers.
|
|
64
|
+
- `@capxul/sdk/node` — Node-only signer and runtime helpers.
|
|
65
|
+
- `@capxul/sdk/testing` — the real identity runtime assembled over
|
|
66
|
+
deterministic in-memory ports, with OTP, advance-only clock, transition,
|
|
67
|
+
observation, seed, and close controls for tests.
|
|
68
|
+
|
|
69
|
+
The many extra subpaths in `package.json#exports` are workspace development
|
|
70
|
+
surfaces. Do not show them in consumer examples unless `publishConfig.exports`
|
|
71
|
+
also contains them.
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
import { createCapxulTestClient } from "@capxul/sdk/testing";
|
|
75
|
+
|
|
76
|
+
const testing = createCapxulTestClient();
|
|
77
|
+
await testing.seedIdentity({ authUserId: "auth_seeded_test", email: "test@example.test" });
|
|
78
|
+
await testing.clock.advance(1_000);
|
|
79
|
+
await testing.client.auth.signIn({ email: "test@example.test" });
|
|
80
|
+
const otp = testing.peekOtp("test@example.test");
|
|
81
|
+
if (!otp) throw new Error("expected a test OTP");
|
|
82
|
+
await testing.client.auth.verifyOtp({ email: "test@example.test", code: otp });
|
|
83
|
+
// Drive the real public client, then inspect testing.transitions.
|
|
84
|
+
await testing.close();
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
The seeded email is bound to the requested auth user ID, so verifying its OTP
|
|
88
|
+
loads that exact seeded Profile. The public clock exposes only `advance(ms)`;
|
|
89
|
+
the internal clock adapter and its Effect/conformance methods remain private.
|
|
90
|
+
The testing entry is identity-scoped and hermetic. Fine-grained
|
|
91
|
+
`@capxul/sdk/testing/*` adapter paths remain workspace-only.
|
|
92
|
+
|
|
93
|
+
## Documentation
|
|
94
|
+
|
|
95
|
+
- [Maintainer context](./CONTEXT.md) — ownership, boundaries, invariants,
|
|
96
|
+
evidence, and update triggers.
|
|
97
|
+
- [Architecture](./docs/architecture.md) — client assembly, flows, ports,
|
|
98
|
+
adapters, and proof map.
|
|
99
|
+
- [Observation](./docs/observation.md) — host-owned failure observation and
|
|
100
|
+
bounded backend linkage.
|
|
101
|
+
- [Public SDK documentation](../../apps/docs/content/docs/sdk/index.mdx) —
|
|
102
|
+
tutorials, guides, reference, and explanation for npm consumers.
|
|
103
|
+
|
|
104
|
+
React integration is a separate projection owned by `@capxul/sdk-react`.
|
|
105
|
+
|
|
106
|
+
## Development
|
|
107
|
+
|
|
108
|
+
Run package commands through Vite+:
|
|
109
|
+
|
|
110
|
+
```bash
|
|
111
|
+
vp run --filter @capxul/sdk check-types
|
|
112
|
+
vp run --filter @capxul/sdk test
|
|
113
|
+
vp run --filter @capxul/sdk build
|
|
114
|
+
vp run --filter @capxul/sdk proofs:live
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
`proofs:live` runs the deterministic Organization Core SDK journey against the
|
|
118
|
+
configured live Convex deployment and Base Sepolia. Live proofs require
|
|
119
|
+
operator secrets and prove only the path named by the command. See
|
|
120
|
+
[maintainer context](./CONTEXT.md#capability-and-proof-boundaries).
|
|
121
|
+
|
|
122
|
+
The browser production path owns its Openfort signer when no signer is supplied.
|
|
123
|
+
Current integration recovery evidence and its published-package boundary are
|
|
124
|
+
tracked in the [#870 receipt](../../docs/receipts/issue-870-openfort-signer-recovery-RECEIPT-2026-07-19.md).
|
package/dist/{InMemoryAuthCacheAdapter-v5W-XB5M.mjs → InMemoryAuthCacheAdapter-Dr1sEd9y.mjs}
RENAMED
|
@@ -22,8 +22,37 @@ const CAPXUL_ERROR_CODES = [
|
|
|
22
22
|
"OTP_EXPIRED",
|
|
23
23
|
"SIGNER_REJECTED",
|
|
24
24
|
"CANCELLED",
|
|
25
|
-
"WRONG_STATE"
|
|
25
|
+
"WRONG_STATE",
|
|
26
|
+
"STALE_EPOCH",
|
|
27
|
+
"SUPERSEDED",
|
|
28
|
+
"WORK_DIED",
|
|
29
|
+
"ACTOR_STOPPED"
|
|
26
30
|
];
|
|
31
|
+
/**
|
|
32
|
+
* The error codes that represent an expected product outcome rather than a
|
|
33
|
+
* defect. The SDK and backend observation boundaries both classify failures
|
|
34
|
+
* against this set to route expected outcomes to their own PostHog event
|
|
35
|
+
* stream; keeping the single copy here (adjacent to `CAPXUL_ERROR_CODES`, so a
|
|
36
|
+
* code rename forces this set to move with it) stops the two sides of the wire
|
|
37
|
+
* from drifting and silently splitting one outcome across two streams.
|
|
38
|
+
*/
|
|
39
|
+
const EXPECTED_OPERATION_OUTCOMES = new Set([
|
|
40
|
+
"INVALID_INPUT",
|
|
41
|
+
"NOT_AUTHENTICATED",
|
|
42
|
+
"SMART_ACCOUNT_MISSING",
|
|
43
|
+
"CANCELLED",
|
|
44
|
+
"SIGNER_REJECTED",
|
|
45
|
+
"VERIFICATION_REQUIRED",
|
|
46
|
+
"INSUFFICIENT_BALANCE",
|
|
47
|
+
"INVALID_RECIPIENT",
|
|
48
|
+
"ROLE_PERMISSION_DENIED",
|
|
49
|
+
"RATE_LIMITED",
|
|
50
|
+
"OTP_EXPIRED",
|
|
51
|
+
"WRONG_STATE",
|
|
52
|
+
"STALE_EPOCH",
|
|
53
|
+
"SUPERSEDED",
|
|
54
|
+
"ACTOR_STOPPED"
|
|
55
|
+
]);
|
|
27
56
|
var CapxulError = class extends Error {
|
|
28
57
|
code;
|
|
29
58
|
details;
|
|
@@ -85,8 +114,7 @@ const Errors = {
|
|
|
85
114
|
} }),
|
|
86
115
|
/**
|
|
87
116
|
* Sibling factory to {@link Errors.providerError} for the per-state timeout
|
|
88
|
-
* path in flows
|
|
89
|
-
* register_indexer `after:` timers). Same `PROVIDER_ERROR` code as
|
|
117
|
+
* path in flows. Same `PROVIDER_ERROR` code as
|
|
90
118
|
* `providerError`, plus a `details.reason: "timeout"` discriminator so
|
|
91
119
|
* downstream observers can distinguish failure modes without parsing the
|
|
92
120
|
* message string. The redacted message names the timeout budget; the
|
|
@@ -156,8 +184,8 @@ const Errors = {
|
|
|
156
184
|
* Method called from a flow state where its precondition fails (TA16). The
|
|
157
185
|
* SDK's method API short-circuits with this error before driving the
|
|
158
186
|
* internal state machine. `currentState` is the Effect-machine snapshot
|
|
159
|
-
* tag (stringified
|
|
160
|
-
* `
|
|
187
|
+
* tag (stringified from the SDK's actor-shell snapshot; see
|
|
188
|
+
* `packages/errors/CONTEXT.md`); `validStates`
|
|
161
189
|
* enumerates the states the method accepts.
|
|
162
190
|
*/
|
|
163
191
|
wrongState: (details) => new CapxulError("WRONG_STATE", `${details.method} called from state '${details.currentState}'; valid states: ${details.validStates.join(", ")}`, { details: {
|
|
@@ -231,7 +259,6 @@ const SUPPORTED_CURRENCY_CODES = SUPPORTED_CURRENCIES.map((currency) => currency
|
|
|
231
259
|
Object.fromEntries(SUPPORTED_CURRENCIES.map((currency) => [currency.code, currency.symbol]));
|
|
232
260
|
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
233
261
|
const COUNTRY_CODE_RE = /^[A-Z]{2}$/;
|
|
234
|
-
const ANONYMOUS_DISTINCT_ID_RE = /^anon_[a-zA-Z0-9-]+$/;
|
|
235
262
|
const ACCOUNT_ID_RE = /^account_[0-9A-Za-z]+$/;
|
|
236
263
|
const SUBACCOUNT_ID_RE = /^subaccount_[0-9A-Za-z]+$/;
|
|
237
264
|
const APP_ID_RE = /^app_[0-7][0-9A-HJKMNP-TV-Z]{25}$/;
|
|
@@ -247,10 +274,6 @@ function toEmail(raw) {
|
|
|
247
274
|
function toAuthUserId(raw) {
|
|
248
275
|
return toNonEmptyStringBrand(raw, "authUserId");
|
|
249
276
|
}
|
|
250
|
-
function toAnonymousDistinctId(raw) {
|
|
251
|
-
if (typeof raw !== "string" || !ANONYMOUS_DISTINCT_ID_RE.test(raw)) throw Errors.invalidInput("anonDistinctId", invalidValueReason("must be anon_ plus letters, digits, or hyphens", raw));
|
|
252
|
-
return raw;
|
|
253
|
-
}
|
|
254
277
|
function toAccountId(raw) {
|
|
255
278
|
if (typeof raw !== "string" || !ACCOUNT_ID_RE.test(raw)) throw Errors.invalidInput("accountId", invalidValueReason("must be account_ plus an alphanumeric id", raw));
|
|
256
279
|
return raw;
|
|
@@ -272,9 +295,6 @@ function toAllowedOrigin(raw) {
|
|
|
272
295
|
if (normalized === null) throw Errors.invalidInput("allowedOrigin", invalidValueReason("must be an http or https origin", raw));
|
|
273
296
|
return normalized;
|
|
274
297
|
}
|
|
275
|
-
function toPublishableKeyId(raw) {
|
|
276
|
-
return toNonEmptyStringBrand(raw, "keyId");
|
|
277
|
-
}
|
|
278
298
|
function toDurationMs(raw) {
|
|
279
299
|
if (typeof raw !== "number" || !Number.isSafeInteger(raw) || raw < 0) throw Errors.invalidInput("duration", invalidValueReason("must be a non-negative safe integer", raw));
|
|
280
300
|
return raw;
|
|
@@ -346,7 +366,7 @@ function invalidValueReason(prefix, raw) {
|
|
|
346
366
|
//#endregion
|
|
347
367
|
//#region src/ports/auth-cache.ts
|
|
348
368
|
var AuthCacheError = class extends Data.TaggedError("AuthCacheError") {};
|
|
349
|
-
var AuthCachePortTag = class extends Context.
|
|
369
|
+
var AuthCachePortTag = class extends Context.Service()("@capxul/sdk/ports/AuthCachePort") {};
|
|
350
370
|
//#endregion
|
|
351
371
|
//#region src/adapters/auth-cache/serialization.ts
|
|
352
372
|
function parseAuthSession(raw) {
|
|
@@ -452,6 +472,6 @@ Layer.effect(AuthCachePortTag, Effect.sync(() => new InMemoryAuthCacheAdapter())
|
|
|
452
472
|
cause
|
|
453
473
|
}))));
|
|
454
474
|
//#endregion
|
|
455
|
-
export {
|
|
475
|
+
export { decodeConvexError as A, toJwtToken as C, toRoleKey as D, toPublishableKey as E, EXPECTED_OPERATION_OUTCOMES as M, Errors as N, toSessionToken as O, isCapxulError as P, toEpochSeconds as S, toOrgId as T, toCountryCode as _, AuthCacheError as a, toEmail as b, BYTES32_RE as c, toAccountId as d, toAddress as f, toChainId as g, toAuthUserId as h, parseCachedJwt as i, CapxulError as j, toSubAccountId as k, EVM_ADDRESS_RE as l, toAppId as m, BrowserAuthCacheAdapter as n, AuthCachePortTag as o, toAllowedOrigin as p, parseAuthSession as r, APP_ID_RE as s, InMemoryAuthCacheAdapter as t, SUPPORTED_CURRENCY_CODES as u, toCurrencyCode as v, toKycTier as w, toEpochMs as x, toDurationMs as y };
|
|
456
476
|
|
|
457
|
-
//# sourceMappingURL=InMemoryAuthCacheAdapter-
|
|
477
|
+
//# sourceMappingURL=InMemoryAuthCacheAdapter-Dr1sEd9y.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"InMemoryAuthCacheAdapter-Dr1sEd9y.mjs","names":[],"sources":["../../errors/src/errors.ts","../../errors/src/convex-error-decoding.ts","../../types/src/index.ts","../src/ports/auth-cache.ts","../src/adapters/auth-cache/serialization.ts","../src/adapters/auth-cache/BrowserAuthCacheAdapter.ts","../src/adapters/auth-cache/InMemoryAuthCacheAdapter.ts"],"sourcesContent":["// The canonical error-code catalog as a runtime constant. `CapxulErrorCode`\n// is derived from it so the type and any runtime check that needs to\n// enumerate codes (e.g. the convex-error codec's `KNOWN_CODES`) share a\n// single source of truth — a TypeScript union alone can't be introspected\n// at runtime, which previously forced a hand-maintained duplicate.\nexport const CAPXUL_ERROR_CODES = [\n \"NOT_AUTHENTICATED\",\n \"EMAIL_DELIVERY_FAILED\",\n \"PROFILE_NOT_FOUND\",\n \"SMART_ACCOUNT_MISSING\",\n \"PLAYER_NOT_FOUND\",\n \"ACCOUNT_NOT_FOUND\",\n \"PROVIDER_ERROR\",\n \"INVALID_INPUT\",\n \"ENV_MISSING\",\n \"NOT_IMPLEMENTED\",\n \"VERIFICATION_REQUIRED\",\n \"INSUFFICIENT_BALANCE\",\n \"INVALID_RECIPIENT\",\n \"ROLE_PERMISSION_DENIED\",\n \"TRANSACTION_FAILED\",\n \"RATE_LIMITED\",\n \"NETWORK_ERROR\",\n \"UNKNOWN\",\n \"OTP_EXPIRED\",\n \"SIGNER_REJECTED\",\n \"CANCELLED\",\n \"WRONG_STATE\",\n \"STALE_EPOCH\",\n \"SUPERSEDED\",\n \"WORK_DIED\",\n \"ACTOR_STOPPED\",\n] as const;\n\nexport type CapxulErrorCode = (typeof CAPXUL_ERROR_CODES)[number];\n\n/**\n * The error codes that represent an expected product outcome rather than a\n * defect. The SDK and backend observation boundaries both classify failures\n * against this set to route expected outcomes to their own PostHog event\n * stream; keeping the single copy here (adjacent to `CAPXUL_ERROR_CODES`, so a\n * code rename forces this set to move with it) stops the two sides of the wire\n * from drifting and silently splitting one outcome across two streams.\n */\nexport const EXPECTED_OPERATION_OUTCOMES: ReadonlySet<CapxulErrorCode> = new Set([\n \"INVALID_INPUT\",\n \"NOT_AUTHENTICATED\",\n // A user with no Safe yet — the normal post-OTP / pre-provision state. Reading\n // the account, current user, or balance in that window is an expected outcome,\n // not a defect, so both observation boundaries route it to their\n // `*_expected_outcome` stream instead of an unexpected `$exception` (#1031).\n \"SMART_ACCOUNT_MISSING\",\n \"CANCELLED\",\n \"SIGNER_REJECTED\",\n \"VERIFICATION_REQUIRED\",\n \"INSUFFICIENT_BALANCE\",\n \"INVALID_RECIPIENT\",\n \"ROLE_PERMISSION_DENIED\",\n \"RATE_LIMITED\",\n \"OTP_EXPIRED\",\n \"WRONG_STATE\",\n \"STALE_EPOCH\",\n \"SUPERSEDED\",\n \"ACTOR_STOPPED\",\n]);\n\n/**\n * Why an auth/provider call failed — a flat CAUSE enum. The *where* (which\n * OpenFort operation) stays in the separate `operation` detail field; this\n * names the root cause so a single `$exception` can be triaged without\n * parsing the message. Five members, no free strings:\n *\n * - `auth-origin-mismatch`: OTP cookies live on `localhost:PORT` but OpenFort\n * hits the Convex host → no session reaches the provider.\n * - `stale-openfort-cache`: an old `userId` in scoped storage makes the SDK\n * skip re-auth → 401 on `v2/accounts`.\n * - `app-env-allowlist`: the selected app/deployment origin is not allowlisted\n * → 401.\n * - `no-secure-context`: sandboxed/headless browser with no Web Crypto, so\n * `getAddress`/`configure` can never produce an address. Previously vanished\n * into `unknown`; the signer's secure-context probe now names it.\n * - `unknown`: catch-all when no cause could be determined.\n */\nexport type FailureMode =\n | \"auth-origin-mismatch\"\n | \"stale-openfort-cache\"\n | \"app-env-allowlist\"\n | \"no-secure-context\"\n | \"unknown\";\n\n/**\n * The one failure representation carried by domain state, actor work, and\n * public error projection. Keeping it beside the canonical error catalog\n * prevents a machine or shell from inventing a second code vocabulary.\n */\nexport interface Failure {\n readonly code: CapxulErrorCode;\n readonly message: string;\n readonly mode?: FailureMode;\n}\n\nexport type CapxulErrorDetails = Record<string, unknown>;\n\nexport type SignerSource = \"openfort-embedded\" | \"injected-eip1193\" | \"local-private-key\";\n\nexport type VerificationRequiredDetails =\n | { readonly requiredTier: number }\n | { readonly rail: string; readonly currentKind: string };\n\nexport type SerializedCapxulError = {\n readonly code: CapxulErrorCode;\n readonly message: string;\n readonly details?: CapxulErrorDetails;\n readonly correlationId?: string;\n readonly layer?: string;\n};\n\nexport type CapxulErrorOptions = {\n readonly cause?: unknown;\n readonly details?: CapxulErrorDetails;\n readonly correlationId?: string;\n readonly layer?: string;\n};\n\nexport class CapxulError extends Error {\n readonly code: CapxulErrorCode;\n readonly details?: CapxulErrorDetails;\n readonly correlationId?: string;\n readonly layer?: string;\n\n constructor(code: CapxulErrorCode, message: string, options: CapxulErrorOptions = {}) {\n super(message, \"cause\" in options ? { cause: options.cause } : undefined);\n this.name = \"CapxulError\";\n this.code = code;\n if (options.details !== undefined) {\n this.details = options.details;\n }\n if (options.correlationId !== undefined) {\n this.correlationId = options.correlationId;\n }\n if (options.layer !== undefined) {\n this.layer = options.layer;\n }\n }\n}\n\nexport function isCapxulError(value: unknown): value is CapxulError {\n return value instanceof CapxulError;\n}\n\nexport function serializeCapxulError(error: CapxulError): SerializedCapxulError {\n return compactSerialized({\n code: error.code,\n message: error.message,\n details: error.details,\n correlationId: error.correlationId,\n layer: error.layer,\n });\n}\n\nexport function deserializeCapxulError(serialized: SerializedCapxulError): CapxulError {\n return new CapxulError(\n serialized.code,\n serialized.message,\n compactErrorOptions({\n details: serialized.details,\n correlationId: serialized.correlationId,\n layer: serialized.layer,\n }),\n );\n}\n\nfunction compactSerialized(serialized: {\n readonly code: CapxulErrorCode;\n readonly message: string;\n readonly details: CapxulErrorDetails | undefined;\n readonly correlationId: string | undefined;\n readonly layer: string | undefined;\n}): SerializedCapxulError {\n const result: {\n code: CapxulErrorCode;\n message: string;\n details?: CapxulErrorDetails;\n correlationId?: string;\n layer?: string;\n } = {\n code: serialized.code,\n message: serialized.message,\n };\n\n if (serialized.details !== undefined) {\n result.details = serialized.details;\n }\n if (serialized.correlationId !== undefined) {\n result.correlationId = serialized.correlationId;\n }\n if (serialized.layer !== undefined) {\n result.layer = serialized.layer;\n }\n\n return result;\n}\n\nfunction compactErrorOptions(options: {\n readonly cause?: unknown;\n readonly details: CapxulErrorDetails | undefined;\n readonly correlationId: string | undefined;\n readonly layer: string | undefined;\n}): CapxulErrorOptions {\n const result: {\n cause?: unknown;\n details?: CapxulErrorDetails;\n correlationId?: string;\n layer?: string;\n } = {};\n\n if (\"cause\" in options) {\n result.cause = options.cause;\n }\n if (options.details !== undefined) {\n result.details = options.details;\n }\n if (options.correlationId !== undefined) {\n result.correlationId = options.correlationId;\n }\n if (options.layer !== undefined) {\n result.layer = options.layer;\n }\n\n return result;\n}\n\nexport const Errors = {\n notAuthenticated: (message?: string, opts?: { readonly failure_mode?: FailureMode }) =>\n new CapxulError(\n \"NOT_AUTHENTICATED\",\n message ?? \"Not authenticated\",\n opts?.failure_mode ? { details: { failure_mode: opts.failure_mode } } : undefined,\n ),\n emailDeliveryFailed: (detail: string) =>\n new CapxulError(\"EMAIL_DELIVERY_FAILED\", \"Failed to send email\", {\n details: { detail },\n }),\n\n profileNotFound: (authUserId: string) =>\n new CapxulError(\"PROFILE_NOT_FOUND\", `Profile not found for user ${authUserId}`, {\n details: { authUserId },\n }),\n\n smartAccountMissing: (authUserId: string) =>\n new CapxulError(\"SMART_ACCOUNT_MISSING\", \"Smart account not provisioned\", {\n details: { authUserId },\n }),\n\n playerNotFound: (playerId?: string) =>\n new CapxulError(\n \"PLAYER_NOT_FOUND\",\n playerId ? `Openfort player ${playerId} not found` : \"Openfort player not found\",\n playerId === undefined ? undefined : { details: { playerId } },\n ),\n\n accountNotFound: (accountId?: string) =>\n new CapxulError(\n \"ACCOUNT_NOT_FOUND\",\n accountId ? `Openfort account ${accountId} not found` : \"Openfort account not found\",\n accountId === undefined ? undefined : { details: { accountId } },\n ),\n\n providerError: (\n provider: string,\n operation: string,\n cause: unknown,\n opts?: { readonly failure_mode?: FailureMode },\n ) => {\n const details: Record<string, unknown> = { provider, operation };\n if (opts?.failure_mode) {\n details.failure_mode = opts.failure_mode;\n }\n return new CapxulError(\"PROVIDER_ERROR\", `Provider error: ${provider} ${operation}`, {\n cause,\n details,\n });\n },\n\n invalidInput: (field: string, reason: string) =>\n new CapxulError(\"INVALID_INPUT\", `Invalid ${field}: ${reason}`, {\n details: { field, reason },\n }),\n\n envMissing: (name: string) =>\n new CapxulError(\"ENV_MISSING\", `Environment variable ${name} not configured`, {\n details: { name },\n }),\n\n notImplemented: (domain: string, method: string) =>\n new CapxulError(\n \"NOT_IMPLEMENTED\",\n `${domain}.${method} is not yet implemented. This feature is planned for a future release.`,\n { details: { domain, method } },\n ),\n\n /**\n * Sibling factory to {@link Errors.providerError} for the per-state timeout\n * path in flows. Same `PROVIDER_ERROR` code as\n * `providerError`, plus a `details.reason: \"timeout\"` discriminator so\n * downstream observers can distinguish failure modes without parsing the\n * message string. The redacted message names the timeout budget; the\n * native `cause` carries the same information for `reportError` fidelity.\n */\n providerTimeout: (provider: string, operation: string, timeoutMs: number) =>\n new CapxulError(\n \"PROVIDER_ERROR\",\n `Provider error: ${provider} ${operation} (timeout exceeded ${timeoutMs}ms)`,\n {\n details: { provider, operation, reason: \"timeout\" },\n cause: new Error(`timeout: ${operation} exceeded ${timeoutMs}ms`),\n },\n ),\n\n verificationRequired: (details: VerificationRequiredDetails) => {\n const message =\n \"rail\" in details\n ? `Verification is required before ${details.rail} can use ${details.currentKind}.`\n : `Verification tier ${details.requiredTier} is required.`;\n\n return new CapxulError(\"VERIFICATION_REQUIRED\", message, {\n details,\n });\n },\n\n insufficientBalance: (asset: string, available: string, required: string) =>\n new CapxulError(\"INSUFFICIENT_BALANCE\", `Insufficient ${asset} balance`, {\n details: { asset, available, required },\n }),\n\n invalidRecipient: (reason: string) =>\n new CapxulError(\"INVALID_RECIPIENT\", `Invalid recipient: ${reason}`, {\n details: { reason },\n }),\n\n /**\n * The org Zodiac Roles modifier REFUSED the spend on-chain (G4 · #547): the\n * member's role condition (per-tx cap, per-day allowance, allowed recipient,\n * or membership) was violated, so `execTransactionWithRole` reverted. This is\n * a PERMISSION denial — explicitly NOT an `INSUFFICIENT_BALANCE` (the treasury\n * held the funds; the role's authority is what bound). `reason` discriminates\n * the violated condition (`over_cap` / `daily_cap` / `not_member` /\n * `disallowed_recipient` / `condition_violation`); leak-safe — no on-chain\n * identifiers ever enter the details.\n */\n rolePermissionDenied: (details: {\n readonly reason:\n | \"over_cap\"\n | \"daily_cap\"\n | \"not_member\"\n | \"disallowed_recipient\"\n | \"condition_violation\";\n readonly operation?: string;\n }) =>\n new CapxulError(\n \"ROLE_PERMISSION_DENIED\",\n `Org role denied this spend on-chain (${details.reason}).`,\n {\n details:\n details.operation === undefined\n ? { reason: details.reason }\n : { reason: details.reason, operation: details.operation },\n },\n ),\n\n /**\n * A transaction (or sponsored UserOp) failed. `details.reason` discriminates\n * the failure mode for callers that must distinguish a CONFIRMED on-chain\n * revert (`\"onchain_revert\"` — the op executed and reverted, e.g. a Zodiac\n * Roles condition violation) from an inconclusive infra failure. A confirmed\n * revert is the ONLY mode the org spend port may map to a roles denial.\n */\n transactionFailed: (operation: string, cause?: unknown, extra?: { readonly reason?: string }) =>\n new CapxulError(\"TRANSACTION_FAILED\", `Transaction failed: ${operation}`, {\n cause,\n details: extra?.reason === undefined ? { operation } : { operation, reason: extra.reason },\n }),\n\n rateLimited: (details?: { readonly retryAfterMs?: number; readonly resource?: string }) =>\n new CapxulError(\n \"RATE_LIMITED\",\n \"Rate limit exceeded\",\n details === undefined ? undefined : { details: { ...details } },\n ),\n\n networkError: (operation: string, cause?: unknown) =>\n new CapxulError(\"NETWORK_ERROR\", `Network error during ${operation}`, {\n cause,\n details: { operation },\n }),\n\n unknown: (cause?: unknown) => new CapxulError(\"UNKNOWN\", \"Unknown error\", { cause }),\n\n otpExpired: (details?: { readonly email?: string; readonly expiredAt?: number }) =>\n new CapxulError(\n \"OTP_EXPIRED\",\n \"Verification code has expired. Request a new one.\",\n details === undefined ? undefined : { details: { ...details } },\n ),\n\n signerRejected: (details: {\n readonly source: SignerSource;\n readonly reason?: string;\n readonly cause?: unknown;\n }) =>\n new CapxulError(\"SIGNER_REJECTED\", \"Signer rejected the request.\", {\n cause: details.cause,\n details:\n details.reason === undefined\n ? { source: details.source }\n : { source: details.source, reason: details.reason },\n }),\n\n cancelled: (details?: { readonly operation?: string; readonly reason?: string }) =>\n new CapxulError(\n \"CANCELLED\",\n \"Operation was cancelled.\",\n details === undefined ? undefined : { details: { ...details } },\n ),\n\n /**\n * Method called from a flow state where its precondition fails (TA16). The\n * SDK's method API short-circuits with this error before driving the\n * internal state machine. `currentState` is the Effect-machine snapshot\n * tag (stringified from the SDK's actor-shell snapshot; see\n * `packages/errors/CONTEXT.md`); `validStates`\n * enumerates the states the method accepts.\n */\n wrongState: (details: {\n readonly method: string;\n readonly currentState: string;\n readonly validStates: readonly string[];\n }) =>\n new CapxulError(\n \"WRONG_STATE\",\n `${details.method} called from state '${details.currentState}'; valid states: ${details.validStates.join(\", \")}`,\n { details: { ...details, validStates: [...details.validStates] } },\n ),\n} as const;\n","// Shared `decodeConvexError` helper (TA5) — used by both the SDK's\n// `ConvexCallAdapter.mapToCapxulError` AND the backend `credentials/http.ts`\n// `bootstrapClient` handler. Single source of truth for cross-Convex-boundary\n// error decoding rules.\n//\n// Recognizes the `ConvexError(SerializedCapxulError)` object-shape produced by\n// `withErrorBoundary` (Probe B finding, 2026-05-19):\n//\n// { name: \"ConvexError\", data: { code, message, details?, correlationId?, layer? } }\n//\n// AND the defensive string-shape branch for older Convex versions where\n// `data` is a JSON-serialized string. Pass-through for raw `CapxulError`\n// instances (which arrive directly when the throw happened in the same\n// V8 isolate as the catch). Returns null when the value is not a\n// recognizable shape — the caller falls back to NETWORK_ERROR + reportError.\n\nimport {\n CAPXUL_ERROR_CODES,\n CapxulError,\n type CapxulErrorCode,\n type SerializedCapxulError,\n deserializeCapxulError,\n} from \"./errors.ts\";\n\n// Derived from the canonical catalog in errors.ts — single source of truth,\n// so a new code added to `CAPXUL_ERROR_CODES` is recognized here automatically.\nconst KNOWN_CODES: ReadonlySet<CapxulErrorCode> = new Set(CAPXUL_ERROR_CODES);\n\nfunction isCapxulCode(value: unknown): value is CapxulErrorCode {\n return typeof value === \"string\" && KNOWN_CODES.has(value as CapxulErrorCode);\n}\n\nfunction reconstruct(serialized: Record<string, unknown>): CapxulError | null {\n if (!isCapxulCode(serialized.code)) return null;\n const payload: SerializedCapxulError = {\n code: serialized.code,\n message: typeof serialized.message === \"string\" ? serialized.message : String(serialized.code),\n ...(typeof serialized.details === \"object\" &&\n serialized.details !== null &&\n !Array.isArray(serialized.details)\n ? { details: serialized.details as Record<string, unknown> }\n : {}),\n ...(typeof serialized.correlationId === \"string\"\n ? { correlationId: serialized.correlationId }\n : {}),\n ...(typeof serialized.layer === \"string\" ? { layer: serialized.layer } : {}),\n };\n return deserializeCapxulError(payload);\n}\n\nexport function decodeConvexError(err: unknown): CapxulError | null {\n if (err === null || err === undefined) return null;\n\n // Pass-through: same isolate, real CapxulError instance.\n if (err instanceof CapxulError) return err;\n\n if (typeof err !== \"object\") return null;\n\n // The canonical shape produced by `withErrorBoundary` then crossed by\n // Convex's `ctx.runQuery` / `ConvexHttpClient`: a `ConvexError` whose\n // `data` is the `SerializedCapxulError` object literal.\n const record = err as Record<string, unknown>;\n if (!(\"data\" in record)) return null;\n const data = record.data;\n\n if (typeof data === \"object\" && data !== null) {\n return reconstruct(data as Record<string, unknown>);\n }\n\n // Defensive depth — some Convex versions JSON-stringify the data at\n // the runtime boundary. Probe B confirmed @convex-dev/better-auth 0.10.13\n // + convex 1.39.x do NOT do this, but the cheap parse keeps forward\n // compatibility.\n if (typeof data === \"string\") {\n try {\n const parsed = JSON.parse(data) as unknown;\n if (typeof parsed === \"object\" && parsed !== null) {\n return reconstruct(parsed as Record<string, unknown>);\n }\n } catch {\n // Fall through.\n }\n }\n\n return null;\n}\n","import { Errors } from \"@capxul/errors\";\nimport type { Brand } from \"./brand\";\n\nexport type { Brand } from \"./brand\";\n\nexport type Address = Brand<string, \"Address\">;\nexport type Email = Brand<string, \"Email\">;\nexport type Identity = Brand<string, \"Identity\">;\n// `Profile` is the SDK's user-shaped record returned by `IdentityPort`. Pure\n// record of brand-typed fields — not itself a brand. The field-level brands\n// satisfy `IdentityPort` clause I8 at compile time. Hosted here per the\n// package contract (`packages/types/CONTEXT.md`).\nexport type Profile = {\n readonly authUserId: AuthUserId;\n readonly email: Email;\n readonly displayName: string | null;\n readonly country: CountryCode | null;\n readonly onboarded: boolean;\n readonly withdrawalAddress: Address | null;\n // #1062: globally-unique normalized handle; #1061 / ADR-0014: profile-image\n // serving URL resolved at read time. Plain strings (not branded in this\n // slice); null when unset — the Convex read boundary always maps both.\n readonly username: string | null;\n readonly imageUrl: string | null;\n readonly kycTier: KycTier;\n readonly createdAt: EpochMs;\n readonly updatedAt: EpochMs;\n};\n// `SmartAccount` is the SDK's ERC-4337 record returned by `SmartAccountPort`.\n// Pure record of brand-typed fields — not itself a brand. `deployedAt` is\n// nullable: `null` means the address is counterfactual (derived, not yet\n// on-chain). PRD #462 (derivation v2): `signerAddress` is the CLAIMED owner —\n// `null` until the claim userOp installs the user's signer (`claimedAt`\n// records that event); the address derives from the email alone. Hosted here\n// per the package contract (`packages/types/CONTEXT.md`).\nexport type SmartAccount = {\n readonly authUserId: AuthUserId;\n readonly signerAddress: Address | null;\n readonly smartAccountAddress: Address;\n readonly chainId: ChainId;\n readonly deployedAt: EpochMs | null;\n readonly claimedAt: EpochMs | null;\n readonly createdAt: EpochMs;\n};\n// `Money` is the SDK's consumer-facing value type (canon\n// `account-balance-model.md` §10). Every public monetary value is a `Money`\n// — never wei, never raw token units. `value` is a major-unit decimal string\n// (e.g. \"1.5\" USD); `decimals` is the on-chain token precision used for the\n// internal `fromWei`/`toWei` round-trip at the SDK boundary (USDX is 6).\n// Pure record of a brand-typed field + primitives — not itself a brand.\nexport type Money = {\n readonly currency: CurrencyCode;\n readonly value: string;\n readonly decimals: number;\n};\n\n// `Account` is the SDK's logical money account (canon §6, §9). `id` is the\n// `account_`-shaped `AccountId` — NOT the Safe address and NOT an Openfort id.\n// `balance` is the Safe's top-line holdings; `available` is money not assigned\n// to any sub-account (canon §5/§12). With no sub-accounts (Slice 1a),\n// `available === balance`. Pure record of brand-typed fields — not a brand.\nexport type Account = {\n readonly id: AccountId;\n readonly balance: Money;\n readonly available: Money;\n};\n\n/** Named bucket partitioning a logical Account (canon §9). */\nexport type SubAccount = {\n readonly id: SubAccountId;\n readonly accountId: AccountId;\n readonly name: string;\n readonly balance: Money;\n readonly createdAt: EpochMs;\n};\n\nexport type AuthUserId = Brand<string, \"AuthUserId\">;\nexport type AnonymousDistinctId = Brand<string, \"AnonymousDistinctId\">;\nexport type PlayerId = Brand<string, \"PlayerId\">;\nexport type AccountId = Brand<string, \"AccountId\">;\nexport type SubAccountId = Brand<string, \"SubAccountId\">;\nexport type OrgId = Brand<string, \"OrgId\">;\nexport type AppId = Brand<string, \"AppId\">;\nexport type AllowedOrigin = Brand<string, \"AllowedOrigin\">;\nexport type PublishableKey = Brand<string, \"PublishableKey\">;\nexport type PublishableKeyId = Brand<string, \"PublishableKeyId\">;\nexport type DurationMs = Brand<number, \"DurationMs\">;\n// `DeveloperApplication` and `PublishableKeyRecord` are the SDK's record\n// shapes returned by `CredentialsPort`. Pure records of brand-typed fields\n// — not themselves brands. The field-level brands satisfy CR13 + the record\n// branding clauses of `credentials.test-d.ts` at compile time. Hosted here\n// per the package contract (`packages/types/CONTEXT.md`).\nexport type DeveloperApplication = {\n readonly id: AppId;\n readonly authUserId: AuthUserId;\n readonly name: string;\n readonly allowedOrigins: readonly AllowedOrigin[];\n readonly createdAt: EpochMs;\n readonly archivedAt: EpochMs | null;\n};\nexport type PublishableKeyRecord = {\n readonly id: PublishableKeyId;\n readonly applicationId: AppId;\n readonly activeFromMs: EpochMs;\n readonly gracePeriodEndsMs: EpochMs | null;\n readonly revokedAt: EpochMs | null;\n};\nexport type TxHash = Brand<string, \"TxHash\">;\nexport type DocumentHash = Brand<string, \"DocumentHash\">;\nexport type EpochMs = Brand<number, \"EpochMs\">;\nexport type EpochSeconds = Brand<number, \"EpochSeconds\">;\nexport type ChainId = Brand<number, \"ChainId\">;\nexport type CountryCode = Brand<string, \"CountryCode\">;\nexport type CurrencyCode = Brand<SupportedCurrencyCode, \"CurrencyCode\">;\nexport type KycTier = Brand<0 | 1 | 2 | 3, \"KycTier\">;\nexport type BlockNumber = Brand<number, \"BlockNumber\">;\nexport type LogIndex = Brand<number, \"LogIndex\">;\nexport type WeiAmount = Brand<string, \"WeiAmount\">;\nexport type SafeAddress = Brand<string, \"SafeAddress\">;\nexport type ModuleAddress = Brand<string, \"ModuleAddress\">;\nexport type RunId = Brand<string, \"RunId\">;\nexport type RoleKey = Brand<string, \"RoleKey\">;\nexport type AllowanceKey = Brand<string, \"AllowanceKey\">;\nexport type SessionToken = Brand<string, \"SessionToken\">;\nexport type JwtToken = Brand<string, \"JwtToken\">;\n\n// `AuthSession` is the record type shared by `AuthClientPort` and\n// `SessionStoragePort`. Hosted here per the canon\n// (`packages/types/CONTEXT.md`) so both ports depend on it\n// symmetrically. Every field is branded — field-level brands satisfy the\n// AuthSession branding contract asserted in `auth-client.test-d.ts`.\nexport type AuthSession = {\n readonly authUserId: AuthUserId;\n readonly email: Email;\n readonly token: SessionToken;\n readonly expiresAt: EpochMs;\n};\n\nexport const EVM_ADDRESS_RE = /^0x[0-9a-f]{40}$/i;\nexport const BYTES32_RE = /^0x[0-9a-f]{64}$/i;\nexport const PUBLISHABLE_KEY_PATTERN = /^cap_pk_(test|live)_[0-9A-HJKMNP-TV-Z]{32}$/;\nexport const SUPPORTED_CURRENCIES = [\n { code: \"USD\", symbol: \"$\", name: \"US Dollar\" },\n { code: \"NGN\", symbol: \"NGN\", name: \"Nigerian Naira\" },\n { code: \"GHS\", symbol: \"GHS\", name: \"Ghanaian Cedi\" },\n { code: \"KES\", symbol: \"KSh\", name: \"Kenyan Shilling\" },\n { code: \"UGX\", symbol: \"USh\", name: \"Ugandan Shilling\" },\n] as const;\nexport const SUPPORTED_CURRENCY_CODES = SUPPORTED_CURRENCIES.map((currency) => currency.code);\ntype SupportedCurrencyCode = (typeof SUPPORTED_CURRENCIES)[number][\"code\"];\nexport const CURRENCY_SYMBOLS = Object.fromEntries(\n SUPPORTED_CURRENCIES.map((currency) => [currency.code, currency.symbol]),\n) as Record<SupportedCurrencyCode, string>;\n\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\nconst COUNTRY_CODE_RE = /^[A-Z]{2}$/;\nconst ANONYMOUS_DISTINCT_ID_RE = /^anon_[a-zA-Z0-9-]+$/;\n// Canon §6: the logical Account brand is `account_`-shaped. The tail mirrors\n// the `app_` ULID-shape generator (`account_<26 Crockford base32 chars>`) but\n// the brand only enforces the `account_` prefix + a non-empty alphanumeric\n// tail so existing opaque test ids (`account_123`) and generated ULIDs both\n// satisfy it.\nconst ACCOUNT_ID_RE = /^account_[0-9A-Za-z]+$/;\nconst SUBACCOUNT_ID_RE = /^subaccount_[0-9A-Za-z]+$/;\n// Exported so `@capxul/wire`'s `AppIdSchema` can reuse the same regex via\n// `Schema.filter(...)` and stay in lockstep with `toAppId` (Decision 2,\n// 2b parity).\nexport const APP_ID_RE = /^app_[0-7][0-9A-HJKMNP-TV-Z]{25}$/;\nconst TX_HASH_RE = /^0x[0-9a-f]{64}$/i;\nconst DOCUMENT_HASH_HEX_RE = /^[0-9a-fA-F]{64}$/;\nconst WEI_RE = /^[0-9]+$/;\nconst RUN_ID_RE = /^run_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;\nconst MAX_SAFE_EPOCH_SECONDS = Math.floor(Number.MAX_SAFE_INTEGER / 1000);\n\nexport function toAddress(raw: unknown): Address {\n if (typeof raw !== \"string\" || !EVM_ADDRESS_RE.test(raw)) {\n throw Errors.invalidInput(\"address\", invalidValueReason(\"invalid EVM address format\", raw));\n }\n\n return raw.toLowerCase() as Address;\n}\n\nexport function isEvmAddress(raw: unknown): raw is string {\n return typeof raw === \"string\" && EVM_ADDRESS_RE.test(raw);\n}\n\nexport function toEmail(raw: unknown): Email {\n if (typeof raw !== \"string\" || !EMAIL_RE.test(raw)) {\n throw Errors.invalidInput(\"email\", invalidValueReason(\"must look like an email address\", raw));\n }\n\n return raw.toLowerCase() as Email;\n}\n\nexport function toIdentity(raw: unknown): Identity {\n return toNonEmptyStringBrand(raw, \"identity\") as Identity;\n}\n\nexport function toAuthUserId(raw: unknown): AuthUserId {\n return toNonEmptyStringBrand(raw, \"authUserId\") as AuthUserId;\n}\n\nexport function toAnonymousDistinctId(raw: unknown): AnonymousDistinctId {\n if (typeof raw !== \"string\" || !ANONYMOUS_DISTINCT_ID_RE.test(raw)) {\n throw Errors.invalidInput(\n \"anonDistinctId\",\n invalidValueReason(\"must be anon_ plus letters, digits, or hyphens\", raw),\n );\n }\n\n return raw as AnonymousDistinctId;\n}\n\nexport function toPlayerId(raw: unknown): PlayerId {\n return toNonEmptyStringBrand(raw, \"playerId\") as PlayerId;\n}\n\nexport function toAccountId(raw: unknown): AccountId {\n if (typeof raw !== \"string\" || !ACCOUNT_ID_RE.test(raw)) {\n throw Errors.invalidInput(\n \"accountId\",\n invalidValueReason(\"must be account_ plus an alphanumeric id\", raw),\n );\n }\n\n return raw as AccountId;\n}\n\nexport function toSubAccountId(raw: unknown): SubAccountId {\n if (typeof raw !== \"string\" || !SUBACCOUNT_ID_RE.test(raw)) {\n throw Errors.invalidInput(\n \"subAccountId\",\n invalidValueReason(\"must be subaccount_ plus an alphanumeric id\", raw),\n );\n }\n\n return raw as SubAccountId;\n}\n\nexport function toOrgId(raw: unknown): OrgId {\n return toNonEmptyStringBrand(raw, \"orgId\") as OrgId;\n}\n\nexport function toAppId(raw: unknown): AppId {\n if (typeof raw !== \"string\" || !APP_ID_RE.test(raw)) {\n throw Errors.invalidInput(\"appId\", invalidValueReason(\"must be app_ plus a ULID\", raw));\n }\n\n return raw as AppId;\n}\n\nexport function toAllowedOrigin(raw: unknown): AllowedOrigin {\n if (typeof raw !== \"string\") {\n throw Errors.invalidInput(\"allowedOrigin\", \"must be an http or https origin string\");\n }\n\n const normalized = normalizeAllowedOrigin(raw);\n if (normalized === null) {\n throw Errors.invalidInput(\n \"allowedOrigin\",\n invalidValueReason(\"must be an http or https origin\", raw),\n );\n }\n\n return normalized as AllowedOrigin;\n}\n\nexport function toPublishableKeyId(raw: unknown): PublishableKeyId {\n return toNonEmptyStringBrand(raw, \"keyId\") as PublishableKeyId;\n}\n\nexport function toDurationMs(raw: unknown): DurationMs {\n if (typeof raw !== \"number\" || !Number.isSafeInteger(raw) || raw < 0) {\n throw Errors.invalidInput(\n \"duration\",\n invalidValueReason(\"must be a non-negative safe integer\", raw),\n );\n }\n\n return raw as DurationMs;\n}\n\nexport function toPublishableKey(raw: unknown): PublishableKey {\n if (typeof raw !== \"string\" || !PUBLISHABLE_KEY_PATTERN.test(raw)) {\n throw Errors.invalidInput(\n \"publishableKey\",\n invalidValueReason(\"must match cap_pk_(test|live) plus 32 Crockford base32 chars\", raw),\n );\n }\n\n return raw as PublishableKey;\n}\n\nexport function toTxHash(raw: unknown): TxHash {\n if (typeof raw !== \"string\" || !TX_HASH_RE.test(raw)) {\n throw Errors.invalidInput(\"txHash\", invalidValueReason(\"must be 0x + 64 hex chars\", raw));\n }\n\n return raw.toLowerCase() as TxHash;\n}\n\nexport function toDocumentHash(raw: unknown): DocumentHash {\n if (typeof raw !== \"string\") {\n throw Errors.invalidInput(\"documentHash\", \"must be a string\");\n }\n\n const stripped = raw.startsWith(\"0x\") || raw.startsWith(\"0X\") ? raw.slice(2) : raw;\n if (!DOCUMENT_HASH_HEX_RE.test(stripped)) {\n throw Errors.invalidInput(\"documentHash\", \"must be 32 bytes of hex\");\n }\n\n return `0x${stripped.toLowerCase()}` as DocumentHash;\n}\n\nexport function toEpochMs(raw: unknown): EpochMs {\n assertSafeNonNegativeInteger(raw, \"epochMs\");\n return raw as EpochMs;\n}\n\nexport function toEpochSeconds(raw: unknown): EpochSeconds {\n assertSafeNonNegativeInteger(raw, \"epochSeconds\");\n return raw as EpochSeconds;\n}\n\nexport function secondsToMs(seconds: EpochSeconds): EpochMs {\n if (seconds > MAX_SAFE_EPOCH_SECONDS) {\n throw Errors.invalidInput(\"epochSeconds\", `${seconds} would overflow when multiplied by 1000`);\n }\n\n return toEpochMs(seconds * 1000);\n}\n\nexport function epochMsToSeconds(ms: EpochMs): EpochSeconds {\n return toEpochSeconds(Math.floor(ms / 1000));\n}\n\nexport function toChainId(raw: unknown): ChainId {\n if (typeof raw !== \"number\" || !Number.isSafeInteger(raw) || raw <= 0) {\n throw Errors.invalidInput(\n \"chainId\",\n invalidValueReason(\"must be a positive safe integer\", raw),\n );\n }\n\n return raw as ChainId;\n}\n\nexport function toBlockNumber(raw: unknown): BlockNumber {\n assertSafeNonNegativeInteger(raw, \"blockNumber\");\n return raw as BlockNumber;\n}\n\nexport function toLogIndex(raw: unknown): LogIndex {\n assertSafeNonNegativeInteger(raw, \"logIndex\");\n return raw as LogIndex;\n}\n\nexport function toWeiAmount(raw: unknown): WeiAmount {\n if (typeof raw !== \"string\" || !WEI_RE.test(raw)) {\n throw Errors.invalidInput(\n \"weiAmount\",\n invalidValueReason(\"must be a non-negative integer string\", raw),\n );\n }\n\n return raw as WeiAmount;\n}\n\nexport function toCountryCode(raw: unknown): CountryCode {\n if (typeof raw !== \"string\") {\n throw Errors.invalidInput(\"countryCode\", \"must be a string\");\n }\n\n const upper = raw.toUpperCase();\n if (!COUNTRY_CODE_RE.test(upper)) {\n throw Errors.invalidInput(\n \"countryCode\",\n invalidValueReason(\"must be a 2-letter ISO 3166-1 alpha-2 code\", raw),\n );\n }\n\n return upper as CountryCode;\n}\n\nexport function toCurrencyCode(raw: unknown): CurrencyCode {\n if (typeof raw !== \"string\" || !SUPPORTED_CURRENCY_CODES.includes(raw as SupportedCurrencyCode)) {\n throw Errors.invalidInput(\"currencyCode\", invalidValueReason(\"unsupported currency\", raw));\n }\n\n return raw as CurrencyCode;\n}\n\nexport function currencySymbolFor(code: CurrencyCode): string {\n const symbol = CURRENCY_SYMBOLS[code as SupportedCurrencyCode];\n if (symbol === undefined) {\n throw Errors.invalidInput(\"currencyCode\", `no symbol registered for \"${String(code)}\"`);\n }\n\n return symbol;\n}\n\nexport function toKycTier(raw: unknown): KycTier {\n if (typeof raw !== \"number\" || !Number.isInteger(raw) || raw < 0 || raw > 3) {\n throw Errors.invalidInput(\"kycTier\", invalidValueReason(\"must be an integer in [0, 3]\", raw));\n }\n\n return raw as KycTier;\n}\n\nexport function toSafeAddress(raw: unknown): SafeAddress {\n if (typeof raw !== \"string\" || !EVM_ADDRESS_RE.test(raw)) {\n throw Errors.invalidInput(\"safeAddress\", invalidValueReason(\"invalid EVM address format\", raw));\n }\n\n return raw.toLowerCase() as SafeAddress;\n}\n\nexport function toModuleAddress(raw: unknown): ModuleAddress {\n if (typeof raw !== \"string\" || !EVM_ADDRESS_RE.test(raw)) {\n throw Errors.invalidInput(\n \"moduleAddress\",\n invalidValueReason(\"invalid EVM address format\", raw),\n );\n }\n\n return raw.toLowerCase() as ModuleAddress;\n}\n\nexport function toRunId(raw: unknown): RunId {\n if (typeof raw !== \"string\" || !RUN_ID_RE.test(raw)) {\n throw Errors.invalidInput(\"runId\", \"must match the format run_<uuid>\");\n }\n\n return raw as RunId;\n}\n\nexport function toRoleKey(raw: unknown): RoleKey {\n if (typeof raw !== \"string\" || !BYTES32_RE.test(raw)) {\n throw Errors.invalidInput(\"roleKey\", invalidValueReason(\"must be 0x + 64 hex chars\", raw));\n }\n\n return raw.toLowerCase() as RoleKey;\n}\n\nexport function toAllowanceKey(raw: unknown): AllowanceKey {\n if (typeof raw !== \"string\" || !BYTES32_RE.test(raw)) {\n throw Errors.invalidInput(\"allowanceKey\", invalidValueReason(\"must be 0x + 64 hex chars\", raw));\n }\n\n return raw.toLowerCase() as AllowanceKey;\n}\n\nexport function toSessionToken(raw: unknown): SessionToken {\n if (typeof raw !== \"string\" || raw.length === 0) {\n throw Errors.invalidInput(\"token\", \"must be a non-empty string\");\n }\n\n return raw as SessionToken;\n}\n\nexport function toJwtToken(raw: unknown): JwtToken {\n if (typeof raw !== \"string\" || raw.length === 0) {\n throw Errors.invalidInput(\"jwtToken\", \"must be a non-empty string\");\n }\n\n return raw as JwtToken;\n}\n\nfunction toNonEmptyStringBrand(raw: unknown, field: string): string {\n if (typeof raw !== \"string\" || raw.length === 0) {\n throw Errors.invalidInput(field, \"must be a non-empty string\");\n }\n\n return raw;\n}\n\nfunction assertSafeNonNegativeInteger(raw: unknown, field: string): asserts raw is number {\n if (typeof raw !== \"number\" || !Number.isSafeInteger(raw) || raw < 0) {\n throw Errors.invalidInput(\n field,\n invalidValueReason(\"must be a non-negative safe integer\", raw),\n );\n }\n}\n\nfunction normalizeAllowedOrigin(raw: string): string | null {\n let parsed: URL;\n try {\n parsed = new URL(raw);\n } catch {\n return null;\n }\n\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n return null;\n }\n\n if (parsed.hostname.includes(\"*\")) {\n return null;\n }\n\n return parsed.origin;\n}\n\nfunction invalidValueReason(prefix: string, raw: unknown): string {\n if (typeof raw === \"string\") {\n return `${prefix}: ${raw.slice(0, 40)}`;\n }\n\n return `${prefix}: ${String(raw)}`;\n}\n","import { Context, Data, Effect } from \"effect\";\nimport type { AuthSession, EpochSeconds, JwtToken } from \"@capxul/types\";\n\n/**\n * AuthCachePort (TA4) — replaces `SessionStoragePort` in the rebuild slice's\n * consumer-facing wiring. Stores the user-snapshot Session AND the cached\n * Convex JWT (W7 bridge endpoint). The two slots are independent so a session\n * refresh doesn't invalidate the JWT and vice versa.\n *\n * Three adapters (TA7):\n * - `BrowserAuthCacheAdapter` — backed by `localStorage`\n * - `FileSystemAuthCacheAdapter` — mode-0600 JSON file in `~/.config/capxul/`\n * - `InMemoryAuthCacheAdapter` — for tests\n *\n * `SessionStoragePort` was retired by the Stage 4 rebuild; session and JWT\n * persistence now share this cache boundary.\n */\nexport interface AuthCachePort {\n readonly getSession: Effect.Effect<AuthSession | null, AuthCacheError>;\n readonly setSession: (session: AuthSession) => Effect.Effect<void, AuthCacheError>;\n readonly clearSession: Effect.Effect<void, AuthCacheError>;\n\n /**\n * JWT cache for the `/api/auth/convex/token` bridge endpoint (W7).\n * Stored separately from the session so a session refresh doesn't\n * invalidate cached JWT.\n */\n readonly getJwt: Effect.Effect<CachedJwt | null, AuthCacheError>;\n readonly setJwt: (jwt: CachedJwt) => Effect.Effect<void, AuthCacheError>;\n readonly clearJwt: Effect.Effect<void, AuthCacheError>;\n}\n\n/**\n * Cached Convex JWT shape (TA4). `expEpochSeconds` is decoded from the JWT's\n * `exp` claim at fetch time so the `tokenProvider` cache eviction logic can\n * proactively refresh at `exp - 30s` per TA3.\n */\nexport interface CachedJwt {\n readonly token: JwtToken;\n readonly expEpochSeconds: EpochSeconds;\n}\n\nexport class AuthCacheError extends Data.TaggedError(\"AuthCacheError\")<{\n readonly operation: string;\n readonly cause: unknown;\n}> {}\n\nexport class AuthCachePortTag extends Context.Service<AuthCachePortTag, AuthCachePort>()(\n \"@capxul/sdk/ports/AuthCachePort\",\n) {}\n","import {\n toAuthUserId,\n toEmail,\n toEpochMs,\n toEpochSeconds,\n toJwtToken,\n toSessionToken,\n type AuthSession,\n} from \"@capxul/types\";\n\nimport type { CachedJwt } from \"../../ports/auth-cache\";\n\nexport function parseAuthSession(raw: unknown): AuthSession | null {\n if (typeof raw !== \"object\" || raw === null) return null;\n const candidate = raw as {\n readonly authUserId?: unknown;\n readonly email?: unknown;\n readonly token?: unknown;\n readonly expiresAt?: unknown;\n };\n\n try {\n return {\n authUserId: toAuthUserId(candidate.authUserId),\n email: toEmail(candidate.email),\n token: toSessionToken(candidate.token),\n expiresAt: toEpochMs(candidate.expiresAt),\n };\n } catch {\n return null;\n }\n}\n\nexport function parseCachedJwt(raw: unknown): CachedJwt | null {\n if (typeof raw !== \"object\" || raw === null) return null;\n const candidate = raw as {\n readonly token?: unknown;\n readonly expEpochSeconds?: unknown;\n };\n\n try {\n return {\n token: toJwtToken(candidate.token),\n expEpochSeconds: toEpochSeconds(candidate.expEpochSeconds),\n };\n } catch {\n return null;\n }\n}\n","import { Effect, Layer } from \"effect\";\nimport type { AuthSession } from \"@capxul/types\";\n\nimport {\n AuthCacheError,\n AuthCachePortTag,\n type AuthCachePort,\n type CachedJwt,\n} from \"../../ports/auth-cache\";\nimport { parseAuthSession, parseCachedJwt } from \"./serialization\";\n\nexport interface BrowserStorageShape {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n}\n\nconst SESSION_KEY = \"capxul.session\";\nconst JWT_KEY = \"capxul.jwt\";\n\nexport class BrowserAuthCacheAdapter implements AuthCachePort {\n private readonly storage: BrowserStorageShape;\n\n constructor(storage: BrowserStorageShape) {\n this.storage = storage;\n }\n\n readonly getSession = authCacheTry(\"getSession\", () => {\n const raw = this.storage.getItem(SESSION_KEY);\n if (raw === null) return null;\n try {\n return parseAuthSession(JSON.parse(raw));\n } catch {\n return null;\n }\n });\n\n readonly setSession = (session: AuthSession) =>\n authCacheTry(\"setSession\", () => {\n this.storage.setItem(SESSION_KEY, JSON.stringify(session));\n });\n\n readonly clearSession = authCacheTry(\"clearSession\", () => {\n this.storage.removeItem(SESSION_KEY);\n });\n\n readonly getJwt = authCacheTry(\"getJwt\", () => {\n const raw = this.storage.getItem(JWT_KEY);\n if (raw === null) return null;\n try {\n return parseCachedJwt(JSON.parse(raw));\n } catch {\n return null;\n }\n });\n\n readonly setJwt = (jwt: CachedJwt) =>\n authCacheTry(\"setJwt\", () => {\n this.storage.setItem(JWT_KEY, JSON.stringify(jwt));\n });\n\n readonly clearJwt = authCacheTry(\"clearJwt\", () => {\n this.storage.removeItem(JWT_KEY);\n });\n}\n\nexport function BrowserAuthCacheLayer(input: {\n readonly storage: BrowserStorageShape;\n}): Layer.Layer<AuthCachePortTag, AuthCacheError> {\n return Layer.effect(\n AuthCachePortTag,\n Effect.sync(() => new BrowserAuthCacheAdapter(input.storage)).pipe(\n Effect.mapError((cause) => toAuthCacheError(\"initialize\", cause)),\n ),\n );\n}\n\nfunction toAuthCacheError(operation: string, cause: unknown): AuthCacheError {\n return new AuthCacheError({ operation, cause });\n}\n\nfunction authCacheTry<T>(operation: string, run: () => T): Effect.Effect<T, AuthCacheError> {\n return Effect.try({\n try: run,\n catch: (cause) => toAuthCacheError(operation, cause),\n });\n}\n","import { Effect, Layer } from \"effect\";\nimport type { AuthSession } from \"@capxul/types\";\n\nimport {\n AuthCacheError,\n AuthCachePortTag,\n type AuthCachePort,\n type CachedJwt,\n} from \"../../ports/auth-cache\";\n\nexport class InMemoryAuthCacheAdapter implements AuthCachePort {\n private session: AuthSession | null = null;\n private jwt: CachedJwt | null = null;\n\n readonly getSession = Effect.sync(() => this.session);\n\n readonly setSession = (session: AuthSession) =>\n Effect.sync(() => {\n this.session = session;\n });\n\n readonly clearSession = Effect.sync(() => {\n this.session = null;\n });\n\n readonly getJwt = Effect.sync(() => this.jwt);\n\n readonly setJwt = (jwt: CachedJwt) =>\n Effect.sync(() => {\n this.jwt = jwt;\n });\n\n readonly clearJwt = Effect.sync(() => {\n this.jwt = null;\n });\n}\n\nexport const InMemoryAuthCacheLayer = Layer.effect(\n AuthCachePortTag,\n Effect.sync(() => new InMemoryAuthCacheAdapter()).pipe(\n Effect.mapError((cause) => new AuthCacheError({ operation: \"initialize\", cause })),\n ),\n);\n"],"mappings":";;AAKA,MAAa,qBAAqB;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;AAYA,MAAa,8BAA4D,IAAI,IAAI;CAC/E;CACA;CAKA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AA4DD,IAAa,cAAb,cAAiC,MAAM;CACrC;CACA;CACA;CACA;CAEA,YAAY,MAAuB,SAAiB,UAA8B,CAAC,GAAG;EACpF,MAAM,SAAS,WAAW,UAAU,EAAE,OAAO,QAAQ,MAAM,IAAI,KAAA,CAAS;EACxE,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,IAAI,QAAQ,YAAY,KAAA,GACtB,KAAK,UAAU,QAAQ;E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