@capxul/sdk 1.2.2 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -20
- package/dist/{InMemoryAuthCacheAdapter-Dr1sEd9y.mjs → InMemoryAuthCacheAdapter-Rc8tCtml.mjs} +9 -8
- package/dist/{create-capxul-client-DVzm78RU.mjs → create-capxul-client-N36cHqE2.mjs} +2323 -1331
- package/dist/{create-capxul-client-C7H5b68l.d.mts → create-capxul-client-klbklLYW.d.mts} +513 -871
- package/dist/index.d.mts +29 -79
- package/dist/index.mjs +134 -513
- package/dist/node/index.d.mts +2 -3
- package/dist/node/index.mjs +1 -3
- package/dist/{signer-CJT0pPiO.d.mts → signer-ZijoFiUs.d.mts} +15 -20
- package/dist/testing/index.d.mts +2 -3
- package/dist/testing/index.mjs +5 -143
- package/package.json +10 -8
- package/dist/InMemoryAuthCacheAdapter-Dr1sEd9y.mjs.map +0 -1
- package/dist/create-capxul-client-C7H5b68l.d.mts.map +0 -1
- package/dist/create-capxul-client-DVzm78RU.mjs.map +0 -1
- package/dist/index.d.mts.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/dist/node/index.d.mts.map +0 -1
- package/dist/node/index.mjs.map +0 -1
- package/dist/signer-CJT0pPiO.d.mts.map +0 -1
- package/dist/testing/index.d.mts.map +0 -1
- package/dist/testing/index.mjs.map +0 -1
package/dist/node/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { E as AuthSession, _ as AuthCachePortTag, g as AuthCachePort, h as AuthCacheError, n as CapxulSigner, v as CachedJwt } from "../signer-ZijoFiUs.mjs";
|
|
2
2
|
import { Hex } from "viem";
|
|
3
3
|
import { Effect, FileSystem, Layer, Path } from "effect";
|
|
4
4
|
|
|
@@ -48,5 +48,4 @@ declare function localPrivateKeySigner(input: {
|
|
|
48
48
|
*/
|
|
49
49
|
declare function detectNodeAuthCacheAdapter(options?: DetectNodeAuthCacheAdapterOptions): AuthCachePort;
|
|
50
50
|
//#endregion
|
|
51
|
-
export { DetectNodeAuthCacheAdapterOptions, FileSystemAuthCacheAdapter, FileSystemAuthCacheLayer, detectNodeAuthCacheAdapter, localPrivateKeySigner };
|
|
52
|
-
//# sourceMappingURL=index.d.mts.map
|
|
51
|
+
export { DetectNodeAuthCacheAdapterOptions, FileSystemAuthCacheAdapter, FileSystemAuthCacheLayer, detectNodeAuthCacheAdapter, localPrivateKeySigner };
|
package/dist/node/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as AuthCacheError,
|
|
1
|
+
import { a as AuthCacheError, i as parseCachedJwt, m as toAddress, n as BrowserAuthCacheAdapter, o as AuthCachePortTag, r as parseAuthSession, t as InMemoryAuthCacheAdapter } from "../InMemoryAuthCacheAdapter-Rc8tCtml.mjs";
|
|
2
2
|
import { Effect, FileSystem, Layer, Path } from "effect";
|
|
3
3
|
import { privateKeyToAccount } from "viem/accounts";
|
|
4
4
|
import * as os from "node:os";
|
|
@@ -154,5 +154,3 @@ function resolveDefaultAuthCachePath(resolveHomeDirectory) {
|
|
|
154
154
|
}
|
|
155
155
|
//#endregion
|
|
156
156
|
export { FileSystemAuthCacheAdapter, FileSystemAuthCacheLayer, detectNodeAuthCacheAdapter, localPrivateKeySigner };
|
|
157
|
-
|
|
158
|
-
//# sourceMappingURL=index.mjs.map
|
|
@@ -2,7 +2,7 @@ import { Account, Hex } from "viem";
|
|
|
2
2
|
import { Context, Effect } from "effect";
|
|
3
3
|
|
|
4
4
|
//#region ../errors/src/errors.d.ts
|
|
5
|
-
declare const CAPXUL_ERROR_CODES: readonly ["NOT_AUTHENTICATED", "EMAIL_DELIVERY_FAILED", "PROFILE_NOT_FOUND", "SMART_ACCOUNT_MISSING", "PLAYER_NOT_FOUND", "ACCOUNT_NOT_FOUND", "PROVIDER_ERROR", "INVALID_INPUT", "ENV_MISSING", "NOT_IMPLEMENTED", "VERIFICATION_REQUIRED", "INSUFFICIENT_BALANCE", "INVALID_RECIPIENT", "ROLE_PERMISSION_DENIED", "TRANSACTION_FAILED", "RATE_LIMITED", "NETWORK_ERROR", "UNKNOWN", "OTP_EXPIRED", "SIGNER_REJECTED", "CANCELLED", "WRONG_STATE", "STALE_EPOCH", "SUPERSEDED", "WORK_DIED", "ACTOR_STOPPED"];
|
|
5
|
+
declare const CAPXUL_ERROR_CODES: readonly ["NOT_AUTHENTICATED", "EMAIL_DELIVERY_FAILED", "PROFILE_NOT_FOUND", "SMART_ACCOUNT_MISSING", "PLAYER_NOT_FOUND", "ACCOUNT_NOT_FOUND", "PROVIDER_ERROR", "CAPABILITY_UNAVAILABLE", "INVALID_INPUT", "ENV_MISSING", "NOT_IMPLEMENTED", "VERIFICATION_REQUIRED", "INSUFFICIENT_BALANCE", "INVALID_RECIPIENT", "ROLE_PERMISSION_DENIED", "TRANSACTION_FAILED", "RATE_LIMITED", "NETWORK_ERROR", "UNKNOWN", "OTP_EXPIRED", "SIGNER_REJECTED", "CANCELLED", "WRONG_STATE", "STALE_EPOCH", "SUPERSEDED", "WORK_DIED", "ACTOR_STOPPED"];
|
|
6
6
|
type CapxulErrorCode = (typeof CAPXUL_ERROR_CODES)[number];
|
|
7
7
|
/**
|
|
8
8
|
* Why an auth/provider call failed — a flat CAUSE enum. The *where* (which
|
|
@@ -61,7 +61,7 @@ type Brand<T, B extends string> = T & {
|
|
|
61
61
|
};
|
|
62
62
|
//#endregion
|
|
63
63
|
//#region ../types/src/index.d.ts
|
|
64
|
-
type Address = Brand<string, "Address">;
|
|
64
|
+
type Address$1 = Brand<string, "Address">;
|
|
65
65
|
type Email = Brand<string, "Email">;
|
|
66
66
|
type Profile$1 = {
|
|
67
67
|
readonly authUserId: AuthUserId;
|
|
@@ -69,7 +69,7 @@ type Profile$1 = {
|
|
|
69
69
|
readonly displayName: string | null;
|
|
70
70
|
readonly country: CountryCode | null;
|
|
71
71
|
readonly onboarded: boolean;
|
|
72
|
-
readonly withdrawalAddress: Address | null;
|
|
72
|
+
readonly withdrawalAddress: Address$1 | null;
|
|
73
73
|
readonly username: string | null;
|
|
74
74
|
readonly imageUrl: string | null;
|
|
75
75
|
readonly kycTier: KycTier;
|
|
@@ -78,8 +78,8 @@ type Profile$1 = {
|
|
|
78
78
|
};
|
|
79
79
|
type SmartAccount$1 = {
|
|
80
80
|
readonly authUserId: AuthUserId;
|
|
81
|
-
readonly signerAddress: Address | null;
|
|
82
|
-
readonly smartAccountAddress: Address;
|
|
81
|
+
readonly signerAddress: Address$1 | null;
|
|
82
|
+
readonly smartAccountAddress: Address$1;
|
|
83
83
|
readonly chainId: ChainId;
|
|
84
84
|
readonly deployedAt: EpochMs | null;
|
|
85
85
|
readonly claimedAt: EpochMs | null;
|
|
@@ -95,18 +95,13 @@ type Account$1 = {
|
|
|
95
95
|
readonly balance: Money;
|
|
96
96
|
readonly available: Money;
|
|
97
97
|
};
|
|
98
|
-
/** Named bucket partitioning a logical Account (canon §9). */
|
|
99
|
-
type SubAccount = {
|
|
100
|
-
readonly id: SubAccountId;
|
|
101
|
-
readonly accountId: AccountId;
|
|
102
|
-
readonly name: string;
|
|
103
|
-
readonly balance: Money;
|
|
104
|
-
readonly createdAt: EpochMs;
|
|
105
|
-
};
|
|
106
98
|
type AuthUserId = Brand<string, "AuthUserId">;
|
|
107
99
|
type AnonymousDistinctId = Brand<string, "AnonymousDistinctId">;
|
|
108
100
|
type AccountId = Brand<string, "AccountId">;
|
|
109
|
-
type
|
|
101
|
+
type MovementId = Brand<string, "MovementId">;
|
|
102
|
+
type PermissionId = Brand<string, "PermissionId">;
|
|
103
|
+
type PermissionAssignmentId = Brand<string, "PermissionAssignmentId">;
|
|
104
|
+
type PaymentCommandId = Brand<string, "PaymentCommandId">;
|
|
110
105
|
type OrgId = Brand<string, "OrgId">;
|
|
111
106
|
type AppId = Brand<string, "AppId">;
|
|
112
107
|
type AllowedOrigin = Brand<string, "AllowedOrigin">;
|
|
@@ -121,8 +116,9 @@ type CountryCode = Brand<string, "CountryCode">;
|
|
|
121
116
|
type CurrencyCode = Brand<SupportedCurrencyCode, "CurrencyCode">;
|
|
122
117
|
type KycTier = Brand<0 | 1 | 2 | 3, "KycTier">;
|
|
123
118
|
type BlockNumber = Brand<number, "BlockNumber">;
|
|
124
|
-
type
|
|
119
|
+
type WeiAmount = Brand<string, "WeiAmount">;
|
|
125
120
|
type RoleKey = Brand<string, "RoleKey">;
|
|
121
|
+
type AllowanceKey = Brand<string, "AllowanceKey">;
|
|
126
122
|
type SessionToken = Brand<string, "SessionToken">;
|
|
127
123
|
type JwtToken = Brand<string, "JwtToken">;
|
|
128
124
|
type AuthSession = {
|
|
@@ -153,7 +149,7 @@ declare const SUPPORTED_CURRENCIES: readonly [{
|
|
|
153
149
|
readonly name: "Ugandan Shilling";
|
|
154
150
|
}];
|
|
155
151
|
type SupportedCurrencyCode = (typeof SUPPORTED_CURRENCIES)[number]["code"];
|
|
156
|
-
declare function toAddress(raw: unknown): Address;
|
|
152
|
+
declare function toAddress(raw: unknown): Address$1;
|
|
157
153
|
declare function toCountryCode(raw: unknown): CountryCode;
|
|
158
154
|
//#endregion
|
|
159
155
|
//#region src/ports/auth-cache.d.ts
|
|
@@ -247,7 +243,7 @@ interface AccountProvider {
|
|
|
247
243
|
*
|
|
248
244
|
* Custom providers MUST honor this contract.
|
|
249
245
|
*/
|
|
250
|
-
getAddress(): Promise<CapxulResult<Address>>;
|
|
246
|
+
getAddress(): Promise<CapxulResult<Address$1>>;
|
|
251
247
|
getDeployAccount(): Promise<CapxulResult<Account>>;
|
|
252
248
|
}
|
|
253
249
|
interface Eip1193Provider {
|
|
@@ -279,7 +275,7 @@ interface CapxulSigner extends CapxulDigestSigner {
|
|
|
279
275
|
*/
|
|
280
276
|
readonly source: AccountProviderSource;
|
|
281
277
|
/** Owner EOA address — the Safe's single owner. */
|
|
282
|
-
getAddress(): Promise<Address>;
|
|
278
|
+
getAddress(): Promise<Address$1>;
|
|
283
279
|
}
|
|
284
280
|
/** Minimal EIP-1193 surface an injected browser wallet exposes. */
|
|
285
281
|
interface Eip1193RequestProvider {
|
|
@@ -297,5 +293,4 @@ interface Eip1193RequestProvider {
|
|
|
297
293
|
*/
|
|
298
294
|
declare function injectedWalletSigner(provider: Eip1193RequestProvider): CapxulSigner;
|
|
299
295
|
//#endregion
|
|
300
|
-
export {
|
|
301
|
-
//# sourceMappingURL=signer-CJT0pPiO.d.mts.map
|
|
296
|
+
export { CapxulErrorDetails as $, CountryCode as A, PermissionAssignmentId as B, AllowedOrigin as C, AuthUserId as D, AuthSession as E, EpochMs as F, SessionToken as G, Profile$1 as H, Money as I, WeiAmount as J, SmartAccount$1 as K, MovementId as L, DocumentHash as M, DurationMs as N, BlockNumber as O, Email as P, CapxulErrorCode as Q, OrgId as R, AllowanceKey as S, AppId as T, PublishableKey as U, PermissionId as V, RoleKey as W, toCountryCode as X, toAddress as Y, CapxulError as Z, AuthCachePortTag as _, AccountProvider as a, AccountId as b, Eip1193Provider as c, CapxulResult as d, Failure as et, Profile as f, AuthCachePort as g, AuthCacheError as h, injectedWalletSigner as i, CurrencyCode as j, ChainId as k, eip1193AccountProvider as l, SmartAccount as m, CapxulSigner as n, isCapxulError as nt, AccountProviderSource as o, Session as p, TxHash as q, Eip1193RequestProvider as r, AccountRequirement as s, CapxulDigestSigner as t, FailureMode as tt, localPrivateKeyAccountProvider as u, CachedJwt as v, AnonymousDistinctId as w, Address$1 as x, Account$1 as y, PaymentCommandId as z };
|
package/dist/testing/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { _n as IdentityTransition, an as TelemetryEvent, on as TelemetryGroupInput, sn as TelemetryIdentifyInput, t as CapxulClient } from "../create-capxul-client-klbklLYW.mjs";
|
|
2
2
|
import { Effect, Layer } from "effect";
|
|
3
3
|
|
|
4
4
|
//#region src/testing/telemetry/RecordingTelemetryAdapter.d.ts
|
|
@@ -50,5 +50,4 @@ interface CapxulTestObservation {
|
|
|
50
50
|
*/
|
|
51
51
|
declare function createCapxulTestClient(options?: CreateCapxulTestClientOptions): CapxulTestClient;
|
|
52
52
|
//#endregion
|
|
53
|
-
export { CapxulTestClient, CapxulTestClock, CapxulTestObservation, CreateCapxulTestClientOptions, SeedTestIdentityInput, createCapxulTestClient };
|
|
54
|
-
//# sourceMappingURL=index.d.mts.map
|
|
53
|
+
export { CapxulTestClient, CapxulTestClock, CapxulTestObservation, CreateCapxulTestClientOptions, SeedTestIdentityInput, createCapxulTestClient };
|
package/dist/testing/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { E as authClientPortFromPromiseAdapter, T as bootstrapErrorFromCapxul, W as deriveCapxulSafeAddress, _ as wireChainId, f as smartAccountErrorFromCapxul, g as toWei, h as accountReadErrorFromCapxul, p as fromWei, t as assembleCapxulClient, u as redactTelemetryEvent, x as convexCallErrorFromCapxul, y as identityErrorFromCapxul } from "../create-capxul-client-N36cHqE2.mjs";
|
|
2
|
+
import { A as toSessionToken, C as toEpochMs, E as toKycTier, M as CapxulError, O as toPublishableKey, P as Errors, S as toEmail, T as toJwtToken, _ as toAuthUserId, g as toAppId, h as toAllowedOrigin, m as toAddress, p as toAccountId, t as InMemoryAuthCacheAdapter, v as toChainId, w as toEpochSeconds, x as toDurationMs, y as toCountryCode } from "../InMemoryAuthCacheAdapter-Rc8tCtml.mjs";
|
|
3
3
|
import { keccak256 } from "viem";
|
|
4
4
|
import { Effect, Result, Semaphore } from "effect";
|
|
5
5
|
import { getFunctionName } from "convex/server";
|
|
@@ -618,7 +618,7 @@ function isSupportedSmartAccountChain(chainId) {
|
|
|
618
618
|
//#region src/testing/smart-account/InMemorySmartAccountAdapter.ts
|
|
619
619
|
/**
|
|
620
620
|
* Hermetic backend stand-in (PRD #462 / derivation v2): `provision` derives
|
|
621
|
-
* the Safe from the
|
|
621
|
+
* the Safe from the authenticated email via the REAL canonical derivation
|
|
622
622
|
* (`deriveCapxulSafeAddress({ email })` — owner is the pinned bootstrap
|
|
623
623
|
* constant). No signer exists at provision; `claim` installs the signer and
|
|
624
624
|
* marks the row deployed, mirroring the backend's one-userOp claim lane.
|
|
@@ -626,12 +626,10 @@ function isSupportedSmartAccountChain(chainId) {
|
|
|
626
626
|
var InMemorySmartAccountAdapter = class {
|
|
627
627
|
#accounts = /* @__PURE__ */ new Map();
|
|
628
628
|
#clock;
|
|
629
|
-
#identity;
|
|
630
629
|
#failures;
|
|
631
630
|
#provisionMutex = Semaphore.makeUnsafe(1);
|
|
632
631
|
constructor(deps) {
|
|
633
632
|
this.#clock = deps.clock;
|
|
634
|
-
this.#identity = deps.identity;
|
|
635
633
|
this.#failures = deps.failures;
|
|
636
634
|
}
|
|
637
635
|
loadByAuthUserId(authUserId) {
|
|
@@ -654,15 +652,13 @@ var InMemorySmartAccountAdapter = class {
|
|
|
654
652
|
const self = this;
|
|
655
653
|
return Effect.gen(function* () {
|
|
656
654
|
if (!isSupportedSmartAccountChain(input.chainId)) return yield* fail("provision", Errors.invalidInput("chainId", `unsupported chainId ${String(input.chainId)}`));
|
|
657
|
-
const identity = yield* self.#identity.loadByAuthUserId(input.authUserId).pipe(Effect.mapError((error) => smartAccountErrorFromCapxul("provision.identity", error.publicError, error)));
|
|
658
|
-
if (identity === null) return yield* fail("provision", Errors.profileNotFound(String(input.authUserId)));
|
|
659
655
|
const existing = self.#accounts.get(input.authUserId);
|
|
660
656
|
if (existing !== void 0) return cloneSmartAccount(existing);
|
|
661
657
|
const now = yield* self.#now("provision.clock");
|
|
662
658
|
const account = {
|
|
663
659
|
authUserId: input.authUserId,
|
|
664
660
|
signerAddress: null,
|
|
665
|
-
smartAccountAddress: toAddress(deriveCapxulSafeAddress({ email:
|
|
661
|
+
smartAccountAddress: toAddress(deriveCapxulSafeAddress({ email: input.email })),
|
|
666
662
|
chainId: input.chainId,
|
|
667
663
|
deployedAt: null,
|
|
668
664
|
claimedAt: null,
|
|
@@ -743,134 +739,6 @@ function cloneSmartAccountOrNull(account) {
|
|
|
743
739
|
return account === null ? null : cloneSmartAccount(account);
|
|
744
740
|
}
|
|
745
741
|
//#endregion
|
|
746
|
-
//#region src/testing/sub-account/InMemorySubAccountAdapter.ts
|
|
747
|
-
var InMemorySubAccountAdapter = class {
|
|
748
|
-
#rows = /* @__PURE__ */ new Map();
|
|
749
|
-
#failures;
|
|
750
|
-
#balanceOfRaw;
|
|
751
|
-
#created;
|
|
752
|
-
constructor(deps = {}) {
|
|
753
|
-
this.#failures = deps.failures ?? {};
|
|
754
|
-
this.#balanceOfRaw = deps.balanceOfRaw ?? "0";
|
|
755
|
-
for (const row of deps.seed ?? []) this.#rows.set(row.id, row);
|
|
756
|
-
this.#created = this.#rows.size;
|
|
757
|
-
}
|
|
758
|
-
create(input) {
|
|
759
|
-
const failure = this.#failures.create;
|
|
760
|
-
if (failure !== void 0) return Effect.fail(subAccountErrorFromCapxul("create", failure));
|
|
761
|
-
this.#created += 1;
|
|
762
|
-
const id = toSubAccountId(`subaccount_test${String(this.#created)}`);
|
|
763
|
-
const row = {
|
|
764
|
-
id,
|
|
765
|
-
accountId: input.accountId,
|
|
766
|
-
name: input.name,
|
|
767
|
-
balance: {
|
|
768
|
-
currency: toCurrencyCode("USD"),
|
|
769
|
-
value: "0",
|
|
770
|
-
decimals: 6
|
|
771
|
-
},
|
|
772
|
-
createdAt: toEpochMs(Date.now())
|
|
773
|
-
};
|
|
774
|
-
this.#rows.set(id, row);
|
|
775
|
-
return Effect.succeed(row);
|
|
776
|
-
}
|
|
777
|
-
get(input) {
|
|
778
|
-
return Effect.succeed(this.#rows.get(input.subAccountId) ?? null);
|
|
779
|
-
}
|
|
780
|
-
list(input) {
|
|
781
|
-
const accountId = input.accountId;
|
|
782
|
-
return Effect.succeed([...this.#rows.values()].filter((row) => row.accountId === accountId));
|
|
783
|
-
}
|
|
784
|
-
rename(input) {
|
|
785
|
-
const existing = this.#rows.get(input.subAccountId);
|
|
786
|
-
if (existing === void 0) return Effect.fail(subAccountErrorFromCapxul("rename", Errors.accountNotFound(input.subAccountId)));
|
|
787
|
-
const next = {
|
|
788
|
-
...existing,
|
|
789
|
-
name: input.name
|
|
790
|
-
};
|
|
791
|
-
this.#rows.set(input.subAccountId, next);
|
|
792
|
-
return Effect.succeed(next);
|
|
793
|
-
}
|
|
794
|
-
delete(input) {
|
|
795
|
-
const existing = this.#rows.get(input.subAccountId);
|
|
796
|
-
if (existing === void 0) return Effect.fail(subAccountErrorFromCapxul("delete", Errors.accountNotFound(input.subAccountId)));
|
|
797
|
-
if (Number(existing.balance.value) !== 0) return Effect.fail(subAccountErrorFromCapxul("delete", Errors.invalidInput("subAccountId", "delete requires zero balance")));
|
|
798
|
-
this.#rows.delete(input.subAccountId);
|
|
799
|
-
return Effect.succeed(void 0);
|
|
800
|
-
}
|
|
801
|
-
transfer(input) {
|
|
802
|
-
const decimals = input.amount.decimals;
|
|
803
|
-
const invalid = (field, reason) => Effect.fail(subAccountErrorFromCapxul("transfer", Errors.invalidInput(field, reason)));
|
|
804
|
-
let rawAmount;
|
|
805
|
-
try {
|
|
806
|
-
rawAmount = BigInt(toWei(input.amount));
|
|
807
|
-
} catch {
|
|
808
|
-
return invalid("amount", "must be a decimal money string");
|
|
809
|
-
}
|
|
810
|
-
if (rawAmount <= 0n) return invalid("amount", "must be positive");
|
|
811
|
-
if (input.from === input.to) return invalid("transfer", "from and to must differ");
|
|
812
|
-
const fromRow = input.from === "main" ? null : this.#rows.get(input.from) ?? "missing";
|
|
813
|
-
if (fromRow === "missing") return invalid("subAccountId", "unknown sub-account");
|
|
814
|
-
const toRow = input.to === "main" ? null : this.#rows.get(input.to) ?? "missing";
|
|
815
|
-
if (toRow === "missing") return invalid("subAccountId", "unknown sub-account");
|
|
816
|
-
const safeRaw = BigInt(this.#balanceOfRaw);
|
|
817
|
-
const subTotalRaw = this.#sumSubAccountRaws(decimals);
|
|
818
|
-
if (input.from === "main") {
|
|
819
|
-
const availableRaw = safeRaw - subTotalRaw;
|
|
820
|
-
if (availableRaw < rawAmount) return Effect.fail(subAccountErrorFromCapxul("transfer", Errors.insufficientBalance("main", maxRaw(availableRaw), rawAmount.toString(10))));
|
|
821
|
-
} else if (fromRow !== null) {
|
|
822
|
-
const fromRaw = BigInt(toWei({
|
|
823
|
-
value: fromRow.balance.value,
|
|
824
|
-
decimals
|
|
825
|
-
}));
|
|
826
|
-
if (fromRaw < rawAmount) return Effect.fail(subAccountErrorFromCapxul("transfer", Errors.insufficientBalance(fromRow.name, fromRaw.toString(10), rawAmount.toString(10))));
|
|
827
|
-
}
|
|
828
|
-
let nextFrom = null;
|
|
829
|
-
let nextTo = null;
|
|
830
|
-
if (fromRow !== null) {
|
|
831
|
-
const fromRaw = BigInt(toWei({
|
|
832
|
-
value: fromRow.balance.value,
|
|
833
|
-
decimals
|
|
834
|
-
}));
|
|
835
|
-
nextFrom = this.#patchBalance(fromRow, (fromRaw - rawAmount).toString(10), decimals);
|
|
836
|
-
}
|
|
837
|
-
if (toRow !== null) {
|
|
838
|
-
const toRaw = BigInt(toWei({
|
|
839
|
-
value: toRow.balance.value,
|
|
840
|
-
decimals
|
|
841
|
-
}));
|
|
842
|
-
nextTo = this.#patchBalance(toRow, (toRaw + rawAmount).toString(10), decimals);
|
|
843
|
-
}
|
|
844
|
-
const available = fromWei(maxRaw(safeRaw - this.#sumSubAccountRaws(decimals)), decimals, input.amount.currency);
|
|
845
|
-
return Effect.succeed({
|
|
846
|
-
available,
|
|
847
|
-
from: nextFrom,
|
|
848
|
-
to: nextTo
|
|
849
|
-
});
|
|
850
|
-
}
|
|
851
|
-
#sumSubAccountRaws(decimals) {
|
|
852
|
-
let total = 0n;
|
|
853
|
-
for (const row of this.#rows.values()) total += BigInt(toWei({
|
|
854
|
-
value: row.balance.value,
|
|
855
|
-
decimals
|
|
856
|
-
}));
|
|
857
|
-
return total;
|
|
858
|
-
}
|
|
859
|
-
#patchBalance(row, rawBalance, decimals) {
|
|
860
|
-
const balance = fromWei(rawBalance, decimals, row.balance.currency);
|
|
861
|
-
const next = {
|
|
862
|
-
...row,
|
|
863
|
-
balance
|
|
864
|
-
};
|
|
865
|
-
this.#rows.set(row.id, next);
|
|
866
|
-
return next;
|
|
867
|
-
}
|
|
868
|
-
};
|
|
869
|
-
/** Floor a (possibly negative) base-unit raw to a non-negative base-10 string. */
|
|
870
|
-
function maxRaw(raw) {
|
|
871
|
-
return (raw < 0n ? 0n : raw).toString(10);
|
|
872
|
-
}
|
|
873
|
-
//#endregion
|
|
874
742
|
//#region src/testing/telemetry/RecordingTelemetryAdapter.ts
|
|
875
743
|
var RecordingTelemetryAdapter = class {
|
|
876
744
|
#events = [];
|
|
@@ -1007,12 +875,8 @@ function createCapxulTestClient(options = {}) {
|
|
|
1007
875
|
authClient: authClientPortFromPromiseAdapter(authClient),
|
|
1008
876
|
authCache,
|
|
1009
877
|
identity,
|
|
1010
|
-
smartAccount: new InMemorySmartAccountAdapter({
|
|
1011
|
-
clock,
|
|
1012
|
-
identity
|
|
1013
|
-
}),
|
|
878
|
+
smartAccount: new InMemorySmartAccountAdapter({ clock }),
|
|
1014
879
|
accountRead: new InMemoryAccountReadAdapter({ rawBalance: "0" }),
|
|
1015
|
-
subAccount: new InMemorySubAccountAdapter(),
|
|
1016
880
|
bootstrap: new BootstrapStubAdapter({ script: { resolutions: new Map([[`${toPublishableKey("cap_pk_test_0123456789ABCDEFGHJKMNPQRSTVWXYZ")}::${toAllowedOrigin("https://example.test")}`, TEST_BOOTSTRAP]]) } }),
|
|
1017
881
|
clock,
|
|
1018
882
|
telemetry,
|
|
@@ -1064,5 +928,3 @@ function createCapxulTestClient(options = {}) {
|
|
|
1064
928
|
}
|
|
1065
929
|
//#endregion
|
|
1066
930
|
export { createCapxulTestClient };
|
|
1067
|
-
|
|
1068
|
-
//# sourceMappingURL=index.mjs.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@capxul/sdk",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "git+https://github.com/Xelmar-tech/infrastructure.git",
|
|
@@ -38,29 +38,31 @@
|
|
|
38
38
|
},
|
|
39
39
|
"devDependencies": {
|
|
40
40
|
"@effect/vitest": "4.0.0-beta.105",
|
|
41
|
+
"@typescript/native": "npm:typescript@7.0.2",
|
|
41
42
|
"@vitest/coverage-v8": "4.1.7",
|
|
42
43
|
"fast-check": "^3.23.2",
|
|
43
44
|
"permissionless": "0.3.4",
|
|
44
45
|
"posthog-js": "^1.399.2",
|
|
45
|
-
"typescript": "
|
|
46
|
+
"typescript": "npm:@typescript/typescript6@6.0.2",
|
|
47
|
+
"vite-plus": "0.1.23",
|
|
46
48
|
"vitest": "npm:@voidzero-dev/vite-plus-test@0.1.23",
|
|
49
|
+
"@capxul/config": "0.1.1",
|
|
47
50
|
"@capxul/errors": "0.0.1",
|
|
51
|
+
"@capxul/typescript-config": "0.0.0",
|
|
52
|
+
"@capxul/observability": "2.0.0",
|
|
48
53
|
"@capxul/wire": "0.1.0",
|
|
49
|
-
"@capxul/observability": "1.2.2",
|
|
50
|
-
"@capxul/config": "0.1.0",
|
|
51
54
|
"@capxul/types": "0.1.0"
|
|
52
55
|
},
|
|
53
56
|
"_permissionlessPinReason": "permissionless.toSafeSmartAccount is pinned to 0.3.4 for live Safe deployment E2E. Counterfactual address fixtures captured 2026-05-17 in packages/backend/convex/_shared/__tests__/counterfactual.test.ts and packages/config/tests/safe.test.ts must be re-verified before upgrading.",
|
|
54
57
|
"scripts": {
|
|
55
|
-
"check-types": "vp exec tsc -p tsconfig.json --noEmit",
|
|
58
|
+
"check-types": "vp exec ../../node_modules/@typescript/native/bin/tsc -p tsconfig.json --noEmit",
|
|
56
59
|
"lint": "vp exec oxlint -c ../../.oxlintrc.json . --deny-warnings",
|
|
57
|
-
"build": "
|
|
60
|
+
"build": "vp pack",
|
|
58
61
|
"_vp-tasks-allowed": "vp-allowed: `test` + `test:coverage` are vp tasks in vite.config.ts so vitest self-writes don't bust cache (#205). `test:coverage:full` keeps the script form because it composes 5 reporters at invocation time.",
|
|
59
62
|
"test:coverage:full": "CAPXUL_FAST_CHECK_NUM_RUNS=50 vp test run --coverage --coverage.reporter=text --coverage.reporter=json-summary --coverage.reporter=json --coverage.reporter=html --coverage.reporter=clover",
|
|
60
63
|
"test:e2e": "vp test run --config vitest.e2e.config.ts",
|
|
61
64
|
"proofs:live": "vp exec bash ../../scripts/prove-organization-core-live.sh",
|
|
62
65
|
"proof:openfort-embedded-deploy": "vp test run --config vitest.e2e.config.ts e2e/openfort-embedded-deploy.live.ts",
|
|
63
|
-
"proof:
|
|
64
|
-
"org:domain-live": "vp dlx tsx e2e/org-domain-sdk-live.ts"
|
|
66
|
+
"proof:dev-identity": "vp test run src/__e2e__/dev-identity-capability.l4.test.ts"
|
|
65
67
|
}
|
|
66
68
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"InMemoryAuthCacheAdapter-Dr1sEd9y.mjs","names":[],"sources":["../../errors/src/errors.ts","../../errors/src/convex-error-decoding.ts","../../types/src/index.ts","../src/ports/auth-cache.ts","../src/adapters/auth-cache/serialization.ts","../src/adapters/auth-cache/BrowserAuthCacheAdapter.ts","../src/adapters/auth-cache/InMemoryAuthCacheAdapter.ts"],"sourcesContent":["// The canonical error-code catalog as a runtime constant. `CapxulErrorCode`\n// is derived from it so the type and any runtime check that needs to\n// enumerate codes (e.g. the convex-error codec's `KNOWN_CODES`) share a\n// single source of truth — a TypeScript union alone can't be introspected\n// at runtime, which previously forced a hand-maintained duplicate.\nexport const CAPXUL_ERROR_CODES = [\n \"NOT_AUTHENTICATED\",\n \"EMAIL_DELIVERY_FAILED\",\n \"PROFILE_NOT_FOUND\",\n \"SMART_ACCOUNT_MISSING\",\n \"PLAYER_NOT_FOUND\",\n \"ACCOUNT_NOT_FOUND\",\n \"PROVIDER_ERROR\",\n \"INVALID_INPUT\",\n \"ENV_MISSING\",\n \"NOT_IMPLEMENTED\",\n \"VERIFICATION_REQUIRED\",\n \"INSUFFICIENT_BALANCE\",\n \"INVALID_RECIPIENT\",\n \"ROLE_PERMISSION_DENIED\",\n \"TRANSACTION_FAILED\",\n \"RATE_LIMITED\",\n \"NETWORK_ERROR\",\n \"UNKNOWN\",\n \"OTP_EXPIRED\",\n \"SIGNER_REJECTED\",\n \"CANCELLED\",\n \"WRONG_STATE\",\n \"STALE_EPOCH\",\n \"SUPERSEDED\",\n \"WORK_DIED\",\n \"ACTOR_STOPPED\",\n] as const;\n\nexport type CapxulErrorCode = (typeof CAPXUL_ERROR_CODES)[number];\n\n/**\n * The error codes that represent an expected product outcome rather than a\n * defect. The SDK and backend observation boundaries both classify failures\n * against this set to route expected outcomes to their own PostHog event\n * stream; keeping the single copy here (adjacent to `CAPXUL_ERROR_CODES`, so a\n * code rename forces this set to move with it) stops the two sides of the wire\n * from drifting and silently splitting one outcome across two streams.\n */\nexport const EXPECTED_OPERATION_OUTCOMES: ReadonlySet<CapxulErrorCode> = new Set([\n \"INVALID_INPUT\",\n \"NOT_AUTHENTICATED\",\n // A user with no Safe yet — the normal post-OTP / pre-provision state. Reading\n // the account, current user, or balance in that window is an expected outcome,\n // not a defect, so both observation boundaries route it to their\n // `*_expected_outcome` stream instead of an unexpected `$exception` (#1031).\n \"SMART_ACCOUNT_MISSING\",\n \"CANCELLED\",\n \"SIGNER_REJECTED\",\n \"VERIFICATION_REQUIRED\",\n \"INSUFFICIENT_BALANCE\",\n \"INVALID_RECIPIENT\",\n \"ROLE_PERMISSION_DENIED\",\n \"RATE_LIMITED\",\n \"OTP_EXPIRED\",\n \"WRONG_STATE\",\n \"STALE_EPOCH\",\n \"SUPERSEDED\",\n \"ACTOR_STOPPED\",\n]);\n\n/**\n * Why an auth/provider call failed — a flat CAUSE enum. The *where* (which\n * OpenFort operation) stays in the separate `operation` detail field; this\n * names the root cause so a single `$exception` can be triaged without\n * parsing the message. Five members, no free strings:\n *\n * - `auth-origin-mismatch`: OTP cookies live on `localhost:PORT` but OpenFort\n * hits the Convex host → no session reaches the provider.\n * - `stale-openfort-cache`: an old `userId` in scoped storage makes the SDK\n * skip re-auth → 401 on `v2/accounts`.\n * - `app-env-allowlist`: the selected app/deployment origin is not allowlisted\n * → 401.\n * - `no-secure-context`: sandboxed/headless browser with no Web Crypto, so\n * `getAddress`/`configure` can never produce an address. Previously vanished\n * into `unknown`; the signer's secure-context probe now names it.\n * - `unknown`: catch-all when no cause could be determined.\n */\nexport type FailureMode =\n | \"auth-origin-mismatch\"\n | \"stale-openfort-cache\"\n | \"app-env-allowlist\"\n | \"no-secure-context\"\n | \"unknown\";\n\n/**\n * The one failure representation carried by domain state, actor work, and\n * public error projection. Keeping it beside the canonical error catalog\n * prevents a machine or shell from inventing a second code vocabulary.\n */\nexport interface Failure {\n readonly code: CapxulErrorCode;\n readonly message: string;\n readonly mode?: FailureMode;\n}\n\nexport type CapxulErrorDetails = Record<string, unknown>;\n\nexport type SignerSource = \"openfort-embedded\" | \"injected-eip1193\" | \"local-private-key\";\n\nexport type VerificationRequiredDetails =\n | { readonly requiredTier: number }\n | { readonly rail: string; readonly currentKind: string };\n\nexport type SerializedCapxulError = {\n readonly code: CapxulErrorCode;\n readonly message: string;\n readonly details?: CapxulErrorDetails;\n readonly correlationId?: string;\n readonly layer?: string;\n};\n\nexport type CapxulErrorOptions = {\n readonly cause?: unknown;\n readonly details?: CapxulErrorDetails;\n readonly correlationId?: string;\n readonly layer?: string;\n};\n\nexport class CapxulError extends Error {\n readonly code: CapxulErrorCode;\n readonly details?: CapxulErrorDetails;\n readonly correlationId?: string;\n readonly layer?: string;\n\n constructor(code: CapxulErrorCode, message: string, options: CapxulErrorOptions = {}) {\n super(message, \"cause\" in options ? { cause: options.cause } : undefined);\n this.name = \"CapxulError\";\n this.code = code;\n if (options.details !== undefined) {\n this.details = options.details;\n }\n if (options.correlationId !== undefined) {\n this.correlationId = options.correlationId;\n }\n if (options.layer !== undefined) {\n this.layer = options.layer;\n }\n }\n}\n\nexport function isCapxulError(value: unknown): value is CapxulError {\n return value instanceof CapxulError;\n}\n\nexport function serializeCapxulError(error: CapxulError): SerializedCapxulError {\n return compactSerialized({\n code: error.code,\n message: error.message,\n details: error.details,\n correlationId: error.correlationId,\n layer: error.layer,\n });\n}\n\nexport function deserializeCapxulError(serialized: SerializedCapxulError): CapxulError {\n return new CapxulError(\n serialized.code,\n serialized.message,\n compactErrorOptions({\n details: serialized.details,\n correlationId: serialized.correlationId,\n layer: serialized.layer,\n }),\n );\n}\n\nfunction compactSerialized(serialized: {\n readonly code: CapxulErrorCode;\n readonly message: string;\n readonly details: CapxulErrorDetails | undefined;\n readonly correlationId: string | undefined;\n readonly layer: string | undefined;\n}): SerializedCapxulError {\n const result: {\n code: CapxulErrorCode;\n message: string;\n details?: CapxulErrorDetails;\n correlationId?: string;\n layer?: string;\n } = {\n code: serialized.code,\n message: serialized.message,\n };\n\n if (serialized.details !== undefined) {\n result.details = serialized.details;\n }\n if (serialized.correlationId !== undefined) {\n result.correlationId = serialized.correlationId;\n }\n if (serialized.layer !== undefined) {\n result.layer = serialized.layer;\n }\n\n return result;\n}\n\nfunction compactErrorOptions(options: {\n readonly cause?: unknown;\n readonly details: CapxulErrorDetails | undefined;\n readonly correlationId: string | undefined;\n readonly layer: string | undefined;\n}): CapxulErrorOptions {\n const result: {\n cause?: unknown;\n details?: CapxulErrorDetails;\n correlationId?: string;\n layer?: string;\n } = {};\n\n if (\"cause\" in options) {\n result.cause = options.cause;\n }\n if (options.details !== undefined) {\n result.details = options.details;\n }\n if (options.correlationId !== undefined) {\n result.correlationId = options.correlationId;\n }\n if (options.layer !== undefined) {\n result.layer = options.layer;\n }\n\n return result;\n}\n\nexport const Errors = {\n notAuthenticated: (message?: string, opts?: { readonly failure_mode?: FailureMode }) =>\n new CapxulError(\n \"NOT_AUTHENTICATED\",\n message ?? \"Not authenticated\",\n opts?.failure_mode ? { details: { failure_mode: opts.failure_mode } } : undefined,\n ),\n emailDeliveryFailed: (detail: string) =>\n new CapxulError(\"EMAIL_DELIVERY_FAILED\", \"Failed to send email\", {\n details: { detail },\n }),\n\n profileNotFound: (authUserId: string) =>\n new CapxulError(\"PROFILE_NOT_FOUND\", `Profile not found for user ${authUserId}`, {\n details: { authUserId },\n }),\n\n smartAccountMissing: (authUserId: string) =>\n new CapxulError(\"SMART_ACCOUNT_MISSING\", \"Smart account not provisioned\", {\n details: { authUserId },\n }),\n\n playerNotFound: (playerId?: string) =>\n new CapxulError(\n \"PLAYER_NOT_FOUND\",\n playerId ? `Openfort player ${playerId} not found` : \"Openfort player not found\",\n playerId === undefined ? undefined : { details: { playerId } },\n ),\n\n accountNotFound: (accountId?: string) =>\n new CapxulError(\n \"ACCOUNT_NOT_FOUND\",\n accountId ? `Openfort account ${accountId} not found` : \"Openfort account not found\",\n accountId === undefined ? undefined : { details: { accountId } },\n ),\n\n providerError: (\n provider: string,\n operation: string,\n cause: unknown,\n opts?: { readonly failure_mode?: FailureMode },\n ) => {\n const details: Record<string, unknown> = { provider, operation };\n if (opts?.failure_mode) {\n details.failure_mode = opts.failure_mode;\n }\n return new CapxulError(\"PROVIDER_ERROR\", `Provider error: ${provider} ${operation}`, {\n cause,\n details,\n });\n },\n\n invalidInput: (field: string, reason: string) =>\n new CapxulError(\"INVALID_INPUT\", `Invalid ${field}: ${reason}`, {\n details: { field, reason },\n }),\n\n envMissing: (name: string) =>\n new CapxulError(\"ENV_MISSING\", `Environment variable ${name} not configured`, {\n details: { name },\n }),\n\n notImplemented: (domain: string, method: string) =>\n new CapxulError(\n \"NOT_IMPLEMENTED\",\n `${domain}.${method} is not yet implemented. This feature is planned for a future release.`,\n { details: { domain, method } },\n ),\n\n /**\n * Sibling factory to {@link Errors.providerError} for the per-state timeout\n * path in flows. Same `PROVIDER_ERROR` code as\n * `providerError`, plus a `details.reason: \"timeout\"` discriminator so\n * downstream observers can distinguish failure modes without parsing the\n * message string. The redacted message names the timeout budget; the\n * native `cause` carries the same information for `reportError` fidelity.\n */\n providerTimeout: (provider: string, operation: string, timeoutMs: number) =>\n new CapxulError(\n \"PROVIDER_ERROR\",\n `Provider error: ${provider} ${operation} (timeout exceeded ${timeoutMs}ms)`,\n {\n details: { provider, operation, reason: \"timeout\" },\n cause: new Error(`timeout: ${operation} exceeded ${timeoutMs}ms`),\n },\n ),\n\n verificationRequired: (details: VerificationRequiredDetails) => {\n const message =\n \"rail\" in details\n ? `Verification is required before ${details.rail} can use ${details.currentKind}.`\n : `Verification tier ${details.requiredTier} is required.`;\n\n return new CapxulError(\"VERIFICATION_REQUIRED\", message, {\n details,\n });\n },\n\n insufficientBalance: (asset: string, available: string, required: string) =>\n new CapxulError(\"INSUFFICIENT_BALANCE\", `Insufficient ${asset} balance`, {\n details: { asset, available, required },\n }),\n\n invalidRecipient: (reason: string) =>\n new CapxulError(\"INVALID_RECIPIENT\", `Invalid recipient: ${reason}`, {\n details: { reason },\n }),\n\n /**\n * The org Zodiac Roles modifier REFUSED the spend on-chain (G4 · #547): the\n * member's role condition (per-tx cap, per-day allowance, allowed recipient,\n * or membership) was violated, so `execTransactionWithRole` reverted. This is\n * a PERMISSION denial — explicitly NOT an `INSUFFICIENT_BALANCE` (the treasury\n * held the funds; the role's authority is what bound). `reason` discriminates\n * the violated condition (`over_cap` / `daily_cap` / `not_member` /\n * `disallowed_recipient` / `condition_violation`); leak-safe — no on-chain\n * identifiers ever enter the details.\n */\n rolePermissionDenied: (details: {\n readonly reason:\n | \"over_cap\"\n | \"daily_cap\"\n | \"not_member\"\n | \"disallowed_recipient\"\n | \"condition_violation\";\n readonly operation?: string;\n }) =>\n new CapxulError(\n \"ROLE_PERMISSION_DENIED\",\n `Org role denied this spend on-chain (${details.reason}).`,\n {\n details:\n details.operation === undefined\n ? { reason: details.reason }\n : { reason: details.reason, operation: details.operation },\n },\n ),\n\n /**\n * A transaction (or sponsored UserOp) failed. `details.reason` discriminates\n * the failure mode for callers that must distinguish a CONFIRMED on-chain\n * revert (`\"onchain_revert\"` — the op executed and reverted, e.g. a Zodiac\n * Roles condition violation) from an inconclusive infra failure. A confirmed\n * revert is the ONLY mode the org spend port may map to a roles denial.\n */\n transactionFailed: (operation: string, cause?: unknown, extra?: { readonly reason?: string }) =>\n new CapxulError(\"TRANSACTION_FAILED\", `Transaction failed: ${operation}`, {\n cause,\n details: extra?.reason === undefined ? { operation } : { operation, reason: extra.reason },\n }),\n\n rateLimited: (details?: { readonly retryAfterMs?: number; readonly resource?: string }) =>\n new CapxulError(\n \"RATE_LIMITED\",\n \"Rate limit exceeded\",\n details === undefined ? undefined : { details: { ...details } },\n ),\n\n networkError: (operation: string, cause?: unknown) =>\n new CapxulError(\"NETWORK_ERROR\", `Network error during ${operation}`, {\n cause,\n details: { operation },\n }),\n\n unknown: (cause?: unknown) => new CapxulError(\"UNKNOWN\", \"Unknown error\", { cause }),\n\n otpExpired: (details?: { readonly email?: string; readonly expiredAt?: number }) =>\n new CapxulError(\n \"OTP_EXPIRED\",\n \"Verification code has expired. Request a new one.\",\n details === undefined ? undefined : { details: { ...details } },\n ),\n\n signerRejected: (details: {\n readonly source: SignerSource;\n readonly reason?: string;\n readonly cause?: unknown;\n }) =>\n new CapxulError(\"SIGNER_REJECTED\", \"Signer rejected the request.\", {\n cause: details.cause,\n details:\n details.reason === undefined\n ? { source: details.source }\n : { source: details.source, reason: details.reason },\n }),\n\n cancelled: (details?: { readonly operation?: string; readonly reason?: string }) =>\n new CapxulError(\n \"CANCELLED\",\n \"Operation was cancelled.\",\n details === undefined ? undefined : { details: { ...details } },\n ),\n\n /**\n * Method called from a flow state where its precondition fails (TA16). The\n * SDK's method API short-circuits with this error before driving the\n * internal state machine. `currentState` is the Effect-machine snapshot\n * tag (stringified from the SDK's actor-shell snapshot; see\n * `packages/errors/CONTEXT.md`); `validStates`\n * enumerates the states the method accepts.\n */\n wrongState: (details: {\n readonly method: string;\n readonly currentState: string;\n readonly validStates: readonly string[];\n }) =>\n new CapxulError(\n \"WRONG_STATE\",\n `${details.method} called from state '${details.currentState}'; valid states: ${details.validStates.join(\", \")}`,\n { details: { ...details, validStates: [...details.validStates] } },\n ),\n} as const;\n","// Shared `decodeConvexError` helper (TA5) — used by both the SDK's\n// `ConvexCallAdapter.mapToCapxulError` AND the backend `credentials/http.ts`\n// `bootstrapClient` handler. Single source of truth for cross-Convex-boundary\n// error decoding rules.\n//\n// Recognizes the `ConvexError(SerializedCapxulError)` object-shape produced by\n// `withErrorBoundary` (Probe B finding, 2026-05-19):\n//\n// { name: \"ConvexError\", data: { code, message, details?, correlationId?, layer? } }\n//\n// AND the defensive string-shape branch for older Convex versions where\n// `data` is a JSON-serialized string. Pass-through for raw `CapxulError`\n// instances (which arrive directly when the throw happened in the same\n// V8 isolate as the catch). Returns null when the value is not a\n// recognizable shape — the caller falls back to NETWORK_ERROR + reportError.\n\nimport {\n CAPXUL_ERROR_CODES,\n CapxulError,\n type CapxulErrorCode,\n type SerializedCapxulError,\n deserializeCapxulError,\n} from \"./errors.ts\";\n\n// Derived from the canonical catalog in errors.ts — single source of truth,\n// so a new code added to `CAPXUL_ERROR_CODES` is recognized here automatically.\nconst KNOWN_CODES: ReadonlySet<CapxulErrorCode> = new Set(CAPXUL_ERROR_CODES);\n\nfunction isCapxulCode(value: unknown): value is CapxulErrorCode {\n return typeof value === \"string\" && KNOWN_CODES.has(value as CapxulErrorCode);\n}\n\nfunction reconstruct(serialized: Record<string, unknown>): CapxulError | null {\n if (!isCapxulCode(serialized.code)) return null;\n const payload: SerializedCapxulError = {\n code: serialized.code,\n message: typeof serialized.message === \"string\" ? serialized.message : String(serialized.code),\n ...(typeof serialized.details === \"object\" &&\n serialized.details !== null &&\n !Array.isArray(serialized.details)\n ? { details: serialized.details as Record<string, unknown> }\n : {}),\n ...(typeof serialized.correlationId === \"string\"\n ? { correlationId: serialized.correlationId }\n : {}),\n ...(typeof serialized.layer === \"string\" ? { layer: serialized.layer } : {}),\n };\n return deserializeCapxulError(payload);\n}\n\nexport function decodeConvexError(err: unknown): CapxulError | null {\n if (err === null || err === undefined) return null;\n\n // Pass-through: same isolate, real CapxulError instance.\n if (err instanceof CapxulError) return err;\n\n if (typeof err !== \"object\") return null;\n\n // The canonical shape produced by `withErrorBoundary` then crossed by\n // Convex's `ctx.runQuery` / `ConvexHttpClient`: a `ConvexError` whose\n // `data` is the `SerializedCapxulError` object literal.\n const record = err as Record<string, unknown>;\n if (!(\"data\" in record)) return null;\n const data = record.data;\n\n if (typeof data === \"object\" && data !== null) {\n return reconstruct(data as Record<string, unknown>);\n }\n\n // Defensive depth — some Convex versions JSON-stringify the data at\n // the runtime boundary. Probe B confirmed @convex-dev/better-auth 0.10.13\n // + convex 1.39.x do NOT do this, but the cheap parse keeps forward\n // compatibility.\n if (typeof data === \"string\") {\n try {\n const parsed = JSON.parse(data) as unknown;\n if (typeof parsed === \"object\" && parsed !== null) {\n return reconstruct(parsed as Record<string, unknown>);\n }\n } catch {\n // Fall through.\n }\n }\n\n return null;\n}\n","import { Errors } from \"@capxul/errors\";\nimport type { Brand } from \"./brand\";\n\nexport type { Brand } from \"./brand\";\n\nexport type Address = Brand<string, \"Address\">;\nexport type Email = Brand<string, \"Email\">;\nexport type Identity = Brand<string, \"Identity\">;\n// `Profile` is the SDK's user-shaped record returned by `IdentityPort`. Pure\n// record of brand-typed fields — not itself a brand. The field-level brands\n// satisfy `IdentityPort` clause I8 at compile time. Hosted here per the\n// package contract (`packages/types/CONTEXT.md`).\nexport type Profile = {\n readonly authUserId: AuthUserId;\n readonly email: Email;\n readonly displayName: string | null;\n readonly country: CountryCode | null;\n readonly onboarded: boolean;\n readonly withdrawalAddress: Address | null;\n // #1062: globally-unique normalized handle; #1061 / ADR-0014: profile-image\n // serving URL resolved at read time. Plain strings (not branded in this\n // slice); null when unset — the Convex read boundary always maps both.\n readonly username: string | null;\n readonly imageUrl: string | null;\n readonly kycTier: KycTier;\n readonly createdAt: EpochMs;\n readonly updatedAt: EpochMs;\n};\n// `SmartAccount` is the SDK's ERC-4337 record returned by `SmartAccountPort`.\n// Pure record of brand-typed fields — not itself a brand. `deployedAt` is\n// nullable: `null` means the address is counterfactual (derived, not yet\n// on-chain). PRD #462 (derivation v2): `signerAddress` is the CLAIMED owner —\n// `null` until the claim userOp installs the user's signer (`claimedAt`\n// records that event); the address derives from the email alone. Hosted here\n// per the package contract (`packages/types/CONTEXT.md`).\nexport type SmartAccount = {\n readonly authUserId: AuthUserId;\n readonly signerAddress: Address | null;\n readonly smartAccountAddress: Address;\n readonly chainId: ChainId;\n readonly deployedAt: EpochMs | null;\n readonly claimedAt: EpochMs | null;\n readonly createdAt: EpochMs;\n};\n// `Money` is the SDK's consumer-facing value type (canon\n// `account-balance-model.md` §10). Every public monetary value is a `Money`\n// — never wei, never raw token units. `value` is a major-unit decimal string\n// (e.g. \"1.5\" USD); `decimals` is the on-chain token precision used for the\n// internal `fromWei`/`toWei` round-trip at the SDK boundary (USDX is 6).\n// Pure record of a brand-typed field + primitives — not itself a brand.\nexport type Money = {\n readonly currency: CurrencyCode;\n readonly value: string;\n readonly decimals: number;\n};\n\n// `Account` is the SDK's logical money account (canon §6, §9). `id` is the\n// `account_`-shaped `AccountId` — NOT the Safe address and NOT an Openfort id.\n// `balance` is the Safe's top-line holdings; `available` is money not assigned\n// to any sub-account (canon §5/§12). With no sub-accounts (Slice 1a),\n// `available === balance`. Pure record of brand-typed fields — not a brand.\nexport type Account = {\n readonly id: AccountId;\n readonly balance: Money;\n readonly available: Money;\n};\n\n/** Named bucket partitioning a logical Account (canon §9). */\nexport type SubAccount = {\n readonly id: SubAccountId;\n readonly accountId: AccountId;\n readonly name: string;\n readonly balance: Money;\n readonly createdAt: EpochMs;\n};\n\nexport type AuthUserId = Brand<string, \"AuthUserId\">;\nexport type AnonymousDistinctId = Brand<string, \"AnonymousDistinctId\">;\nexport type PlayerId = Brand<string, \"PlayerId\">;\nexport type AccountId = Brand<string, \"AccountId\">;\nexport type SubAccountId = Brand<string, \"SubAccountId\">;\nexport type OrgId = Brand<string, \"OrgId\">;\nexport type AppId = Brand<string, \"AppId\">;\nexport type AllowedOrigin = Brand<string, \"AllowedOrigin\">;\nexport type PublishableKey = Brand<string, \"PublishableKey\">;\nexport type PublishableKeyId = Brand<string, \"PublishableKeyId\">;\nexport type DurationMs = Brand<number, \"DurationMs\">;\n// `DeveloperApplication` and `PublishableKeyRecord` are the SDK's record\n// shapes returned by `CredentialsPort`. Pure records of brand-typed fields\n// — not themselves brands. The field-level brands satisfy CR13 + the record\n// branding clauses of `credentials.test-d.ts` at compile time. Hosted here\n// per the package contract (`packages/types/CONTEXT.md`).\nexport type DeveloperApplication = {\n readonly id: AppId;\n readonly authUserId: AuthUserId;\n readonly name: string;\n readonly allowedOrigins: readonly AllowedOrigin[];\n readonly createdAt: EpochMs;\n readonly archivedAt: EpochMs | null;\n};\nexport type PublishableKeyRecord = {\n readonly id: PublishableKeyId;\n readonly applicationId: AppId;\n readonly activeFromMs: EpochMs;\n readonly gracePeriodEndsMs: EpochMs | null;\n readonly revokedAt: EpochMs | null;\n};\nexport type TxHash = Brand<string, \"TxHash\">;\nexport type DocumentHash = Brand<string, \"DocumentHash\">;\nexport type EpochMs = Brand<number, \"EpochMs\">;\nexport type EpochSeconds = Brand<number, \"EpochSeconds\">;\nexport type ChainId = Brand<number, \"ChainId\">;\nexport type CountryCode = Brand<string, \"CountryCode\">;\nexport type CurrencyCode = Brand<SupportedCurrencyCode, \"CurrencyCode\">;\nexport type KycTier = Brand<0 | 1 | 2 | 3, \"KycTier\">;\nexport type BlockNumber = Brand<number, \"BlockNumber\">;\nexport type LogIndex = Brand<number, \"LogIndex\">;\nexport type WeiAmount = Brand<string, \"WeiAmount\">;\nexport type SafeAddress = Brand<string, \"SafeAddress\">;\nexport type ModuleAddress = Brand<string, \"ModuleAddress\">;\nexport type RunId = Brand<string, \"RunId\">;\nexport type RoleKey = Brand<string, \"RoleKey\">;\nexport type AllowanceKey = Brand<string, \"AllowanceKey\">;\nexport type SessionToken = Brand<string, \"SessionToken\">;\nexport type JwtToken = Brand<string, \"JwtToken\">;\n\n// `AuthSession` is the record type shared by `AuthClientPort` and\n// `SessionStoragePort`. Hosted here per the canon\n// (`packages/types/CONTEXT.md`) so both ports depend on it\n// symmetrically. Every field is branded — field-level brands satisfy the\n// AuthSession branding contract asserted in `auth-client.test-d.ts`.\nexport type AuthSession = {\n readonly authUserId: AuthUserId;\n readonly email: Email;\n readonly token: SessionToken;\n readonly expiresAt: EpochMs;\n};\n\nexport const EVM_ADDRESS_RE = /^0x[0-9a-f]{40}$/i;\nexport const BYTES32_RE = /^0x[0-9a-f]{64}$/i;\nexport const PUBLISHABLE_KEY_PATTERN = /^cap_pk_(test|live)_[0-9A-HJKMNP-TV-Z]{32}$/;\nexport const SUPPORTED_CURRENCIES = [\n { code: \"USD\", symbol: \"$\", name: \"US Dollar\" },\n { code: \"NGN\", symbol: \"NGN\", name: \"Nigerian Naira\" },\n { code: \"GHS\", symbol: \"GHS\", name: \"Ghanaian Cedi\" },\n { code: \"KES\", symbol: \"KSh\", name: \"Kenyan Shilling\" },\n { code: \"UGX\", symbol: \"USh\", name: \"Ugandan Shilling\" },\n] as const;\nexport const SUPPORTED_CURRENCY_CODES = SUPPORTED_CURRENCIES.map((currency) => currency.code);\ntype SupportedCurrencyCode = (typeof SUPPORTED_CURRENCIES)[number][\"code\"];\nexport const CURRENCY_SYMBOLS = Object.fromEntries(\n SUPPORTED_CURRENCIES.map((currency) => [currency.code, currency.symbol]),\n) as Record<SupportedCurrencyCode, string>;\n\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\nconst COUNTRY_CODE_RE = /^[A-Z]{2}$/;\nconst ANONYMOUS_DISTINCT_ID_RE = /^anon_[a-zA-Z0-9-]+$/;\n// Canon §6: the logical Account brand is `account_`-shaped. The tail mirrors\n// the `app_` ULID-shape generator (`account_<26 Crockford base32 chars>`) but\n// the brand only enforces the `account_` prefix + a non-empty alphanumeric\n// tail so existing opaque test ids (`account_123`) and generated ULIDs both\n// satisfy it.\nconst ACCOUNT_ID_RE = /^account_[0-9A-Za-z]+$/;\nconst SUBACCOUNT_ID_RE = /^subaccount_[0-9A-Za-z]+$/;\n// Exported so `@capxul/wire`'s `AppIdSchema` can reuse the same regex via\n// `Schema.filter(...)` and stay in lockstep with `toAppId` (Decision 2,\n// 2b parity).\nexport const APP_ID_RE = /^app_[0-7][0-9A-HJKMNP-TV-Z]{25}$/;\nconst TX_HASH_RE = /^0x[0-9a-f]{64}$/i;\nconst DOCUMENT_HASH_HEX_RE = /^[0-9a-fA-F]{64}$/;\nconst WEI_RE = /^[0-9]+$/;\nconst RUN_ID_RE = /^run_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;\nconst MAX_SAFE_EPOCH_SECONDS = Math.floor(Number.MAX_SAFE_INTEGER / 1000);\n\nexport function toAddress(raw: unknown): Address {\n if (typeof raw !== \"string\" || !EVM_ADDRESS_RE.test(raw)) {\n throw Errors.invalidInput(\"address\", invalidValueReason(\"invalid EVM address format\", raw));\n }\n\n return raw.toLowerCase() as Address;\n}\n\nexport function isEvmAddress(raw: unknown): raw is string {\n return typeof raw === \"string\" && EVM_ADDRESS_RE.test(raw);\n}\n\nexport function toEmail(raw: unknown): Email {\n if (typeof raw !== \"string\" || !EMAIL_RE.test(raw)) {\n throw Errors.invalidInput(\"email\", invalidValueReason(\"must look like an email address\", raw));\n }\n\n return raw.toLowerCase() as Email;\n}\n\nexport function toIdentity(raw: unknown): Identity {\n return toNonEmptyStringBrand(raw, \"identity\") as Identity;\n}\n\nexport function toAuthUserId(raw: unknown): AuthUserId {\n return toNonEmptyStringBrand(raw, \"authUserId\") as AuthUserId;\n}\n\nexport function toAnonymousDistinctId(raw: unknown): AnonymousDistinctId {\n if (typeof raw !== \"string\" || !ANONYMOUS_DISTINCT_ID_RE.test(raw)) {\n throw Errors.invalidInput(\n \"anonDistinctId\",\n invalidValueReason(\"must be anon_ plus letters, digits, or hyphens\", raw),\n );\n }\n\n return raw as AnonymousDistinctId;\n}\n\nexport function toPlayerId(raw: unknown): PlayerId {\n return toNonEmptyStringBrand(raw, \"playerId\") as PlayerId;\n}\n\nexport function toAccountId(raw: unknown): AccountId {\n if (typeof raw !== \"string\" || !ACCOUNT_ID_RE.test(raw)) {\n throw Errors.invalidInput(\n \"accountId\",\n invalidValueReason(\"must be account_ plus an alphanumeric id\", raw),\n );\n }\n\n return raw as AccountId;\n}\n\nexport function toSubAccountId(raw: unknown): SubAccountId {\n if (typeof raw !== \"string\" || !SUBACCOUNT_ID_RE.test(raw)) {\n throw Errors.invalidInput(\n \"subAccountId\",\n invalidValueReason(\"must be subaccount_ plus an alphanumeric id\", raw),\n );\n }\n\n return raw as SubAccountId;\n}\n\nexport function toOrgId(raw: unknown): OrgId {\n return toNonEmptyStringBrand(raw, \"orgId\") as OrgId;\n}\n\nexport function toAppId(raw: unknown): AppId {\n if (typeof raw !== \"string\" || !APP_ID_RE.test(raw)) {\n throw Errors.invalidInput(\"appId\", invalidValueReason(\"must be app_ plus a ULID\", raw));\n }\n\n return raw as AppId;\n}\n\nexport function toAllowedOrigin(raw: unknown): AllowedOrigin {\n if (typeof raw !== \"string\") {\n throw Errors.invalidInput(\"allowedOrigin\", \"must be an http or https origin string\");\n }\n\n const normalized = normalizeAllowedOrigin(raw);\n if (normalized === null) {\n throw Errors.invalidInput(\n \"allowedOrigin\",\n invalidValueReason(\"must be an http or https origin\", raw),\n );\n }\n\n return normalized as AllowedOrigin;\n}\n\nexport function toPublishableKeyId(raw: unknown): PublishableKeyId {\n return toNonEmptyStringBrand(raw, \"keyId\") as PublishableKeyId;\n}\n\nexport function toDurationMs(raw: unknown): DurationMs {\n if (typeof raw !== \"number\" || !Number.isSafeInteger(raw) || raw < 0) {\n throw Errors.invalidInput(\n \"duration\",\n invalidValueReason(\"must be a non-negative safe integer\", raw),\n );\n }\n\n return raw as DurationMs;\n}\n\nexport function toPublishableKey(raw: unknown): PublishableKey {\n if (typeof raw !== \"string\" || !PUBLISHABLE_KEY_PATTERN.test(raw)) {\n throw Errors.invalidInput(\n \"publishableKey\",\n invalidValueReason(\"must match cap_pk_(test|live) plus 32 Crockford base32 chars\", raw),\n );\n }\n\n return raw as PublishableKey;\n}\n\nexport function toTxHash(raw: unknown): TxHash {\n if (typeof raw !== \"string\" || !TX_HASH_RE.test(raw)) {\n throw Errors.invalidInput(\"txHash\", invalidValueReason(\"must be 0x + 64 hex chars\", raw));\n }\n\n return raw.toLowerCase() as TxHash;\n}\n\nexport function toDocumentHash(raw: unknown): DocumentHash {\n if (typeof raw !== \"string\") {\n throw Errors.invalidInput(\"documentHash\", \"must be a string\");\n }\n\n const stripped = raw.startsWith(\"0x\") || raw.startsWith(\"0X\") ? raw.slice(2) : raw;\n if (!DOCUMENT_HASH_HEX_RE.test(stripped)) {\n throw Errors.invalidInput(\"documentHash\", \"must be 32 bytes of hex\");\n }\n\n return `0x${stripped.toLowerCase()}` as DocumentHash;\n}\n\nexport function toEpochMs(raw: unknown): EpochMs {\n assertSafeNonNegativeInteger(raw, \"epochMs\");\n return raw as EpochMs;\n}\n\nexport function toEpochSeconds(raw: unknown): EpochSeconds {\n assertSafeNonNegativeInteger(raw, \"epochSeconds\");\n return raw as EpochSeconds;\n}\n\nexport function secondsToMs(seconds: EpochSeconds): EpochMs {\n if (seconds > MAX_SAFE_EPOCH_SECONDS) {\n throw Errors.invalidInput(\"epochSeconds\", `${seconds} would overflow when multiplied by 1000`);\n }\n\n return toEpochMs(seconds * 1000);\n}\n\nexport function epochMsToSeconds(ms: EpochMs): EpochSeconds {\n return toEpochSeconds(Math.floor(ms / 1000));\n}\n\nexport function toChainId(raw: unknown): ChainId {\n if (typeof raw !== \"number\" || !Number.isSafeInteger(raw) || raw <= 0) {\n throw Errors.invalidInput(\n \"chainId\",\n invalidValueReason(\"must be a positive safe integer\", raw),\n );\n }\n\n return raw as ChainId;\n}\n\nexport function toBlockNumber(raw: unknown): BlockNumber {\n assertSafeNonNegativeInteger(raw, \"blockNumber\");\n return raw as BlockNumber;\n}\n\nexport function toLogIndex(raw: unknown): LogIndex {\n assertSafeNonNegativeInteger(raw, \"logIndex\");\n return raw as LogIndex;\n}\n\nexport function toWeiAmount(raw: unknown): WeiAmount {\n if (typeof raw !== \"string\" || !WEI_RE.test(raw)) {\n throw Errors.invalidInput(\n \"weiAmount\",\n invalidValueReason(\"must be a non-negative integer string\", raw),\n );\n }\n\n return raw as WeiAmount;\n}\n\nexport function toCountryCode(raw: unknown): CountryCode {\n if (typeof raw !== \"string\") {\n throw Errors.invalidInput(\"countryCode\", \"must be a string\");\n }\n\n const upper = raw.toUpperCase();\n if (!COUNTRY_CODE_RE.test(upper)) {\n throw Errors.invalidInput(\n \"countryCode\",\n invalidValueReason(\"must be a 2-letter ISO 3166-1 alpha-2 code\", raw),\n );\n }\n\n return upper as CountryCode;\n}\n\nexport function toCurrencyCode(raw: unknown): CurrencyCode {\n if (typeof raw !== \"string\" || !SUPPORTED_CURRENCY_CODES.includes(raw as SupportedCurrencyCode)) {\n throw Errors.invalidInput(\"currencyCode\", invalidValueReason(\"unsupported currency\", raw));\n }\n\n return raw as CurrencyCode;\n}\n\nexport function currencySymbolFor(code: CurrencyCode): string {\n const symbol = CURRENCY_SYMBOLS[code as SupportedCurrencyCode];\n if (symbol === undefined) {\n throw Errors.invalidInput(\"currencyCode\", `no symbol registered for \"${String(code)}\"`);\n }\n\n return symbol;\n}\n\nexport function toKycTier(raw: unknown): KycTier {\n if (typeof raw !== \"number\" || !Number.isInteger(raw) || raw < 0 || raw > 3) {\n throw Errors.invalidInput(\"kycTier\", invalidValueReason(\"must be an integer in [0, 3]\", raw));\n }\n\n return raw as KycTier;\n}\n\nexport function toSafeAddress(raw: unknown): SafeAddress {\n if (typeof raw !== \"string\" || !EVM_ADDRESS_RE.test(raw)) {\n throw Errors.invalidInput(\"safeAddress\", invalidValueReason(\"invalid EVM address format\", raw));\n }\n\n return raw.toLowerCase() as SafeAddress;\n}\n\nexport function toModuleAddress(raw: unknown): ModuleAddress {\n if (typeof raw !== \"string\" || !EVM_ADDRESS_RE.test(raw)) {\n throw Errors.invalidInput(\n \"moduleAddress\",\n invalidValueReason(\"invalid EVM address format\", raw),\n );\n }\n\n return raw.toLowerCase() as ModuleAddress;\n}\n\nexport function toRunId(raw: unknown): RunId {\n if (typeof raw !== \"string\" || !RUN_ID_RE.test(raw)) {\n throw Errors.invalidInput(\"runId\", \"must match the format run_<uuid>\");\n }\n\n return raw as RunId;\n}\n\nexport function toRoleKey(raw: unknown): RoleKey {\n if (typeof raw !== \"string\" || !BYTES32_RE.test(raw)) {\n throw Errors.invalidInput(\"roleKey\", invalidValueReason(\"must be 0x + 64 hex chars\", raw));\n }\n\n return raw.toLowerCase() as RoleKey;\n}\n\nexport function toAllowanceKey(raw: unknown): AllowanceKey {\n if (typeof raw !== \"string\" || !BYTES32_RE.test(raw)) {\n throw Errors.invalidInput(\"allowanceKey\", invalidValueReason(\"must be 0x + 64 hex chars\", raw));\n }\n\n return raw.toLowerCase() as AllowanceKey;\n}\n\nexport function toSessionToken(raw: unknown): SessionToken {\n if (typeof raw !== \"string\" || raw.length === 0) {\n throw Errors.invalidInput(\"token\", \"must be a non-empty string\");\n }\n\n return raw as SessionToken;\n}\n\nexport function toJwtToken(raw: unknown): JwtToken {\n if (typeof raw !== \"string\" || raw.length === 0) {\n throw Errors.invalidInput(\"jwtToken\", \"must be a non-empty string\");\n }\n\n return raw as JwtToken;\n}\n\nfunction toNonEmptyStringBrand(raw: unknown, field: string): string {\n if (typeof raw !== \"string\" || raw.length === 0) {\n throw Errors.invalidInput(field, \"must be a non-empty string\");\n }\n\n return raw;\n}\n\nfunction assertSafeNonNegativeInteger(raw: unknown, field: string): asserts raw is number {\n if (typeof raw !== \"number\" || !Number.isSafeInteger(raw) || raw < 0) {\n throw Errors.invalidInput(\n field,\n invalidValueReason(\"must be a non-negative safe integer\", raw),\n );\n }\n}\n\nfunction normalizeAllowedOrigin(raw: string): string | null {\n let parsed: URL;\n try {\n parsed = new URL(raw);\n } catch {\n return null;\n }\n\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n return null;\n }\n\n if (parsed.hostname.includes(\"*\")) {\n return null;\n }\n\n return parsed.origin;\n}\n\nfunction invalidValueReason(prefix: string, raw: unknown): string {\n if (typeof raw === \"string\") {\n return `${prefix}: ${raw.slice(0, 40)}`;\n }\n\n return `${prefix}: ${String(raw)}`;\n}\n","import { Context, Data, Effect } from \"effect\";\nimport type { AuthSession, EpochSeconds, JwtToken } from \"@capxul/types\";\n\n/**\n * AuthCachePort (TA4) — replaces `SessionStoragePort` in the rebuild slice's\n * consumer-facing wiring. Stores the user-snapshot Session AND the cached\n * Convex JWT (W7 bridge endpoint). The two slots are independent so a session\n * refresh doesn't invalidate the JWT and vice versa.\n *\n * Three adapters (TA7):\n * - `BrowserAuthCacheAdapter` — backed by `localStorage`\n * - `FileSystemAuthCacheAdapter` — mode-0600 JSON file in `~/.config/capxul/`\n * - `InMemoryAuthCacheAdapter` — for tests\n *\n * `SessionStoragePort` was retired by the Stage 4 rebuild; session and JWT\n * persistence now share this cache boundary.\n */\nexport interface AuthCachePort {\n readonly getSession: Effect.Effect<AuthSession | null, AuthCacheError>;\n readonly setSession: (session: AuthSession) => Effect.Effect<void, AuthCacheError>;\n readonly clearSession: Effect.Effect<void, AuthCacheError>;\n\n /**\n * JWT cache for the `/api/auth/convex/token` bridge endpoint (W7).\n * Stored separately from the session so a session refresh doesn't\n * invalidate cached JWT.\n */\n readonly getJwt: Effect.Effect<CachedJwt | null, AuthCacheError>;\n readonly setJwt: (jwt: CachedJwt) => Effect.Effect<void, AuthCacheError>;\n readonly clearJwt: Effect.Effect<void, AuthCacheError>;\n}\n\n/**\n * Cached Convex JWT shape (TA4). `expEpochSeconds` is decoded from the JWT's\n * `exp` claim at fetch time so the `tokenProvider` cache eviction logic can\n * proactively refresh at `exp - 30s` per TA3.\n */\nexport interface CachedJwt {\n readonly token: JwtToken;\n readonly expEpochSeconds: EpochSeconds;\n}\n\nexport class AuthCacheError extends Data.TaggedError(\"AuthCacheError\")<{\n readonly operation: string;\n readonly cause: unknown;\n}> {}\n\nexport class AuthCachePortTag extends Context.Service<AuthCachePortTag, AuthCachePort>()(\n \"@capxul/sdk/ports/AuthCachePort\",\n) {}\n","import {\n toAuthUserId,\n toEmail,\n toEpochMs,\n toEpochSeconds,\n toJwtToken,\n toSessionToken,\n type AuthSession,\n} from \"@capxul/types\";\n\nimport type { CachedJwt } from \"../../ports/auth-cache\";\n\nexport function parseAuthSession(raw: unknown): AuthSession | null {\n if (typeof raw !== \"object\" || raw === null) return null;\n const candidate = raw as {\n readonly authUserId?: unknown;\n readonly email?: unknown;\n readonly token?: unknown;\n readonly expiresAt?: unknown;\n };\n\n try {\n return {\n authUserId: toAuthUserId(candidate.authUserId),\n email: toEmail(candidate.email),\n token: toSessionToken(candidate.token),\n expiresAt: toEpochMs(candidate.expiresAt),\n };\n } catch {\n return null;\n }\n}\n\nexport function parseCachedJwt(raw: unknown): CachedJwt | null {\n if (typeof raw !== \"object\" || raw === null) return null;\n const candidate = raw as {\n readonly token?: unknown;\n readonly expEpochSeconds?: unknown;\n };\n\n try {\n return {\n token: toJwtToken(candidate.token),\n expEpochSeconds: toEpochSeconds(candidate.expEpochSeconds),\n };\n } catch {\n return null;\n }\n}\n","import { Effect, Layer } from \"effect\";\nimport type { AuthSession } from \"@capxul/types\";\n\nimport {\n AuthCacheError,\n AuthCachePortTag,\n type AuthCachePort,\n type CachedJwt,\n} from \"../../ports/auth-cache\";\nimport { parseAuthSession, parseCachedJwt } from \"./serialization\";\n\nexport interface BrowserStorageShape {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n}\n\nconst SESSION_KEY = \"capxul.session\";\nconst JWT_KEY = \"capxul.jwt\";\n\nexport class BrowserAuthCacheAdapter implements AuthCachePort {\n private readonly storage: BrowserStorageShape;\n\n constructor(storage: BrowserStorageShape) {\n this.storage = storage;\n }\n\n readonly getSession = authCacheTry(\"getSession\", () => {\n const raw = this.storage.getItem(SESSION_KEY);\n if (raw === null) return null;\n try {\n return parseAuthSession(JSON.parse(raw));\n } catch {\n return null;\n }\n });\n\n readonly setSession = (session: AuthSession) =>\n authCacheTry(\"setSession\", () => {\n this.storage.setItem(SESSION_KEY, JSON.stringify(session));\n });\n\n readonly clearSession = authCacheTry(\"clearSession\", () => {\n this.storage.removeItem(SESSION_KEY);\n });\n\n readonly getJwt = authCacheTry(\"getJwt\", () => {\n const raw = this.storage.getItem(JWT_KEY);\n if (raw === null) return null;\n try {\n return parseCachedJwt(JSON.parse(raw));\n } catch {\n return null;\n }\n });\n\n readonly setJwt = (jwt: CachedJwt) =>\n authCacheTry(\"setJwt\", () => {\n this.storage.setItem(JWT_KEY, JSON.stringify(jwt));\n });\n\n readonly clearJwt = authCacheTry(\"clearJwt\", () => {\n this.storage.removeItem(JWT_KEY);\n });\n}\n\nexport function BrowserAuthCacheLayer(input: {\n readonly storage: BrowserStorageShape;\n}): Layer.Layer<AuthCachePortTag, AuthCacheError> {\n return Layer.effect(\n AuthCachePortTag,\n Effect.sync(() => new BrowserAuthCacheAdapter(input.storage)).pipe(\n Effect.mapError((cause) => toAuthCacheError(\"initialize\", cause)),\n ),\n );\n}\n\nfunction toAuthCacheError(operation: string, cause: unknown): AuthCacheError {\n return new AuthCacheError({ operation, cause });\n}\n\nfunction authCacheTry<T>(operation: string, run: () => T): Effect.Effect<T, AuthCacheError> {\n return Effect.try({\n try: run,\n catch: (cause) => toAuthCacheError(operation, cause),\n });\n}\n","import { Effect, Layer } from \"effect\";\nimport type { AuthSession } from \"@capxul/types\";\n\nimport {\n AuthCacheError,\n AuthCachePortTag,\n type AuthCachePort,\n type CachedJwt,\n} from \"../../ports/auth-cache\";\n\nexport class InMemoryAuthCacheAdapter implements AuthCachePort {\n private session: AuthSession | null = null;\n private jwt: CachedJwt | null = null;\n\n readonly getSession = Effect.sync(() => this.session);\n\n readonly setSession = (session: AuthSession) =>\n Effect.sync(() => {\n this.session = session;\n });\n\n readonly clearSession = Effect.sync(() => {\n this.session = null;\n });\n\n readonly getJwt = Effect.sync(() => this.jwt);\n\n readonly setJwt = (jwt: CachedJwt) =>\n Effect.sync(() => {\n this.jwt = jwt;\n });\n\n readonly clearJwt = Effect.sync(() => {\n this.jwt = null;\n });\n}\n\nexport const InMemoryAuthCacheLayer = Layer.effect(\n AuthCachePortTag,\n Effect.sync(() => new InMemoryAuthCacheAdapter()).pipe(\n Effect.mapError((cause) => new AuthCacheError({ operation: \"initialize\", cause })),\n ),\n);\n"],"mappings":";;AAKA,MAAa,qBAAqB;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;AAYA,MAAa,8BAA4D,IAAI,IAAI;CAC/E;CACA;CAKA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AA4DD,IAAa,cAAb,cAAiC,MAAM;CACrC;CACA;CACA;CACA;CAEA,YAAY,MAAuB,SAAiB,UAA8B,CAAC,GAAG;EACpF,MAAM,SAAS,WAAW,UAAU,EAAE,OAAO,QAAQ,MAAM,IAAI,KAAA,CAAS;EACxE,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,IAAI,QAAQ,YAAY,KAAA,GACtB,KAAK,UAAU,QAAQ;EAEzB,IAAI,QAAQ,kBAAkB,KAAA,GAC5B,KAAK,gBAAgB,QAAQ;EAE/B,IAAI,QAAQ,UAAU,KAAA,GACpB,KAAK,QAAQ,QAAQ;CAEzB;AACF;AAEA,SAAgB,cAAc,OAAsC;CAClE,OAAO,iBAAiB;AAC1B;AAYA,SAAgB,uBAAuB,YAAgD;CACrF,OAAO,IAAI,YACT,WAAW,MACX,WAAW,SACX,oBAAoB;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