@lightconexyz/lightcone-sdk 0.8.4-rc.55 → 0.8.4-rc.57
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 +20 -2
- package/dist/auth/client.d.ts +6 -1
- package/dist/auth/client.d.ts.map +1 -1
- package/dist/auth/client.js +6 -1
- package/dist/auth/client.js.map +1 -1
- package/dist/client.d.ts +7 -0
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +11 -1
- package/dist/client.js.map +1 -1
- package/dist/http/client.d.ts +16 -1
- package/dist/http/client.d.ts.map +1 -1
- package/dist/http/client.js +42 -6
- package/dist/http/client.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -14,6 +14,7 @@ TypeScript SDK for the Lightcone impact market protocol on Solana.
|
|
|
14
14
|
- [Step 6: Exit a Position](#step-6-exit-a-position)
|
|
15
15
|
- [Step 7: Withdraw](#step-7-withdraw)
|
|
16
16
|
- [Authentication](#authentication)
|
|
17
|
+
- [API Key](#api-key)
|
|
17
18
|
- [Environment Configuration](#environment-configuration)
|
|
18
19
|
- [Examples](#examples)
|
|
19
20
|
- [Error Handling](#error-handling)
|
|
@@ -469,9 +470,11 @@ const withdrawIx = client.positions().withdraw()
|
|
|
469
470
|
|
|
470
471
|
## Authentication
|
|
471
472
|
|
|
472
|
-
|
|
473
|
+
Native clients running in Node follow the [native client recovery guide](../docs/auth-session-recovery.md) for session teardown and WebSocket recovery. It explains per-token logout, incomplete teardown, anonymous public continuity, and finite reconnect budgets. Browser clients use Privy authentication.
|
|
473
474
|
|
|
474
|
-
|
|
475
|
+
Authentication is required for user-specific endpoints. Native clients using Lightcone sessions fetch `/api/auth/nonce`. Sign the exact message `Sign in to Lightcone\nNonce: {nonce}` with ED25519. Use `auth.signLoginMessage` to construct this challenge, then exchange the signed message for a session. Do not sign a timestamp or the nonce alone.
|
|
476
|
+
|
|
477
|
+
Authenticate before connecting a private WebSocket. Native clients running in Node send the Lightcone session cookie during the upgrade. Browser clients supply their Privy cookie automatically. Private user subscriptions require `wallet_address`. Derive the Trading Wallet with `tradingWallet(session.user, session.auth_method)`. Refer to the [authenticated streaming example](examples/ws_user_and_market.ts).
|
|
475
478
|
|
|
476
479
|
Privy hosts can also authenticate with passwordless Email, Google, X, or Wallet. After every interactive success, call `client.auth().registerPrivy({ attempted_identity })`. The backend validates the exact selector against Privy's verified methods, creates or synchronizes the Account, and changes the Primary Login Identity only for a new Account. `session.user.identity` is that stable primary; `session.user.linked_identities` contains every connected method with primary first.
|
|
477
480
|
|
|
@@ -517,6 +520,21 @@ const positions = await client
|
|
|
517
520
|
|
|
518
521
|
In browsers, use the ordinary methods. The browser supplies the cookie through `credentials: "include"`.
|
|
519
522
|
|
|
523
|
+
## API Key
|
|
524
|
+
|
|
525
|
+
Configure an API key for native or server-side submit, cancel, and cancel-all requests. Public reads and authentication need no API key. The key identifies an API Consumer; user authentication, wallet ownership, and signed-order validation still apply.
|
|
526
|
+
|
|
527
|
+
```ts
|
|
528
|
+
const client = LightconeClient.builder()
|
|
529
|
+
.env(LightconeEnv.Staging)
|
|
530
|
+
.apiKey(process.env.LIGHTCONE_API_KEY!)
|
|
531
|
+
.build();
|
|
532
|
+
```
|
|
533
|
+
|
|
534
|
+
The SDK attaches `x-lightcone-api-key` only to POST `/api/orders/submit`, `/api/orders/cancel`, and `/api/orders/cancel-all` on the configured API origin. It never forwards the key to another origin or logs it. HTTPS is required except for loopback development. Keep keys out of source control and browsers. Browser builds reject API-key configuration; web users trade with their existing Privy session.
|
|
535
|
+
|
|
536
|
+
Cloudflare limits these trading attempts by public source IP, not by API key: direct API callers share 500 attempts per 10-second window per IP. A 429 response does not revoke credentials. Public reads and WebSocket messages are outside this trading limit. Revocation reaches all backend process caches within 24 hours; new keys work immediately through a database lookup on cache miss.
|
|
537
|
+
|
|
520
538
|
## Environment Configuration
|
|
521
539
|
|
|
522
540
|
The SDK defaults to the **production** environment. Use `LightconeEnv` to target a different deployment:
|
package/dist/auth/client.d.ts
CHANGED
|
@@ -30,11 +30,16 @@ export declare class Auth {
|
|
|
30
30
|
/**
|
|
31
31
|
* Logout — clears the server-side cookie, internal token, and credentials.
|
|
32
32
|
*
|
|
33
|
+
* Server revocation targets native clients' `lightcone-token` credentials.
|
|
34
|
+
* Browser clients must end their Privy session through the Privy SDK.
|
|
35
|
+
*
|
|
33
36
|
* Local state is cleared even when the server call fails — the caller asked
|
|
34
37
|
* to be signed out locally regardless — but the failure is then rethrown:
|
|
35
38
|
* callers gating security decisions on teardown (e.g. whether an app may
|
|
36
39
|
* restart an authenticated transport) must be able to see that the
|
|
37
|
-
*
|
|
40
|
+
* revocation may be unconfirmed, or a revoked token may still await remote
|
|
41
|
+
* WebSocket teardown. Refer to the authentication guide in README.
|
|
42
|
+
* A 401 counts as success: it means
|
|
38
43
|
* "already logged out".
|
|
39
44
|
*/
|
|
40
45
|
logout(): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/auth/client.ts"],"names":[],"mappings":"AACA,OAAO,EAAe,KAAK,aAAa,EAAE,MAAM,SAAS,CAAC;AAG1D,OAAO,KAAK,EACV,eAAe,EAIf,kBAAkB,EAClB,oBAAoB,EACpB,eAAe,EAChB,MAAM,SAAS,CAAC;AAEjB,qEAAqE;AACrE,MAAM,MAAM,qBAAqB,GAC7B;IACE,IAAI,EAAE,mCAAmC,CAAC;IAC1C,cAAc,CAAC,EAAE,kBAAkB,CAAC;CACrC,GACD;IAAE,IAAI,EAAE,uCAAuC,CAAA;CAAE,GACjD;IACE,IAAI,EAAE,iCAAiC,CAAC;IACxC,cAAc,CAAC,EAAE,kBAAkB,CAAC;CACrC,CAAC;AAEN,uEAAuE;AACvE,wBAAgB,6BAA6B,CAC3C,KAAK,EAAE,OAAO,GACb,qBAAqB,GAAG,SAAS,CAoBnC;AAED,UAAU,SAAS;IACjB,cAAc,IAAI,eAAe,GAAG,SAAS,CAA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AI,CAAC;IAC/D,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CAC9B;AAED,UAAU,aAAa;IACrB,IAAI,EAAE,aAAa,CAAC;IACpB,SAAS,EAAE,SAAS,CAAC;CACtB;AAED,qBAAa,IAAI;IACH,OAAO,CAAC,QAAQ,CAAC,MAAM;gBAAN,MAAM,EAAE,aAAa;IAE5C,QAAQ,IAAI,OAAO,CAAC,MAAM,CAAC;IAS3B,gBAAgB,CACpB,OAAO,EAAE,MAAM,EACf,aAAa,EAAE,MAAM,EACrB,WAAW,EAAE,UAAU,EACvB,iBAAiB,CAAC,EAAE,OAAO,GAC1B,OAAO,CAAC,eAAe,CAAC;IAwBrB,YAAY,IAAI,OAAO,CAAC,eAAe,CAAC;IAoB9C;;;;;;;;;;;;;;OAcG;IACG,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC;IAyBvB,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC;IASlC,+EAA+E;IACzE,aAAa,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,eAAe,CAAC;IAe5E,0EAA0E;IACpE,2BAA2B,CAC/B,qBAAqB,EAAE,MAAM,GAC5B,OAAO,CAAC,MAAM,CAAC;IAuBlB,WAAW,IAAI,MAAM;IAIrB,WAAW,IAAI,eAAe,GAAG,SAAS;IAI1C,eAAe,IAAI,OAAO;CAO3B"}
|
package/dist/auth/client.js
CHANGED
|
@@ -72,11 +72,16 @@ class Auth {
|
|
|
72
72
|
/**
|
|
73
73
|
* Logout — clears the server-side cookie, internal token, and credentials.
|
|
74
74
|
*
|
|
75
|
+
* Server revocation targets native clients' `lightcone-token` credentials.
|
|
76
|
+
* Browser clients must end their Privy session through the Privy SDK.
|
|
77
|
+
*
|
|
75
78
|
* Local state is cleared even when the server call fails — the caller asked
|
|
76
79
|
* to be signed out locally regardless — but the failure is then rethrown:
|
|
77
80
|
* callers gating security decisions on teardown (e.g. whether an app may
|
|
78
81
|
* restart an authenticated transport) must be able to see that the
|
|
79
|
-
*
|
|
82
|
+
* revocation may be unconfirmed, or a revoked token may still await remote
|
|
83
|
+
* WebSocket teardown. Refer to the authentication guide in README.
|
|
84
|
+
* A 401 counts as success: it means
|
|
80
85
|
* "already logged out".
|
|
81
86
|
*/
|
|
82
87
|
async logout() {
|
package/dist/auth/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/auth/client.ts"],"names":[],"mappings":";;;AA2BA,sEAsBC;AAjDD,oCAAoD;AACpD,kCAA0D;AAC1D,sCAAwC;AACxC,mCAAwC;AAuBxC,uEAAuE;AACvE,SAAgB,6BAA6B,CAC3C,KAAc;IAEd,IAAI,CAAC,CAAC,KAAK,YAAY,gBAAQ,CAAC,IAAI,KAAK,CAAC,OAAO,KAAK,aAAa;QACjE,OAAO,SAAS,CAAC;IACnB,MAAM,OAAO,GAAG,KAAK,CAAC,kBAAkB,CAAC;IACzC,QAAQ,OAAO,EAAE,SAAS,EAAE,CAAC;QAC3B,KAAK,mCAAmC;YACtC,OAAO;gBACL,IAAI,EAAE,OAAO,CAAC,SAAS;gBACvB,cAAc,EAAE,OAAO,CAAC,cAAc;aACvC,CAAC;QACJ,KAAK,uCAAuC;YAC1C,OAAO,EAAE,IAAI,EAAE,OAAO,CAAC,SAAS,EAAE,CAAC;QACrC,KAAK,iCAAiC;YACpC,OAAO;gBACL,IAAI,EAAE,OAAO,CAAC,SAAS;gBACvB,cAAc,EAAE,OAAO,CAAC,cAAc;aACvC,CAAC;QACJ;YACE,OAAO,SAAS,CAAC;IACrB,CAAC;AACH,CAAC;AAaD,MAAa,IAAI;IACc;IAA7B,YAA6B,MAAqB;QAArB,WAAM,GAAN,MAAM,CAAe;IAAG,CAAC;IAEtD,KAAK,CAAC,QAAQ;QACZ,MAAM,GAAG,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,iBAAiB,CAAC;QAC3D,MAAM,QAAQ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AAC,SAAiB;IACpC,IAAI,SAAS,GAAG,iBAAiB,EAAE,CAAC;QAClC,OAAO,IAAI,IAAI,CAAC,SAAS,CAAC,CAAC;IAC7B,CAAC;IACD,OAAO,IAAI,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC;AACpC,CAAC","sourcesContent":["import { SdkError, isUnauthorized } from \"../error\";\nimport { RetryPolicy, type LightconeHttp } from \"../http\";\nimport { asPubkeyStr } from \"../shared\";\nimport { tradingWallet } from \"./index\";\nimport type {\n AuthCredentials,\n LoginRequest,\n MaxSlippagePreferenceBody,\n NonceResponse,\n LinkedIdentityType,\n RegisterPrivyRequest,\n SessionResponse,\n} from \"./index\";\n\n/** Bounded ownership conflicts safe for client recovery guidance. */\nexport type RegisterPrivyConflict =\n | {\n code: \"IDENTITY_OWNED_BY_ANOTHER_ACCOUNT\";\n existingMethod?: LinkedIdentityType;\n }\n | { code: \"IDENTITIES_OWNED_BY_MULTIPLE_ACCOUNTS\" }\n | {\n code: \"WALLET_OWNED_BY_ANOTHER_ACCOUNT\";\n existingMethod?: LinkedIdentityType;\n };\n\n/** Classify only stable register-or-sync ownership rejection codes. */\nexport function classifyRegisterPrivyConflict(\n error: unknown,\n): RegisterPrivyConflict | undefined {\n if (!(error instanceof SdkError) || error.variant !== \"ApiRejected\")\n return undefined;\n const details = error.apiRejectedDetails;\n switch (details?.errorCode) {\n case \"IDENTITY_OWNED_BY_ANOTHER_ACCOUNT\":\n return {\n code: details.errorCode,\n existingMethod: details.existingMethod,\n };\n case \"IDENTITIES_OWNED_BY_MULTIPLE_ACCOUNTS\":\n return { code: details.errorCode };\n case \"WALLET_OWNED_BY_ANOTHER_ACCOUNT\":\n return {\n code: details.errorCode,\n existingMethod: details.existingMethod,\n };\n default:\n return undefined;\n }\n}\n\ninterface AuthState {\n getCredentials(): AuthCredentials | undefined;\n setCredentials(credentials: AuthCredentials | undefined): void;\n clearCaches(): Promise<void>;\n}\n\ninterface ClientContext {\n http: LightconeHttp;\n authState: AuthState;\n}\n\nexport class Auth {\n constructor(private readonly client: ClientContext) {}\n\n async getNonce(): Promise<string> {\n const url = `${this.client.http.baseUrl()}/api/auth/nonce`;\n const response = await this.client.http.get<NonceResponse>(\n url,\n RetryPolicy.None,\n );\n return response.nonce;\n }\n\n async loginWithMessage(\n message: string,\n signatureBs58: string,\n pubkeyBytes: Uint8Array,\n useEmbeddedWallet?: boolean,\n ): Promise<SessionResponse> {\n const url = `${this.client.http.baseUrl()}/api/auth/login_or_register_with_message`;\n const body: LoginRequest = {\n message,\n signature_bs58: signatureBs58,\n pubkey_bytes: Array.from(pubkeyBytes),\n use_embedded_wallet: useEmbeddedWallet,\n };\n\n // Credential-management endpoint: opts out of the transport's 401\n // restore-and-replay. The backend consumes the login nonce before\n // verifying the signature, so a replayed login deterministically fails —\n // and restoring credentials in order to log in is circular.\n const session = await this.client.http.postWithoutCredentialRestore<\n SessionResponse,\n LoginRequest\n >(url, body, RetryPolicy.None);\n normalizeSessionUser(session);\n\n this.client.authState.setCredentials(credentialsFromSession(session));\n\n return session;\n }\n\n async checkSession(): Promise<SessionResponse> {\n const url = `${this.client.http.baseUrl()}/api/auth/me`;\n\n let session: SessionResponse;\n try {\n session = await this.client.http.get<SessionResponse>(\n url,\n RetryPolicy.Idempotent,\n );\n normalizeSessionUser(session);\n } catch (error) {\n this.client.authState.setCredentials(undefined);\n throw SdkError.from(error);\n }\n\n this.client.authState.setCredentials(credentialsFromSession(session));\n\n return session;\n }\n\n /**\n * Logout — clears the server-side cookie, internal token, and credentials.\n *\n * Local state is cleared even when the server call fails — the caller asked\n * to be signed out locally regardless — but the failure is then rethrown:\n * callers gating security decisions on teardown (e.g. whether an app may\n * restart an authenticated transport) must be able to see that the\n * server-side cookie may still be valid. A 401 counts as success: it means\n * \"already logged out\".\n */\n async logout(): Promise<void> {\n const url = `${this.client.http.baseUrl()}/api/auth/logout`;\n let logoutError: unknown = null;\n try {\n // Credential-management endpoint: opts out of the transport's 401\n // restore-and-replay — a 401 here means \"already logged out\".\n await this.client.http.postWithoutCredentialRestore<\n { success: boolean },\n Record<string, never>\n >(url, {}, RetryPolicy.None);\n } catch (error) {\n if (!isUnauthorized(error)) {\n logoutError = error;\n }\n }\n\n await this.client.http.clearAuthToken();\n this.client.authState.setCredentials(undefined);\n await this.client.authState.clearCaches();\n\n if (logoutError !== null) {\n throw logoutError;\n }\n }\n\n async disconnectX(): Promise<void> {\n const url = `${this.client.http.baseUrl()}/api/auth/disconnect_x`;\n await this.client.http.post<{ success: boolean }, Record<string, never>>(\n url,\n {},\n RetryPolicy.None,\n );\n }\n\n /** Create or synchronize a Privy Account and install the resulting session. */\n async registerPrivy(request: RegisterPrivyRequest): Promise<SessionResponse> {\n const url = `${this.client.http.baseUrl()}/api/auth/register-privy`;\n const session = await this.client.http.post<\n SessionResponse,\n RegisterPrivyRequest\n >(\n url,\n request,\n RetryPolicy.Idempotent,\n );\n normalizeSessionUser(session);\n this.client.authState.setCredentials(credentialsFromSession(session));\n return session;\n }\n\n /** Persist an account-wide max-slippage preference strictly below 10%. */\n async updateMaxSlippagePreference(\n maxSlippagePreference: string,\n ): Promise<string> {\n const url = `${this.client.http.baseUrl()}/api/auth/max_slippage_preference`;\n const response = await this.client.http.post<\n MaxSlippagePreferenceBody,\n MaxSlippagePreferenceBody\n >(\n url,\n { max_slippage_preference: maxSlippagePreference },\n RetryPolicy.Idempotent,\n );\n const preference = decodeMaxSlippagePreference(\n response,\n false,\n \"update response\",\n );\n if (preference === null) {\n throw SdkError.serde(\n \"Max-slippage update response must contain a decimal string\",\n );\n }\n return preference;\n }\n\n connectXUrl(): string {\n return `${this.client.http.baseUrl()}/api/auth/oauth/link/x`;\n }\n\n credentials(): AuthCredentials | undefined {\n return this.client.authState.getCredentials();\n }\n\n isAuthenticated(): boolean {\n const credentials = this.credentials();\n if (!credentials) {\n return false;\n }\n return Date.now() < credentials.expires_at.getTime();\n }\n}\n\n/**\n * Enforces the session user's nullable-field contracts after every\n * session-returning call. Login, session restoration, and Privy registration\n * share it so that no entry point skips a field.\n */\nfunction normalizeSessionUser(session: SessionResponse): void {\n normalizeSessionMaxSlippagePreference(session);\n session.user.telegram_invite_url = decodeTelegramInviteUrl(session.user);\n}\n\n/**\n * Decodes the session user's Telegram invite URL. A missing key (older backend)\n * and an explicit null (Account without an invite) both mean no invite. Any\n * other non-string value is a contract violation. Error text never includes the\n * value, because the URL is a secret of the Account.\n */\nfunction decodeTelegramInviteUrl(user: unknown): string | null {\n if (typeof user !== \"object\" || user === null) {\n throw SdkError.serde(\"Session user is malformed\");\n }\n // An own-property read keeps an inherited value from counting as an invite.\n if (!Object.prototype.hasOwnProperty.call(user, \"telegram_invite_url\")) {\n return null;\n }\n const inviteUrl = (user as Record<string, unknown>).telegram_invite_url;\n if (inviteUrl === undefined || inviteUrl === null) {\n return null;\n }\n if (typeof inviteUrl === \"string\") {\n return inviteUrl;\n }\n throw SdkError.serde(\n \"Session user telegram_invite_url must contain a string or null\",\n );\n}\n\nfunction normalizeSessionMaxSlippagePreference(session: SessionResponse): void {\n const preference = decodeMaxSlippagePreference(\n session?.user,\n true,\n \"session user\",\n true,\n );\n session.user.max_slippage_preference = preference;\n}\n\n/** Enforces the exact nullable/string JSON contract erased by TypeScript types. */\nfunction decodeMaxSlippagePreference(\n payload: unknown,\n allowNull: boolean,\n context: string,\n allowMissing = false,\n): string | null {\n if (typeof payload !== \"object\" || payload === null) {\n throw SdkError.serde(`Max-slippage ${context} is malformed`);\n }\n if (\n !Object.prototype.hasOwnProperty.call(payload, \"max_slippage_preference\")\n ) {\n if (allowMissing) {\n return null;\n }\n throw SdkError.serde(\n `Max-slippage ${context} is missing max_slippage_preference`,\n );\n }\n\n const preference = (payload as Record<string, unknown>)\n .max_slippage_preference;\n if (typeof preference === \"string\") {\n return preference;\n }\n if (allowNull && preference === null) {\n return null;\n }\n throw SdkError.serde(\n `Max-slippage ${context} must contain ${allowNull ? \"a string or null\" : \"a string\"}`,\n );\n}\n\n/**\n * Derive session credentials from the envelope. The trading wallet comes from\n * the identity + auth method.\n */\nfunction credentialsFromSession(session: SessionResponse): AuthCredentials {\n return {\n user_id: session.user.user_id,\n wallet_address: asPubkeyStr(\n tradingWallet(session.user, session.auth_method),\n ),\n expires_at: parseExpiry(session.expires_at),\n };\n}\n\nfunction parseExpiry(timestamp: number): Date {\n if (timestamp > 1_000_000_000_000) {\n return new Date(timestamp);\n }\n return new Date(timestamp * 1000);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/auth/client.ts"],"names":[],"mappings":";;;AA2BA,sEAsBC;AAjDD,oCAAoD;AACpD,kCAA0D;AAC1D,sCAAwC;AACxC,mCAAwC;AAuBxC,uEAAuE;AACvE,SAAgB,6BAA6B,CAC3C,KAAc;IAEd,IAAI,CAAC,CAAC,KAAK,YAAY,gBAAQ,CAAC,IAAI,KAAK,CAAC,OAAO,KAAK,aAAa;QACjE,OAAO,SAAS,CAAC;IACnB,MAAM,OAAO,GAAG,KAAK,CAAC,kBAAkB,CAAC;IACzC,QAAQ,OAAO,EAAE,SAAS,EAAE,CAAC;QAC3B,KAAK,mCAAmC;YACtC,OAAO;gBACL,IAAI,EAAE,OAAO,CAAC,SAAS;gBACvB,cAAc,EAAE,OAAO,CAAC,cAAc;aACvC,CAAC;QACJ,KAAK,uCAAuC;YAC1C,OAAO,EAAE,IAAI,EAAE,OAAO,CAAC,SAAS,EAAE,CAAC;QACrC,KAAK,iCAAiC;YACpC,OAAO;gBACL,IAAI,EAAE,OAAO,CAAC,SAAS;gBACvB,cAAc,EAAE,OAAO,CAAC,cAAc;aACvC,CAAC;QACJ;YACE,OAAO,SAAS,CAAC;IACrB,CAAC;AACH,CAAC;AAaD,MAAa,IAAI;IACc;IAA7B,YAA6B,MAAqB;QAArB,WAAM,GAAN,MAAM,CAAe;IAAG,CAAC;IAEtD,KAAK,CAAC,QAAQ;QACZ,MAAM,GAAG,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,CAA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UAAU,CAAC;KAC5C,CAAC;AACJ,CAAC;AAED,SAAS,WAAW,CAAC,SAAiB;IACpC,IAAI,SAAS,GAAG,iBAAiB,EAAE,CAAC;QAClC,OAAO,IAAI,IAAI,CAAC,SAAS,CAAC,CAAC;IAC7B,CAAC;IACD,OAAO,IAAI,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC;AACpC,CAAC","sourcesContent":["import { SdkError, isUnauthorized } from \"../error\";\nimport { RetryPolicy, type LightconeHttp } from \"../http\";\nimport { asPubkeyStr } from \"../shared\";\nimport { tradingWallet } from \"./index\";\nimport type {\n AuthCredentials,\n LoginRequest,\n MaxSlippagePreferenceBody,\n NonceResponse,\n LinkedIdentityType,\n RegisterPrivyRequest,\n SessionResponse,\n} from \"./index\";\n\n/** Bounded ownership conflicts safe for client recovery guidance. */\nexport type RegisterPrivyConflict =\n | {\n code: \"IDENTITY_OWNED_BY_ANOTHER_ACCOUNT\";\n existingMethod?: LinkedIdentityType;\n }\n | { code: \"IDENTITIES_OWNED_BY_MULTIPLE_ACCOUNTS\" }\n | {\n code: \"WALLET_OWNED_BY_ANOTHER_ACCOUNT\";\n existingMethod?: LinkedIdentityType;\n };\n\n/** Classify only stable register-or-sync ownership rejection codes. */\nexport function classifyRegisterPrivyConflict(\n error: unknown,\n): RegisterPrivyConflict | undefined {\n if (!(error instanceof SdkError) || error.variant !== \"ApiRejected\")\n return undefined;\n const details = error.apiRejectedDetails;\n switch (details?.errorCode) {\n case \"IDENTITY_OWNED_BY_ANOTHER_ACCOUNT\":\n return {\n code: details.errorCode,\n existingMethod: details.existingMethod,\n };\n case \"IDENTITIES_OWNED_BY_MULTIPLE_ACCOUNTS\":\n return { code: details.errorCode };\n case \"WALLET_OWNED_BY_ANOTHER_ACCOUNT\":\n return {\n code: details.errorCode,\n existingMethod: details.existingMethod,\n };\n default:\n return undefined;\n }\n}\n\ninterface AuthState {\n getCredentials(): AuthCredentials | undefined;\n setCredentials(credentials: AuthCredentials | undefined): void;\n clearCaches(): Promise<void>;\n}\n\ninterface ClientContext {\n http: LightconeHttp;\n authState: AuthState;\n}\n\nexport class Auth {\n constructor(private readonly client: ClientContext) {}\n\n async getNonce(): Promise<string> {\n const url = `${this.client.http.baseUrl()}/api/auth/nonce`;\n const response = await this.client.http.get<NonceResponse>(\n url,\n RetryPolicy.None,\n );\n return response.nonce;\n }\n\n async loginWithMessage(\n message: string,\n signatureBs58: string,\n pubkeyBytes: Uint8Array,\n useEmbeddedWallet?: boolean,\n ): Promise<SessionResponse> {\n const url = `${this.client.http.baseUrl()}/api/auth/login_or_register_with_message`;\n const body: LoginRequest = {\n message,\n signature_bs58: signatureBs58,\n pubkey_bytes: Array.from(pubkeyBytes),\n use_embedded_wallet: useEmbeddedWallet,\n };\n\n // Credential-management endpoint: opts out of the transport's 401\n // restore-and-replay. The backend consumes the login nonce before\n // verifying the signature, so a replayed login deterministically fails —\n // and restoring credentials in order to log in is circular.\n const session = await this.client.http.postWithoutCredentialRestore<\n SessionResponse,\n LoginRequest\n >(url, body, RetryPolicy.None);\n normalizeSessionUser(session);\n\n this.client.authState.setCredentials(credentialsFromSession(session));\n\n return session;\n }\n\n async checkSession(): Promise<SessionResponse> {\n const url = `${this.client.http.baseUrl()}/api/auth/me`;\n\n let session: SessionResponse;\n try {\n session = await this.client.http.get<SessionResponse>(\n url,\n RetryPolicy.Idempotent,\n );\n normalizeSessionUser(session);\n } catch (error) {\n this.client.authState.setCredentials(undefined);\n throw SdkError.from(error);\n }\n\n this.client.authState.setCredentials(credentialsFromSession(session));\n\n return session;\n }\n\n /**\n * Logout — clears the server-side cookie, internal token, and credentials.\n *\n * Server revocation targets native clients' `lightcone-token` credentials.\n * Browser clients must end their Privy session through the Privy SDK.\n *\n * Local state is cleared even when the server call fails — the caller asked\n * to be signed out locally regardless — but the failure is then rethrown:\n * callers gating security decisions on teardown (e.g. whether an app may\n * restart an authenticated transport) must be able to see that the\n * revocation may be unconfirmed, or a revoked token may still await remote\n * WebSocket teardown. Refer to the authentication guide in README.\n * A 401 counts as success: it means\n * \"already logged out\".\n */\n async logout(): Promise<void> {\n const url = `${this.client.http.baseUrl()}/api/auth/logout`;\n let logoutError: unknown = null;\n try {\n // Credential-management endpoint: opts out of the transport's 401\n // restore-and-replay — a 401 here means \"already logged out\".\n await this.client.http.postWithoutCredentialRestore<\n { success: boolean },\n Record<string, never>\n >(url, {}, RetryPolicy.None);\n } catch (error) {\n if (!isUnauthorized(error)) {\n logoutError = error;\n }\n }\n\n await this.client.http.clearAuthToken();\n this.client.authState.setCredentials(undefined);\n await this.client.authState.clearCaches();\n\n if (logoutError !== null) {\n throw logoutError;\n }\n }\n\n async disconnectX(): Promise<void> {\n const url = `${this.client.http.baseUrl()}/api/auth/disconnect_x`;\n await this.client.http.post<{ success: boolean }, Record<string, never>>(\n url,\n {},\n RetryPolicy.None,\n );\n }\n\n /** Create or synchronize a Privy Account and install the resulting session. */\n async registerPrivy(request: RegisterPrivyRequest): Promise<SessionResponse> {\n const url = `${this.client.http.baseUrl()}/api/auth/register-privy`;\n const session = await this.client.http.post<\n SessionResponse,\n RegisterPrivyRequest\n >(\n url,\n request,\n RetryPolicy.Idempotent,\n );\n normalizeSessionUser(session);\n this.client.authState.setCredentials(credentialsFromSession(session));\n return session;\n }\n\n /** Persist an account-wide max-slippage preference strictly below 10%. */\n async updateMaxSlippagePreference(\n maxSlippagePreference: string,\n ): Promise<string> {\n const url = `${this.client.http.baseUrl()}/api/auth/max_slippage_preference`;\n const response = await this.client.http.post<\n MaxSlippagePreferenceBody,\n MaxSlippagePreferenceBody\n >(\n url,\n { max_slippage_preference: maxSlippagePreference },\n RetryPolicy.Idempotent,\n );\n const preference = decodeMaxSlippagePreference(\n response,\n false,\n \"update response\",\n );\n if (preference === null) {\n throw SdkError.serde(\n \"Max-slippage update response must contain a decimal string\",\n );\n }\n return preference;\n }\n\n connectXUrl(): string {\n return `${this.client.http.baseUrl()}/api/auth/oauth/link/x`;\n }\n\n credentials(): AuthCredentials | undefined {\n return this.client.authState.getCredentials();\n }\n\n isAuthenticated(): boolean {\n const credentials = this.credentials();\n if (!credentials) {\n return false;\n }\n return Date.now() < credentials.expires_at.getTime();\n }\n}\n\n/**\n * Enforces the session user's nullable-field contracts after every\n * session-returning call. Login, session restoration, and Privy registration\n * share it so that no entry point skips a field.\n */\nfunction normalizeSessionUser(session: SessionResponse): void {\n normalizeSessionMaxSlippagePreference(session);\n session.user.telegram_invite_url = decodeTelegramInviteUrl(session.user);\n}\n\n/**\n * Decodes the session user's Telegram invite URL. A missing key (older backend)\n * and an explicit null (Account without an invite) both mean no invite. Any\n * other non-string value is a contract violation. Error text never includes the\n * value, because the URL is a secret of the Account.\n */\nfunction decodeTelegramInviteUrl(user: unknown): string | null {\n if (typeof user !== \"object\" || user === null) {\n throw SdkError.serde(\"Session user is malformed\");\n }\n // An own-property read keeps an inherited value from counting as an invite.\n if (!Object.prototype.hasOwnProperty.call(user, \"telegram_invite_url\")) {\n return null;\n }\n const inviteUrl = (user as Record<string, unknown>).telegram_invite_url;\n if (inviteUrl === undefined || inviteUrl === null) {\n return null;\n }\n if (typeof inviteUrl === \"string\") {\n return inviteUrl;\n }\n throw SdkError.serde(\n \"Session user telegram_invite_url must contain a string or null\",\n );\n}\n\nfunction normalizeSessionMaxSlippagePreference(session: SessionResponse): void {\n const preference = decodeMaxSlippagePreference(\n session?.user,\n true,\n \"session user\",\n true,\n );\n session.user.max_slippage_preference = preference;\n}\n\n/** Enforces the exact nullable/string JSON contract erased by TypeScript types. */\nfunction decodeMaxSlippagePreference(\n payload: unknown,\n allowNull: boolean,\n context: string,\n allowMissing = false,\n): string | null {\n if (typeof payload !== \"object\" || payload === null) {\n throw SdkError.serde(`Max-slippage ${context} is malformed`);\n }\n if (\n !Object.prototype.hasOwnProperty.call(payload, \"max_slippage_preference\")\n ) {\n if (allowMissing) {\n return null;\n }\n throw SdkError.serde(\n `Max-slippage ${context} is missing max_slippage_preference`,\n );\n }\n\n const preference = (payload as Record<string, unknown>)\n .max_slippage_preference;\n if (typeof preference === \"string\") {\n return preference;\n }\n if (allowNull && preference === null) {\n return null;\n }\n throw SdkError.serde(\n `Max-slippage ${context} must contain ${allowNull ? \"a string or null\" : \"a string\"}`,\n );\n}\n\n/**\n * Derive session credentials from the envelope. The trading wallet comes from\n * the identity + auth method.\n */\nfunction credentialsFromSession(session: SessionResponse): AuthCredentials {\n return {\n user_id: session.user.user_id,\n wallet_address: asPubkeyStr(\n tradingWallet(session.user, session.auth_method),\n ),\n expires_at: parseExpiry(session.expires_at),\n };\n}\n\nfunction parseExpiry(timestamp: number): Date {\n if (timestamp > 1_000_000_000_000) {\n return new Date(timestamp);\n }\n return new Date(timestamp * 1000);\n}\n"]}
|
package/dist/client.d.ts
CHANGED
|
@@ -172,6 +172,7 @@ export declare class LightconeClientBuilder {
|
|
|
172
172
|
private rpcFetchValue?;
|
|
173
173
|
private primaryRpcUrlValue?;
|
|
174
174
|
private backupRpcUrlValue?;
|
|
175
|
+
private apiKeyValue?;
|
|
175
176
|
/**
|
|
176
177
|
* Set the deployment environment. Configures the API URL, WebSocket URL,
|
|
177
178
|
* RPC URL, and program ID for the given environment.
|
|
@@ -182,6 +183,12 @@ export declare class LightconeClientBuilder {
|
|
|
182
183
|
env(environment: LightconeEnv): LightconeClientBuilder;
|
|
183
184
|
baseUrl(url: string): LightconeClientBuilder;
|
|
184
185
|
withBaseUrl(url: string): LightconeClientBuilder;
|
|
186
|
+
/**
|
|
187
|
+
* Set the API key sent as `x-lightcone-api-key` on submit, cancel, and cancel-all POST requests to
|
|
188
|
+
* the API origin. Keep it server-side: it identifies an API Consumer, never
|
|
189
|
+
* a user, and the SDK never logs it.
|
|
190
|
+
*/
|
|
191
|
+
apiKey(key: string): LightconeClientBuilder;
|
|
185
192
|
wsUrl(url: string): LightconeClientBuilder;
|
|
186
193
|
withWsUrl(url: string): LightconeClientBuilder;
|
|
187
194
|
auth(credentials: AuthCredentials): LightconeClientBuilder;
|
package/dist/client.d.ts.map
CHAN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IAKhD,aAAa,CAAC,MAAM,EAAE,aAAa,GAAG,sBAAsB;IAK5D,YAAY,CAAC,OAAO,EAAE,OAAO,GAAG,sBAAsB;IAKtD,cAAc,CAAC,MAAM,EAAE,cAAc,GAAG,sBAAsB;IAK9D,aAAa,CACX,QAAQ,EAAE,MAAM,EAChB,aAAa,CAAC,EAAE,MAAM,GACrB,sBAAsB;IAKzB,qFAAqF;IACrF,sBAAsB,CAAC,OAAO,EAAE,OAAO,GAAG,sBAAsB;IAKhE,gGAAgG;IAChG,oBAAoB,CAAC,SAAS,EAAE,gBAAgB,GAAG,sBAAsB;IAMzE,qGAAqG;IACrG,QAAQ,CAAC,SAAS,EAAE,OAAO,KAAK,GAAG,sBAAsB;IAKzD,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,sBAAsB;IAK3C,0DAA0D;IAC1D,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,sBAAsB;IAKjD,KAAK,IAAI,eAAe;CA0BzB"}
|
package/dist/client.js
CHANGED
|
@@ -295,6 +295,7 @@ class LightconeClientBuilder {
|
|
|
295
295
|
rpcFetchValue;
|
|
296
296
|
primaryRpcUrlValue = (0, env_1.rpcUrl)(env_1.LightconeEnv.Prod);
|
|
297
297
|
backupRpcUrlValue;
|
|
298
|
+
apiKeyValue;
|
|
298
299
|
/**
|
|
299
300
|
* Set the deployment environment. Configures the API URL, WebSocket URL,
|
|
300
301
|
* RPC URL, and program ID for the given environment.
|
|
@@ -316,6 +317,15 @@ class LightconeClientBuilder {
|
|
|
316
317
|
this.baseUrlValue = url;
|
|
317
318
|
return this;
|
|
318
319
|
}
|
|
320
|
+
/**
|
|
321
|
+
* Set the API key sent as `x-lightcone-api-key` on submit, cancel, and cancel-all POST requests to
|
|
322
|
+
* the API origin. Keep it server-side: it identifies an API Consumer, never
|
|
323
|
+
* a user, and the SDK never logs it.
|
|
324
|
+
*/
|
|
325
|
+
apiKey(key) {
|
|
326
|
+
this.apiKeyValue = key;
|
|
327
|
+
return this;
|
|
328
|
+
}
|
|
319
329
|
wsUrl(url) {
|
|
320
330
|
return this.withWsUrl(url);
|
|
321
331
|
}
|
|
@@ -377,7 +387,7 @@ class LightconeClientBuilder {
|
|
|
377
387
|
}
|
|
378
388
|
build() {
|
|
379
389
|
return new LightconeClient({
|
|
380
|
-
http: new http_1.LightconeHttp(this.baseUrlValue),
|
|
390
|
+
http: new http_1.LightconeHttp(this.baseUrlValue, { apiKey: this.apiKeyValue }),
|
|
381
391
|
wsConfig: {
|
|
382
392
|
url: this.wsUrlValue,
|
|
383
393
|
reconnect: true,
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":";;;AAAA,uDAK+B;AAC/B,6CAAiE;AACjE,iCAAoD;AAEpD,uCAKmB;AAGnB,4CAA0C;AAC1C,8CAA2C;AAC3C,wDAAsD;AACtD,0CAAwC;AACxC,kDAAgD;AAChD,gDAA8C;AAC9C,0DAA4D;AAC5D,gDAA8C;AAC9C,0CAAwC;AACxC,iCAA6E;AAC7E,+BAAuF;AACvF,mCAAgC;AAChC,+BAA4B;AAC5B,+CAAiD;AACjD,qCAA8E;AAE9E,6BAA+C;AAE/C,MAAM,SAAS;IACL,gBAAgB,CAA8B;IAEtD,YAAY,OAAyB;QACnC,IAAI,CAAC,gBAAgB,GAAG,OAAO,CAAC;IAClC,CAAC;IAED,cAAc;QACZ,OAAO,IAAI,CAAC,gBAAgB,CAAC;IAC/B,CAAC;IAED,cAAc,CAAC,WAAwC;QACrD,IAAI,CAAC,gBAAgB,GAAG,WAAW,CAAC;IACtC,CAAC;IAED,KAAK,CAAC,WAAW;QACf,6EAA6E;IAC/E,CAAC;CACF;AAED,MAAa,eAAe;IACjB,oBAAoB,CAAoB;IACxC,QAAQ,CAAgB;IACxB,IAAI,CAAgB;IACpB,SAAS,CAAY;IACrB,iBAAiB,CAAc;IAC/B,gBAAgB,CAAc;IAC9B,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1TransactionContext,\n} from \"./program/transaction\";\nimport { Connection, Keypair, PublicKey } from \"@solana/web3.js\";\nimport { Auth, type AuthCredentials } from \"./auth\";\nimport type { ClientContext } from \"./context\";\nimport {\n signAndSubmitTx as signAndSubmitTxFn,\n signAndSubmitTxConfirmed as signAndSubmitTxConfirmedFn,\n signAndSubmitTxConfirmedWithSlot as signAndSubmitTxConfirmedWithSlotFn,\n signAndSubmitPreparedTxConfirmedWithSlot as signAndSubmitPreparedTxConfirmedWithSlotFn,\n} from \"./context\";\nimport type { ConfirmedTransaction } from \"./context\";\nimport type { FaucetRequest, FaucetResponse } from \"./domain/faucet\";\nimport { Markets } from \"./domain/market\";\nimport { Metrics } from \"./domain/metrics\";\nimport { Notifications } from \"./domain/notification\";\nimport { Orders } from \"./domain/order\";\nimport { Orderbooks } from \"./domain/orderbook\";\nimport { Positions } from \"./domain/position\";\nimport { PriceHistoryClient } from \"./domain/price_history\";\nimport { Referrals } from \"./domain/referral\";\nimport { Trades } from \"./domain/trade\";\nimport { LightconeHttp, RetryPolicy, type CredentialRestorer } from \"./http\";\nimport { LightconeEnv, apiUrl, wsUrl, rpcUrl, programId as envProgramId } from \"./env\";\nimport { Privy } from \"./privy\";\nimport { Rpc } from \"./rpc\";\nimport { RpcFailoverState } from \"./rpcFailover\";\nimport { DepositSource, type OrderbookRules, type PubkeyStr } from \"./shared\";\nimport { type ExternalSigner, type SigningStrategy } from \"./shared/signing\";\nimport { WsClient, type WsConfig } from \"./ws\";\n\nclass AuthState {\n private credentialsValue: AuthCredentials | undefined;\n\n constructor(initial?: AuthCredentials) {\n this.credentialsValue = initial;\n }\n\n getCredentials(): AuthCredentials | undefined {\n return this.credentialsValue;\n }\n\n setCredentials(credentials: AuthCredentials | undefined): void {\n this.credentialsValue = credentials;\n }\n\n async clearCaches(): Promise<void> {\n // No caches to clear — decimals are derived locally from orderbook metadata.\n }\n}\n\nexport class LightconeClient implements ClientContext {\n readonly transactionResources?: V1ResourceConfig;\n readonly rpcFetch?: typeof fetch;\n readonly http: LightconeHttp;\n readonly programId: PublicKey;\n readonly primaryConnection?: Connection;\n readonly backupConnection?: Connection;\n readonly rpcFailoverState: RpcFailoverState;\n private depositSourceValue: DepositSource;\n private signingStrategyValue?: SigningStrategy;\n private transactionSponsorshipEnabledValue: boolean;\n private orderNonceValue: number | undefined;\n private readonly wsConfigValue: WsConfig;\n private readonly authStateStore: AuthState;\n readonly orderbookRulesCache: Map<string, Promise<OrderbookRules>>;\n\n /** @deprecated Use primaryConnection — kept for ClientContext compat. */\n get connection(): Connection | undefined {\n return this.primaryConnection;\n }\n\n constructor(params: {\n http: LightconeHttp;\n wsConfig: WsConfig;\n programId?: PublicKey;\n primaryConnection?: Connection;\n backupConnection?: Connection;\n rpcFailoverState?: RpcFailoverState;\n depositSource?: DepositSource;\n signingStrategy?: SigningStrategy;\n transactionSponsorshipEnabled?: boolean;\n transactionResources?: V1ResourceConfig;\n rpcFetch?: typeof fetch;\n orderNonce?: number;\n authCredentials?: AuthCredentials;\n authState?: AuthState;\n orderbookRulesCache?: Map<string, Promise<OrderbookRules>>;\n }) {\n if (params.transactionResources) validateV1Resources(params.transactionResources);\n this.transactionResources = params.transactionResources\n ? Object.freeze({ ...params.transactionResources })\n : undefined;\n this.rpcFetch = params.rpcFetch;\n this.http = params.http;\n this.programId = params.programId ?? envProgramId(LightconeEnv.Prod);\n this.primaryConnection = params.primaryConnection;\n this.backupConnection = params.backupConnection;\n this.rpcFailoverState =\n params.rpcFailoverState ?? new RpcFailoverState();\n this.depositSourceValue = params.depositSource ?? DepositSource.Global;\n this.signingStrategyValue = params.signingStrategy;\n this.transactionSponsorshipEnabledValue =\n params.transactionSponsorshipEnabled ?? false;\n this.orderNonceValue = params.orderNonce;\n this.wsConfigValue = params.wsConfig;\n this.authStateStore =\n params.authState ??\n new AuthState(params.authCredentials);\n this.orderbookRulesCache = params.orderbookRulesCache ?? new Map();\n }\n\n // ── Deposit source ──────────────────────────────────────────────────\n\n get depositSource(): DepositSource {\n return this.depositSourceValue;\n }\n\n setDepositSource(source: DepositSource): void {\n this.depositSourceValue = source;\n }\n\n // ── Signing strategy ────────────────────────────────────────────────\n\n get signingStrategy(): SigningStrategy | undefined {\n return this.signingStrategyValue;\n }\n\n /**\n * Cached authenticated identity shared by domain sub-clients.\n *\n * This is distinct from the HTTP cookie token and may be expired; fund-moving\n * operations must re-check its lifetime and wallet before signing.\n */\n get authCredentials(): AuthCredentials | undefined {\n return this.authStateStore.getCredentials();\n }\n\n setSigningStrategy(strategy: SigningStrategy): void {\n this.signingStrategyValue = strategy;\n }\n\n clearSigningStrategy(): void {\n this.signingStrategyValue = undefined;\n }\n\n /** Return the client-wide trusted assertion that an external sponsor pays fees. */\n get transactionSponsorshipEnabled(): boolean {\n return this.transactionSponsorshipEnabledValue;\n }\n\n /** Replace the Transaction Sponsorship Capability for subsequent submissions. */\n setTransactionSponsorshipEnabled(enabled: boolean): void {\n this.transactionSponsorshipEnabledValue = enabled;\n }\n\n // ── Nonce cache ──────────────────────────────────────────────────────\n\n orderNonce(): number | undefined {\n return this.orderNonceValue;\n }\n\n setOrderNonce(nonce: number): void {\n this.orderNonceValue = nonce;\n }\n\n clearOrderNonce(): void {\n this.orderNonceValue = undefined;\n }\n\n // ── Auth token (cookie) ─────────────────────────────────────────────\n\n /**\n * Get the current `lightcone-token` cookie value, if any. Populated by the SDK\n * after a successful login, then attached on every authed request. Useful\n * for forwarding the token through the `*WithCookies` methods, or\n * persisting the session across processes.\n */\n async authToken(): Promise<string | undefined> {\n return this.http.authTokenRef()();\n }\n\n /**\n * Clear the cached `lightcone-token`. Subsequent authed calls will go out\n * without a `Cookie` header (and 401) unless they use a\n * `*WithCookies` variant.\n */\n async clearAuthToken(): Promise<void> {\n await this.http.clearAuthToken();\n }\n\n /**\n * Register the credential restorer consulted when a request fails with\n * HTTP 401: it attempts to restore credentials (e.g. refresh the app's\n * auth session so the auth cookie is valid again); on success the\n * transport replays the request once IF it declared itself retry-safe\n * (RetryPolicy.None mutations are never auto-replayed). See {@link CredentialRestorer}.\n * Without a restorer, 401s propagate to callers unchanged.\n *\n * Common use: set once at app startup, alongside the signing strategy.\n */\n setCredentialRestorer(restorer: CredentialRestorer): void {\n this.http.setCredentialRestorer(restorer);\n }\n\n /** Remove the credential restorer (e.g. in tests); 401s propagate again. */\n clearCredentialRestorer(): void {\n this.http.clearCredentialRestorer();\n }\n\n /** Fetch a fresh context with configured v1 transaction resources. */\n transactionContext(): Promise<V1TransactionContext> {\n return this.rpc().transactionContext();\n }\n\n /** Fetch a fresh context with explicit limits and total priority fee lamports. */\n transactionContextWithResources(\n resources: V1ResourceConfig\n ): Promise<V1TransactionContext> {\n return this.rpc().transactionContextWithResources(resources);\n }\n\n // ── Transaction signing + submission ────────────────────────────────\n\n async signAndSubmitTx(tx: V1Transaction): Promise<string> {\n return signAndSubmitTxFn(this, tx);\n }\n\n /**\n * Sign and submit a transaction, then wait until it reaches `confirmed`\n * commitment on-chain. Prefer this over {@link signAndSubmitTx} when a\n * follow-up transaction depends on this one's state.\n */\n async signAndSubmitTxConfirmed(tx: V1Transaction): Promise<string> {\n return signAndSubmitTxConfirmedFn(this, tx);\n }\n\n /** Sign, submit, confirm, and return the transaction's processing slot. */\n async signAndSubmitTxConfirmedWithSlot(\n tx: V1Transaction\n ): Promise<ConfirmedTransaction> {\n return signAndSubmitTxConfirmedWithSlotFn(this, tx);\n }\n\n /**\n * Sign, submit, and confirm a fee-prepared transaction without replacing its\n * message. Privy and wallet-adapter message mutation are rejected. A confirmation\n * timeout leaves the outcome unknown; inspect authoritative state before retrying.\n */\n async signAndSubmitPreparedTxConfirmedWithSlot(\n tx: V1Transaction\n ): Promise<ConfirmedTransaction> {\n return signAndSubmitPreparedTxConfirmedWithSlotFn(this, tx);\n }\n\n static builder(): LightconeClientBuilder {\n return new LightconeClientBuilder();\n }\n\n // ── Sub-client accessors ─────────────────────────────────────────────\n\n markets(): Markets {\n return new Markets(this);\n }\n\n orderbooks(): Orderbooks {\n return new Orderbooks(this);\n }\n\n orders(): Orders {\n return new Orders(this);\n }\n\n positions(): Positions {\n return new Positions(this);\n }\n\n trades(): Trades {\n return new Trades(this);\n }\n\n priceHistory(): PriceHistoryClient {\n return new PriceHistoryClient(this);\n }\n\n notifications(): Notifications {\n return new Notifications(this);\n }\n\n /**\n * Metrics sub-client — platform / market / orderbook / category / deposit-token\n * volume metrics, market leaderboard, and time-series history.\n */\n metrics(): Metrics {\n return new Metrics(this);\n }\n\n /**\n * Request testnet SOL and whitelisted deposit tokens for a wallet.\n *\n * Only active on environments whose backend has the faucet enabled (typically\n * local and staging).\n *\n * `POST /api/claim`\n */\n async claim(walletAddress: PubkeyStr): Promise<FaucetResponse> {\n const url = `${this.http.baseUrl()}/api/claim`;\n return this.http.post<FaucetResponse, FaucetRequest>(\n url,\n { wallet_address: walletAddress },\n RetryPolicy.None\n );\n }\n\n auth(): Auth {\n return new Auth({\n http: this.http,\n authState: this.authStateStore,\n });\n }\n\n privy(): Privy {\n return new Privy(this);\n }\n\n referrals(): Referrals {\n return new Referrals(this);\n }\n\n rpc(): Rpc {\n return new Rpc(this);\n }\n\n wsConfig(): WsConfig {\n return this.wsConfigValue;\n }\n\n ws(): WsClient {\n return new WsClient(this.wsConfigValue, this.http.authTokenRef());\n }\n\n /**\n * Return a client whose Transaction Sponsorship Capability starts at this value.\n * Later runtime changes remain local to each clone, matching other mutable settings.\n */\n clone(): LightconeClient {\n return new LightconeClient({\n http: this.http,\n wsConfig: { ...this.wsConfigValue },\n programId: this.programId,\n primaryConnection: this.primaryConnection\n ? new Connection(this.primaryConnection.rpcEndpoint, { commitment: \"confirmed\", fetch: this.rpcFetch })\n : undefined,\n backupConnection: this.backupConnection\n ? new Connection(this.backupConnection.rpcEndpoint, { commitment: \"confirmed\", fetch: this.rpcFetch })\n : undefined,\n rpcFailoverState: this.rpcFailoverState,\n depositSource: this.depositSourceValue,\n signingStrategy: this.signingStrategyValue,\n transactionSponsorshipEnabled: this.transactionSponsorshipEnabledValue,\n transactionResources: this.transactionResources,\n rpcFetch: this.rpcFetch,\n orderNonce: this.orderNonceValue,\n authState: this.authStateStore,\n orderbookRulesCache: this.orderbookRulesCache,\n });\n }\n}\n\nexport class LightconeClientBuilder {\n private baseUrlValue: string = apiUrl(LightconeEnv.Prod);\n private wsUrlValue: string = wsUrl(LightconeEnv.Prod);\n private authCredentials?: AuthCredentials;\n private programIdValue: PublicKey = envProgramId(LightconeEnv.Prod);\n private depositSourceValue: DepositSource = DepositSource.Global;\n private signingStrategyValue?: SigningStrategy;\n private transactionSponsorshipEnabledValue = false;\n private transactionResourcesValue?: V1ResourceConfig;\n private rpcFetchValue?: typeof fetch;\n private primaryRpcUrlValue?: string = rpcUrl(LightconeEnv.Prod);\n private backupRpcUrlValue?: string;\n\n /**\n * Set the deployment environment. Configures the API URL, WebSocket URL,\n * RPC URL, and program ID for the given environment.\n *\n * Individual URL overrides (e.g. `.baseUrl()`) take precedence when\n * called **after** `.env()`.\n */\n env(environment: LightconeEnv): LightconeClientBuilder {\n this.baseUrlValue = apiUrl(environment);\n this.wsUrlValue = wsUrl(environment);\n this.programIdValue = envProgramId(environment);\n this.primaryRpcUrlValue = rpcUrl(environment);\n return this;\n }\n\n baseUrl(url: string): LightconeClientBuilder {\n return this.withBaseUrl(url);\n }\n\n withBaseUrl(url: string): LightconeClientBuilder {\n this.baseUrlValue = url;\n return this;\n }\n\n wsUrl(url: string): LightconeClientBuilder {\n return this.withWsUrl(url);\n }\n\n withWsUrl(url: string): LightconeClientBuilder {\n this.wsUrlValue = url;\n return this;\n }\n\n auth(credentials: AuthCredentials): LightconeClientBuilder {\n return this.withAuth(credentials);\n }\n\n withAuth(credentials: AuthCredentials): LightconeClientBuilder {\n this.authCredentials = credentials;\n return this;\n }\n\n programId(id: PublicKey): LightconeClientBuilder {\n this.programIdValue = id;\n return this;\n }\n\n depositSource(source: DepositSource): LightconeClientBuilder {\n this.depositSourceValue = source;\n return this;\n }\n\n nativeSigner(keypair: Keypair): LightconeClientBuilder {\n this.signingStrategyValue = { type: \"native\", keypair };\n return this;\n }\n\n externalSigner(signer: ExternalSigner): LightconeClientBuilder {\n this.signingStrategyValue = { type: \"walletAdapter\", signer };\n return this;\n }\n\n privyWalletId(\n walletId: string,\n walletAddress?: string\n ): LightconeClientBuilder {\n this.signingStrategyValue = { type: \"privy\", walletId, walletAddress };\n return this;\n }\n\n /** Set the initial trusted Transaction Sponsorship Capability; defaults to false. */\n transactionSponsorship(enabled: boolean): LightconeClientBuilder {\n this.transactionSponsorshipEnabledValue = enabled;\n return this;\n }\n\n /** Set explicit v1 limits and total priority fee lamports for fluent builders and SOL plans. */\n transactionResources(resources: V1ResourceConfig): LightconeClientBuilder {\n validateV1Resources(resources);\n this.transactionResourcesValue = Object.freeze({ ...resources });\n return this;\n }\n\n /** Set the one-attempt fetch transport for v1 RPC, for example to add RPC authentication headers. */\n rpcFetch(transport: typeof fetch): LightconeClientBuilder {\n this.rpcFetchValue = transport;\n return this;\n }\n\n rpcUrl(url: string): LightconeClientBuilder {\n this.primaryRpcUrlValue = url;\n return this;\n }\n\n /** Set a backup Solana RPC URL for automatic failover. */\n backupRpcUrl(url: string): LightconeClientBuilder {\n this.backupRpcUrlValue = url;\n return this;\n }\n\n build(): LightconeClient {\n return new LightconeClient({\n http: new LightconeHttp(this.baseUrlValue),\n wsConfig: {\n url: this.wsUrlValue,\n reconnect: true,\n maxReconnectAttempts: 10,\n baseReconnectDelayMs: 1_000,\n pingIntervalMs: 30_000,\n pongTimeoutMs: 10_000,\n },\n programId: this.programIdValue,\n depositSource: this.depositSourceValue,\n signingStrategy: this.signingStrategyValue,\n transactionSponsorshipEnabled: this.transactionSponsorshipEnabledValue,\n primaryConnection: this.primaryRpcUrlValue\n ? new Connection(this.primaryRpcUrlValue, { commitment: \"confirmed\", fetch: this.rpcFetchValue })\n : undefined,\n backupConnection: this.backupRpcUrlValue\n ? new Connection(this.backupRpcUrlValue, { commitment: \"confirmed\", fetch: this.rpcFetchValue })\n : undefined,\n transactionResources: this.transactionResourcesValue,\n rpcFetch: this.rpcFetchValue,\n authCredentials: this.authCredentials,\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":";;;AAAA,uDAK+B;AAC/B,6CAAiE;AACjE,iCAAoD;AAEpD,uCAKmB;AAGnB,4CAA0C;AAC1C,8CAA2C;AAC3C,wDAAsD;AACtD,0CAAwC;AACxC,kDAAgD;AAChD,gDAA8C;AAC9C,0DAA4D;AAC5D,gDAA8C;AAC9C,0CAAwC;AACxC,iCAA6E;AAC7E,+BAAuF;AACvF,mCAAgC;AAChC,+BAA4B;AAC5B,+CAAiD;AACjD,qCAA8E;AAE9E,6BAA+C;AAE/C,MAAM,SAAS;IACL,gBAAgB,CAA8B;IAEtD,YAAY,OAAyB;QACnC,IAAI,CAAC,gBAAgB,GAAG,OAAO,CAAC;IAClC,CAAC;IAED,cAAc;QACZ,OAAO,IAAI,CAAC,gBAAgB,CAAC;IAC/B,CAAC;IAED,cAAc,CAAC,WAAwC;QACrD,IAAI,CAAC,gBAAgB,GAAG,WAAW,CAAC;IACtC,CAAC;IAED,KAAK,CAAC,WAAW;QACf,6EAA6E;IAC/E,CAAC;CACF;AAED,MAAa,eAAe;IACjB,oBAAoB,CAAoB;IACxC,QAAQ,CAAgB;IACxB,IAAI,CAAgB;IACpB,SAAS,CAAY;IACrB,iBAAiB,CAAc;IAC/B,gBAAgB,CAAc;IAC9B,gBAAgB,CAAmB;IACpC,kBAAkB,CAAgB;IAClC,oBAAoB,CAAmB;IACvC,kCAAkC,CAAU;IAC5C,eAAe,CAAqB;IAC3B,aAAa,CAAW;IACxB,cAAc,CAAY;IAClC,mBAAmB,CAAuC;IAEnE,yEAAyE;IACzE,IAAI,UAAU;QACZ,OAAO,IAAI,CAAC,iBAAiB,CAAC;IAChC,CAAC;IAED,YAAY,MAgBX;QACC,IAAI,MAAM,CAAC,oBAAoB;YAAE,IAAA,iCAAmB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,IAAI,eAAe,CAAC;YACzB,IAAI,EAAE,IAAI,oBAAa,CAAC,IAAI,CAAC,YAAY,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,WAAW,EAAE,CAAC;YACxE,QAAQ,EAAE;gBACR,GAAG,EAAE,IAAI,CAAC,UAAU;gBACpB,SAAS,EAAE,IAAI;gBACf,oBAAoB,EAAE,EAAE;gBACxB,oBAAoB,EAAE,KAAK;gBAC3B,cAAc,EAAE,MAAM;gBACtB,aAAa,EAAE,MAAM;aACtB;YACD,SAAS,EAAE,IAAI,CAAC,cAAc;YAC9B,aAAa,EAAE,IAAI,CAAC,kBAAkB;YACtC,eAAe,EAAE,IAAI,CAAC,oBAAoB;YAC1C,6BAA6B,EAAE,IAAI,CAAC,kCAAkC;YACtE,iBAAiB,EAAE,IAAI,CAAC,kBAAkB;gBACxC,CAAC,CAAC,IAAI,oBAAU,CAAC,IAAI,CAAC,kBAAkB,EAAE,EAAE,UAAU,EAAE,WAAW,EAAE,KAAK,EAAE,IAAI,CAAC,aAAa,EAAE,CAAC;gBACjG,CAAC,CAAC,SAAS;YACb,gBAAgB,EAAE,IAAI,CAAC,iBAAiB;gBACtC,CAAC,CAAC,IAAI,oBAAU,CAAC,IAAI,CAAC,iBAAiB,EAAE,EAAE,UAAU,EAAE,WAAW,EAAE,KAAK,EAAE,IAAI,CAAC,aAAa,EAAE,CAAC;gBAChG,CAAC,CAAC,SAAS;YACb,oBAAoB,EAAE,IAAI,CAAC,yBAAyB;YACpD,QAAQ,EAAE,IAAI,CAAC,aAAa;YAC5B,eAAe,EAAE,IAAI,CAAC,eAAe;SACtC,CAAC,CAAC;IACL,CAAC;CACF;AAtJD,wDAsJC","sourcesContent":["import {\n V1Transaction,\n validateV1Resources,\n type V1ResourceConfig,\n type V1TransactionContext,\n} from \"./program/transaction\";\nimport { Connection, Keypair, PublicKey } from \"@solana/web3.js\";\nimport { Auth, type AuthCredentials } from \"./auth\";\nimport type { ClientContext } from \"./context\";\nimport {\n signAndSubmitTx as signAndSubmitTxFn,\n signAndSubmitTxConfirmed as signAndSubmitTxConfirmedFn,\n signAndSubmitTxConfirmedWithSlot as signAndSubmitTxConfirmedWithSlotFn,\n signAndSubmitPreparedTxConfirmedWithSlot as signAndSubmitPreparedTxConfirmedWithSlotFn,\n} from \"./context\";\nimport type { ConfirmedTransaction } from \"./context\";\nimport type { FaucetRequest, FaucetResponse } from \"./domain/faucet\";\nimport { Markets } from \"./domain/market\";\nimport { Metrics } from \"./domain/metrics\";\nimport { Notifications } from \"./domain/notification\";\nimport { Orders } from \"./domain/order\";\nimport { Orderbooks } from \"./domain/orderbook\";\nimport { Positions } from \"./domain/position\";\nimport { PriceHistoryClient } from \"./domain/price_history\";\nimport { Referrals } from \"./domain/referral\";\nimport { Trades } from \"./domain/trade\";\nimport { LightconeHttp, RetryPolicy, type CredentialRestorer } from \"./http\";\nimport { LightconeEnv, apiUrl, wsUrl, rpcUrl, programId as envProgramId } from \"./env\";\nimport { Privy } from \"./privy\";\nimport { Rpc } from \"./rpc\";\nimport { RpcFailoverState } from \"./rpcFailover\";\nimport { DepositSource, type OrderbookRules, type PubkeyStr } from \"./shared\";\nimport { type ExternalSigner, type SigningStrategy } from \"./shared/signing\";\nimport { WsClient, type WsConfig } from \"./ws\";\n\nclass AuthState {\n private credentialsValue: AuthCredentials | undefined;\n\n constructor(initial?: AuthCredentials) {\n this.credentialsValue = initial;\n }\n\n getCredentials(): AuthCredentials | undefined {\n return this.credentialsValue;\n }\n\n setCredentials(credentials: AuthCredentials | undefined): void {\n this.credentialsValue = credentials;\n }\n\n async clearCaches(): Promise<void> {\n // No caches to clear — decimals are derived locally from orderbook metadata.\n }\n}\n\nexport class LightconeClient implements ClientContext {\n readonly transactionResources?: V1ResourceConfig;\n readonly rpcFetch?: typeof fetch;\n readonly http: LightconeHttp;\n readonly programId: PublicKey;\n readonly primaryConnection?: Connection;\n readonly backupConnection?: Connection;\n readonly rpcFailoverState: RpcFailoverState;\n private depositSourceValue: DepositSource;\n private signingStrategyValue?: SigningStrategy;\n private transactionSponsorshipEnabledValue: boolean;\n private orderNonceValue: number | undefined;\n private readonly wsConfigValue: WsConfig;\n private readonly authStateStore: AuthState;\n readonly orderbookRulesCache: Map<string, Promise<OrderbookRules>>;\n\n /** @deprecated Use primaryConnection — kept for ClientContext compat. */\n get connection(): Connection | undefined {\n return this.primaryConnection;\n }\n\n constructor(params: {\n http: LightconeHttp;\n wsConfig: WsConfig;\n programId?: PublicKey;\n primaryConnection?: Connection;\n backupConnection?: Connection;\n rpcFailoverState?: RpcFailoverState;\n depositSource?: DepositSource;\n signingStrategy?: SigningStrategy;\n transactionSponsorshipEnabled?: boolean;\n transactionResources?: V1ResourceConfig;\n rpcFetch?: typeof fetch;\n orderNonce?: number;\n authCredentials?: AuthCredentials;\n authState?: AuthState;\n orderbookRulesCache?: Map<string, Promise<OrderbookRules>>;\n }) {\n if (params.transactionResources) validateV1Resources(params.transactionResources);\n this.transactionResources = params.transactionResources\n ? Object.freeze({ ...params.transactionResources })\n : undefined;\n this.rpcFetch = params.rpcFetch;\n this.http = params.http;\n this.programId = params.programId ?? envProgramId(LightconeEnv.Prod);\n this.primaryConnection = params.primaryConnection;\n this.backupConnection = params.backupConnection;\n this.rpcFailoverState =\n params.rpcFailoverState ?? new RpcFailoverState();\n this.depositSourceValue = params.depositSource ?? DepositSource.Global;\n this.signingStrategyValue = params.signingStrategy;\n this.transactionSponsorshipEnabledValue =\n params.transactionSponsorshipEnabled ?? false;\n this.orderNonceValue = params.orderNonce;\n this.wsConfigValue = params.wsConfig;\n this.authStateStore =\n params.authState ??\n new AuthState(params.authCredentials);\n this.orderbookRulesCache = params.orderbookRulesCache ?? new Map();\n }\n\n // ── Deposit source ──────────────────────────────────────────────────\n\n get depositSource(): DepositSource {\n return this.depositSourceValue;\n }\n\n setDepositSource(source: DepositSource): void {\n this.depositSourceValue = source;\n }\n\n // ── Signing strategy ────────────────────────────────────────────────\n\n get signingStrategy(): SigningStrategy | undefined {\n return this.signingStrategyValue;\n }\n\n /**\n * Cached authenticated identity shared by domain sub-clients.\n *\n * This is distinct from the HTTP cookie token and may be expired; fund-moving\n * operations must re-check its lifetime and wallet before signing.\n */\n get authCredentials(): AuthCredentials | undefined {\n return this.authStateStore.getCredentials();\n }\n\n setSigningStrategy(strategy: SigningStrategy): void {\n this.signingStrategyValue = strategy;\n }\n\n clearSigningStrategy(): void {\n this.signingStrategyValue = undefined;\n }\n\n /** Return the client-wide trusted assertion that an external sponsor pays fees. */\n get transactionSponsorshipEnabled(): boolean {\n return this.transactionSponsorshipEnabledValue;\n }\n\n /** Replace the Transaction Sponsorship Capability for subsequent submissions. */\n setTransactionSponsorshipEnabled(enabled: boolean): void {\n this.transactionSponsorshipEnabledValue = enabled;\n }\n\n // ── Nonce cache ──────────────────────────────────────────────────────\n\n orderNonce(): number | undefined {\n return this.orderNonceValue;\n }\n\n setOrderNonce(nonce: number): void {\n this.orderNonceValue = nonce;\n }\n\n clearOrderNonce(): void {\n this.orderNonceValue = undefined;\n }\n\n // ── Auth token (cookie) ─────────────────────────────────────────────\n\n /**\n * Get the current `lightcone-token` cookie value, if any. Populated by the SDK\n * after a successful login, then attached on every authed request. Useful\n * for forwarding the token through the `*WithCookies` methods, or\n * persisting the session across processes.\n */\n async authToken(): Promise<string | undefined> {\n return this.http.authTokenRef()();\n }\n\n /**\n * Clear the cached `lightcone-token`. Subsequent authed calls will go out\n * without a `Cookie` header (and 401) unless they use a\n * `*WithCookies` variant.\n */\n async clearAuthToken(): Promise<void> {\n await this.http.clearAuthToken();\n }\n\n /**\n * Register the credential restorer consulted when a request fails with\n * HTTP 401: it attempts to restore credentials (e.g. refresh the app's\n * auth session so the auth cookie is valid again); on success the\n * transport replays the request once IF it declared itself retry-safe\n * (RetryPolicy.None mutations are never auto-replayed). See {@link CredentialRestorer}.\n * Without a restorer, 401s propagate to callers unchanged.\n *\n * Common use: set once at app startup, alongside the signing strategy.\n */\n setCredentialRestorer(restorer: CredentialRestorer): void {\n this.http.setCredentialRestorer(restorer);\n }\n\n /** Remove the credential restorer (e.g. in tests); 401s propagate again. */\n clearCredentialRestorer(): void {\n this.http.clearCredentialRestorer();\n }\n\n /** Fetch a fresh context with configured v1 transaction resources. */\n transactionContext(): Promise<V1TransactionContext> {\n return this.rpc().transactionContext();\n }\n\n /** Fetch a fresh context with explicit limits and total priority fee lamports. */\n transactionContextWithResources(\n resources: V1ResourceConfig\n ): Promise<V1TransactionContext> {\n return this.rpc().transactionContextWithResources(resources);\n }\n\n // ── Transaction signing + submission ────────────────────────────────\n\n async signAndSubmitTx(tx: V1Transaction): Promise<string> {\n return signAndSubmitTxFn(this, tx);\n }\n\n /**\n * Sign and submit a transaction, then wait until it reaches `confirmed`\n * commitment on-chain. Prefer this over {@link signAndSubmitTx} when a\n * follow-up transaction depends on this one's state.\n */\n async signAndSubmitTxConfirmed(tx: V1Transaction): Promise<string> {\n return signAndSubmitTxConfirmedFn(this, tx);\n }\n\n /** Sign, submit, confirm, and return the transaction's processing slot. */\n async signAndSubmitTxConfirmedWithSlot(\n tx: V1Transaction\n ): Promise<ConfirmedTransaction> {\n return signAndSubmitTxConfirmedWithSlotFn(this, tx);\n }\n\n /**\n * Sign, submit, and confirm a fee-prepared transaction without replacing its\n * message. Privy and wallet-adapter message mutation are rejected. A confirmation\n * timeout leaves the outcome unknown; inspect authoritative state before retrying.\n */\n async signAndSubmitPreparedTxConfirmedWithSlot(\n tx: V1Transaction\n ): Promise<ConfirmedTransaction> {\n return signAndSubmitPreparedTxConfirmedWithSlotFn(this, tx);\n }\n\n static builder(): LightconeClientBuilder {\n return new LightconeClientBuilder();\n }\n\n // ── Sub-client accessors ─────────────────────────────────────────────\n\n markets(): Markets {\n return new Markets(this);\n }\n\n orderbooks(): Orderbooks {\n return new Orderbooks(this);\n }\n\n orders(): Orders {\n return new Orders(this);\n }\n\n positions(): Positions {\n return new Positions(this);\n }\n\n trades(): Trades {\n return new Trades(this);\n }\n\n priceHistory(): PriceHistoryClient {\n return new PriceHistoryClient(this);\n }\n\n notifications(): Notifications {\n return new Notifications(this);\n }\n\n /**\n * Metrics sub-client — platform / market / orderbook / category / deposit-token\n * volume metrics, market leaderboard, and time-series history.\n */\n metrics(): Metrics {\n return new Metrics(this);\n }\n\n /**\n * Request testnet SOL and whitelisted deposit tokens for a wallet.\n *\n * Only active on environments whose backend has the faucet enabled (typically\n * local and staging).\n *\n * `POST /api/claim`\n */\n async claim(walletAddress: PubkeyStr): Promise<FaucetResponse> {\n const url = `${this.http.baseUrl()}/api/claim`;\n return this.http.post<FaucetResponse, FaucetRequest>(\n url,\n { wallet_address: walletAddress },\n RetryPolicy.None\n );\n }\n\n auth(): Auth {\n return new Auth({\n http: this.http,\n authState: this.authStateStore,\n });\n }\n\n privy(): Privy {\n return new Privy(this);\n }\n\n referrals(): Referrals {\n return new Referrals(this);\n }\n\n rpc(): Rpc {\n return new Rpc(this);\n }\n\n wsConfig(): WsConfig {\n return this.wsConfigValue;\n }\n\n ws(): WsClient {\n return new WsClient(this.wsConfigValue, this.http.authTokenRef());\n }\n\n /**\n * Return a client whose Transaction Sponsorship Capability starts at this value.\n * Later runtime changes remain local to each clone, matching other mutable settings.\n */\n clone(): LightconeClient {\n return new LightconeClient({\n http: this.http,\n wsConfig: { ...this.wsConfigValue },\n programId: this.programId,\n primaryConnection: this.primaryConnection\n ? new Connection(this.primaryConnection.rpcEndpoint, { commitment: \"confirmed\", fetch: this.rpcFetch })\n : undefined,\n backupConnection: this.backupConnection\n ? new Connection(this.backupConnection.rpcEndpoint, { commitment: \"confirmed\", fetch: this.rpcFetch })\n : undefined,\n rpcFailoverState: this.rpcFailoverState,\n depositSource: this.depositSourceValue,\n signingStrategy: this.signingStrategyValue,\n transactionSponsorshipEnabled: this.transactionSponsorshipEnabledValue,\n transactionResources: this.transactionResources,\n rpcFetch: this.rpcFetch,\n orderNonce: this.orderNonceValue,\n authState: this.authStateStore,\n orderbookRulesCache: this.orderbookRulesCache,\n });\n }\n}\n\nexport class LightconeClientBuilder {\n private baseUrlValue: string = apiUrl(LightconeEnv.Prod);\n private wsUrlValue: string = wsUrl(LightconeEnv.Prod);\n private authCredentials?: AuthCredentials;\n private programIdValue: PublicKey = envProgramId(LightconeEnv.Prod);\n private depositSourceValue: DepositSource = DepositSource.Global;\n private signingStrategyValue?: SigningStrategy;\n private transactionSponsorshipEnabledValue = false;\n private transactionResourcesValue?: V1ResourceConfig;\n private rpcFetchValue?: typeof fetch;\n private primaryRpcUrlValue?: string = rpcUrl(LightconeEnv.Prod);\n private backupRpcUrlValue?: string;\n private apiKeyValue?: string;\n\n /**\n * Set the deployment environment. Configures the API URL, WebSocket URL,\n * RPC URL, and program ID for the given environment.\n *\n * Individual URL overrides (e.g. `.baseUrl()`) take precedence when\n * called **after** `.env()`.\n */\n env(environment: LightconeEnv): LightconeClientBuilder {\n this.baseUrlValue = apiUrl(environment);\n this.wsUrlValue = wsUrl(environment);\n this.programIdValue = envProgramId(environment);\n this.primaryRpcUrlValue = rpcUrl(environment);\n return this;\n }\n\n baseUrl(url: string): LightconeClientBuilder {\n return this.withBaseUrl(url);\n }\n\n withBaseUrl(url: string): LightconeClientBuilder {\n this.baseUrlValue = url;\n return this;\n }\n\n /**\n * Set the API key sent as `x-lightcone-api-key` on submit, cancel, and cancel-all POST requests to\n * the API origin. Keep it server-side: it identifies an API Consumer, never\n * a user, and the SDK never logs it.\n */\n apiKey(key: string): LightconeClientBuilder {\n this.apiKeyValue = key;\n return this;\n }\n\n wsUrl(url: string): LightconeClientBuilder {\n return this.withWsUrl(url);\n }\n\n withWsUrl(url: string): LightconeClientBuilder {\n this.wsUrlValue = url;\n return this;\n }\n\n auth(credentials: AuthCredentials): LightconeClientBuilder {\n return this.withAuth(credentials);\n }\n\n withAuth(credentials: AuthCredentials): LightconeClientBuilder {\n this.authCredentials = credentials;\n return this;\n }\n\n programId(id: PublicKey): LightconeClientBuilder {\n this.programIdValue = id;\n return this;\n }\n\n depositSource(source: DepositSource): LightconeClientBuilder {\n this.depositSourceValue = source;\n return this;\n }\n\n nativeSigner(keypair: Keypair): LightconeClientBuilder {\n this.signingStrategyValue = { type: \"native\", keypair };\n return this;\n }\n\n externalSigner(signer: ExternalSigner): LightconeClientBuilder {\n this.signingStrategyValue = { type: \"walletAdapter\", signer };\n return this;\n }\n\n privyWalletId(\n walletId: string,\n walletAddress?: string\n ): LightconeClientBuilder {\n this.signingStrategyValue = { type: \"privy\", walletId, walletAddress };\n return this;\n }\n\n /** Set the initial trusted Transaction Sponsorship Capability; defaults to false. */\n transactionSponsorship(enabled: boolean): LightconeClientBuilder {\n this.transactionSponsorshipEnabledValue = enabled;\n return this;\n }\n\n /** Set explicit v1 limits and total priority fee lamports for fluent builders and SOL plans. */\n transactionResources(resources: V1ResourceConfig): LightconeClientBuilder {\n validateV1Resources(resources);\n this.transactionResourcesValue = Object.freeze({ ...resources });\n return this;\n }\n\n /** Set the one-attempt fetch transport for v1 RPC, for example to add RPC authentication headers. */\n rpcFetch(transport: typeof fetch): LightconeClientBuilder {\n this.rpcFetchValue = transport;\n return this;\n }\n\n rpcUrl(url: string): LightconeClientBuilder {\n this.primaryRpcUrlValue = url;\n return this;\n }\n\n /** Set a backup Solana RPC URL for automatic failover. */\n backupRpcUrl(url: string): LightconeClientBuilder {\n this.backupRpcUrlValue = url;\n return this;\n }\n\n build(): LightconeClient {\n return new LightconeClient({\n http: new LightconeHttp(this.baseUrlValue, { apiKey: this.apiKeyValue }),\n wsConfig: {\n url: this.wsUrlValue,\n reconnect: true,\n maxReconnectAttempts: 10,\n baseReconnectDelayMs: 1_000,\n pingIntervalMs: 30_000,\n pongTimeoutMs: 10_000,\n },\n programId: this.programIdValue,\n depositSource: this.depositSourceValue,\n signingStrategy: this.signingStrategyValue,\n transactionSponsorshipEnabled: this.transactionSponsorshipEnabledValue,\n primaryConnection: this.primaryRpcUrlValue\n ? new Connection(this.primaryRpcUrlValue, { commitment: \"confirmed\", fetch: this.rpcFetchValue })\n : undefined,\n backupConnection: this.backupRpcUrlValue\n ? new Connection(this.backupRpcUrlValue, { commitment: \"confirmed\", fetch: this.rpcFetchValue })\n : undefined,\n transactionResources: this.transactionResourcesValue,\n rpcFetch: this.rpcFetchValue,\n authCredentials: this.authCredentials,\n });\n }\n}\n"]}
|
package/dist/http/client.d.ts
CHANGED
|
@@ -1,7 +1,20 @@
|
|
|
1
1
|
import type { CredentialRestorer } from "./credentialRestorer";
|
|
2
2
|
import { type RetryPolicy } from "./retry";
|
|
3
|
+
/** Request header that carries an API key. */
|
|
4
|
+
export declare const API_KEY_HEADER = "x-lightcone-api-key";
|
|
5
|
+
export interface LightconeHttpOptions {
|
|
6
|
+
/**
|
|
7
|
+
* API key sent as `x-lightcone-api-key` only on order submission,
|
|
8
|
+
* cancellation, and cancel-all POSTs at the configured API origin.
|
|
9
|
+
* Public reads, authentication, and WebSockets do not receive it.
|
|
10
|
+
* Keep it outside browser bundles. It identifies an API Consumer,
|
|
11
|
+
* never a user, and does not replace user or signed-order authorization.
|
|
12
|
+
*/
|
|
13
|
+
apiKey?: string;
|
|
14
|
+
}
|
|
3
15
|
export declare class LightconeHttp {
|
|
4
16
|
private readonly normalizedBaseUrl;
|
|
17
|
+
private readonly apiKey;
|
|
5
18
|
private authToken;
|
|
6
19
|
private credentialRestorer;
|
|
7
20
|
/**
|
|
@@ -35,7 +48,9 @@ export declare class LightconeHttp {
|
|
|
35
48
|
private lastRestoreOutcome;
|
|
36
49
|
/** Overridable for tests (hung-restorer coverage at test speed). */
|
|
37
50
|
private credentialRestoreTimeoutMs;
|
|
38
|
-
constructor(baseUrl: string);
|
|
51
|
+
constructor(baseUrl: string, options?: LightconeHttpOptions);
|
|
52
|
+
/** True when an API key is configured on this transport. */
|
|
53
|
+
hasApiKey(): boolean;
|
|
39
54
|
/**
|
|
40
55
|
* Run — or share — a credential restoration for a logical request that
|
|
41
56
|
* began at `startEpoch`. Returns whether replaying is worthwhile. Restorer
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/http/client.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAE/D,OAAO,EAIL,KAAK,WAAW,EACjB,MAAM,SAAS,CAAC;AA0CjB,qBAAa,aAAa;IACxB,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAS;IAC3C,OAAO,CAAC,SAAS,CAAqB;IACtC,OAAO,CAAC,kBAAkB,CAAiC;IAC3D;;;;OAIG;IACH,OAAO,CAAC,kBAAkB,CAAiC;IAC3D;;;;;;OAMG;IACH,OAAO,CAAC,gBAAgB,CAAgC;IACxD;;;;;;OAMG;IACH,OAAO,CAAC,mBAAmB,CAAiC;IAC5D;;;;OAIG;IACH,OAAO,CAAC,gBAAgB,CAAK;IAC7B,OAAO,CAAC,kBAAkB,CAAS;IACnC,oEAAoE;IACpE,OAAO,CAAC,0BAA0B,CAAiC;gBAEvD,OAAO,EAAE,MAAM;
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/http/client.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAE/D,OAAO,EAIL,KAAK,WAAW,EACjB,MAAM,SAAS,CAAC;AA0CjB,8CAA8C;AAC9C,eAAO,MAAM,cAAc,wBAAwB,CAAC;AAEpD,MAAM,WAAW,oBAAoB;IACnC;;;;;;OAMG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,qBAAa,aAAa;IACxB,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAS;IAC3C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAqB;IAC5C,OAAO,CAAC,SAAS,CAAqB;IACtC,OAAO,CAAC,kBAAkB,CAAiC;IAC3D;;;;OAIG;IACH,OAAO,CAAC,kBAAkB,CAAiC;IAC3D;;;;;;OAMG;IACH,OAAO,CAAC,gBAAgB,CAAgC;IACxD;;;;;;OAM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IAWb;;;;;;;OAOG;IACG,4BAA4B,CAAC,CAAC,EAAE,CAAC,SAAS,MAAM,EACpD,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,CAAC,EACP,KAAK,EAAE,WAAW,GACjB,OAAO,CAAC,CAAC,CAAC;IAIb;;;;;;;OAOG;IACG,cAAc,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC;IAc1F;;;;;;OAMG;IACG,2BAA2B,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,WAAW,GAAG,OAAO,CAAC,CAAC,CAAC;YAInE,gBAAgB;YA6FhB,WAAW;YAiBX,WAAW;IA+FzB,OAAO,CAAC,cAAc;IAStB,OAAO,CAAC,YAAY;IAepB,OAAO,CAAC,cAAc;IAgBtB,OAAO,CAAC,gBAAgB;CAOzB"}
|
package/dist/http/client.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.LightconeHttp = void 0;
|
|
3
|
+
exports.LightconeHttp = exports.API_KEY_HEADER = void 0;
|
|
4
4
|
const error_1 = require("../error");
|
|
5
5
|
const api_response_1 = require("../shared/api_response");
|
|
6
6
|
const json_1 = require("../shared/json");
|
|
@@ -36,8 +36,11 @@ const NO_RETRY_CONFIG = {
|
|
|
36
36
|
* SDK call ends up awaiting its own restoration degrades to a propagated 401
|
|
37
37
|
* after this bound instead of deadlocking. */
|
|
38
38
|
const CREDENTIAL_RESTORE_TIMEOUT_MS = 30_000;
|
|
39
|
+
/** Request header that carries an API key. */
|
|
40
|
+
exports.API_KEY_HEADER = "x-lightcone-api-key";
|
|
39
41
|
class LightconeHttp {
|
|
40
42
|
normalizedBaseUrl;
|
|
43
|
+
apiKey;
|
|
41
44
|
authToken;
|
|
42
45
|
credentialRestorer;
|
|
43
46
|
/**
|
|
@@ -71,8 +74,20 @@ class LightconeHttp {
|
|
|
71
74
|
lastRestoreOutcome = false;
|
|
72
75
|
/** Overridable for tests (hung-restorer coverage at test speed). */
|
|
73
76
|
credentialRestoreTimeoutMs = CREDENTIAL_RESTORE_TIMEOUT_MS;
|
|
74
|
-
constructor(baseUrl) {
|
|
77
|
+
constructor(baseUrl, options = {}) {
|
|
75
78
|
this.normalizedBaseUrl = baseUrl.replace(/\/+$/, "");
|
|
79
|
+
const apiKey = options.apiKey?.trim();
|
|
80
|
+
if (apiKey && isBrowserRuntime()) {
|
|
81
|
+
throw new Error("API keys may only be configured in server-side SDK builds");
|
|
82
|
+
}
|
|
83
|
+
if (apiKey && !isSecureApiKeyOrigin(this.normalizedBaseUrl)) {
|
|
84
|
+
throw new Error("API keys require HTTPS or a loopback HTTP origin");
|
|
85
|
+
}
|
|
86
|
+
this.apiKey = apiKey ? apiKey : undefined;
|
|
87
|
+
}
|
|
88
|
+
/** True when an API key is configured on this transport. */
|
|
89
|
+
hasApiKey() {
|
|
90
|
+
return this.apiKey !== undefined;
|
|
76
91
|
}
|
|
77
92
|
/**
|
|
78
93
|
* Run — or share — a credential restoration for a logical request that
|
|
@@ -315,10 +330,16 @@ class LightconeHttp {
|
|
|
315
330
|
headers["Content-Type"] = "application/json";
|
|
316
331
|
}
|
|
317
332
|
headers["x-request-id"] = requestId;
|
|
333
|
+
// Keys accompany only trading mutations at the configured API origin.
|
|
334
|
+
// Public reads, authentication, and arbitrary external calls stay key-free.
|
|
335
|
+
if (this.apiKey !== undefined && this.isApiOrigin(url) && method === "POST"
|
|
336
|
+
&& ["/api/orders/submit", "/api/orders/cancel", "/api/orders/cancel-all"].includes(new URL(url).pathname)) {
|
|
337
|
+
headers[exports.API_KEY_HEADER] = this.apiKey;
|
|
338
|
+
}
|
|
318
339
|
// Cookie injection is origin-gated: session credentials only ride to the
|
|
319
340
|
// configured API origin, never to an arbitrary absolute URL a caller
|
|
320
341
|
// supplies. In a browser the runtime owns cookie scoping instead.
|
|
321
|
-
if (!
|
|
342
|
+
if (!isBrowserRuntime() && this.isApiOrigin(url)) {
|
|
322
343
|
const cookie = this.cookieHeader(authMode);
|
|
323
344
|
if (cookie) {
|
|
324
345
|
headers.Cookie = cookie;
|
|
@@ -344,7 +365,7 @@ class LightconeHttp {
|
|
|
344
365
|
// branch is an explicit "omit" because the fetch default is
|
|
345
366
|
// "same-origin" — a URL foreign to the API but matching the PAGE
|
|
346
367
|
// origin would still get that origin's cookies.
|
|
347
|
-
...(
|
|
368
|
+
...(isBrowserRuntime()
|
|
348
369
|
? {
|
|
349
370
|
credentials: (this.isApiOrigin(url)
|
|
350
371
|
? "include"
|
|
@@ -369,7 +390,7 @@ class LightconeHttp {
|
|
|
369
390
|
// Set-Cookie into the process-wide token slot would leak that user's
|
|
370
391
|
// rotated token to every later request from a shared server client
|
|
371
392
|
// (the python SDK has always skipped this; typescript now matches).
|
|
372
|
-
if (!
|
|
393
|
+
if (!isBrowserRuntime() && authMode.kind !== "cookieOverride") {
|
|
373
394
|
this.captureCookies(response);
|
|
374
395
|
}
|
|
375
396
|
const text = await response.text();
|
|
@@ -394,7 +415,7 @@ class LightconeHttp {
|
|
|
394
415
|
}
|
|
395
416
|
}
|
|
396
417
|
cookieHeader(authMode) {
|
|
397
|
-
if (
|
|
418
|
+
if (isBrowserRuntime()) {
|
|
398
419
|
return undefined;
|
|
399
420
|
}
|
|
400
421
|
switch (authMode.kind) {
|
|
@@ -501,4 +522,19 @@ function escapeRegExp(value) {
|
|
|
501
522
|
function hasBrowserWindow() {
|
|
502
523
|
return typeof globalThis !== "undefined" && "window" in globalThis;
|
|
503
524
|
}
|
|
525
|
+
function isBrowserRuntime() {
|
|
526
|
+
// Browser workers have no `window`, but still must not accept a server key.
|
|
527
|
+
return hasBrowserWindow() || "importScripts" in globalThis;
|
|
528
|
+
}
|
|
529
|
+
function isSecureApiKeyOrigin(baseUrl) {
|
|
530
|
+
try {
|
|
531
|
+
const url = new URL(baseUrl);
|
|
532
|
+
return url.protocol === "https:" ||
|
|
533
|
+
(url.protocol === "http:" &&
|
|
534
|
+
["localhost", "127.0.0.1", "[::1]"].includes(url.hostname));
|
|
535
|
+
}
|
|
536
|
+
catch {
|
|
537
|
+
return false;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
504
540
|
//# sourceMappingURL=client.js.map
|
package/dist/http/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/http/client.ts"],"names":[],"mappings":";;;AAAA,oCAA+C;AAC/C,yDAIgC;AAEhC,yCAAoE;AACpE,mCAKiB;AAMjB,MAAM,uBAAuB,GAAG,OAAO,CAAC;AAExC,MAAM,eAAgB,SAAQ,KAAK;IACxB,MAAM,CAAS;IACf,IAAI,CAAS;IACb,OAAO,CAAU;IACjB,SAAS,CAAS;IAE3B,YAAY,MAAc,EAAE,IAAY,EAAE,OAAgB,EAAE,SAAiB;QAC3E,KAAK,CAAC,eAAe,MAAM,KAAK,IAAI,EAAE,CAAC,CAAC;QACxC,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;QAC9B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC7B,CAAC;CACF;AAED;;2BAE2B;AAC3B,MAAM,eAAe,GAAgB;IACnC,UAAU,EAAE,CAAC;IACb,cAAc,EAAE,CAAC;IACjB,UAAU,EAAE,CAAC;IACb,aAAa,EAAE,CAAC;IAChB,MAAM,EAAE,KAAK;IACb,iBAAiB,EAAE,EAAE;CACtB,CAAC;AAEF;;;8CAG8C;AAC9C,MAAM,6BAA6B,GAAG,MAAM,CAAC;AAE7C,MAAa,aAAa;IACP,iBAAiB,CAAS;IACnC,SAAS,CAAqB;IAC9B,kBAAkB,CAAi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GAAG,MAAM,CAAC,KAAK,CACxB,IAAI,MAAM,CAAC,cAAc,YAAY,CAAC,IAAI,CAAC,WAAW,CAAC,CACxD,CAAC;IACF,OAAO,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC;AAED,SAAS,YAAY,CAAC,KAAa;IACjC,OAAO,KAAK,CAAC,OAAO,CAAC,qBAAqB,EAAE,MAAM,CAAC,CAAC;AACtD,CAAC;AAED,SAAS,gBAAgB;IACvB,OAAO,OAAO,UAAU,KAAK,WAAW,IAAI,QAAQ,IAAI,UAAU,CAAC;AACrE,CAAC","sourcesContent":["import { HttpError, SdkError } from \"../error\";\nimport {\n ApiRejectedDetails,\n isApiResponse,\n type ApiResponse,\n} from \"../shared/api_response\";\nimport type { CredentialRestorer } from \"./credentialRestorer\";\nimport { parseJsonExact, stringifyJsonExact } from \"../shared/json\";\nimport {\n delayForAttempt,\n retryConfigForPolicy,\n type RetryConfig,\n type RetryPolicy,\n} from \"./retry\";\n\ntype AuthMode =\n | { kind: \"cookie\" }\n | { kind: \"cookieOverride\"; cookieHeader: string };\n\nconst DEFAULT_HTTP_TIMEOUT_MS = 180_000;\n\nclass HttpStatusError extends Error {\n readonly status: number;\n readonly body: string;\n readonly headers: Headers;\n readonly requestId: string;\n\n constructor(status: number, body: string, headers: Headers, requestId: string) {\n super(`HTTP status ${status}: ${body}`);\n this.name = \"HttpStatusError\";\n this.status = status;\n this.body = body;\n this.headers = headers;\n this.requestId = requestId;\n }\n}\n\n/** Zero-retry config for `RetryPolicy.None`: requests still run through the\n * retry loop so the credential-restore path covers every request, including\n * non-idempotent POSTs. */\nconst NO_RETRY_CONFIG: RetryConfig = {\n maxRetries: 0,\n initialDelayMs: 0,\n maxDelayMs: 0,\n backoffFactor: 1,\n jitter: false,\n retryableStatuses: [],\n};\n\n/** Upper bound on waiting for (or running) a credential restoration. Also the\n * rescue path for restorer reentrancy: a restorer whose own restore-enabled\n * SDK call ends up awaiting its own restoration degrades to a propagated 401\n * after this bound instead of deadlocking. */\nconst CREDENTIAL_RESTORE_TIMEOUT_MS = 30_000;\n\nexport class LightconeHttp {\n private readonly normalizedBaseUrl: string;\n private authToken: string | undefined;\n private credentialRestorer: CredentialRestorer | undefined;\n /**\n * The in-flight restoration, shared by every request that 401s while it\n * runs — concurrent 401s await the same promise (bounded by the timeout)\n * instead of failing fast. Cleared when the restoration settles.\n */\n private restorationPromise: Promise<boolean> | null = null;\n /**\n * Abort handle for the in-flight restoration, set and cleared with\n * `restorationPromise`. Fired when the restoration's deadline abandons it:\n * promises cannot be cancelled, so this is the signal a well-behaved\n * restorer uses to stop instead of running on concurrently with the next\n * restoration.\n */\n private restorationAbort: AbortController | null = null;\n /**\n * The restoration's own deadline, created WITH the restoration and shared\n * by every waiter. Racing each waiter against its own fresh timer instead\n * would let a late joiner outlive the leader's timeout and accept a `true`\n * from a zombie restorer while a replacement restoration is already\n * running.\n */\n private restorationDeadline: Promise<boolean> | null = null;\n /**\n * Bumped after every completed restoration. A request captures the epoch\n * when it starts; if the epoch moved by the time its 401 gets to restore,\n * another request already restored and the stored outcome is reused.\n */\n private restorationEpoch = 0;\n private lastRestoreOutcome = false;\n /** Overridable for tests (hung-restorer coverage at test speed). */\n private credentialRestoreTimeoutMs = CREDENTIAL_RESTORE_TIMEOUT_MS;\n\n constructor(baseUrl: string) {\n this.normalizedBaseUrl = baseUrl.replace(/\\/+$/, \"\");\n }\n\n /**\n * Run — or share — a credential restoration for a logical request that\n * began at `startEpoch`. Returns whether replaying is worthwhile. Restorer\n * rejections count as \"not restored\" so the caller's original 401 is\n * preserved (a callback failure must not replace the auth error).\n */\n private async restoreCredentialsShared(startEpoch: number): Promise<boolean> {\n if (this.restorationEpoch !== startEpoch) {\n // Another request completed a restoration after this one began — its\n // outcome applies to our credentials too.\n return this.lastRestoreOutcome;\n }\n if (!this.restorationPromise) {\n const restorer = this.credentialRestorer;\n if (!restorer) {\n return false;\n }\n const controller = new AbortController();\n const tracked: Promise<boolean> = (async () => {\n try {\n return await restorer(controller.signal);\n } catch (error) {\n console.warn(\"Credential restorer threw; propagating the original 401\", error);\n return false;\n }\n })().then((outcome) => {\n // Only record the outcome if this restoration still owns the slot —\n // an abandoned (timed-out) restoration settling late must not bump\n // the epoch or clobber a newer restoration.\n if (this.restorationPromise === tracked) {\n this.restorationEpoch += 1;\n this.lastRestoreOutcome = outcome;\n this.restorationPromise = null;\n this.restorationAbort = null;\n this.restorationDeadline = null;\n }\n return outcome;\n });\n this.restorationPromise = tracked;\n this.restorationAbort = controller;\n this.restorationDeadline = new Promise<boolean>((resolve) => {\n const timer = setTimeout(() => resolve(false), this.credentialRestoreTimeoutMs);\n // Node: don't hold the process open for the bound; no-op in browsers.\n (timer as { unref?: () => void }).unref?.();\n });\n }\n // Bound the wait with the RESTORATION's deadline (shared by all waiters),\n // not a per-waiter timer: a hung restorer (or a restorer awaiting itself\n // through a restore-enabled nested call) fails every waiting request with\n // its original 401 at the same moment, and no waiter is left listening to\n // an abandoned restoration after that.\n const awaited = this.restorationPromise;\n const deadline = this.restorationDeadline ?? Promise.resolve(false);\n const outcome = await Promise.race([awaited, deadline]);\n if (!outcome && this.restorationPromise === awaited) {\n // Timed out with the restoration still pending (a settled restoration\n // clears the slot itself): abort it — promises can't be cancelled, so\n // the signal is how a well-behaved restorer stops instead of racing the\n // next restoration — and drop the slot so the client isn't stuck\n // \"restoring\" forever. The next 401 starts a fresh restoration.\n // Identity-guarded: concurrent waiters all observe the same deadline,\n // and only the first one through here does the teardown.\n this.restorationAbort?.abort();\n this.restorationPromise = null;\n this.restorationAbort = null;\n this.restorationDeadline = null;\n }\n return outcome;\n }\n\n /**\n * True when `url` shares the configured API origin. Session credentials are\n * only injected — and the credential restorer only consulted — for\n * same-origin requests: a foreign URL that answers 401 must be able to\n * neither trigger a restoration nor receive the restored cookie on a\n * replay. Unparseable URLs count as foreign.\n */\n private isApiOrigin(url: string): boolean {\n try {\n return new URL(url).origin === new URL(this.normalizedBaseUrl).origin;\n } catch {\n return false;\n }\n }\n\n baseUrl(): string {\n return this.normalizedBaseUrl;\n }\n\n async clearAuthToken(): Promise<void> {\n this.authToken = undefined;\n }\n\n /**\n * Register (or replace) the credential restorer consulted on HTTP 401 —\n * see {@link CredentialRestorer}. Pass through\n * `LightconeClient.setCredentialRestorer` in normal use.\n */\n setCredentialRestorer(restorer: CredentialRestorer): void {\n this.credentialRestorer = restorer;\n }\n\n /** Remove the credential restorer; 401s propagate to callers unchanged. */\n clearCredentialRestorer(): void {\n this.credentialRestorer = undefined;\n }\n\n authTokenRef(): () => Promise<string | undefined> {\n return async () => this.authToken;\n }\n\n async get<T>(url: string, retry: RetryPolicy): Promise<T> {\n return this.requestWithRetry<T>(\"GET\", url, undefined, retry, { kind: \"cookie\" });\n }\n\n async post<T, B extends object>(url: string, body: B, retry: RetryPolicy): Promise<T> {\n return this.requestWithRetry<T>(\"POST\", url, body, retry, { kind: \"cookie\" });\n }\n\n async delete<T>(url: string, retry: RetryPolicy): Promise<T> {\n return this.requestWithRetry<T>(\"DELETE\", url, undefined, retry, { kind: \"cookie\" });\n }\n\n async postWithCookies<T, B extends object>(\n url: string,\n body: B,\n retry: RetryPolicy,\n cookieHeader: string\n ): Promise<T> {\n return this.requestWithRetry<T>(\n \"POST\",\n url,\n body,\n retry,\n { kind: \"cookieOverride\", cookieHeader },\n false\n );\n }\n\n async deleteWithCookies<T>(\n url: string,\n retry: RetryPolicy,\n cookieHeader: string\n ): Promise<T> {\n return this.requestWithRetry<T>(\n \"DELETE\",\n url,\n undefined,\n retry,\n { kind: \"cookieOverride\", cookieHeader },\n false\n );\n }\n\n /**\n * POST with the 401 credential-restore-and-replay disabled. For\n * credential-management endpoints (login, logout): they are the machinery\n * restoration would re-run, so replaying them after restoring credentials\n * is at best a no-op and at worst re-consumes single-use state (the login\n * nonce is consumed server-side before the signature is verified, so a\n * replayed login deterministically fails).\n */\n async postWithoutCredentialRestore<T, B extends object>(\n url: string,\n body: B,\n retry: RetryPolicy\n ): Promise<T> {\n return this.requestWithRetry<T>(\"POST\", url, body, retry, { kind: \"cookie\" }, false);\n }\n\n /**\n * GET with retry, forwarding an explicit per-call raw `Cookie` header\n * (e.g. `privy-token=…; lightcone-token=…`) instead of the SDK's process-wide\n * cookie store. Intended for server-side cookie forwarding (SSR / server\n * functions) where the per-request browser cookies can't propagate to the\n * shared client. In a browser context this is equivalent to {@link get} — the\n * runtime is already attaching cookies via `credentials: \"include\"`.\n */\n async getWithCookies<T>(url: string, retry: RetryPolicy, cookieHeader: string): Promise<T> {\n return this.requestWithRetry<T>(\n \"GET\",\n url,\n undefined,\n retry,\n { kind: \"cookieOverride\", cookieHeader },\n // Forwarded per-user cookies are outside the global credential\n // machinery: the process-wide restorer can't mint a new cookie for\n // THIS user, and a replay would resend the same stale header.\n false\n );\n }\n\n /**\n * GET with the 401 credential restoration disabled. Use this (and\n * {@link postWithoutCredentialRestore}) inside credential restorers for any\n * SDK calls the restorer itself makes: a restore-enabled call from inside a\n * restorer ends up awaiting its own restoration and only the restoration\n * timeout rescues it.\n */\n async getWithoutCredentialRestore<T>(url: string, retry: RetryPolicy): Promise<T> {\n return this.requestWithRetry<T>(\"GET\", url, undefined, retry, { kind: \"cookie\" }, false);\n }\n\n private async requestWithRetry<T>(\n method: \"GET\" | \"POST\" | \"DELETE\",\n url: string,\n body: object | undefined,\n policy: RetryPolicy,\n authMode: AuthMode,\n allowCredentialRestore = true\n ): Promise<T> {\n // `None` still means \"no transport retries\"; it runs through the same\n // loop with zero retry attempts so the credential-restore path below\n // covers every request. It ALSO means \"never auto-replay\": mutations\n // declare themselves non-idempotent via RetryPolicy.None, so a 401 still\n // triggers restoration (healing the session for the caller's next\n // attempt) but the 401 propagates instead of replaying.\n const replayAllowed = policy.kind !== \"none\";\n const config = retryConfigForPolicy(policy) ?? NO_RETRY_CONFIG;\n\n // One request id and one body serialization per LOGICAL request:\n // transport retries and the auth replay resend the same id (tracing\n // correlation, and the hook for future server-side idempotency) and the\n // same bytes (a mutable body can't drift between attempts).\n const requestId = generateRequestId();\n const bodyText = body === undefined ? undefined : stringifyJsonExact(body);\n\n const startEpoch = this.restorationEpoch;\n let credentialsRestored = false;\n let attempt = 0;\n\n for (;;) {\n try {\n const apiResponse = await this.sendRequest<ApiResponse<T>>(\n method,\n url,\n bodyText,\n authMode,\n requestId\n );\n return parseApiResponse<T>(apiResponse, requestId);\n } catch (error) {\n if (error instanceof HttpStatusError) {\n // On the first 401, give the host a chance to restore its\n // credentials (e.g. refresh an auth session) — at most once per\n // logical request, shared with any concurrent requests (see\n // restoreCredentialsShared), and only for requests to the API\n // origin whose endpoint allows it (login/logout opt out). The\n // replay itself additionally requires the request to have\n // declared itself retry-safe.\n if (\n !credentialsRestored &&\n allowCredentialRestore &&\n error.status === 401 &&\n this.isApiOrigin(url)\n ) {\n credentialsRestored = true;\n const restored = await this.restoreCredentialsShared(startEpoch);\n if (restored && replayAllowed) {\n continue;\n }\n }\n\n const shouldRetry = config.retryableStatuses.includes(error.status);\n if (!shouldRetry || attempt >= config.maxRetries) {\n throw this.statusErrorToSdk(error);\n }\n\n const retryAfter = retryAfterMs(error.headers);\n const delay = retryAfter ?? delayForAttempt(config, attempt);\n attempt += 1;\n\n await sleep(delay);\n continue;\n }\n\n if (!(error instanceof HttpError)) {\n throw error;\n }\n\n const shouldRetry = await this.shouldRetry(\n error,\n config.retryableStatuses\n );\n if (!shouldRetry || attempt >= config.maxRetries) {\n throw error;\n }\n\n const delay = delayForAttempt(config, attempt);\n attempt += 1;\n\n await sleep(delay);\n }\n }\n }\n\n private async shouldRetry(\n error: HttpError,\n retryableStatuses: readonly number[]\n ): Promise<boolean> {\n switch (error.variant) {\n case \"Timeout\":\n case \"Request\":\n return true;\n case \"RateLimited\":\n return retryableStatuses.includes(429);\n case \"ServerError\":\n return error.status !== undefined && retryableStatuses.includes(error.status);\n default:\n return false;\n }\n }\n\n private async sendRequest<T>(\n method: \"GET\" | \"POST\" | \"DELETE\",\n url: string,\n bodyText: string | undefined,\n authMode: AuthMode,\n requestId: string\n ): Promise<T> {\n const headers: Record<string, string> = {};\n\n if (bodyText !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n }\n headers[\"x-request-id\"] = requestId;\n\n // Cookie injection is origin-gated: session credentials only ride to the\n // configured API origin, never to an arbitrary absolute URL a caller\n // supplies. In a browser the runtime owns cookie scoping instead.\n if (!hasBrowserWindow() && this.isApiOrigin(url)) {\n const cookie = this.cookieHeader(authMode);\n if (cookie) {\n headers.Cookie = cookie;\n }\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), DEFAULT_HTTP_TIMEOUT_MS);\n\n let response: Response;\n\n try {\n response = await fetch(url, {\n method,\n headers,\n body: bodyText,\n signal: controller.signal,\n // The API never legitimately redirects; following one would let a\n // redirect target observe the request while origin checks still see\n // the original URL. A 3xx therefore surfaces as an error below.\n redirect: \"manual\",\n // Browser credentials mode is origin-gated like the Cookie header\n // above: the browser's own cookie scoping already keeps the API\n // cookie off foreign origins, this just avoids asking it to attach\n // ANY cookies to a URL the SDK shouldn't be talking to. The foreign\n // branch is an explicit \"omit\" because the fetch default is\n // \"same-origin\" — a URL foreign to the API but matching the PAGE\n // origin would still get that origin's cookies.\n ...(hasBrowserWindow()\n ? {\n credentials: (this.isApiOrigin(url)\n ? \"include\"\n : \"omit\") as RequestCredentials,\n }\n : {}),\n });\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof Error && error.name === \"AbortError\") {\n throw HttpError.timeout();\n }\n throw HttpError.request(error instanceof Error ? error.message : String(error));\n } finally {\n clearTimeout(timeoutId);\n }\n\n if (response.ok) {\n // Capture only for the built-in session: a cookieOverride request\n // carries one specific user's forwarded cookies, and capturing its\n // Set-Cookie into the process-wide token slot would leak that user's\n // rotated token to every later request from a shared server client\n // (the python SDK has always skipped this; typescript now matches).\n if (!hasBrowserWindow() && authMode.kind !== \"cookieOverride\") {\n this.captureCookies(response);\n }\n\n const text = await response.text();\n let payload: T;\n try {\n payload = parseJsonExact<T>(text);\n } catch (e) {\n throw HttpError.request(e instanceof Error ? e.message : \"JSON parse failed\");\n }\n\n return payload;\n }\n\n const errorBody = await response.text().catch(() => \"\");\n throw new HttpStatusError(response.status, errorBody, response.headers, requestId);\n }\n\n private captureCookies(response: Response): void {\n for (const cookieHeader of getSetCookieHeaders(response.headers)) {\n const authToken = extractCookieValue(cookieHeader, \"lightcone-token\");\n if (authToken) {\n this.authToken = authToken;\n }\n }\n }\n\n private cookieHeader(authMode: AuthMode): string | undefined {\n if (hasBrowserWindow()) {\n return undefined;\n }\n\n switch (authMode.kind) {\n case \"cookieOverride\":\n // Forward the supplied Cookie header verbatim (may carry privy-token\n // and/or lightcone-token).\n return authMode.cookieHeader;\n case \"cookie\":\n return this.authToken ? `lightcone-token=${this.authToken}` : undefined;\n }\n }\n\n private mapStatusError(statusCode: number, bodyText: string, headers: Headers): HttpError {\n if (statusCode === 401) {\n return HttpError.unauthorized();\n }\n if (statusCode === 404) {\n return HttpError.notFound(bodyText);\n }\n if (statusCode === 429) {\n return HttpError.rateLimited(retryAfterMs(headers));\n }\n if (statusCode >= 400 && statusCode < 500) {\n return HttpError.badRequest(bodyText);\n }\n return HttpError.serverError(statusCode, bodyText);\n }\n\n private statusErrorToSdk(error: HttpStatusError): Error {\n const rejected = parseRejectedBody(error.body, error.requestId, error.status);\n if (rejected) {\n return rejected;\n }\n return this.mapStatusError(error.status, error.body, error.headers);\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\nfunction parseApiResponse<T>(payload: unknown, requestId: string): T {\n if (!isApiResponse<T>(payload)) {\n throw SdkError.serde(\"Invalid ApiResponse envelope\");\n }\n\n if (payload.status === \"success\") {\n return payload.body;\n }\n\n throw SdkError.apiRejected(\n ApiRejectedDetails.fromWire(payload.error_details, requestId)\n );\n}\n\nfunction parseRejectedBody(\n body: string,\n requestId: string,\n httpStatus: number\n): SdkError | undefined {\n let payload: unknown;\n try {\n payload = parseJsonExact(body);\n } catch {\n return undefined;\n }\n\n if (!isApiResponse<unknown>(payload) || payload.status !== \"error\") {\n return undefined;\n }\n\n return SdkError.apiRejected(\n ApiRejectedDetails.fromWire(payload.error_details, requestId, httpStatus)\n );\n}\n\nfunction generateRequestId(): string {\n if (typeof globalThis.crypto?.randomUUID === \"function\") {\n return globalThis.crypto.randomUUID();\n }\n\n return `lc-${Date.now()}-${Math.random().toString(16).slice(2)}`;\n}\n\nfunction getSetCookieHeaders(headers: Headers): string[] {\n const headersWithCookies = headers as Headers & {\n getSetCookie?: () => string[];\n };\n\n if (typeof headersWithCookies.getSetCookie === \"function\") {\n const values = headersWithCookies.getSetCookie();\n if (values.length > 0) {\n return values;\n }\n }\n\n const combined = headers.get(\"set-cookie\");\n return combined ? [combined] : [];\n}\n\nfunction retryAfterMs(headers: Headers): number | undefined {\n const retryAfterMsValue = headers.get(\"retry-after-ms\");\n if (retryAfterMsValue) {\n const parsed = Number.parseInt(retryAfterMsValue, 10);\n if (Number.isFinite(parsed)) {\n return parsed;\n }\n }\n\n const retryAfterValue = headers.get(\"retry-after\");\n if (retryAfterValue) {\n const parsed = Number.parseFloat(retryAfterValue);\n if (Number.isFinite(parsed)) {\n return Math.round(parsed * 1000);\n }\n }\n\n return undefined;\n}\n\nfunction extractCookieValue(header: string, name: string): string | undefined {\n const match = header.match(\n new RegExp(`(?:^|,\\\\s*)${escapeRegExp(name)}=([^;,]+)`)\n );\n return match?.[1];\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction hasBrowserWindow(): boolean {\n return typeof globalThis !== \"undefined\" && \"window\" in globalThis;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/http/client.ts"],"names":[],"mappings":";;;AAAA,oCAA+C;AAC/C,yDAIgC;AAEhC,yCAAoE;AACpE,mCAKiB;AAMjB,MAAM,uBAAuB,GAAG,OAAO,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AQ,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC;IAClE,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC","sourcesContent":["import { HttpError, SdkError } from \"../error\";\nimport {\n ApiRejectedDetails,\n isApiResponse,\n type ApiResponse,\n} from \"../shared/api_response\";\nimport type { CredentialRestorer } from \"./credentialRestorer\";\nimport { parseJsonExact, stringifyJsonExact } from \"../shared/json\";\nimport {\n delayForAttempt,\n retryConfigForPolicy,\n type RetryConfig,\n type RetryPolicy,\n} from \"./retry\";\n\ntype AuthMode =\n | { kind: \"cookie\" }\n | { kind: \"cookieOverride\"; cookieHeader: string };\n\nconst DEFAULT_HTTP_TIMEOUT_MS = 180_000;\n\nclass HttpStatusError extends Error {\n readonly status: number;\n readonly body: string;\n readonly headers: Headers;\n readonly requestId: string;\n\n constructor(status: number, body: string, headers: Headers, requestId: string) {\n super(`HTTP status ${status}: ${body}`);\n this.name = \"HttpStatusError\";\n this.status = status;\n this.body = body;\n this.headers = headers;\n this.requestId = requestId;\n }\n}\n\n/** Zero-retry config for `RetryPolicy.None`: requests still run through the\n * retry loop so the credential-restore path covers every request, including\n * non-idempotent POSTs. */\nconst NO_RETRY_CONFIG: RetryConfig = {\n maxRetries: 0,\n initialDelayMs: 0,\n maxDelayMs: 0,\n backoffFactor: 1,\n jitter: false,\n retryableStatuses: [],\n};\n\n/** Upper bound on waiting for (or running) a credential restoration. Also the\n * rescue path for restorer reentrancy: a restorer whose own restore-enabled\n * SDK call ends up awaiting its own restoration degrades to a propagated 401\n * after this bound instead of deadlocking. */\nconst CREDENTIAL_RESTORE_TIMEOUT_MS = 30_000;\n\n/** Request header that carries an API key. */\nexport const API_KEY_HEADER = \"x-lightcone-api-key\";\n\nexport interface LightconeHttpOptions {\n /**\n * API key sent as `x-lightcone-api-key` only on order submission,\n * cancellation, and cancel-all POSTs at the configured API origin.\n * Public reads, authentication, and WebSockets do not receive it.\n * Keep it outside browser bundles. It identifies an API Consumer,\n * never a user, and does not replace user or signed-order authorization.\n */\n apiKey?: string;\n}\n\nexport class LightconeHttp {\n private readonly normalizedBaseUrl: string;\n private readonly apiKey: string | undefined;\n private authToken: string | undefined;\n private credentialRestorer: CredentialRestorer | undefined;\n /**\n * The in-flight restoration, shared by every request that 401s while it\n * runs — concurrent 401s await the same promise (bounded by the timeout)\n * instead of failing fast. Cleared when the restoration settles.\n */\n private restorationPromise: Promise<boolean> | null = null;\n /**\n * Abort handle for the in-flight restoration, set and cleared with\n * `restorationPromise`. Fired when the restoration's deadline abandons it:\n * promises cannot be cancelled, so this is the signal a well-behaved\n * restorer uses to stop instead of running on concurrently with the next\n * restoration.\n */\n private restorationAbort: AbortController | null = null;\n /**\n * The restoration's own deadline, created WITH the restoration and shared\n * by every waiter. Racing each waiter against its own fresh timer instead\n * would let a late joiner outlive the leader's timeout and accept a `true`\n * from a zombie restorer while a replacement restoration is already\n * running.\n */\n private restorationDeadline: Promise<boolean> | null = null;\n /**\n * Bumped after every completed restoration. A request captures the epoch\n * when it starts; if the epoch moved by the time its 401 gets to restore,\n * another request already restored and the stored outcome is reused.\n */\n private restorationEpoch = 0;\n private lastRestoreOutcome = false;\n /** Overridable for tests (hung-restorer coverage at test speed). */\n private credentialRestoreTimeoutMs = CREDENTIAL_RESTORE_TIMEOUT_MS;\n\n constructor(baseUrl: string, options: LightconeHttpOptions = {}) {\n this.normalizedBaseUrl = baseUrl.replace(/\\/+$/, \"\");\n const apiKey = options.apiKey?.trim();\n if (apiKey && isBrowserRuntime()) {\n throw new Error(\"API keys may only be configured in server-side SDK builds\");\n }\n if (apiKey && !isSecureApiKeyOrigin(this.normalizedBaseUrl)) {\n throw new Error(\"API keys require HTTPS or a loopback HTTP origin\");\n }\n this.apiKey = apiKey ? apiKey : undefined;\n }\n\n /** True when an API key is configured on this transport. */\n hasApiKey(): boolean {\n return this.apiKey !== undefined;\n }\n\n /**\n * Run — or share — a credential restoration for a logical request that\n * began at `startEpoch`. Returns whether replaying is worthwhile. Restorer\n * rejections count as \"not restored\" so the caller's original 401 is\n * preserved (a callback failure must not replace the auth error).\n */\n private async restoreCredentialsShared(startEpoch: number): Promise<boolean> {\n if (this.restorationEpoch !== startEpoch) {\n // Another request completed a restoration after this one began — its\n // outcome applies to our credentials too.\n return this.lastRestoreOutcome;\n }\n if (!this.restorationPromise) {\n const restorer = this.credentialRestorer;\n if (!restorer) {\n return false;\n }\n const controller = new AbortController();\n const tracked: Promise<boolean> = (async () => {\n try {\n return await restorer(controller.signal);\n } catch (error) {\n console.warn(\"Credential restorer threw; propagating the original 401\", error);\n return false;\n }\n })().then((outcome) => {\n // Only record the outcome if this restoration still owns the slot —\n // an abandoned (timed-out) restoration settling late must not bump\n // the epoch or clobber a newer restoration.\n if (this.restorationPromise === tracked) {\n this.restorationEpoch += 1;\n this.lastRestoreOutcome = outcome;\n this.restorationPromise = null;\n this.restorationAbort = null;\n this.restorationDeadline = null;\n }\n return outcome;\n });\n this.restorationPromise = tracked;\n this.restorationAbort = controller;\n this.restorationDeadline = new Promise<boolean>((resolve) => {\n const timer = setTimeout(() => resolve(false), this.credentialRestoreTimeoutMs);\n // Node: don't hold the process open for the bound; no-op in browsers.\n (timer as { unref?: () => void }).unref?.();\n });\n }\n // Bound the wait with the RESTORATION's deadline (shared by all waiters),\n // not a per-waiter timer: a hung restorer (or a restorer awaiting itself\n // through a restore-enabled nested call) fails every waiting request with\n // its original 401 at the same moment, and no waiter is left listening to\n // an abandoned restoration after that.\n const awaited = this.restorationPromise;\n const deadline = this.restorationDeadline ?? Promise.resolve(false);\n const outcome = await Promise.race([awaited, deadline]);\n if (!outcome && this.restorationPromise === awaited) {\n // Timed out with the restoration still pending (a settled restoration\n // clears the slot itself): abort it — promises can't be cancelled, so\n // the signal is how a well-behaved restorer stops instead of racing the\n // next restoration — and drop the slot so the client isn't stuck\n // \"restoring\" forever. The next 401 starts a fresh restoration.\n // Identity-guarded: concurrent waiters all observe the same deadline,\n // and only the first one through here does the teardown.\n this.restorationAbort?.abort();\n this.restorationPromise = null;\n this.restorationAbort = null;\n this.restorationDeadline = null;\n }\n return outcome;\n }\n\n /**\n * True when `url` shares the configured API origin. Session credentials are\n * only injected — and the credential restorer only consulted — for\n * same-origin requests: a foreign URL that answers 401 must be able to\n * neither trigger a restoration nor receive the restored cookie on a\n * replay. Unparseable URLs count as foreign.\n */\n private isApiOrigin(url: string): boolean {\n try {\n return new URL(url).origin === new URL(this.normalizedBaseUrl).origin;\n } catch {\n return false;\n }\n }\n\n baseUrl(): string {\n return this.normalizedBaseUrl;\n }\n\n async clearAuthToken(): Promise<void> {\n this.authToken = undefined;\n }\n\n /**\n * Register (or replace) the credential restorer consulted on HTTP 401 —\n * see {@link CredentialRestorer}. Pass through\n * `LightconeClient.setCredentialRestorer` in normal use.\n */\n setCredentialRestorer(restorer: CredentialRestorer): void {\n this.credentialRestorer = restorer;\n }\n\n /** Remove the credential restorer; 401s propagate to callers unchanged. */\n clearCredentialRestorer(): void {\n this.credentialRestorer = undefined;\n }\n\n authTokenRef(): () => Promise<string | undefined> {\n return async () => this.authToken;\n }\n\n async get<T>(url: string, retry: RetryPolicy): Promise<T> {\n return this.requestWithRetry<T>(\"GET\", url, undefined, retry, { kind: \"cookie\" });\n }\n\n async post<T, B extends object>(url: string, body: B, retry: RetryPolicy): Promise<T> {\n return this.requestWithRetry<T>(\"POST\", url, body, retry, { kind: \"cookie\" });\n }\n\n async delete<T>(url: string, retry: RetryPolicy): Promise<T> {\n return this.requestWithRetry<T>(\"DELETE\", url, undefined, retry, { kind: \"cookie\" });\n }\n\n async postWithCookies<T, B extends object>(\n url: string,\n body: B,\n retry: RetryPolicy,\n cookieHeader: string\n ): Promise<T> {\n return this.requestWithRetry<T>(\n \"POST\",\n url,\n body,\n retry,\n { kind: \"cookieOverride\", cookieHeader },\n false\n );\n }\n\n async deleteWithCookies<T>(\n url: string,\n retry: RetryPolicy,\n cookieHeader: string\n ): Promise<T> {\n return this.requestWithRetry<T>(\n \"DELETE\",\n url,\n undefined,\n retry,\n { kind: \"cookieOverride\", cookieHeader },\n false\n );\n }\n\n /**\n * POST with the 401 credential-restore-and-replay disabled. For\n * credential-management endpoints (login, logout): they are the machinery\n * restoration would re-run, so replaying them after restoring credentials\n * is at best a no-op and at worst re-consumes single-use state (the login\n * nonce is consumed server-side before the signature is verified, so a\n * replayed login deterministically fails).\n */\n async postWithoutCredentialRestore<T, B extends object>(\n url: string,\n body: B,\n retry: RetryPolicy\n ): Promise<T> {\n return this.requestWithRetry<T>(\"POST\", url, body, retry, { kind: \"cookie\" }, false);\n }\n\n /**\n * GET with retry, forwarding an explicit per-call raw `Cookie` header\n * (e.g. `privy-token=…; lightcone-token=…`) instead of the SDK's process-wide\n * cookie store. Intended for server-side cookie forwarding (SSR / server\n * functions) where the per-request browser cookies can't propagate to the\n * shared client. In a browser context this is equivalent to {@link get} — the\n * runtime is already attaching cookies via `credentials: \"include\"`.\n */\n async getWithCookies<T>(url: string, retry: RetryPolicy, cookieHeader: string): Promise<T> {\n return this.requestWithRetry<T>(\n \"GET\",\n url,\n undefined,\n retry,\n { kind: \"cookieOverride\", cookieHeader },\n // Forwarded per-user cookies are outside the global credential\n // machinery: the process-wide restorer can't mint a new cookie for\n // THIS user, and a replay would resend the same stale header.\n false\n );\n }\n\n /**\n * GET with the 401 credential restoration disabled. Use this (and\n * {@link postWithoutCredentialRestore}) inside credential restorers for any\n * SDK calls the restorer itself makes: a restore-enabled call from inside a\n * restorer ends up awaiting its own restoration and only the restoration\n * timeout rescues it.\n */\n async getWithoutCredentialRestore<T>(url: string, retry: RetryPolicy): Promise<T> {\n return this.requestWithRetry<T>(\"GET\", url, undefined, retry, { kind: \"cookie\" }, false);\n }\n\n private async requestWithRetry<T>(\n method: \"GET\" | \"POST\" | \"DELETE\",\n url: string,\n body: object | undefined,\n policy: RetryPolicy,\n authMode: AuthMode,\n allowCredentialRestore = true\n ): Promise<T> {\n // `None` still means \"no transport retries\"; it runs through the same\n // loop with zero retry attempts so the credential-restore path below\n // covers every request. It ALSO means \"never auto-replay\": mutations\n // declare themselves non-idempotent via RetryPolicy.None, so a 401 still\n // triggers restoration (healing the session for the caller's next\n // attempt) but the 401 propagates instead of replaying.\n const replayAllowed = policy.kind !== \"none\";\n const config = retryConfigForPolicy(policy) ?? NO_RETRY_CONFIG;\n\n // One request id and one body serialization per LOGICAL request:\n // transport retries and the auth replay resend the same id (tracing\n // correlation, and the hook for future server-side idempotency) and the\n // same bytes (a mutable body can't drift between attempts).\n const requestId = generateRequestId();\n const bodyText = body === undefined ? undefined : stringifyJsonExact(body);\n\n const startEpoch = this.restorationEpoch;\n let credentialsRestored = false;\n let attempt = 0;\n\n for (;;) {\n try {\n const apiResponse = await this.sendRequest<ApiResponse<T>>(\n method,\n url,\n bodyText,\n authMode,\n requestId\n );\n return parseApiResponse<T>(apiResponse, requestId);\n } catch (error) {\n if (error instanceof HttpStatusError) {\n // On the first 401, give the host a chance to restore its\n // credentials (e.g. refresh an auth session) — at most once per\n // logical request, shared with any concurrent requests (see\n // restoreCredentialsShared), and only for requests to the API\n // origin whose endpoint allows it (login/logout opt out). The\n // replay itself additionally requires the request to have\n // declared itself retry-safe.\n if (\n !credentialsRestored &&\n allowCredentialRestore &&\n error.status === 401 &&\n this.isApiOrigin(url)\n ) {\n credentialsRestored = true;\n const restored = await this.restoreCredentialsShared(startEpoch);\n if (restored && replayAllowed) {\n continue;\n }\n }\n\n const shouldRetry = config.retryableStatuses.includes(error.status);\n if (!shouldRetry || attempt >= config.maxRetries) {\n throw this.statusErrorToSdk(error);\n }\n\n const retryAfter = retryAfterMs(error.headers);\n const delay = retryAfter ?? delayForAttempt(config, attempt);\n attempt += 1;\n\n await sleep(delay);\n continue;\n }\n\n if (!(error instanceof HttpError)) {\n throw error;\n }\n\n const shouldRetry = await this.shouldRetry(\n error,\n config.retryableStatuses\n );\n if (!shouldRetry || attempt >= config.maxRetries) {\n throw error;\n }\n\n const delay = delayForAttempt(config, attempt);\n attempt += 1;\n\n await sleep(delay);\n }\n }\n }\n\n private async shouldRetry(\n error: HttpError,\n retryableStatuses: readonly number[]\n ): Promise<boolean> {\n switch (error.variant) {\n case \"Timeout\":\n case \"Request\":\n return true;\n case \"RateLimited\":\n return retryableStatuses.includes(429);\n case \"ServerError\":\n return error.status !== undefined && retryableStatuses.includes(error.status);\n default:\n return false;\n }\n }\n\n private async sendRequest<T>(\n method: \"GET\" | \"POST\" | \"DELETE\",\n url: string,\n bodyText: string | undefined,\n authMode: AuthMode,\n requestId: string\n ): Promise<T> {\n const headers: Record<string, string> = {};\n\n if (bodyText !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n }\n headers[\"x-request-id\"] = requestId;\n // Keys accompany only trading mutations at the configured API origin.\n // Public reads, authentication, and arbitrary external calls stay key-free.\n if (this.apiKey !== undefined && this.isApiOrigin(url) && method === \"POST\"\n && [\"/api/orders/submit\", \"/api/orders/cancel\", \"/api/orders/cancel-all\"].includes(new URL(url).pathname)) {\n headers[API_KEY_HEADER] = this.apiKey;\n }\n\n // Cookie injection is origin-gated: session credentials only ride to the\n // configured API origin, never to an arbitrary absolute URL a caller\n // supplies. In a browser the runtime owns cookie scoping instead.\n if (!isBrowserRuntime() && this.isApiOrigin(url)) {\n const cookie = this.cookieHeader(authMode);\n if (cookie) {\n headers.Cookie = cookie;\n }\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), DEFAULT_HTTP_TIMEOUT_MS);\n\n let response: Response;\n\n try {\n response = await fetch(url, {\n method,\n headers,\n body: bodyText,\n signal: controller.signal,\n // The API never legitimately redirects; following one would let a\n // redirect target observe the request while origin checks still see\n // the original URL. A 3xx therefore surfaces as an error below.\n redirect: \"manual\",\n // Browser credentials mode is origin-gated like the Cookie header\n // above: the browser's own cookie scoping already keeps the API\n // cookie off foreign origins, this just avoids asking it to attach\n // ANY cookies to a URL the SDK shouldn't be talking to. The foreign\n // branch is an explicit \"omit\" because the fetch default is\n // \"same-origin\" — a URL foreign to the API but matching the PAGE\n // origin would still get that origin's cookies.\n ...(isBrowserRuntime()\n ? {\n credentials: (this.isApiOrigin(url)\n ? \"include\"\n : \"omit\") as RequestCredentials,\n }\n : {}),\n });\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof Error && error.name === \"AbortError\") {\n throw HttpError.timeout();\n }\n throw HttpError.request(error instanceof Error ? error.message : String(error));\n } finally {\n clearTimeout(timeoutId);\n }\n\n if (response.ok) {\n // Capture only for the built-in session: a cookieOverride request\n // carries one specific user's forwarded cookies, and capturing its\n // Set-Cookie into the process-wide token slot would leak that user's\n // rotated token to every later request from a shared server client\n // (the python SDK has always skipped this; typescript now matches).\n if (!isBrowserRuntime() && authMode.kind !== \"cookieOverride\") {\n this.captureCookies(response);\n }\n\n const text = await response.text();\n let payload: T;\n try {\n payload = parseJsonExact<T>(text);\n } catch (e) {\n throw HttpError.request(e instanceof Error ? e.message : \"JSON parse failed\");\n }\n\n return payload;\n }\n\n const errorBody = await response.text().catch(() => \"\");\n throw new HttpStatusError(response.status, errorBody, response.headers, requestId);\n }\n\n private captureCookies(response: Response): void {\n for (const cookieHeader of getSetCookieHeaders(response.headers)) {\n const authToken = extractCookieValue(cookieHeader, \"lightcone-token\");\n if (authToken) {\n this.authToken = authToken;\n }\n }\n }\n\n private cookieHeader(authMode: AuthMode): string | undefined {\n if (isBrowserRuntime()) {\n return undefined;\n }\n\n switch (authMode.kind) {\n case \"cookieOverride\":\n // Forward the supplied Cookie header verbatim (may carry privy-token\n // and/or lightcone-token).\n return authMode.cookieHeader;\n case \"cookie\":\n return this.authToken ? `lightcone-token=${this.authToken}` : undefined;\n }\n }\n\n private mapStatusError(statusCode: number, bodyText: string, headers: Headers): HttpError {\n if (statusCode === 401) {\n return HttpError.unauthorized();\n }\n if (statusCode === 404) {\n return HttpError.notFound(bodyText);\n }\n if (statusCode === 429) {\n return HttpError.rateLimited(retryAfterMs(headers));\n }\n if (statusCode >= 400 && statusCode < 500) {\n return HttpError.badRequest(bodyText);\n }\n return HttpError.serverError(statusCode, bodyText);\n }\n\n private statusErrorToSdk(error: HttpStatusError): Error {\n const rejected = parseRejectedBody(error.body, error.requestId, error.status);\n if (rejected) {\n return rejected;\n }\n return this.mapStatusError(error.status, error.body, error.headers);\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\nfunction parseApiResponse<T>(payload: unknown, requestId: string): T {\n if (!isApiResponse<T>(payload)) {\n throw SdkError.serde(\"Invalid ApiResponse envelope\");\n }\n\n if (payload.status === \"success\") {\n return payload.body;\n }\n\n throw SdkError.apiRejected(\n ApiRejectedDetails.fromWire(payload.error_details, requestId)\n );\n}\n\nfunction parseRejectedBody(\n body: string,\n requestId: string,\n httpStatus: number\n): SdkError | undefined {\n let payload: unknown;\n try {\n payload = parseJsonExact(body);\n } catch {\n return undefined;\n }\n\n if (!isApiResponse<unknown>(payload) || payload.status !== \"error\") {\n return undefined;\n }\n\n return SdkError.apiRejected(\n ApiRejectedDetails.fromWire(payload.error_details, requestId, httpStatus)\n );\n}\n\nfunction generateRequestId(): string {\n if (typeof globalThis.crypto?.randomUUID === \"function\") {\n return globalThis.crypto.randomUUID();\n }\n\n return `lc-${Date.now()}-${Math.random().toString(16).slice(2)}`;\n}\n\nfunction getSetCookieHeaders(headers: Headers): string[] {\n const headersWithCookies = headers as Headers & {\n getSetCookie?: () => string[];\n };\n\n if (typeof headersWithCookies.getSetCookie === \"function\") {\n const values = headersWithCookies.getSetCookie();\n if (values.length > 0) {\n return values;\n }\n }\n\n const combined = headers.get(\"set-cookie\");\n return combined ? [combined] : [];\n}\n\nfunction retryAfterMs(headers: Headers): number | undefined {\n const retryAfterMsValue = headers.get(\"retry-after-ms\");\n if (retryAfterMsValue) {\n const parsed = Number.parseInt(retryAfterMsValue, 10);\n if (Number.isFinite(parsed)) {\n return parsed;\n }\n }\n\n const retryAfterValue = headers.get(\"retry-after\");\n if (retryAfterValue) {\n const parsed = Number.parseFloat(retryAfterValue);\n if (Number.isFinite(parsed)) {\n return Math.round(parsed * 1000);\n }\n }\n\n return undefined;\n}\n\nfunction extractCookieValue(header: string, name: string): string | undefined {\n const match = header.match(\n new RegExp(`(?:^|,\\\\s*)${escapeRegExp(name)}=([^;,]+)`)\n );\n return match?.[1];\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction hasBrowserWindow(): boolean {\n return typeof globalThis !== \"undefined\" && \"window\" in globalThis;\n}\n\nfunction isBrowserRuntime(): boolean {\n // Browser workers have no `window`, but still must not accept a server key.\n return hasBrowserWindow() || \"importScripts\" in globalThis;\n}\n\nfunction isSecureApiKeyOrigin(baseUrl: string): boolean {\n try {\n const url = new URL(baseUrl);\n return url.protocol === \"https:\" ||\n (url.protocol === \"http:\" &&\n [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname));\n } catch {\n return false;\n }\n}\n"]}
|