@capxul/sdk 0.2.0-alpha.5 → 1.0.0-alpha.7
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 +5 -4
- package/dist/InMemoryAuthCacheAdapter-v5W-XB5M.mjs +457 -0
- package/dist/InMemoryAuthCacheAdapter-v5W-XB5M.mjs.map +1 -0
- package/dist/index-CTXgQ_xR.d.mts +158 -0
- package/dist/index-CTXgQ_xR.d.mts.map +1 -0
- package/dist/index.d.mts +1061 -233
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +6211 -3999
- package/dist/index.mjs.map +1 -1
- package/dist/node/index.d.mts +3 -3
- package/dist/node/index.mjs +1 -2
- package/dist/node/index.mjs.map +1 -1
- package/dist/ports/safe-deployment.d.mts +1 -1
- package/dist/{safe-deployment-Vni46k3t.d.mts → safe-deployment-D3k9yndM.d.mts} +4 -5
- package/dist/safe-deployment-D3k9yndM.d.mts.map +1 -0
- package/dist/{signer-oaYGfjDe.d.mts → signer-DqDtJU1l.d.mts} +17 -14
- package/dist/signer-DqDtJU1l.d.mts.map +1 -0
- package/package.json +13 -10
- package/dist/InMemoryAuthCacheAdapter-BK-B_ERB.mjs +0 -113
- package/dist/InMemoryAuthCacheAdapter-BK-B_ERB.mjs.map +0 -1
- package/dist/safe-deployment-Vni46k3t.d.mts.map +0 -1
- package/dist/signer-oaYGfjDe.d.mts.map +0 -1
package/README.md
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
# @capxul/sdk
|
|
2
2
|
|
|
3
|
-
Layer 0 SDK package.
|
|
3
|
+
Layer 0 SDK package.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
- [Getting started](./docs/getting-started.md) — canonical consumer DX
|
|
6
|
+
- [Package docs index](./docs/README.md)
|
|
7
|
+
- [Env module](./docs/env.md)
|
|
6
8
|
|
|
7
|
-
|
|
8
|
-
Layer exports.
|
|
9
|
+
React apps: [`@capxul/sdk-react` provider docs](../sdk-react/docs/provider.md).
|
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
import { Context, Data, Effect, Layer } from "effect";
|
|
2
|
+
//#region ../errors/src/errors.ts
|
|
3
|
+
const CAPXUL_ERROR_CODES = [
|
|
4
|
+
"NOT_AUTHENTICATED",
|
|
5
|
+
"EMAIL_DELIVERY_FAILED",
|
|
6
|
+
"PROFILE_NOT_FOUND",
|
|
7
|
+
"SMART_ACCOUNT_MISSING",
|
|
8
|
+
"PLAYER_NOT_FOUND",
|
|
9
|
+
"ACCOUNT_NOT_FOUND",
|
|
10
|
+
"PROVIDER_ERROR",
|
|
11
|
+
"INVALID_INPUT",
|
|
12
|
+
"ENV_MISSING",
|
|
13
|
+
"NOT_IMPLEMENTED",
|
|
14
|
+
"VERIFICATION_REQUIRED",
|
|
15
|
+
"INSUFFICIENT_BALANCE",
|
|
16
|
+
"INVALID_RECIPIENT",
|
|
17
|
+
"ROLE_PERMISSION_DENIED",
|
|
18
|
+
"TRANSACTION_FAILED",
|
|
19
|
+
"RATE_LIMITED",
|
|
20
|
+
"NETWORK_ERROR",
|
|
21
|
+
"UNKNOWN",
|
|
22
|
+
"OTP_EXPIRED",
|
|
23
|
+
"SIGNER_REJECTED",
|
|
24
|
+
"CANCELLED",
|
|
25
|
+
"WRONG_STATE"
|
|
26
|
+
];
|
|
27
|
+
var CapxulError = class extends Error {
|
|
28
|
+
code;
|
|
29
|
+
details;
|
|
30
|
+
correlationId;
|
|
31
|
+
layer;
|
|
32
|
+
constructor(code, message, options = {}) {
|
|
33
|
+
super(message, "cause" in options ? { cause: options.cause } : void 0);
|
|
34
|
+
this.name = "CapxulError";
|
|
35
|
+
this.code = code;
|
|
36
|
+
if (options.details !== void 0) this.details = options.details;
|
|
37
|
+
if (options.correlationId !== void 0) this.correlationId = options.correlationId;
|
|
38
|
+
if (options.layer !== void 0) this.layer = options.layer;
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
function isCapxulError(value) {
|
|
42
|
+
return value instanceof CapxulError;
|
|
43
|
+
}
|
|
44
|
+
function deserializeCapxulError(serialized) {
|
|
45
|
+
return new CapxulError(serialized.code, serialized.message, compactErrorOptions({
|
|
46
|
+
details: serialized.details,
|
|
47
|
+
correlationId: serialized.correlationId,
|
|
48
|
+
layer: serialized.layer
|
|
49
|
+
}));
|
|
50
|
+
}
|
|
51
|
+
function compactErrorOptions(options) {
|
|
52
|
+
const result = {};
|
|
53
|
+
if ("cause" in options) result.cause = options.cause;
|
|
54
|
+
if (options.details !== void 0) result.details = options.details;
|
|
55
|
+
if (options.correlationId !== void 0) result.correlationId = options.correlationId;
|
|
56
|
+
if (options.layer !== void 0) result.layer = options.layer;
|
|
57
|
+
return result;
|
|
58
|
+
}
|
|
59
|
+
const Errors = {
|
|
60
|
+
notAuthenticated: (message, opts) => new CapxulError("NOT_AUTHENTICATED", message ?? "Not authenticated", opts?.failure_mode ? { details: { failure_mode: opts.failure_mode } } : void 0),
|
|
61
|
+
emailDeliveryFailed: (detail) => new CapxulError("EMAIL_DELIVERY_FAILED", "Failed to send email", { details: { detail } }),
|
|
62
|
+
profileNotFound: (authUserId) => new CapxulError("PROFILE_NOT_FOUND", `Profile not found for user ${authUserId}`, { details: { authUserId } }),
|
|
63
|
+
smartAccountMissing: (authUserId) => new CapxulError("SMART_ACCOUNT_MISSING", "Smart account not provisioned", { details: { authUserId } }),
|
|
64
|
+
playerNotFound: (playerId) => new CapxulError("PLAYER_NOT_FOUND", playerId ? `Openfort player ${playerId} not found` : "Openfort player not found", playerId === void 0 ? void 0 : { details: { playerId } }),
|
|
65
|
+
accountNotFound: (accountId) => new CapxulError("ACCOUNT_NOT_FOUND", accountId ? `Openfort account ${accountId} not found` : "Openfort account not found", accountId === void 0 ? void 0 : { details: { accountId } }),
|
|
66
|
+
providerError: (provider, operation, cause, opts) => {
|
|
67
|
+
const details = {
|
|
68
|
+
provider,
|
|
69
|
+
operation
|
|
70
|
+
};
|
|
71
|
+
if (opts?.failure_mode) details.failure_mode = opts.failure_mode;
|
|
72
|
+
return new CapxulError("PROVIDER_ERROR", `Provider error: ${provider} ${operation}`, {
|
|
73
|
+
cause,
|
|
74
|
+
details
|
|
75
|
+
});
|
|
76
|
+
},
|
|
77
|
+
invalidInput: (field, reason) => new CapxulError("INVALID_INPUT", `Invalid ${field}: ${reason}`, { details: {
|
|
78
|
+
field,
|
|
79
|
+
reason
|
|
80
|
+
} }),
|
|
81
|
+
envMissing: (name) => new CapxulError("ENV_MISSING", `Environment variable ${name} not configured`, { details: { name } }),
|
|
82
|
+
notImplemented: (domain, method) => new CapxulError("NOT_IMPLEMENTED", `${domain}.${method} is not yet implemented. This feature is planned for a future release.`, { details: {
|
|
83
|
+
domain,
|
|
84
|
+
method
|
|
85
|
+
} }),
|
|
86
|
+
/**
|
|
87
|
+
* Sibling factory to {@link Errors.providerError} for the per-state timeout
|
|
88
|
+
* path in flows (initially ProvisioningFlow's mint_openfort / deploy_safe /
|
|
89
|
+
* register_indexer `after:` timers). Same `PROVIDER_ERROR` code as
|
|
90
|
+
* `providerError`, plus a `details.reason: "timeout"` discriminator so
|
|
91
|
+
* downstream observers can distinguish failure modes without parsing the
|
|
92
|
+
* message string. The redacted message names the timeout budget; the
|
|
93
|
+
* native `cause` carries the same information for `reportError` fidelity.
|
|
94
|
+
*/
|
|
95
|
+
providerTimeout: (provider, operation, timeoutMs) => new CapxulError("PROVIDER_ERROR", `Provider error: ${provider} ${operation} (timeout exceeded ${timeoutMs}ms)`, {
|
|
96
|
+
details: {
|
|
97
|
+
provider,
|
|
98
|
+
operation,
|
|
99
|
+
reason: "timeout"
|
|
100
|
+
},
|
|
101
|
+
cause: /* @__PURE__ */ new Error(`timeout: ${operation} exceeded ${timeoutMs}ms`)
|
|
102
|
+
}),
|
|
103
|
+
verificationRequired: (details) => {
|
|
104
|
+
return new CapxulError("VERIFICATION_REQUIRED", "rail" in details ? `Verification is required before ${details.rail} can use ${details.currentKind}.` : `Verification tier ${details.requiredTier} is required.`, { details });
|
|
105
|
+
},
|
|
106
|
+
insufficientBalance: (asset, available, required) => new CapxulError("INSUFFICIENT_BALANCE", `Insufficient ${asset} balance`, { details: {
|
|
107
|
+
asset,
|
|
108
|
+
available,
|
|
109
|
+
required
|
|
110
|
+
} }),
|
|
111
|
+
invalidRecipient: (reason) => new CapxulError("INVALID_RECIPIENT", `Invalid recipient: ${reason}`, { details: { reason } }),
|
|
112
|
+
/**
|
|
113
|
+
* The org Zodiac Roles modifier REFUSED the spend on-chain (G4 · #547): the
|
|
114
|
+
* member's role condition (per-tx cap, per-day allowance, allowed recipient,
|
|
115
|
+
* or membership) was violated, so `execTransactionWithRole` reverted. This is
|
|
116
|
+
* a PERMISSION denial — explicitly NOT an `INSUFFICIENT_BALANCE` (the treasury
|
|
117
|
+
* held the funds; the role's authority is what bound). `reason` discriminates
|
|
118
|
+
* the violated condition (`over_cap` / `daily_cap` / `not_member` /
|
|
119
|
+
* `disallowed_recipient` / `condition_violation`); leak-safe — no on-chain
|
|
120
|
+
* identifiers ever enter the details.
|
|
121
|
+
*/
|
|
122
|
+
rolePermissionDenied: (details) => new CapxulError("ROLE_PERMISSION_DENIED", `Org role denied this spend on-chain (${details.reason}).`, { details: details.operation === void 0 ? { reason: details.reason } : {
|
|
123
|
+
reason: details.reason,
|
|
124
|
+
operation: details.operation
|
|
125
|
+
} }),
|
|
126
|
+
/**
|
|
127
|
+
* A transaction (or sponsored UserOp) failed. `details.reason` discriminates
|
|
128
|
+
* the failure mode for callers that must distinguish a CONFIRMED on-chain
|
|
129
|
+
* revert (`"onchain_revert"` — the op executed and reverted, e.g. a Zodiac
|
|
130
|
+
* Roles condition violation) from an inconclusive infra failure. A confirmed
|
|
131
|
+
* revert is the ONLY mode the org spend port may map to a roles denial.
|
|
132
|
+
*/
|
|
133
|
+
transactionFailed: (operation, cause, extra) => new CapxulError("TRANSACTION_FAILED", `Transaction failed: ${operation}`, {
|
|
134
|
+
cause,
|
|
135
|
+
details: extra?.reason === void 0 ? { operation } : {
|
|
136
|
+
operation,
|
|
137
|
+
reason: extra.reason
|
|
138
|
+
}
|
|
139
|
+
}),
|
|
140
|
+
rateLimited: (details) => new CapxulError("RATE_LIMITED", "Rate limit exceeded", details === void 0 ? void 0 : { details: { ...details } }),
|
|
141
|
+
networkError: (operation, cause) => new CapxulError("NETWORK_ERROR", `Network error during ${operation}`, {
|
|
142
|
+
cause,
|
|
143
|
+
details: { operation }
|
|
144
|
+
}),
|
|
145
|
+
unknown: (cause) => new CapxulError("UNKNOWN", "Unknown error", { cause }),
|
|
146
|
+
otpExpired: (details) => new CapxulError("OTP_EXPIRED", "Verification code has expired. Request a new one.", details === void 0 ? void 0 : { details: { ...details } }),
|
|
147
|
+
signerRejected: (details) => new CapxulError("SIGNER_REJECTED", "Signer rejected the request.", {
|
|
148
|
+
cause: details.cause,
|
|
149
|
+
details: details.reason === void 0 ? { source: details.source } : {
|
|
150
|
+
source: details.source,
|
|
151
|
+
reason: details.reason
|
|
152
|
+
}
|
|
153
|
+
}),
|
|
154
|
+
cancelled: (details) => new CapxulError("CANCELLED", "Operation was cancelled.", details === void 0 ? void 0 : { details: { ...details } }),
|
|
155
|
+
/**
|
|
156
|
+
* Method called from a flow state where its precondition fails (TA16). The
|
|
157
|
+
* SDK's method API short-circuits with this error before driving the
|
|
158
|
+
* internal state machine. `currentState` is the Effect-machine snapshot
|
|
159
|
+
* tag (stringified — substrate is `@effect/experimental/Machine` per
|
|
160
|
+
* `docs/canon/decisions/state-machine-substrate.md`); `validStates`
|
|
161
|
+
* enumerates the states the method accepts.
|
|
162
|
+
*/
|
|
163
|
+
wrongState: (details) => new CapxulError("WRONG_STATE", `${details.method} called from state '${details.currentState}'; valid states: ${details.validStates.join(", ")}`, { details: {
|
|
164
|
+
...details,
|
|
165
|
+
validStates: [...details.validStates]
|
|
166
|
+
} })
|
|
167
|
+
};
|
|
168
|
+
//#endregion
|
|
169
|
+
//#region ../errors/src/convex-error-decoding.ts
|
|
170
|
+
const KNOWN_CODES = new Set(CAPXUL_ERROR_CODES);
|
|
171
|
+
function isCapxulCode(value) {
|
|
172
|
+
return typeof value === "string" && KNOWN_CODES.has(value);
|
|
173
|
+
}
|
|
174
|
+
function reconstruct(serialized) {
|
|
175
|
+
if (!isCapxulCode(serialized.code)) return null;
|
|
176
|
+
return deserializeCapxulError({
|
|
177
|
+
code: serialized.code,
|
|
178
|
+
message: typeof serialized.message === "string" ? serialized.message : String(serialized.code),
|
|
179
|
+
...typeof serialized.details === "object" && serialized.details !== null && !Array.isArray(serialized.details) ? { details: serialized.details } : {},
|
|
180
|
+
...typeof serialized.correlationId === "string" ? { correlationId: serialized.correlationId } : {},
|
|
181
|
+
...typeof serialized.layer === "string" ? { layer: serialized.layer } : {}
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
function decodeConvexError(err) {
|
|
185
|
+
if (err === null || err === void 0) return null;
|
|
186
|
+
if (err instanceof CapxulError) return err;
|
|
187
|
+
if (typeof err !== "object") return null;
|
|
188
|
+
const record = err;
|
|
189
|
+
if (!("data" in record)) return null;
|
|
190
|
+
const data = record.data;
|
|
191
|
+
if (typeof data === "object" && data !== null) return reconstruct(data);
|
|
192
|
+
if (typeof data === "string") try {
|
|
193
|
+
const parsed = JSON.parse(data);
|
|
194
|
+
if (typeof parsed === "object" && parsed !== null) return reconstruct(parsed);
|
|
195
|
+
} catch {}
|
|
196
|
+
return null;
|
|
197
|
+
}
|
|
198
|
+
//#endregion
|
|
199
|
+
//#region ../types/src/index.ts
|
|
200
|
+
const EVM_ADDRESS_RE = /^0x[0-9a-f]{40}$/i;
|
|
201
|
+
const BYTES32_RE = /^0x[0-9a-f]{64}$/i;
|
|
202
|
+
const PUBLISHABLE_KEY_PATTERN = /^cap_pk_(test|live)_[0-9A-HJKMNP-TV-Z]{32}$/;
|
|
203
|
+
const SUPPORTED_CURRENCIES = [
|
|
204
|
+
{
|
|
205
|
+
code: "USD",
|
|
206
|
+
symbol: "$",
|
|
207
|
+
name: "US Dollar"
|
|
208
|
+
},
|
|
209
|
+
{
|
|
210
|
+
code: "NGN",
|
|
211
|
+
symbol: "NGN",
|
|
212
|
+
name: "Nigerian Naira"
|
|
213
|
+
},
|
|
214
|
+
{
|
|
215
|
+
code: "GHS",
|
|
216
|
+
symbol: "GHS",
|
|
217
|
+
name: "Ghanaian Cedi"
|
|
218
|
+
},
|
|
219
|
+
{
|
|
220
|
+
code: "KES",
|
|
221
|
+
symbol: "KSh",
|
|
222
|
+
name: "Kenyan Shilling"
|
|
223
|
+
},
|
|
224
|
+
{
|
|
225
|
+
code: "UGX",
|
|
226
|
+
symbol: "USh",
|
|
227
|
+
name: "Ugandan Shilling"
|
|
228
|
+
}
|
|
229
|
+
];
|
|
230
|
+
const SUPPORTED_CURRENCY_CODES = SUPPORTED_CURRENCIES.map((currency) => currency.code);
|
|
231
|
+
Object.fromEntries(SUPPORTED_CURRENCIES.map((currency) => [currency.code, currency.symbol]));
|
|
232
|
+
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
233
|
+
const COUNTRY_CODE_RE = /^[A-Z]{2}$/;
|
|
234
|
+
const ANONYMOUS_DISTINCT_ID_RE = /^anon_[a-zA-Z0-9-]+$/;
|
|
235
|
+
const ACCOUNT_ID_RE = /^account_[0-9A-Za-z]+$/;
|
|
236
|
+
const SUBACCOUNT_ID_RE = /^subaccount_[0-9A-Za-z]+$/;
|
|
237
|
+
const APP_ID_RE = /^app_[0-7][0-9A-HJKMNP-TV-Z]{25}$/;
|
|
238
|
+
Math.floor(Number.MAX_SAFE_INTEGER / 1e3);
|
|
239
|
+
function toAddress(raw) {
|
|
240
|
+
if (typeof raw !== "string" || !EVM_ADDRESS_RE.test(raw)) throw Errors.invalidInput("address", invalidValueReason("invalid EVM address format", raw));
|
|
241
|
+
return raw.toLowerCase();
|
|
242
|
+
}
|
|
243
|
+
function toEmail(raw) {
|
|
244
|
+
if (typeof raw !== "string" || !EMAIL_RE.test(raw)) throw Errors.invalidInput("email", invalidValueReason("must look like an email address", raw));
|
|
245
|
+
return raw.toLowerCase();
|
|
246
|
+
}
|
|
247
|
+
function toAuthUserId(raw) {
|
|
248
|
+
return toNonEmptyStringBrand(raw, "authUserId");
|
|
249
|
+
}
|
|
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
|
+
function toAccountId(raw) {
|
|
255
|
+
if (typeof raw !== "string" || !ACCOUNT_ID_RE.test(raw)) throw Errors.invalidInput("accountId", invalidValueReason("must be account_ plus an alphanumeric id", raw));
|
|
256
|
+
return raw;
|
|
257
|
+
}
|
|
258
|
+
function toSubAccountId(raw) {
|
|
259
|
+
if (typeof raw !== "string" || !SUBACCOUNT_ID_RE.test(raw)) throw Errors.invalidInput("subAccountId", invalidValueReason("must be subaccount_ plus an alphanumeric id", raw));
|
|
260
|
+
return raw;
|
|
261
|
+
}
|
|
262
|
+
function toOrgId(raw) {
|
|
263
|
+
return toNonEmptyStringBrand(raw, "orgId");
|
|
264
|
+
}
|
|
265
|
+
function toAppId(raw) {
|
|
266
|
+
if (typeof raw !== "string" || !APP_ID_RE.test(raw)) throw Errors.invalidInput("appId", invalidValueReason("must be app_ plus a ULID", raw));
|
|
267
|
+
return raw;
|
|
268
|
+
}
|
|
269
|
+
function toAllowedOrigin(raw) {
|
|
270
|
+
if (typeof raw !== "string") throw Errors.invalidInput("allowedOrigin", "must be an http or https origin string");
|
|
271
|
+
const normalized = normalizeAllowedOrigin(raw);
|
|
272
|
+
if (normalized === null) throw Errors.invalidInput("allowedOrigin", invalidValueReason("must be an http or https origin", raw));
|
|
273
|
+
return normalized;
|
|
274
|
+
}
|
|
275
|
+
function toPublishableKeyId(raw) {
|
|
276
|
+
return toNonEmptyStringBrand(raw, "keyId");
|
|
277
|
+
}
|
|
278
|
+
function toDurationMs(raw) {
|
|
279
|
+
if (typeof raw !== "number" || !Number.isSafeInteger(raw) || raw < 0) throw Errors.invalidInput("duration", invalidValueReason("must be a non-negative safe integer", raw));
|
|
280
|
+
return raw;
|
|
281
|
+
}
|
|
282
|
+
function toPublishableKey(raw) {
|
|
283
|
+
if (typeof raw !== "string" || !PUBLISHABLE_KEY_PATTERN.test(raw)) throw Errors.invalidInput("publishableKey", invalidValueReason("must match cap_pk_(test|live) plus 32 Crockford base32 chars", raw));
|
|
284
|
+
return raw;
|
|
285
|
+
}
|
|
286
|
+
function toEpochMs(raw) {
|
|
287
|
+
assertSafeNonNegativeInteger(raw, "epochMs");
|
|
288
|
+
return raw;
|
|
289
|
+
}
|
|
290
|
+
function toEpochSeconds(raw) {
|
|
291
|
+
assertSafeNonNegativeInteger(raw, "epochSeconds");
|
|
292
|
+
return raw;
|
|
293
|
+
}
|
|
294
|
+
function toChainId(raw) {
|
|
295
|
+
if (typeof raw !== "number" || !Number.isSafeInteger(raw) || raw <= 0) throw Errors.invalidInput("chainId", invalidValueReason("must be a positive safe integer", raw));
|
|
296
|
+
return raw;
|
|
297
|
+
}
|
|
298
|
+
function toCountryCode(raw) {
|
|
299
|
+
if (typeof raw !== "string") throw Errors.invalidInput("countryCode", "must be a string");
|
|
300
|
+
const upper = raw.toUpperCase();
|
|
301
|
+
if (!COUNTRY_CODE_RE.test(upper)) throw Errors.invalidInput("countryCode", invalidValueReason("must be a 2-letter ISO 3166-1 alpha-2 code", raw));
|
|
302
|
+
return upper;
|
|
303
|
+
}
|
|
304
|
+
function toCurrencyCode(raw) {
|
|
305
|
+
if (typeof raw !== "string" || !SUPPORTED_CURRENCY_CODES.includes(raw)) throw Errors.invalidInput("currencyCode", invalidValueReason("unsupported currency", raw));
|
|
306
|
+
return raw;
|
|
307
|
+
}
|
|
308
|
+
function toKycTier(raw) {
|
|
309
|
+
if (typeof raw !== "number" || !Number.isInteger(raw) || raw < 0 || raw > 3) throw Errors.invalidInput("kycTier", invalidValueReason("must be an integer in [0, 3]", raw));
|
|
310
|
+
return raw;
|
|
311
|
+
}
|
|
312
|
+
function toRoleKey(raw) {
|
|
313
|
+
if (typeof raw !== "string" || !BYTES32_RE.test(raw)) throw Errors.invalidInput("roleKey", invalidValueReason("must be 0x + 64 hex chars", raw));
|
|
314
|
+
return raw.toLowerCase();
|
|
315
|
+
}
|
|
316
|
+
function toSessionToken(raw) {
|
|
317
|
+
if (typeof raw !== "string" || raw.length === 0) throw Errors.invalidInput("token", "must be a non-empty string");
|
|
318
|
+
return raw;
|
|
319
|
+
}
|
|
320
|
+
function toJwtToken(raw) {
|
|
321
|
+
if (typeof raw !== "string" || raw.length === 0) throw Errors.invalidInput("jwtToken", "must be a non-empty string");
|
|
322
|
+
return raw;
|
|
323
|
+
}
|
|
324
|
+
function toNonEmptyStringBrand(raw, field) {
|
|
325
|
+
if (typeof raw !== "string" || raw.length === 0) throw Errors.invalidInput(field, "must be a non-empty string");
|
|
326
|
+
return raw;
|
|
327
|
+
}
|
|
328
|
+
function assertSafeNonNegativeInteger(raw, field) {
|
|
329
|
+
if (typeof raw !== "number" || !Number.isSafeInteger(raw) || raw < 0) throw Errors.invalidInput(field, invalidValueReason("must be a non-negative safe integer", raw));
|
|
330
|
+
}
|
|
331
|
+
function normalizeAllowedOrigin(raw) {
|
|
332
|
+
let parsed;
|
|
333
|
+
try {
|
|
334
|
+
parsed = new URL(raw);
|
|
335
|
+
} catch {
|
|
336
|
+
return null;
|
|
337
|
+
}
|
|
338
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
|
|
339
|
+
if (parsed.hostname.includes("*")) return null;
|
|
340
|
+
return parsed.origin;
|
|
341
|
+
}
|
|
342
|
+
function invalidValueReason(prefix, raw) {
|
|
343
|
+
if (typeof raw === "string") return `${prefix}: ${raw.slice(0, 40)}`;
|
|
344
|
+
return `${prefix}: ${String(raw)}`;
|
|
345
|
+
}
|
|
346
|
+
//#endregion
|
|
347
|
+
//#region src/ports/auth-cache.ts
|
|
348
|
+
var AuthCacheError = class extends Data.TaggedError("AuthCacheError") {};
|
|
349
|
+
var AuthCachePortTag = class extends Context.Tag("@capxul/sdk/ports/AuthCachePort")() {};
|
|
350
|
+
//#endregion
|
|
351
|
+
//#region src/adapters/auth-cache/serialization.ts
|
|
352
|
+
function parseAuthSession(raw) {
|
|
353
|
+
if (typeof raw !== "object" || raw === null) return null;
|
|
354
|
+
const candidate = raw;
|
|
355
|
+
try {
|
|
356
|
+
return {
|
|
357
|
+
authUserId: toAuthUserId(candidate.authUserId),
|
|
358
|
+
email: toEmail(candidate.email),
|
|
359
|
+
token: toSessionToken(candidate.token),
|
|
360
|
+
expiresAt: toEpochMs(candidate.expiresAt)
|
|
361
|
+
};
|
|
362
|
+
} catch {
|
|
363
|
+
return null;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
function parseCachedJwt(raw) {
|
|
367
|
+
if (typeof raw !== "object" || raw === null) return null;
|
|
368
|
+
const candidate = raw;
|
|
369
|
+
try {
|
|
370
|
+
return {
|
|
371
|
+
token: toJwtToken(candidate.token),
|
|
372
|
+
expEpochSeconds: toEpochSeconds(candidate.expEpochSeconds)
|
|
373
|
+
};
|
|
374
|
+
} catch {
|
|
375
|
+
return null;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
//#endregion
|
|
379
|
+
//#region src/adapters/auth-cache/BrowserAuthCacheAdapter.ts
|
|
380
|
+
const SESSION_KEY = "capxul.session";
|
|
381
|
+
const JWT_KEY = "capxul.jwt";
|
|
382
|
+
var BrowserAuthCacheAdapter = class {
|
|
383
|
+
storage;
|
|
384
|
+
constructor(storage) {
|
|
385
|
+
this.storage = storage;
|
|
386
|
+
}
|
|
387
|
+
getSession = authCacheTry("getSession", () => {
|
|
388
|
+
const raw = this.storage.getItem(SESSION_KEY);
|
|
389
|
+
if (raw === null) return null;
|
|
390
|
+
try {
|
|
391
|
+
return parseAuthSession(JSON.parse(raw));
|
|
392
|
+
} catch {
|
|
393
|
+
return null;
|
|
394
|
+
}
|
|
395
|
+
});
|
|
396
|
+
setSession = (session) => authCacheTry("setSession", () => {
|
|
397
|
+
this.storage.setItem(SESSION_KEY, JSON.stringify(session));
|
|
398
|
+
});
|
|
399
|
+
clearSession = authCacheTry("clearSession", () => {
|
|
400
|
+
this.storage.removeItem(SESSION_KEY);
|
|
401
|
+
});
|
|
402
|
+
getJwt = authCacheTry("getJwt", () => {
|
|
403
|
+
const raw = this.storage.getItem(JWT_KEY);
|
|
404
|
+
if (raw === null) return null;
|
|
405
|
+
try {
|
|
406
|
+
return parseCachedJwt(JSON.parse(raw));
|
|
407
|
+
} catch {
|
|
408
|
+
return null;
|
|
409
|
+
}
|
|
410
|
+
});
|
|
411
|
+
setJwt = (jwt) => authCacheTry("setJwt", () => {
|
|
412
|
+
this.storage.setItem(JWT_KEY, JSON.stringify(jwt));
|
|
413
|
+
});
|
|
414
|
+
clearJwt = authCacheTry("clearJwt", () => {
|
|
415
|
+
this.storage.removeItem(JWT_KEY);
|
|
416
|
+
});
|
|
417
|
+
};
|
|
418
|
+
function toAuthCacheError(operation, cause) {
|
|
419
|
+
return new AuthCacheError({
|
|
420
|
+
operation,
|
|
421
|
+
cause
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
function authCacheTry(operation, run) {
|
|
425
|
+
return Effect.try({
|
|
426
|
+
try: run,
|
|
427
|
+
catch: (cause) => toAuthCacheError(operation, cause)
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
//#endregion
|
|
431
|
+
//#region src/adapters/auth-cache/InMemoryAuthCacheAdapter.ts
|
|
432
|
+
var InMemoryAuthCacheAdapter = class {
|
|
433
|
+
session = null;
|
|
434
|
+
jwt = null;
|
|
435
|
+
getSession = Effect.sync(() => this.session);
|
|
436
|
+
setSession = (session) => Effect.sync(() => {
|
|
437
|
+
this.session = session;
|
|
438
|
+
});
|
|
439
|
+
clearSession = Effect.sync(() => {
|
|
440
|
+
this.session = null;
|
|
441
|
+
});
|
|
442
|
+
getJwt = Effect.sync(() => this.jwt);
|
|
443
|
+
setJwt = (jwt) => Effect.sync(() => {
|
|
444
|
+
this.jwt = jwt;
|
|
445
|
+
});
|
|
446
|
+
clearJwt = Effect.sync(() => {
|
|
447
|
+
this.jwt = null;
|
|
448
|
+
});
|
|
449
|
+
};
|
|
450
|
+
Layer.effect(AuthCachePortTag, Effect.sync(() => new InMemoryAuthCacheAdapter()).pipe(Effect.mapError((cause) => new AuthCacheError({
|
|
451
|
+
operation: "initialize",
|
|
452
|
+
cause
|
|
453
|
+
}))));
|
|
454
|
+
//#endregion
|
|
455
|
+
export { toSessionToken as A, toEpochSeconds as C, toPublishableKey as D, toOrgId as E, isCapxulError as F, decodeConvexError as M, CapxulError as N, toPublishableKeyId as O, Errors as P, toEpochMs as S, toKycTier as T, toChainId as _, AuthCacheError as a, toDurationMs as b, BYTES32_RE as c, toAccountId as d, toAddress as f, toAuthUserId as g, toAppId as h, parseCachedJwt as i, toSubAccountId as j, toRoleKey as k, EVM_ADDRESS_RE as l, toAnonymousDistinctId 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, toCountryCode as v, toJwtToken as w, toEmail as x, toCurrencyCode as y };
|
|
456
|
+
|
|
457
|
+
//# sourceMappingURL=InMemoryAuthCacheAdapter-v5W-XB5M.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"InMemoryAuthCacheAdapter-v5W-XB5M.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] as const;\n\nexport type CapxulErrorCode = (typeof CAPXUL_ERROR_CODES)[number];\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`: missing `VITE_CAPXUL_CONVEX_SITE_URL` / the origin is\n * not allowlisted → 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\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 (initially ProvisioningFlow's mint_openfort / deploy_safe /\n * register_indexer `after:` timers). 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 — substrate is `@effect/experimental/Machine` per\n * `docs/canon/decisions/state-machine-substrate.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// canon (`docs/canon/ports/identity.md`).\nexport type Profile = {\n readonly authUserId: AuthUserId;\n readonly email: Email;\n readonly displayName: string | null;\n readonly country: CountryCode | 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 canon (`docs/canon/ports/smart-account.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 canon (`docs/canon/ports/credentials.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// (`docs/canon/ports/auth-client.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.Tag(\"@capxul/sdk/ports/AuthCachePort\")<\n AuthCachePortTag,\n 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;AACF;AAmDA,IAAa,cAAb,cAAiC,MAAM;CACrC;CACA;CACA;CACA;CAEA,YAAY,MAAuB,SAAiB,UAA8B,CAAC,GAAG;EACpF,MAAM,SAAS,WAAW,UAAU,EAAE,OAAO,QAAQ,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