@capxul/sdk 1.0.0-alpha.17 → 1.0.0-alpha.19
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 +64 -7
- package/dist/{InMemoryAuthCacheAdapter-v5W-XB5M.mjs → InMemoryAuthCacheAdapter-BuVZpnSx.mjs} +25 -4
- package/dist/InMemoryAuthCacheAdapter-BuVZpnSx.mjs.map +1 -0
- package/dist/{index-D0SflScT.d.mts → index-D1rNjmof.d.mts} +3 -3
- package/dist/index-D1rNjmof.d.mts.map +1 -0
- package/dist/index.d.mts +113 -12
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +862 -146
- package/dist/index.mjs.map +1 -1
- package/dist/node/index.d.mts +2 -2
- package/dist/node/index.mjs +1 -1
- package/dist/ports/safe-deployment.d.mts +1 -1
- package/dist/ports/safe-deployment.mjs.map +1 -1
- package/dist/{safe-deployment-ToMPzqwk.d.mts → safe-deployment-BID2pXZN.d.mts} +4 -5
- package/dist/safe-deployment-BID2pXZN.d.mts.map +1 -0
- package/dist/{signer-Cp2G98ZK.d.mts → signer-AXnBJuAN.d.mts} +2 -2
- package/dist/{signer-Cp2G98ZK.d.mts.map → signer-AXnBJuAN.d.mts.map} +1 -1
- package/package.json +5 -4
- package/dist/InMemoryAuthCacheAdapter-v5W-XB5M.mjs.map +0 -1
- package/dist/index-D0SflScT.d.mts.map +0 -1
- package/dist/safe-deployment-ToMPzqwk.d.mts.map +0 -1
package/README.md
CHANGED
|
@@ -1,10 +1,67 @@
|
|
|
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)
|
|
8
|
-
- [Host-owned SDK observation](./docs/observation.md) — one PostHog client, capture once
|
|
7
|
+
```ts
|
|
8
|
+
import { createCapxulClient } from "@capxul/sdk";
|
|
9
9
|
|
|
10
|
-
|
|
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
|
+
## Published entry points
|
|
23
|
+
|
|
24
|
+
The packed npm package exposes only:
|
|
25
|
+
|
|
26
|
+
- `@capxul/sdk` — the client factory, public method and value types, signers,
|
|
27
|
+
and observation helpers.
|
|
28
|
+
- `@capxul/sdk/node` — Node-only signer and runtime helpers.
|
|
29
|
+
- `@capxul/sdk/ports/safe-deployment` — the explicitly published Safe
|
|
30
|
+
deployment contract.
|
|
31
|
+
|
|
32
|
+
The many extra subpaths in `package.json#exports` are workspace development
|
|
33
|
+
surfaces. Do not show them in consumer examples unless `publishConfig.exports`
|
|
34
|
+
also contains them.
|
|
35
|
+
|
|
36
|
+
## Documentation
|
|
37
|
+
|
|
38
|
+
- [Maintainer context](./CONTEXT.md) — ownership, boundaries, invariants,
|
|
39
|
+
evidence, and update triggers.
|
|
40
|
+
- [Architecture](./docs/architecture.md) — client assembly, flows, ports,
|
|
41
|
+
adapters, and proof map.
|
|
42
|
+
- [Observation](./docs/observation.md) — host-owned failure observation and
|
|
43
|
+
bounded backend linkage.
|
|
44
|
+
- [Public SDK documentation](../../apps/docs/content/docs/sdk/index.mdx) —
|
|
45
|
+
tutorials, guides, reference, and explanation for npm consumers.
|
|
46
|
+
|
|
47
|
+
React integration is a separate projection owned by `@capxul/sdk-react`.
|
|
48
|
+
|
|
49
|
+
## Development
|
|
50
|
+
|
|
51
|
+
Run package commands through Vite+:
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
vp run --filter @capxul/sdk check-types
|
|
55
|
+
vp run --filter @capxul/sdk test
|
|
56
|
+
vp run --filter @capxul/sdk build
|
|
57
|
+
vp run --filter @capxul/sdk proofs:live
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
`proofs:live` runs the deterministic Organization Core SDK journey against the
|
|
61
|
+
configured live Convex deployment and Base Sepolia. Live proofs require
|
|
62
|
+
operator secrets and prove only the path named by the command. See
|
|
63
|
+
[maintainer context](./CONTEXT.md#capability-and-proof-boundaries).
|
|
64
|
+
|
|
65
|
+
The browser production path owns its Openfort signer when no signer is supplied.
|
|
66
|
+
Current integration recovery evidence and its published-package boundary are
|
|
67
|
+
tracked in the [#870 receipt](../../docs/receipts/issue-870-openfort-signer-recovery-RECEIPT-2026-07-19.md).
|
package/dist/{InMemoryAuthCacheAdapter-v5W-XB5M.mjs → InMemoryAuthCacheAdapter-BuVZpnSx.mjs}
RENAMED
|
@@ -24,6 +24,27 @@ const CAPXUL_ERROR_CODES = [
|
|
|
24
24
|
"CANCELLED",
|
|
25
25
|
"WRONG_STATE"
|
|
26
26
|
];
|
|
27
|
+
/**
|
|
28
|
+
* The error codes that represent an expected product outcome rather than a
|
|
29
|
+
* defect. The SDK and backend observation boundaries both classify failures
|
|
30
|
+
* against this set to route expected outcomes to their own PostHog event
|
|
31
|
+
* stream; keeping the single copy here (adjacent to `CAPXUL_ERROR_CODES`, so a
|
|
32
|
+
* code rename forces this set to move with it) stops the two sides of the wire
|
|
33
|
+
* from drifting and silently splitting one outcome across two streams.
|
|
34
|
+
*/
|
|
35
|
+
const EXPECTED_OPERATION_OUTCOMES = new Set([
|
|
36
|
+
"INVALID_INPUT",
|
|
37
|
+
"NOT_AUTHENTICATED",
|
|
38
|
+
"CANCELLED",
|
|
39
|
+
"SIGNER_REJECTED",
|
|
40
|
+
"VERIFICATION_REQUIRED",
|
|
41
|
+
"INSUFFICIENT_BALANCE",
|
|
42
|
+
"INVALID_RECIPIENT",
|
|
43
|
+
"ROLE_PERMISSION_DENIED",
|
|
44
|
+
"RATE_LIMITED",
|
|
45
|
+
"OTP_EXPIRED",
|
|
46
|
+
"WRONG_STATE"
|
|
47
|
+
]);
|
|
27
48
|
var CapxulError = class extends Error {
|
|
28
49
|
code;
|
|
29
50
|
details;
|
|
@@ -156,8 +177,8 @@ const Errors = {
|
|
|
156
177
|
* Method called from a flow state where its precondition fails (TA16). The
|
|
157
178
|
* SDK's method API short-circuits with this error before driving the
|
|
158
179
|
* internal state machine. `currentState` is the Effect-machine snapshot
|
|
159
|
-
* tag (stringified — substrate is `@effect/experimental/Machine
|
|
160
|
-
* `
|
|
180
|
+
* tag (stringified — substrate is `@effect/experimental/Machine`; see
|
|
181
|
+
* `packages/errors/CONTEXT.md`); `validStates`
|
|
161
182
|
* enumerates the states the method accepts.
|
|
162
183
|
*/
|
|
163
184
|
wrongState: (details) => new CapxulError("WRONG_STATE", `${details.method} called from state '${details.currentState}'; valid states: ${details.validStates.join(", ")}`, { details: {
|
|
@@ -452,6 +473,6 @@ Layer.effect(AuthCachePortTag, Effect.sync(() => new InMemoryAuthCacheAdapter())
|
|
|
452
473
|
cause
|
|
453
474
|
}))));
|
|
454
475
|
//#endregion
|
|
455
|
-
export { toSessionToken as A, toEpochSeconds as C, toPublishableKey as D, toOrgId as E,
|
|
476
|
+
export { toSessionToken as A, toEpochSeconds as C, toPublishableKey as D, toOrgId as E, Errors as F, isCapxulError as I, decodeConvexError as M, CapxulError as N, toPublishableKeyId as O, EXPECTED_OPERATION_OUTCOMES 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
477
|
|
|
457
|
-
//# sourceMappingURL=InMemoryAuthCacheAdapter-
|
|
478
|
+
//# sourceMappingURL=InMemoryAuthCacheAdapter-BuVZpnSx.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"InMemoryAuthCacheAdapter-BuVZpnSx.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 * 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 \"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]);\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\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`; 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 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.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;;;;;;;;;AAYA,MAAa,8BAA4D,IAAI,IAAI;CAC/E;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAiDD,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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OAAO,WAAW;EAChB,KAAK,UAAU;CACjB,CAAC;CAEH,eAAwB,OAAO,WAAW;EACxC,KAAK,UAAU;CACjB,CAAC;CAED,SAAkB,OAAO,WAAW,KAAK,GAAG;CAE5C,UAAmB,QACjB,OAAO,WAAW;EAChB,KAAK,MAAM;CACb,CAAC;CAEH,WAAoB,OAAO,WAAW;EACpC,KAAK,MAAM;CACb,CAAC;AACH;AAEsC,MAAM,OAC1C,kBACA,OAAO,WAAW,IAAI,yBAAyB,CAAC,EAAE,KAChD,OAAO,UAAU,UAAU,IAAI,eAAe;CAAE,WAAW;CAAc;AAAM,CAAC,CAAC,CACnF,CACF"}
|
|
@@ -11,8 +11,8 @@ type CapxulErrorCode = (typeof CAPXUL_ERROR_CODES)[number];
|
|
|
11
11
|
* hits the Convex host → no session reaches the provider.
|
|
12
12
|
* - `stale-openfort-cache`: an old `userId` in scoped storage makes the SDK
|
|
13
13
|
* skip re-auth → 401 on `v2/accounts`.
|
|
14
|
-
* - `app-env-allowlist`:
|
|
15
|
-
*
|
|
14
|
+
* - `app-env-allowlist`: the selected app/deployment origin is not allowlisted
|
|
15
|
+
* → 401.
|
|
16
16
|
* - `no-secure-context`: sandboxed/headless browser with no Web Crypto, so
|
|
17
17
|
* `getAddress`/`configure` can never produce an address. Previously vanished
|
|
18
18
|
* into `unknown`; the signer's secure-context probe now names it.
|
|
@@ -154,4 +154,4 @@ declare const SUPPORTED_CURRENCIES: readonly [{
|
|
|
154
154
|
type SupportedCurrencyCode = (typeof SUPPORTED_CURRENCIES)[number]["code"];
|
|
155
155
|
//#endregion
|
|
156
156
|
export { SubAccount as A, PublishableKey as C, RunId as D, RoleKey as E, CapxulErrorDetails as F, FailureMode as I, isCapxulError as L, TxHash as M, CapxulError as N, SessionToken as O, CapxulErrorCode as P, Profile as S, PublishableKeyRecord as T, EpochMs as _, AnonymousDistinctId as a, Money as b, AuthUserId as c, CountryCode as d, CurrencyCode as f, Email as g, DurationMs as h, AllowedOrigin as i, SubAccountId as j, SmartAccount as k, BlockNumber as l, DocumentHash as m, AccountId as n, AppId as o, DeveloperApplication as p, Address as r, AuthSession as s, Account as t, ChainId as u, EpochSeconds as v, PublishableKeyId as w, OrgId as x, JwtToken as y };
|
|
157
|
-
//# sourceMappingURL=index-
|
|
157
|
+
//# sourceMappingURL=index-D1rNjmof.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index-D1rNjmof.d.mts","names":[],"sources":["../../errors/src/errors.ts","../../types/src/brand.ts","../../types/src/index.ts"],"mappings":";cAKa,kBAAA;AAAA,KAyBD,eAAA,WAA0B,kBAAkB;AAyCxD;;;;AAAuB;AAOvB;;;;AAAuC;AAgBvC;;;;;;;AAvBA,KAAY,WAAA;AAAA,KAOA,kBAAA,GAAqB,MAAM;AAAA,KAgB3B,kBAAA;EAAA,SACD,KAAA;EAAA,SACA,OAAA,GAAU,kBAAkB;EAAA,SAC5B,aAAA;EAAA,SACA,KAAA;AAAA;AAAA,cAGE,WAAA,SAAoB,KAAA;EAAA,SACtB,IAAA,EAAM,eAAA;EAAA,SACN,OAAA,GAAU,kBAAA;EAAA,SACV,aAAA;EAAA,SACA,KAAA;cAEG,IAAA,EAAM,eAAA,EAAiB,OAAA,UAAiB,OAAA,GAAS,kBAAA;AAAA;AAAA,iBAgB/C,aAAA,CAAc,KAAA,YAAiB,KAAA,IAAS,WAAW;;;;AAtHnE;;;;AAuBU;cCtBI,KAAA;AAAA,KAEF,KAAA,wBAA6B,CAAA;EAAA,UAAgB,KAAA,GAAQ,CAAA;AAAA;;;KCHrD,OAAA,GAAU,KAAK;AAAA,KACf,KAAA,GAAQ,KAAK;AAAA,KAMb,OAAA;EAAA,SACD,UAAA,EAAY,UAAA;EAAA,SACZ,KAAA,EAAO,KAAA;EAAA,SACP,WAAA;EAAA,SACA,OAAA,EAAS,WAAA;EAAA,SACT,OAAA,EAAS,OAAA;EAAA,SACT,SAAA,EAAW,OAAA;EAAA,SACX,SAAA,EAAW,O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AA;EAAA,SACnB,SAAA,EAAW,OAAA;AAAA;AAAA,KAEV,MAAA,GAAS,KAAK;AAAA,KACd,YAAA,GAAe,KAAK;AAAA,KACpB,OAAA,GAAU,KAAK;AAAA,KACf,YAAA,GAAe,KAAK;AAAA,KACpB,OAAA,GAAU,KAAK;AAAA,KACf,WAAA,GAAc,KAAK;AAAA,KACnB,YAAA,GAAe,KAAK,CAAC,qBAAA;AAAA,KACrB,OAAA,GAAU,KAAK;AAAA,KACf,WAAA,GAAc,KAAK;AAAA,KAKnB,KAAA,GAAQ,KAAK;AAAA,KACb,OAAA,GAAU,KAAK;AAAA,KAEf,YAAA,GAAe,KAAK;AAAA,KACpB,QAAA,GAAW,KAAK;AAAA,KAOhB,WAAA;EAAA,SACD,UAAA,EAAY,UAAA;EAAA,SACZ,KAAA,EAAO,KAAA;EAAA,SACP,KAAA,EAAO,YAAA;EAAA,SACP,SAAA,EAAW,OAAA;AAAA;AAAA,cAMT,oBAAA;EAAA;;;;;;;;;;;;;;;;;;;;KAQR,qBAAA,WAAgC,oBAAoB"}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { A as SubAccount, C as PublishableKey, D as RunId, E as RoleKey, F as CapxulErrorDetails, I as FailureMode, L as isCapxulError, N as CapxulError, O as SessionToken, P as CapxulErrorCode, S as Profile$1, T as PublishableKeyRecord, _ as EpochMs, a as AnonymousDistinctId, b as Money, c as AuthUserId, d as CountryCode, f as CurrencyCode, g as Email, h as DurationMs, i as AllowedOrigin, j as SubAccountId, k as SmartAccount$1, m as DocumentHash, n as AccountId, o as AppId, p as DeveloperApplication, r as Address, s as AuthSession, t as Account, u as ChainId, w as PublishableKeyId, x as OrgId } from "./index-
|
|
2
|
-
import { a as SafeDeploymentEvidence, n as SafeDeploymentConfig } from "./safe-deployment-
|
|
3
|
-
import { a as AccountProvider, c as Eip1193Provider, d as CapxulResult, f as Profile, g as AuthCachePort, i as injectedWalletSigner, l as eip1193AccountProvider, m as SmartAccount, n as CapxulSigner, o as AccountProviderSource, p as Session, r as Eip1193RequestProvider, s as AccountRequirement, t as CapxulDigestSigner, u as localPrivateKeyAccountProvider, v as CachedJwt } from "./signer-
|
|
1
|
+
import { A as SubAccount, C as PublishableKey, D as RunId, E as RoleKey, F as CapxulErrorDetails, I as FailureMode, L as isCapxulError, N as CapxulError, O as SessionToken, P as CapxulErrorCode, S as Profile$1, T as PublishableKeyRecord, _ as EpochMs, a as AnonymousDistinctId, b as Money, c as AuthUserId, d as CountryCode, f as CurrencyCode, g as Email, h as DurationMs, i as AllowedOrigin, j as SubAccountId, k as SmartAccount$1, m as DocumentHash, n as AccountId, o as AppId, p as DeveloperApplication, r as Address, s as AuthSession, t as Account, u as ChainId, w as PublishableKeyId, x as OrgId } from "./index-D1rNjmof.mjs";
|
|
2
|
+
import { a as SafeDeploymentEvidence, n as SafeDeploymentConfig } from "./safe-deployment-BID2pXZN.mjs";
|
|
3
|
+
import { a as AccountProvider, c as Eip1193Provider, d as CapxulResult, f as Profile, g as AuthCachePort, i as injectedWalletSigner, l as eip1193AccountProvider, m as SmartAccount, n as CapxulSigner, o as AccountProviderSource, p as Session, r as Eip1193RequestProvider, s as AccountRequirement, t as CapxulDigestSigner, u as localPrivateKeyAccountProvider, v as CachedJwt } from "./signer-AXnBJuAN.mjs";
|
|
4
4
|
import { Hex } from "viem";
|
|
5
5
|
import { Context, Effect, Layer, Request } from "effect";
|
|
6
6
|
import { FunctionReference } from "convex/server";
|
|
@@ -449,7 +449,7 @@ interface SmartAccountPort {
|
|
|
449
449
|
*
|
|
450
450
|
* γ-B trust model: the SDK supplies evidence pointers only. The
|
|
451
451
|
* backend is the SOLE oracle for `deployedAt` — see
|
|
452
|
-
* `
|
|
452
|
+
* `packages/sdk/docs/architecture.md`.
|
|
453
453
|
*/
|
|
454
454
|
confirmDeployment(input: ConfirmDeploymentInput): Effect.Effect<SmartAccount$1, SmartAccountError, never>;
|
|
455
455
|
/**
|
|
@@ -905,7 +905,7 @@ declare const PaymentDocumentEnvelope: Schema.Union<[Schema.Union<[Schema.Struct
|
|
|
905
905
|
* `hashLineItems` (payment-document-hash.ts) into the Invoice `lineItemsHash`,
|
|
906
906
|
* and Σ(quantity × unitMinor) MUST equal the invoice `amount`. The hash binds
|
|
907
907
|
* the documentHash to the exact items; the sum-check makes the items add up to
|
|
908
|
-
* the amount due. See the
|
|
908
|
+
* the amount due. See the financial-operations contract in `packages/wire/CONTEXT.md`.
|
|
909
909
|
*/
|
|
910
910
|
declare const LineItem: Schema.Struct<{
|
|
911
911
|
description: typeof Schema.String;
|
|
@@ -1836,12 +1836,12 @@ type AccountStatus = {
|
|
|
1836
1836
|
* methods. `provision` and `deploySafe` are intentionally NOT here —
|
|
1837
1837
|
* they are advanced/testing-only and will live on
|
|
1838
1838
|
* `client._internal.account` when sibling issue #161 lands. Per
|
|
1839
|
-
* `
|
|
1839
|
+
* `packages/sdk/CONTEXT.md`, the narrowing is enforced at
|
|
1840
1840
|
* both the type level (the `keyof AccountMethods` extract is exactly
|
|
1841
1841
|
* `"getStatus" | "ensureReady"`) and at runtime (the bundle returned
|
|
1842
1842
|
* here has those two own-keys and nothing else).
|
|
1843
1843
|
*
|
|
1844
|
-
* Per `
|
|
1844
|
+
* Per `packages/sdk/docs/architecture.md`, the
|
|
1845
1845
|
* `AccountStatus` discriminant — including the variants this slice can
|
|
1846
1846
|
* only reach via `getStatus` (e.g. `accountPrepared`) — is the durable
|
|
1847
1847
|
* shape consumers depend on. Sibling #161 will extend `ensureReady` to
|
|
@@ -2052,6 +2052,67 @@ interface OrgSpendPort {
|
|
|
2052
2052
|
submitBatchPayroll?(input: SubmitOrgBatchPayrollInput): Effect.Effect<readonly Payment[], OrgError, never>;
|
|
2053
2053
|
}
|
|
2054
2054
|
//#endregion
|
|
2055
|
+
//#region src/client/org-lifecycle.d.ts
|
|
2056
|
+
type OrgSetupStep = "preparingFounderAccount" | "awaitingFounderAuthorization" | "submittingBootstrap" | "confirmingBootstrap";
|
|
2057
|
+
/** Leak-safe readiness for exactly one Organization. */
|
|
2058
|
+
type OrgLifecycle = {
|
|
2059
|
+
readonly status: "loading";
|
|
2060
|
+
readonly orgId: OrgId;
|
|
2061
|
+
} | {
|
|
2062
|
+
readonly status: "settingUp";
|
|
2063
|
+
readonly orgId: OrgId;
|
|
2064
|
+
readonly step: OrgSetupStep;
|
|
2065
|
+
} | {
|
|
2066
|
+
readonly status: "ready";
|
|
2067
|
+
readonly orgId: OrgId;
|
|
2068
|
+
readonly canTransact: true;
|
|
2069
|
+
} | {
|
|
2070
|
+
readonly status: "failed";
|
|
2071
|
+
readonly orgId: OrgId;
|
|
2072
|
+
readonly at: OrgSetupStep;
|
|
2073
|
+
readonly error: CapxulError;
|
|
2074
|
+
readonly retryable: boolean;
|
|
2075
|
+
};
|
|
2076
|
+
type StartOrResumeOrganizationInput = {
|
|
2077
|
+
readonly name: string;
|
|
2078
|
+
readonly handle: string;
|
|
2079
|
+
readonly country: string;
|
|
2080
|
+
};
|
|
2081
|
+
type OrganizationSetupStepInput = {
|
|
2082
|
+
readonly orgId: OrgId;
|
|
2083
|
+
readonly signal?: AbortSignal;
|
|
2084
|
+
};
|
|
2085
|
+
type RecordOrganizationSetupFailureInput = {
|
|
2086
|
+
readonly orgId: OrgId;
|
|
2087
|
+
readonly error: CapxulError;
|
|
2088
|
+
readonly retryable: boolean;
|
|
2089
|
+
};
|
|
2090
|
+
/**
|
|
2091
|
+
* Internal capability set used by the Core SDK's deep Organization boundary.
|
|
2092
|
+
* Consumers never coordinate these steps directly. Production composition
|
|
2093
|
+
* supplies them; hermetic contract tests provide a stateful implementation.
|
|
2094
|
+
*/
|
|
2095
|
+
interface OrganizationSetupOps {
|
|
2096
|
+
startOrResume(input: StartOrResumeOrganizationInput): Promise<CapxulResult<{
|
|
2097
|
+
readonly orgId: OrgId;
|
|
2098
|
+
readonly lifecycle: OrgLifecycle;
|
|
2099
|
+
}>>;
|
|
2100
|
+
/** Completes and verifies the founder Account ownership handoff. */
|
|
2101
|
+
prepareFounderAccount(input: OrganizationSetupStepInput): Promise<CapxulResult<OrgLifecycle>>;
|
|
2102
|
+
/** Obtains configured signer authorization and submits the bootstrap once. */
|
|
2103
|
+
authorizeAndSubmitBootstrap(input: OrganizationSetupStepInput): Promise<CapxulResult<OrgLifecycle>>;
|
|
2104
|
+
/** Resumes a recorded provider-known submission without invoking the signer. */
|
|
2105
|
+
resumeSubmittedBootstrap(input: OrganizationSetupStepInput): Promise<CapxulResult<OrgLifecycle>>;
|
|
2106
|
+
/** Confirms a previously recorded submission without requesting authorization again. */
|
|
2107
|
+
confirmSubmittedBootstrap(input: OrganizationSetupStepInput): Promise<CapxulResult<OrgLifecycle>>;
|
|
2108
|
+
recordFailure(input: RecordOrganizationSetupFailureInput): Promise<CapxulResult<OrgLifecycle>>;
|
|
2109
|
+
loadLifecycle(input: {
|
|
2110
|
+
readonly orgId: OrgId;
|
|
2111
|
+
}): Promise<CapxulResult<OrgLifecycle>>;
|
|
2112
|
+
/** Resets durable failure state only; the Core SDK resumes the correct step. */
|
|
2113
|
+
retry(input: OrganizationSetupStepInput): Promise<CapxulResult<OrgLifecycle>>;
|
|
2114
|
+
}
|
|
2115
|
+
//#endregion
|
|
2055
2116
|
//#region src/client/org.d.ts
|
|
2056
2117
|
/**
|
|
2057
2118
|
* A member's lifecycle status (D9 — unified `Member` with status
|
|
@@ -2280,6 +2341,14 @@ interface PayrollMethods {
|
|
|
2280
2341
|
}): Promise<CapxulResult<readonly Payment[]>>;
|
|
2281
2342
|
}
|
|
2282
2343
|
interface OrgScopedMethods extends ActorRelationshipMethods {
|
|
2344
|
+
/** Observe the durable, leak-safe lifecycle for this Organization only. */
|
|
2345
|
+
getLifecycle(options?: {
|
|
2346
|
+
readonly signal?: AbortSignal;
|
|
2347
|
+
}): Promise<CapxulResult<OrgLifecycle>>;
|
|
2348
|
+
/** Explicitly resume this Organization's durable setup lane. */
|
|
2349
|
+
retrySetup(options?: {
|
|
2350
|
+
readonly signal?: AbortSignal;
|
|
2351
|
+
}): Promise<CapxulResult<OrgLifecycle>>;
|
|
2283
2352
|
/** The Org treasury — the real M2 Account over the Org Safe (D3). */
|
|
2284
2353
|
treasury(options?: {
|
|
2285
2354
|
readonly signal?: AbortSignal;
|
|
@@ -2434,10 +2503,10 @@ type CompleteOrganizationOnboardingInput = {
|
|
|
2434
2503
|
type CompletePersonalOnboardingResult = {
|
|
2435
2504
|
readonly lifecycle: AccountLifecycle;
|
|
2436
2505
|
};
|
|
2437
|
-
/** Result of `completeOrganization` —
|
|
2506
|
+
/** Result of `completeOrganization` — one durable Organization lifecycle. */
|
|
2438
2507
|
type CompleteOrganizationOnboardingResult = {
|
|
2439
|
-
readonly
|
|
2440
|
-
readonly lifecycle:
|
|
2508
|
+
readonly orgId: OrgId;
|
|
2509
|
+
readonly lifecycle: OrgLifecycle;
|
|
2441
2510
|
};
|
|
2442
2511
|
/**
|
|
2443
2512
|
* Onboarding method bundle, exposed at `client.onboarding`. Exactly two verbs;
|
|
@@ -2453,6 +2522,32 @@ interface OnboardingMethods {
|
|
|
2453
2522
|
}
|
|
2454
2523
|
//#endregion
|
|
2455
2524
|
//#region src/client/create-capxul-client.d.ts
|
|
2525
|
+
type OrganizationSetupProofReceipt = {
|
|
2526
|
+
readonly state: "submitted";
|
|
2527
|
+
readonly orgId: string;
|
|
2528
|
+
readonly chainId: number;
|
|
2529
|
+
readonly signerEoa: string;
|
|
2530
|
+
readonly founderAccount: string;
|
|
2531
|
+
readonly organizationAccount: string;
|
|
2532
|
+
readonly userOperationHash: string;
|
|
2533
|
+
readonly submittedAt: number;
|
|
2534
|
+
readonly attempt: number;
|
|
2535
|
+
} | {
|
|
2536
|
+
readonly state: "confirmed";
|
|
2537
|
+
readonly orgId: string;
|
|
2538
|
+
readonly chainId: number;
|
|
2539
|
+
readonly signerEoa: string;
|
|
2540
|
+
readonly founderAccount: string;
|
|
2541
|
+
readonly organizationAccount: string;
|
|
2542
|
+
readonly userOperationHash: string;
|
|
2543
|
+
readonly submittedAt: number;
|
|
2544
|
+
readonly attempt: number;
|
|
2545
|
+
readonly confirmationTransactionHash: string;
|
|
2546
|
+
readonly readyAt: number;
|
|
2547
|
+
};
|
|
2548
|
+
type OrganizationSetupProofMethods = {
|
|
2549
|
+
readonly getProofReceipt: (orgId: string) => Promise<CapxulResult<OrganizationSetupProofReceipt | null>>;
|
|
2550
|
+
};
|
|
2456
2551
|
interface CapxulClient {
|
|
2457
2552
|
readonly auth: AuthMethods;
|
|
2458
2553
|
readonly smartAccount: SmartAccountMethods;
|
|
@@ -2536,7 +2631,8 @@ interface CapxulClient {
|
|
|
2536
2631
|
* Dev-only faucet bundle (production-surface-policy.md). `fund` lives here,
|
|
2537
2632
|
* NOT on the public `client.accounts` surface.
|
|
2538
2633
|
*/
|
|
2539
|
-
readonly accounts: AccountsFaucetMethods; /**
|
|
2634
|
+
readonly accounts: AccountsFaucetMethods; /** Quarantined Reference-harness evidence; never a product Organization method. */
|
|
2635
|
+
readonly organizationSetup: OrganizationSetupProofMethods; /** Telemetry port for error reporting. Used by React hooks to report errors before throwing. */
|
|
2540
2636
|
readonly telemetry?: TelemetryPort;
|
|
2541
2637
|
readonly close?: () => Promise<void>;
|
|
2542
2638
|
};
|
|
@@ -2605,6 +2701,11 @@ interface CreateCapxulClientInput {
|
|
|
2605
2701
|
readonly orgRolesDeploymentPort?: OrgRolesDeploymentPort;
|
|
2606
2702
|
/** S4 treasury-spend authority + submit port. */
|
|
2607
2703
|
readonly orgSpendPort?: OrgSpendPort;
|
|
2704
|
+
/**
|
|
2705
|
+
* Internal Organization lifecycle capability. The Core SDK owns its
|
|
2706
|
+
* choreography; production composition supplies the provider/backend steps.
|
|
2707
|
+
*/
|
|
2708
|
+
readonly organizationSetup?: OrganizationSetupOps;
|
|
2608
2709
|
readonly orgDeploymentConfig?: SafeDeploymentConfig;
|
|
2609
2710
|
}
|
|
2610
2711
|
//#endregion
|
|
@@ -2804,5 +2905,5 @@ declare function captureException(telemetry: TelemetryPort, error: unknown, cont
|
|
|
2804
2905
|
*/
|
|
2805
2906
|
declare function captureExceptionSync(telemetry: TelemetryPort, error: unknown, context?: HandledErrorReportContext): void;
|
|
2806
2907
|
//#endregion
|
|
2807
|
-
export { type Account, type AccountId, type AccountLifecycle, type AccountMethods, type AccountProvider, type AccountProviderSource, type AccountRequirement, type AccountSetupStep, type AccountsMethods, type ActivityItem, type ActivityListParams, type ActivityMethods, type ActivityPage, type ActorProfile, type ActorProfileMethods, type ActorReference, type ActorRelationshipMethods, type ActorRequest, type ActorRequestIssueInput, type ActorRequestsMethods, type Address, type AddressBookAddInput, type AddressBookEntry, type AddressBookLabelInput, type AddressBookMethods, type AssignRoleInput, type AuthMethods, type AuthSession, type AuthUserId, CAPXUL_SDK_EXPECTED_OUTCOME_EVENT, type CapxulClient, type CapxulClientInput, type CapxulDigestSigner, CapxulError, type CapxulErrorCode, type CapxulErrorDetails, type CapxulResult, type CapxulSigner, type CompleteOrganizationOnboardingInput, type CompleteOrganizationOnboardingResult, type CompletePersonalOnboardingInput, type CompletePersonalOnboardingResult, type CreateCapxulClientInput, type CreateOrgInput, type CurrentUserContext, type CurrentUserMethods, type DepositInstructions, type Destination, type DestinationAddInput, type DestinationKind, type DestinationListInput, type DestinationPayload, type DestinationRail, type DestinationRemoveInput, type DestinationsMethods, type DetectPendingOrgInvitationsResult, type DevPrivateKeySignerInput, type Eip1193Provider, type Eip1193RequestProvider, type FinancialOpsMethods, type HandledErrorReportContext, type HandlesMethods, type IdentityMethods, type InboxApproveInput, type InboxItem, type InboxMethods, type InsightsMethods, type InsightsSummary, type InviteMemberInput, type MeMethods, type MeProfile, type MemberStatus, type MemberView, type Money, type ObservationAdapter, type ObservationContext, type ObservationDelivery, type OfframpMethods, type OfframpQuote, type OfframpQuoteInput, type OfframpStatus, type OnboardingMethods, type OpenfortEmbeddedSignerInput, type OpenfortEmbeddedWalletApi, type OpenfortEmbeddedWalletPort, type OrgBatchPayrollInput, type OrgId, type OrgMethods, type OrgPayrollRun, type OrgScopedMethods, type OrgSpendViaPaymentsInput, type OrgTemplate, type OrgView, type OrganizationAccount, type OrganizationAuditLogItem, type Payee, type PayeesMethods, type Payment, type PaymentDocumentRef, type PaymentDocumentRender, type PaymentDocumentVerification, type PaymentDocumentsMethods, type PaymentDraft, type PaymentDraftStatus, type PaymentMoney, type PaymentRequest, type PaymentRequestStatus, type PaymentRequestsCreateInput, type PaymentRequestsMethods, type PaymentSettlementInput, type PaymentStatus, type PaymentTiming, type PaymentType, type PaymentsMethods, type PaymentsPayInput, type PaymentsPayoutInput, type PaymentsWithdrawInput, type PayrollMethods, type PayrollPayslipTemplate, type PayrollRosterAddInput, type PayrollRosterLine, type PayrollRunInput, type PostHogObservationClient, type PostHogObservationOptions, type Profile, type RecipientResolution, type RecipientResolutionKind, type ReconciliationEntry, type Ref, type RemoveMemberInput, type ResendInviteTokenInput, type ResolvedTarget, type RoleDefinition, type RoleKey, type RoleSpendCap, type RoleView, type SdkFailureObservation, type Session, type SmartAccount, type SmartAccountMethods, type SubAccount, type SubAccountId, type SubAccountsMethods, type TargetReference, type TargetsMethods, type TelemetryPort, type TransferEndpoint, type TransferInput, type TransferResult, type WorkbenchDraftInput, type WorkbenchExecuteInput, type WorkbenchMethods, type WorkbenchMintResult, captureException, captureExceptionSync, createCapxulClient, deriveDevPrivateKey, devPrivateKeySigner, eip1193AccountProvider, embeddedSigner, fromPostHog, injectedWalletSigner, isCapxulError, isSettingUpLifecycle, localPrivateKeyAccountProvider, openfortEmbeddedSigner, openfortEmbeddedSignerFromWallet, openfortEmbeddedWalletPort };
|
|
2908
|
+
export { type Account, type AccountId, type AccountLifecycle, type AccountMethods, type AccountProvider, type AccountProviderSource, type AccountRequirement, type AccountSetupStep, type AccountsMethods, type ActivityItem, type ActivityListParams, type ActivityMethods, type ActivityPage, type ActorProfile, type ActorProfileMethods, type ActorReference, type ActorRelationshipMethods, type ActorRequest, type ActorRequestIssueInput, type ActorRequestsMethods, type Address, type AddressBookAddInput, type AddressBookEntry, type AddressBookLabelInput, type AddressBookMethods, type AssignRoleInput, type AuthMethods, type AuthSession, type AuthUserId, CAPXUL_SDK_EXPECTED_OUTCOME_EVENT, type CapxulClient, type CapxulClientInput, type CapxulDigestSigner, CapxulError, type CapxulErrorCode, type CapxulErrorDetails, type CapxulResult, type CapxulSigner, type CompleteOrganizationOnboardingInput, type CompleteOrganizationOnboardingResult, type CompletePersonalOnboardingInput, type CompletePersonalOnboardingResult, type CreateCapxulClientInput, type CreateOrgInput, type CurrentUserContext, type CurrentUserMethods, type DepositInstructions, type Destination, type DestinationAddInput, type DestinationKind, type DestinationListInput, type DestinationPayload, type DestinationRail, type DestinationRemoveInput, type DestinationsMethods, type DetectPendingOrgInvitationsResult, type DevPrivateKeySignerInput, type Eip1193Provider, type Eip1193RequestProvider, type FinancialOpsMethods, type HandledErrorReportContext, type HandlesMethods, type IdentityMethods, type InboxApproveInput, type InboxItem, type InboxMethods, type InsightsMethods, type InsightsSummary, type InviteMemberInput, type MeMethods, type MeProfile, type MemberStatus, type MemberView, type Money, type ObservationAdapter, type ObservationContext, type ObservationDelivery, type OfframpMethods, type OfframpQuote, type OfframpQuoteInput, type OfframpStatus, type OnboardingMethods, type OpenfortEmbeddedSignerInput, type OpenfortEmbeddedWalletApi, type OpenfortEmbeddedWalletPort, type OrgBatchPayrollInput, type OrgId, type OrgLifecycle, type OrgMethods, type OrgPayrollRun, type OrgScopedMethods, type OrgSetupStep, type OrgSpendViaPaymentsInput, type OrgTemplate, type OrgView, type OrganizationAccount, type OrganizationAuditLogItem, type Payee, type PayeesMethods, type Payment, type PaymentDocumentRef, type PaymentDocumentRender, type PaymentDocumentVerification, type PaymentDocumentsMethods, type PaymentDraft, type PaymentDraftStatus, type PaymentMoney, type PaymentRequest, type PaymentRequestStatus, type PaymentRequestsCreateInput, type PaymentRequestsMethods, type PaymentSettlementInput, type PaymentStatus, type PaymentTiming, type PaymentType, type PaymentsMethods, type PaymentsPayInput, type PaymentsPayoutInput, type PaymentsWithdrawInput, type PayrollMethods, type PayrollPayslipTemplate, type PayrollRosterAddInput, type PayrollRosterLine, type PayrollRunInput, type PostHogObservationClient, type PostHogObservationOptions, type Profile, type RecipientResolution, type RecipientResolutionKind, type ReconciliationEntry, type Ref, type RemoveMemberInput, type ResendInviteTokenInput, type ResolvedTarget, type RoleDefinition, type RoleKey, type RoleSpendCap, type RoleView, type SdkFailureObservation, type Session, type SmartAccount, type SmartAccountMethods, type SubAccount, type SubAccountId, type SubAccountsMethods, type TargetReference, type TargetsMethods, type TelemetryPort, type TransferEndpoint, type TransferInput, type TransferResult, type WorkbenchDraftInput, type WorkbenchExecuteInput, type WorkbenchMethods, type WorkbenchMintResult, captureException, captureExceptionSync, createCapxulClient, deriveDevPrivateKey, devPrivateKeySigner, eip1193AccountProvider, embeddedSigner, fromPostHog, injectedWalletSigner, isCapxulError, isSettingUpLifecycle, localPrivateKeyAccountProvider, openfortEmbeddedSigner, openfortEmbeddedSignerFromWallet, openfortEmbeddedWalletPort };
|
|
2808
2909
|
//# sourceMappingURL=index.d.mts.map
|