@coinlist-co/react 0.12.0 → 0.12.1-rc.0fa5c3b
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/dist/{chunk-ZFBEI3BW.js → chunk-3EOK47CQ.js} +20 -330
- package/dist/chunk-3EOK47CQ.js.map +1 -0
- package/dist/{chunk-F6WGUKZC.js → chunk-I5EHOV7V.js} +129 -3
- package/dist/chunk-I5EHOV7V.js.map +1 -0
- package/dist/{chunk-6CQHDASY.js → chunk-VSYGGTI6.js} +1173 -156
- package/dist/chunk-VSYGGTI6.js.map +1 -0
- package/dist/client/index.cjs +8559 -7690
- package/dist/client/index.cjs.map +1 -1
- package/dist/client/index.d.cts +116 -48
- package/dist/client/index.d.ts +116 -48
- package/dist/client/index.js +4059 -4007
- package/dist/client/index.js.map +1 -1
- package/dist/{collections-DOm9VKVm.d.cts → collections-C6b-rJpx.d.ts} +1 -1
- package/dist/{collections-aCv-Wr2a.d.ts → collections-UYVlXbEh.d.cts} +1 -1
- package/dist/server/index.cjs +1291 -166
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.d.cts +1 -1
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.js +5 -3
- package/dist/server/index.js.map +1 -1
- package/dist/{config-DIaFzrMW.d.cts → tokens-namespace-C-BxcYMj.d.cts} +362 -188
- package/dist/{config-DIaFzrMW.d.ts → tokens-namespace-C-BxcYMj.d.ts} +362 -188
- package/dist/universal/index.cjs +1103 -405
- package/dist/universal/index.cjs.map +1 -1
- package/dist/universal/index.d.cts +427 -45
- package/dist/universal/index.d.ts +427 -45
- package/dist/universal/index.js +16 -14
- package/package.json +1 -1
- package/dist/chunk-6CQHDASY.js.map +0 -1
- package/dist/chunk-F6WGUKZC.js.map +0 -1
- package/dist/chunk-ZFBEI3BW.js.map +0 -1
package/dist/server/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as AuthorizationCode, C as CodeVerifier,
|
|
1
|
+
import { A as AuthorizationCode, C as CodeVerifier, an as OAuthSession, v as OAuthAccessToken, ao as ClientCredentialsOAuth, u as Config, ap as ClientSecret, aq as Sender, L as Logger, w as OffersNamespace, G as Offer, ar as PaginationParams, as as PaginatedResponse, O as OfferId, z as OfferDetail, R as RequirementsNamespace, d as OfferOptionId, s as Requirement, t as RequirementsNamespaceImpl, U as UniversalNamespaceContext, o as WalletsNamespace, E as Erc20Namespace, c as CoinListTokenSaleNamespace, S as SuperstateSwapNamespace, g as OndoNamespace, T as TokensNamespace, X as PinoLoggerOptions } from '../tokens-namespace-C-BxcYMj.cjs';
|
|
2
2
|
import 'viem';
|
|
3
3
|
|
|
4
4
|
interface SessionStore {
|
package/dist/server/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as AuthorizationCode, C as CodeVerifier,
|
|
1
|
+
import { A as AuthorizationCode, C as CodeVerifier, an as OAuthSession, v as OAuthAccessToken, ao as ClientCredentialsOAuth, u as Config, ap as ClientSecret, aq as Sender, L as Logger, w as OffersNamespace, G as Offer, ar as PaginationParams, as as PaginatedResponse, O as OfferId, z as OfferDetail, R as RequirementsNamespace, d as OfferOptionId, s as Requirement, t as RequirementsNamespaceImpl, U as UniversalNamespaceContext, o as WalletsNamespace, E as Erc20Namespace, c as CoinListTokenSaleNamespace, S as SuperstateSwapNamespace, g as OndoNamespace, T as TokensNamespace, X as PinoLoggerOptions } from '../tokens-namespace-C-BxcYMj.js';
|
|
2
2
|
import 'viem';
|
|
3
3
|
|
|
4
4
|
interface SessionStore {
|
package/dist/server/index.js
CHANGED
|
@@ -3,8 +3,9 @@ import {
|
|
|
3
3
|
NABU_BASE_URL,
|
|
4
4
|
PINO_LEVEL,
|
|
5
5
|
SDK_LOGGER_NAME,
|
|
6
|
-
loggerOverPino
|
|
7
|
-
|
|
6
|
+
loggerOverPino,
|
|
7
|
+
publicClients
|
|
8
|
+
} from "../chunk-I5EHOV7V.js";
|
|
8
9
|
import {
|
|
9
10
|
API_VERSION,
|
|
10
11
|
ClientCredentialsOAuth,
|
|
@@ -24,7 +25,7 @@ import {
|
|
|
24
25
|
fetchOffers,
|
|
25
26
|
fetchOffersPage,
|
|
26
27
|
internalLogger
|
|
27
|
-
} from "../chunk-
|
|
28
|
+
} from "../chunk-VSYGGTI6.js";
|
|
28
29
|
|
|
29
30
|
// src/server/core/api/api-client.ts
|
|
30
31
|
var ApiClient = class {
|
|
@@ -263,6 +264,7 @@ var CoinListServerImpl = class {
|
|
|
263
264
|
});
|
|
264
265
|
const ctx = {
|
|
265
266
|
api: this.api,
|
|
267
|
+
rpc: publicClients(this.api, _config.rpc, _config.logger ?? null),
|
|
266
268
|
logger,
|
|
267
269
|
ensureUserAuthenticated: () => this.ensureAuthenticated(void 0),
|
|
268
270
|
ensureAuthenticated: (clientCreds) => this.ensureAuthenticated(clientCreds)
|
package/dist/server/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/server/core/api/api-client.ts","../../src/server/shared/errors.ts","../../src/server/core/server-auth-namespace.ts","../../src/server/core/server-offers-namespace.ts","../../src/server/core/server-requirements-namespace.ts","../../src/server/core/coinlist-server.ts","../../src/server/core/observability/pino-server-logger.ts"],"sourcesContent":["import { AuthenticatedApiClient } from '@/universal/api/authenticated-api-client';\nimport type { HttpClientConfig, HttpRequest } from '@/universal/api/http';\nimport type { Logger } from '@/universal/types/logger';\nimport type { OAuthAccessToken } from '@/universal/types/oauth-session';\n\nexport class ApiClient {\n private readonly client: AuthenticatedApiClient;\n\n constructor(\n config: HttpClientConfig,\n fetchAccessToken: (refresh: boolean) => Promise<OAuthAccessToken | null>,\n logger: Logger | null = null\n ) {\n this.client = new AuthenticatedApiClient(\n config,\n fetchAccessToken,\n [],\n logger\n );\n }\n\n async send<TResponse>(request: HttpRequest): Promise<TResponse> {\n return this.client.send<TResponse>(request);\n }\n}\n","export class WritableSessionStoreRequiredError extends Error {\n constructor(\n message = 'This operation requires a writable SessionStore. Provide a `setSession` implementation in your SessionStore to persist or clear OAuth sessions.'\n ) {\n super(message);\n this.name = 'WritableSessionStoreRequiredError';\n }\n}\n","import { WritableSessionStoreRequiredError } from '@/server/shared/errors';\nimport { HttpError } from '@/universal/api/http';\nimport type { Sender } from '@/universal/api/http-client';\nimport {\n type InternalLogger,\n internalLogger,\n} from '@/universal/core/shared/observability/internal-logger';\nimport type { Config } from '@/universal/types/config';\nimport type { OAuthSessionDto } from '@/universal/types/dto/oauth-session';\nimport type {\n AuthorizationCode,\n ClientSecret,\n CodeVerifier,\n} from '@/universal/types/oauth';\nimport {\n ClientCredentialsOAuth,\n type OAuthAccessToken,\n type OAuthRefreshToken,\n OAuthSession,\n} from '@/universal/types/oauth-session';\n\nexport interface SessionStore {\n getSession(): Promise<OAuthSession | null>;\n /**\n * Persists or clears the OAuth session.\n *\n * **Omit this method to create a read-only store.** When absent, the SDK\n * skips token refresh entirely — no network call is made and no refresh\n * token is consumed. This is the correct approach for contexts that can read\n * the session but cannot write it back, such as Next.js Server Components.\n *\n * ⚠️ Do **not** implement this as a no-op (`async () => {}`). If the method\n * is present, the SDK assumes writes succeed: it will fire a token refresh\n * network call, consume the refresh token, then invoke `setSession` — which\n * would silently discard the new session and leave the browser holding an\n * invalidated refresh token. Simply **omit** `setSession` to prevent any\n * refresh from being attempted.\n *\n * {@link ServerAuthNamespace.completeOAuth} and\n * {@link ServerAuthNamespace.logout} always require a writable store and\n * throw {@link WritableSessionStoreRequiredError} if `setSession` is absent.\n */\n setSession?(session: OAuthSession | null): Promise<void>;\n}\n\n/**\n * The empty session store: holds no session, reads nothing, never writes.\n *\n * For server contexts that act without a user — the client-credentials grant\n * (`auth.clientCredentials`) and the public token registry (`tokens`) read\n * nothing from the store, so hosts building those paths need no store of\n * their own.\n *\n * `setSession` is deliberately absent, not a no-op — see\n * {@link SessionStore.setSession} for why a no-op is a bug.\n */\nexport function emptySessionStore(): SessionStore {\n return { getSession: async () => null };\n}\n\n/** The PKCE pair `CoinListClient#auth.completeOAuth` hands to the backend. */\nexport interface CompleteOAuthParams {\n /** The short-lived authorization code parsed out of the redirect URL. */\n code: AuthorizationCode;\n /** The `code_verifier` the browser generated when starting the flow. */\n codeVerifier: CodeVerifier;\n}\n\n/**\n * OAuth session lifecycle on your backend: exchanging authorization codes,\n * keeping the access token fresh, minting app-level tokens, and logging out.\n *\n * This namespace is server-only: every method needs the `clientSecret` and the\n * {@link SessionStore}, neither of which may exist in a browser.\n */\nexport interface ServerAuthNamespace {\n /**\n * Exchanges an authorization code from `CoinListClient#auth.completeOAuth`\n * for an OAuth session and persists it via {@link SessionStore.setSession}.\n *\n * Throws {@link WritableSessionStoreRequiredError} if the session store does\n * not provide `setSession`.\n */\n completeOAuth(params: CompleteOAuthParams): Promise<OAuthSession>;\n\n /**\n * Returns a valid access token for the current session, refreshing it if it\n * is expired or near expiry. This is what you serve to\n * {@link ClientConfig.getAccessToken}.\n *\n * **Writable store**: if the token is expired, the SDK exchanges the refresh\n * token for a new session, persists it, and returns the fresh access token.\n * Returns `null` if there is no session or the refresh fails.\n *\n * **Read-only store** (no `setSession`): refresh is skipped entirely. The\n * stored token is returned as-is, even if it is expired — a non-null return\n * value does **not** guarantee the token is accepted by the API. Before\n * making API calls, check `token.expiresAt > new Date()`. Use a writable\n * store (e.g. in a Route Handler) when you need the SDK to renew the session\n * automatically.\n *\n * @returns the access token, or `null` if there is no session or the session\n * could not be refreshed.\n */\n getAccessToken(): Promise<OAuthAccessToken | null>;\n\n /**\n * Obtains an app-level access token via the OAuth 2.0 `client_credentials`\n * grant (RFC 6749 §4.4). No user is involved: the token authenticates the\n * partner application itself and only grants access to app-level resources\n * such as offers and offer requirements.\n *\n * The token is **not** persisted to the {@link SessionStore} and has no\n * refresh token. It expires at `expiresAt`; once expired, call this method\n * again to obtain a fresh token — the SDK does not renew it automatically.\n *\n * Pass the result to `ServerOffersNamespace` or\n * `ServerRequirementsNamespace.forOffer` to read without a user session.\n */\n clientCredentials(): Promise<ClientCredentialsOAuth>;\n\n /**\n * Revokes the current token via `POST /oauth/revoke` and clears the session.\n *\n * Throws {@link WritableSessionStoreRequiredError} if the session store does\n * not provide `setSession`.\n */\n logout(): Promise<void>;\n}\n\n/** What {@link ServerAuthNamespaceImpl} needs out of `ServerConfig`. */\nexport type ServerAuthConfig = Config & {\n readonly clientSecret: ClientSecret;\n readonly sessionStore: SessionStore;\n /** Seconds before expiry at which a token counts as expired for refresh. */\n readonly accessTokenExpiryBufferSeconds: number;\n /** Whether to rethrow errors the SDK could otherwise swallow (e.g. revoke). */\n readonly strict: boolean;\n};\n\nexport class ServerAuthNamespaceImpl implements ServerAuthNamespace {\n private readonly log: InternalLogger;\n\n constructor(\n private readonly api: Sender,\n private readonly config: ServerAuthConfig\n ) {\n this.log = internalLogger(config.logger ?? null, 'AUTH');\n }\n\n async completeOAuth(params: CompleteOAuthParams): Promise<OAuthSession> {\n return this.log.wrap('completeOAuth', undefined, async () => {\n const setSession = this.writableSessionStore();\n const sessionDto = await this.api.send<OAuthSessionDto>({\n method: 'POST',\n url: `/oauth/token`,\n body: {\n grant_type: 'authorization_code',\n code: params.code,\n redirect_uri: this.config.redirectUri,\n client_id: this.config.clientId,\n client_secret: this.config.clientSecret,\n code_verifier: params.codeVerifier,\n },\n });\n const session = OAuthSession.fromDto(sessionDto);\n await setSession(session);\n return session;\n });\n }\n\n async getAccessToken(): Promise<OAuthAccessToken | null> {\n // Wrapped despite running on every request: `sessionStore.getSession` is\n // host code, and when it throws there is nothing else between the failure\n // and the host's own catch to say which SDK call it came out of.\n return this.log.wrap('getAccessToken', undefined, () =>\n this.readAccessToken()\n );\n }\n\n private async readAccessToken(): Promise<OAuthAccessToken | null> {\n const sessionStore = this.config.sessionStore;\n const session = await sessionStore.getSession();\n if (session == null) return null;\n\n const now = Date.now();\n const expiresAt = session.accessToken.expiresAt.getTime();\n const bufferMs = this.config.accessTokenExpiryBufferSeconds * 1000;\n if (expiresAt > now + bufferMs) {\n // Valid access token, return it regardless\n return session.accessToken;\n }\n\n const setSession = sessionStore.setSession?.bind(sessionStore);\n if (!setSession) {\n // No write session capabilities => can't refresh!\n // Return the access token as-is\n this.log.child({ op: 'getAccessToken' }).warn(() => ({\n msg: 'serving an expired token: the session store is read-only, so it cannot be refreshed',\n }));\n return session.accessToken;\n }\n return this.refreshSession(session.refreshToken, setSession);\n }\n\n private async refreshSession(\n refreshToken: OAuthRefreshToken | undefined,\n setSession: (session: OAuthSession | null) => Promise<void>\n ): Promise<OAuthAccessToken | null> {\n const log = this.log.child({ op: 'refresh' });\n if (!refreshToken) {\n log.warn(() => ({\n msg: 'clearing the session: it carries no refresh token',\n }));\n await setSession(null);\n return null;\n }\n\n try {\n const sessionDto = await this.api.send<OAuthSessionDto>({\n method: 'POST',\n url: `/oauth/token`,\n body: {\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n client_id: this.config.clientId,\n client_secret: this.config.clientSecret,\n },\n });\n const newSession = OAuthSession.fromDto(sessionDto);\n await setSession(newSession);\n log.info(() => ({ msg: 'session renewed' }));\n return newSession.accessToken;\n } catch (error) {\n // The user is logged out by this line, and nothing above sees why:\n // `getAccessToken` answers `null` either way.\n log.failure(\n () => ({ msg: 'refresh failed; clearing the session' }),\n error\n );\n await setSession(null);\n return null;\n }\n }\n\n async clientCredentials(): Promise<ClientCredentialsOAuth> {\n return this.log.wrap('clientCredentials', undefined, async () => {\n const sessionDto = await this.api.send<OAuthSessionDto>({\n method: 'POST',\n url: `/oauth/token`,\n body: {\n grant_type: 'client_credentials',\n client_id: this.config.clientId,\n client_secret: this.config.clientSecret,\n },\n });\n const session = OAuthSession.fromDto(sessionDto);\n return ClientCredentialsOAuth(session.accessToken);\n });\n }\n\n async logout(): Promise<void> {\n return this.log.wrap('logout', undefined, () => this.revokeAndClear());\n }\n\n private async revokeAndClear(): Promise<void> {\n const setSession = this.writableSessionStore();\n const session = await this.config.sessionStore.getSession();\n if (session == null) return;\n\n try {\n await this.api.send({\n method: 'POST',\n url: `/oauth/revoke`,\n body: {\n token: session.accessToken.value,\n client_id: this.config.clientId,\n client_secret: this.config.clientSecret,\n },\n });\n } catch (err) {\n // A failed revoke still leaves the local session invalid, so only strict\n // callers care; anything that is not an HTTP failure is a real bug.\n if (!(err instanceof HttpError) || this.config.strict) {\n throw err;\n }\n this.log.child({ op: 'logout' }).warn(() => ({\n msg: 'the token was not revoked upstream; the local session is cleared regardless',\n }));\n }\n await setSession(null);\n }\n\n /**\n * Returns the store's `setSession`, or throws — the guard every\n * session-writing operation shares.\n */\n private writableSessionStore(): (\n session: OAuthSession | null\n ) => Promise<void> {\n const sessionStore = this.config.sessionStore;\n const setSession = sessionStore.setSession?.bind(sessionStore);\n if (!setSession) {\n throw new WritableSessionStoreRequiredError();\n }\n return setSession;\n }\n}\n","import type { ServerNamespaceContext } from '@/server/core/server-namespace-context';\nimport * as offersApi from '@/universal/api/frontline/offers';\nimport type { OffersNamespace } from '@/universal/core/offers/offers-namespace';\nimport {\n type InternalLogger,\n internalLogger,\n} from '@/universal/core/shared/observability/internal-logger';\nimport type { ClientCredentialsOAuth } from '@/universal/types/oauth-session';\nimport type { Offer, OfferId } from '@/universal/types/offer';\nimport type { OfferDetail } from '@/universal/types/offer-detail';\nimport type {\n PaginatedResponse,\n PaginationParams,\n} from '@/universal/types/pagination';\n\n/**\n * The server-side offers namespace: the same reads as the shared\n * {@link OffersNamespace}, each additionally callable with an app-level token\n * from `ServerAuthNamespace.clientCredentials` instead of a user session.\n *\n * When a user session exists it takes precedence and `clientCreds` acts as a\n * fallback. Without either, the reads throw {@link NotAuthenticatedError}.\n */\nexport interface ServerOffersNamespace extends OffersNamespace {\n /** @param clientCreds app-level token to read without a user session. */\n list(clientCreds?: ClientCredentialsOAuth): Promise<Offer[]>;\n\n /** @param clientCreds app-level token to read without a user session. */\n listPage(\n params: PaginationParams,\n clientCreds?: ClientCredentialsOAuth\n ): Promise<PaginatedResponse<Offer>>;\n\n /** @param clientCreds app-level token to read without a user session. */\n get(id: OfferId, clientCreds?: ClientCredentialsOAuth): Promise<OfferDetail>;\n}\n\nexport class ServerOffersNamespaceImpl implements ServerOffersNamespace {\n private readonly log: InternalLogger;\n\n constructor(private readonly ctx: ServerNamespaceContext) {\n this.log = internalLogger(ctx.logger, 'OFFERS');\n }\n\n async list(clientCreds?: ClientCredentialsOAuth): Promise<Offer[]> {\n return this.log.wrap('list', clientCreds, async () => {\n await this.ctx.ensureAuthenticated(clientCreds);\n return offersApi.fetchOffers(this.ctx.api, clientCreds);\n });\n }\n\n async listPage(\n params: PaginationParams,\n clientCreds?: ClientCredentialsOAuth\n ): Promise<PaginatedResponse<Offer>> {\n return this.log.wrap('listPage', { params, clientCreds }, async () => {\n await this.ctx.ensureAuthenticated(clientCreds);\n return offersApi.fetchOffersPage(this.ctx.api, params, clientCreds);\n });\n }\n\n async get(\n id: OfferId,\n clientCreds?: ClientCredentialsOAuth\n ): Promise<OfferDetail> {\n return this.log.wrap('get', { id, clientCreds }, async () => {\n await this.ctx.ensureAuthenticated(clientCreds);\n return offersApi.fetchOfferDetails(this.ctx.api, id, clientCreds);\n });\n }\n}\n","import type { ServerNamespaceContext } from '@/server/core/server-namespace-context';\nimport * as requirementsApi from '@/universal/api/frontline/requirements';\nimport {\n type RequirementsNamespace,\n RequirementsNamespaceImpl,\n} from '@/universal/core/requirements/requirements-namespace';\nimport type { UniversalNamespaceContext } from '@/universal/core/shared/namespace-context';\nimport type { ClientCredentialsOAuth } from '@/universal/types/oauth-session';\nimport type { OfferId } from '@/universal/types/offer';\nimport type { OfferOptionId } from '@/universal/types/offer-detail';\nimport type { Requirement } from '@/universal/types/requirement';\n\n/**\n * The server-side requirements namespace: the same surface as the shared\n * {@link RequirementsNamespace}, except {@link forOffer} — the offer's\n * requirement definitions are app-level data, so it is additionally callable\n * with a token from `ServerAuthNamespace.clientCredentials`.\n *\n * Everything else is per-user data and needs a user session. `handle` is\n * client-only: there is no browser tab to open on a server.\n */\nexport interface ServerRequirementsNamespace extends RequirementsNamespace {\n /** @param clientCreds app-level token to read without a user session. */\n forOffer(\n offerId: OfferId,\n clientCreds?: ClientCredentialsOAuth\n ): Promise<Record<OfferOptionId, Requirement[]>>;\n}\n\nexport class ServerRequirementsNamespaceImpl\n extends RequirementsNamespaceImpl\n implements ServerRequirementsNamespace\n{\n constructor(\n private readonly serverCtx: UniversalNamespaceContext &\n ServerNamespaceContext\n ) {\n super(serverCtx);\n }\n\n async forOffer(\n offerId: OfferId,\n clientCreds?: ClientCredentialsOAuth\n ): Promise<Record<OfferOptionId, Requirement[]>> {\n return this.log.wrap('forOffer', { offerId, clientCreds }, async () => {\n await this.serverCtx.ensureAuthenticated(clientCreds);\n return requirementsApi.fetchOfferRequirements(\n this.serverCtx.api,\n offerId,\n clientCreds\n );\n });\n }\n}\n","import { ApiClient } from '@/server/core/api/api-client';\nimport {\n type ServerAuthNamespace,\n ServerAuthNamespaceImpl,\n type SessionStore,\n} from '@/server/core/server-auth-namespace';\nimport type { ServerNamespaceContext } from '@/server/core/server-namespace-context';\nimport {\n type ServerOffersNamespace,\n ServerOffersNamespaceImpl,\n} from '@/server/core/server-offers-namespace';\nimport {\n type ServerRequirementsNamespace,\n ServerRequirementsNamespaceImpl,\n} from '@/server/core/server-requirements-namespace';\nimport {\n API_VERSION,\n PUBLIC_API_BASE_URL,\n} from '@/universal/api/frontline/config';\nimport { NABU_BASE_URL } from '@/universal/api/nabu/config';\nimport {\n type CoinListTokenSaleNamespace,\n CoinListTokenSaleNamespaceImpl,\n} from '@/universal/core/checkout/coin-list/token-sale-namespace';\nimport {\n type OndoNamespace,\n OndoNamespaceImpl,\n} from '@/universal/core/checkout/ondo/ondo-namespace';\nimport {\n type SuperstateSwapNamespace,\n SuperstateSwapNamespaceImpl,\n} from '@/universal/core/checkout/superstate/swap-namespace';\nimport {\n type Erc20Namespace,\n Erc20NamespaceImpl,\n} from '@/universal/core/shared/blockchain/erc20/erc20-namespace';\nimport type { UniversalNamespaceContext } from '@/universal/core/shared/namespace-context';\nimport {\n type TokensNamespace,\n TokensNamespaceImpl,\n} from '@/universal/core/tokens/tokens-namespace';\nimport {\n type WalletsNamespace,\n WalletsNamespaceImpl,\n} from '@/universal/core/wallets/wallets-namespace';\nimport type { Config } from '@/universal/types/config';\nimport { NotAuthenticatedError } from '@/universal/types/errors';\nimport type { ClientSecret } from '@/universal/types/oauth';\nimport type { ClientCredentialsOAuth } from '@/universal/types/oauth-session';\n\n/** Buffer in seconds before expiry to consider token expired for refresh. */\nconst ACCESS_TOKEN_EXPIRY_BUFFER_SECONDS = 60;\n\nexport interface ServerConfig extends Config {\n readonly clientSecret: ClientSecret;\n readonly sessionStore: SessionStore;\n /** Buffer in seconds before expiry to consider token expired for refresh. */\n readonly accessTokenExpiryBufferSeconds?: number;\n /**\n * Whether SDK will throw an exception in cases it can be silent.\n * For example, if token revokation on logout fails.\n */\n readonly strict?: boolean;\n}\n\n/**\n * Server-side CoinList SDK client.\n *\n * Functionality is grouped into namespaces — `coinlist.auth.getAccessToken()`,\n * `coinlist.offers.list()`, `coinlist.requirements.statuses(offerId)`.\n *\n * Operates in one of two modes depending on whether {@link SessionStore}\n * includes a `setSession` implementation:\n *\n * - **Writable store** (`setSession` provided) — full functionality: token\n * refresh, `auth.completeOAuth`, and `auth.logout` all work normally.\n *\n * - **Read-only store** (no `setSession`) — token refresh is skipped entirely,\n * meaning no network call is made and no refresh token is consumed.\n * `auth.completeOAuth` and `auth.logout` throw\n * {@link WritableSessionStoreRequiredError}. `auth.getAccessToken` may\n * return an expired token (see its docs). Use this mode in execution\n * contexts that can read the session but cannot write it back, such as\n * Next.js Server Components.\n *\n * Unless a namespace says otherwise, its methods require a user session and\n * throw {@link NotAuthenticatedError} when there is none.\n */\nexport interface CoinListServer {\n /**\n * OAuth session lifecycle: exchanging an authorization code, serving a valid\n * access token to the browser, minting app-level tokens, and logging out —\n * e.g. `coinlist.auth.getAccessToken()`.\n */\n readonly auth: ServerAuthNamespace;\n\n /**\n * The offer catalogue — e.g. `coinlist.offers.list()`. Every read also\n * accepts an app-level token from {@link ServerAuthNamespace.clientCredentials}\n * so it can run without a user session.\n */\n readonly offers: ServerOffersNamespace;\n\n /**\n * Offer requirements and the operations that satisfy them — e.g.\n * `coinlist.requirements.statuses(offerId)`. `forOffer` also accepts an\n * app-level token; the rest is per-user data and needs a user session.\n */\n readonly requirements: ServerRequirementsNamespace;\n\n /**\n * The user's external wallets: ownership proofs and offer-option bindings —\n * e.g. `coinlist.wallets.list({ offerId, offerOptionId })`.\n */\n readonly wallets: WalletsNamespace;\n\n /**\n * Generic ERC-20 reads (token allowance and balance) — e.g.\n * `coinlist.erc20.getBalance({ ... })`.\n */\n readonly erc20: Erc20Namespace;\n\n /**\n * Token-sale operations: listing, reading, and recording participations —\n * e.g. `coinlist.tokenSale.list()`. The on-chain `execute`\n * flow is client-only and is not exposed here.\n */\n readonly tokenSale: CoinListTokenSaleNamespace;\n\n /**\n * On-chain swap operations: quoting a swap, reading swap-contract state, and\n * allow-listing a proven wallet — e.g.\n * `coinlist.superstate.getOutputToken({ contractAddress, chain })`.\n */\n readonly superstate: SuperstateSwapNamespace;\n\n /**\n * Ondo swap reads: trading status and quoting. Both are free to poll.\n *\n * No CoinList fee is applied to a quote; see {@link OndoNamespace}.\n *\n * This is Ondo's whole surface for now — the wallet-driven half arrives with\n * ENG-1680 and will be client-only, since it needs a wallet to sign with.\n */\n readonly ondo: OndoNamespace;\n\n /**\n * Token display metadata (name, symbol, decimals, logos) from CoinList's\n * public token registry, keyed by chain + contract address — e.g.\n * `coinlist.tokens.get({ chain, address })` for an entry of\n * `Offer.tokens`, or `coinlist.tokens.list()` for the whole\n * catalogue in one request.\n *\n * Public and unauthenticated: unlike the other namespaces, its methods never\n * require a session, so it also works with a read-only store.\n */\n readonly tokens: TokensNamespace;\n}\n\nclass CoinListServerImpl implements CoinListServer {\n private readonly api: ApiClient;\n readonly auth: ServerAuthNamespace;\n readonly offers: ServerOffersNamespace;\n readonly requirements: ServerRequirementsNamespace;\n readonly wallets: WalletsNamespace;\n readonly erc20: Erc20Namespace;\n readonly tokenSale: CoinListTokenSaleNamespace;\n readonly superstate: SuperstateSwapNamespace;\n readonly ondo: OndoNamespace;\n readonly tokens: TokensNamespace;\n\n constructor(private readonly _config: ServerConfig) {\n const logger = _config.logger ?? null;\n this.api = new ApiClient(\n {\n baseUrl: _config.baseUrl ?? PUBLIC_API_BASE_URL,\n xApiVersion: API_VERSION,\n },\n // When refresh=true the renewal middleware has received a 401 and wants a\n // fresh token. A read-only store cannot persist a new session, so return\n // null immediately — this tells the middleware to skip the retry rather\n // than re-sending with the same expired token and wasting a round-trip.\n (refresh) =>\n refresh && !this._config.sessionStore.setSession\n ? Promise.resolve(null)\n : this.auth.getAccessToken(),\n logger\n );\n this.auth = new ServerAuthNamespaceImpl(this.api, {\n ..._config,\n accessTokenExpiryBufferSeconds:\n _config.accessTokenExpiryBufferSeconds ??\n ACCESS_TOKEN_EXPIRY_BUFFER_SECONDS,\n strict: _config.strict ?? false,\n });\n\n const ctx: UniversalNamespaceContext & ServerNamespaceContext = {\n api: this.api,\n logger,\n ensureUserAuthenticated: () => this.ensureAuthenticated(undefined),\n ensureAuthenticated: (clientCreds) =>\n this.ensureAuthenticated(clientCreds),\n };\n this.offers = new ServerOffersNamespaceImpl(ctx);\n this.requirements = new ServerRequirementsNamespaceImpl(ctx);\n this.wallets = new WalletsNamespaceImpl(ctx);\n this.erc20 = new Erc20NamespaceImpl(ctx);\n this.tokenSale = new CoinListTokenSaleNamespaceImpl(ctx);\n this.superstate = new SuperstateSwapNamespaceImpl(ctx);\n this.ondo = new OndoNamespaceImpl(ctx);\n this.tokens = new TokensNamespaceImpl(\n _config.tokensBaseUrl ?? NABU_BASE_URL,\n logger\n );\n }\n\n /**\n * An app-level token authenticates a request on its own; without one the\n * caller needs a user session.\n */\n private async ensureAuthenticated(\n clientCreds: ClientCredentialsOAuth | undefined\n ): Promise<void> {\n if (clientCreds) return;\n const token = await this.auth.getAccessToken();\n if (token === null) {\n throw new NotAuthenticatedError();\n }\n }\n}\n\nexport function createCoinListServer(config: ServerConfig): CoinListServer {\n return new CoinListServerImpl(config);\n}\n","import { pino } from 'pino';\nimport {\n loggerOverPino,\n PINO_LEVEL,\n SDK_LOGGER_NAME,\n} from '@/universal/core/shared/observability/pino-logger';\nimport type { Logger, PinoLoggerOptions } from '@/universal/types/logger';\n\n/**\n * A {@link Logger} that writes newline-delimited JSON to stdout through pino.\n *\n * ```ts\n * createCoinListServer({\n * ...config,\n * logger: pinoServerLogger({ isDev: false, level: 'info' }),\n * });\n * ```\n *\n * The Node counterpart of {@link pinoClientLogger}, for a route handler, a BFF\n * or SSR. One line per record, which is what every log aggregator ingests\n * without configuration.\n *\n * ## What it deliberately does not do\n *\n * **No transport, and no `pino-pretty`.** A pino transport runs on a worker\n * thread through `thread-stream`, which every bundler has to be told about\n * (`serverExternalPackages` in Next) and which edge runtimes cannot run at\n * all. Pretty-printing is a pipe the host owns rather than a dependency the\n * SDK takes on their behalf:\n *\n * ```sh\n * node server.js | npx pino-pretty\n * ```\n *\n * **No environment-dependent formatting.** `isDev` decides which levels are\n * legal and nothing else, so a development record and a production record are\n * the same shape - what you debug is what you ship.\n *\n * If you already run pino, or want transports, redaction or `destination`,\n * implement {@link Logger} yourself: it is four methods over an event, and\n * `@opentelemetry/instrumentation-pino` patches the pino module rather than an\n * instance, so trace correlation reaches this logger either way.\n *\n * ## Production\n *\n * **Not advised in production**, the same as everywhere else this seam is\n * documented: the SDK's default answer is to leave {@link Config.logger}\n * undefined outside development, staging and incident reproduction. A backend\n * is the least bad place to disregard that - the records go to your process\n * and your sink rather than to a page the end user can read - but it is still\n * a disregard, and the retention and access questions become yours.\n *\n * If you run one, `isDev: false` restricts you to `'error'`, `'warn'` and\n * `'info'` - `{ isDev: false, level: 'debug' }` does not compile, see\n * {@link PinoLoggerOptions}. Those levels are redacted by construction, which\n * is a mechanism the SDK holds itself to; whether that clears your bar is a\n * judgement the SDK is not in a position to make for you.\n *\n * Holds no module-level state: every call builds its own pino instance, and\n * the level is fixed at construction, so two loggers never interfere. Fixed is\n * this implementation's choice, not the seam's - the SDK re-reads\n * {@link Logger.level} before every log call - so if you want a level you can\n * change at runtime, implement {@link Logger} over your own pino instance\n * rather than calling this.\n */\nexport function pinoServerLogger(options: PinoLoggerOptions): Logger {\n return loggerOverPino(\n // `name` as a child binding rather than pino's `name` option: the option\n // is honoured by pino's node build and silently dropped by its browser\n // build, so a binding is the only spelling that identifies the SDK in\n // both environments.\n pino({\n level: PINO_LEVEL[options.level],\n }).child({ name: SDK_LOGGER_NAME }),\n options.level\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKO,IAAM,YAAN,MAAgB;AAAA,EAGrB,YACE,QACA,kBACA,SAAwB,MACxB;AACA,SAAK,SAAS,IAAI;AAAA,MAChB;AAAA,MACA;AAAA,MACA,CAAC;AAAA,MACD;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,KAAgB,SAA0C;AAC9D,WAAO,KAAK,OAAO,KAAgB,OAAO;AAAA,EAC5C;AACF;;;ACxBO,IAAM,oCAAN,cAAgD,MAAM;AAAA,EAC3D,YACE,UAAU,mJACV;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;;;ACiDO,SAAS,oBAAkC;AAChD,SAAO,EAAE,YAAY,YAAY,KAAK;AACxC;AAkFO,IAAM,0BAAN,MAA6D;AAAA,EAGlE,YACmB,KACA,QACjB;AAFiB;AACA;AAEjB,SAAK,MAAM,eAAe,OAAO,UAAU,MAAM,MAAM;AAAA,EACzD;AAAA,EAEA,MAAM,cAAc,QAAoD;AACtE,WAAO,KAAK,IAAI,KAAK,iBAAiB,QAAW,YAAY;AAC3D,YAAM,aAAa,KAAK,qBAAqB;AAC7C,YAAM,aAAa,MAAM,KAAK,IAAI,KAAsB;AAAA,QACtD,QAAQ;AAAA,QACR,KAAK;AAAA,QACL,MAAM;AAAA,UACJ,YAAY;AAAA,UACZ,MAA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,IAAI,+BAA+B,GAAG;AACvD,SAAK,aAAa,IAAI,4BAA4B,GAAG;AACrD,SAAK,OAAO,IAAI,kBAAkB,GAAG;AACrC,SAAK,SAAS,IAAI;AAAA,MAChB,QAAQ,iBAAiB;AAAA,MACzB;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAc,oBACZ,aACe;AACf,QAAI,YAAa;AACjB,UAAM,QAAQ,MAAM,KAAK,KAAK,eAAe;AAC7C,QAAI,UAAU,MAAM;AAClB,YAAM,IAAI,sBAAsB;AAAA,IAClC;AAAA,EACF;AACF;AAEO,SAAS,qBAAqB,QAAsC;AACzE,SAAO,IAAI,mBAAmB,MAAM;AACtC;;;ACzOA,SAAS,YAAY;AAiEd,SAAS,iBAAiB,SAAoC;AACnE,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA,IAKL,KAAK;AAAA,MACH,OAAO,WAAW,QAAQ,KAAK;AAAA,IACjC,CAAC,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAAA,IAClC,QAAQ;AAAA,EACV;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/server/core/api/api-client.ts","../../src/server/shared/errors.ts","../../src/server/core/server-auth-namespace.ts","../../src/server/core/server-offers-namespace.ts","../../src/server/core/server-requirements-namespace.ts","../../src/server/core/coinlist-server.ts","../../src/server/core/observability/pino-server-logger.ts"],"sourcesContent":["import { AuthenticatedApiClient } from '@/universal/api/authenticated-api-client';\nimport type { HttpClientConfig, HttpRequest } from '@/universal/api/http';\nimport type { Logger } from '@/universal/types/logger';\nimport type { OAuthAccessToken } from '@/universal/types/oauth-session';\n\nexport class ApiClient {\n private readonly client: AuthenticatedApiClient;\n\n constructor(\n config: HttpClientConfig,\n fetchAccessToken: (refresh: boolean) => Promise<OAuthAccessToken | null>,\n logger: Logger | null = null\n ) {\n this.client = new AuthenticatedApiClient(\n config,\n fetchAccessToken,\n [],\n logger\n );\n }\n\n async send<TResponse>(request: HttpRequest): Promise<TResponse> {\n return this.client.send<TResponse>(request);\n }\n}\n","export class WritableSessionStoreRequiredError extends Error {\n constructor(\n message = 'This operation requires a writable SessionStore. Provide a `setSession` implementation in your SessionStore to persist or clear OAuth sessions.'\n ) {\n super(message);\n this.name = 'WritableSessionStoreRequiredError';\n }\n}\n","import { WritableSessionStoreRequiredError } from '@/server/shared/errors';\nimport { HttpError } from '@/universal/api/http';\nimport type { Sender } from '@/universal/api/http-client';\nimport {\n type InternalLogger,\n internalLogger,\n} from '@/universal/core/shared/observability/internal-logger';\nimport type { Config } from '@/universal/types/config';\nimport type { OAuthSessionDto } from '@/universal/types/dto/oauth-session';\nimport type {\n AuthorizationCode,\n ClientSecret,\n CodeVerifier,\n} from '@/universal/types/oauth';\nimport {\n ClientCredentialsOAuth,\n type OAuthAccessToken,\n type OAuthRefreshToken,\n OAuthSession,\n} from '@/universal/types/oauth-session';\n\nexport interface SessionStore {\n getSession(): Promise<OAuthSession | null>;\n /**\n * Persists or clears the OAuth session.\n *\n * **Omit this method to create a read-only store.** When absent, the SDK\n * skips token refresh entirely — no network call is made and no refresh\n * token is consumed. This is the correct approach for contexts that can read\n * the session but cannot write it back, such as Next.js Server Components.\n *\n * ⚠️ Do **not** implement this as a no-op (`async () => {}`). If the method\n * is present, the SDK assumes writes succeed: it will fire a token refresh\n * network call, consume the refresh token, then invoke `setSession` — which\n * would silently discard the new session and leave the browser holding an\n * invalidated refresh token. Simply **omit** `setSession` to prevent any\n * refresh from being attempted.\n *\n * {@link ServerAuthNamespace.completeOAuth} and\n * {@link ServerAuthNamespace.logout} always require a writable store and\n * throw {@link WritableSessionStoreRequiredError} if `setSession` is absent.\n */\n setSession?(session: OAuthSession | null): Promise<void>;\n}\n\n/**\n * The empty session store: holds no session, reads nothing, never writes.\n *\n * For server contexts that act without a user — the client-credentials grant\n * (`auth.clientCredentials`) and the public token registry (`tokens`) read\n * nothing from the store, so hosts building those paths need no store of\n * their own.\n *\n * `setSession` is deliberately absent, not a no-op — see\n * {@link SessionStore.setSession} for why a no-op is a bug.\n */\nexport function emptySessionStore(): SessionStore {\n return { getSession: async () => null };\n}\n\n/** The PKCE pair `CoinListClient#auth.completeOAuth` hands to the backend. */\nexport interface CompleteOAuthParams {\n /** The short-lived authorization code parsed out of the redirect URL. */\n code: AuthorizationCode;\n /** The `code_verifier` the browser generated when starting the flow. */\n codeVerifier: CodeVerifier;\n}\n\n/**\n * OAuth session lifecycle on your backend: exchanging authorization codes,\n * keeping the access token fresh, minting app-level tokens, and logging out.\n *\n * This namespace is server-only: every method needs the `clientSecret` and the\n * {@link SessionStore}, neither of which may exist in a browser.\n */\nexport interface ServerAuthNamespace {\n /**\n * Exchanges an authorization code from `CoinListClient#auth.completeOAuth`\n * for an OAuth session and persists it via {@link SessionStore.setSession}.\n *\n * Throws {@link WritableSessionStoreRequiredError} if the session store does\n * not provide `setSession`.\n */\n completeOAuth(params: CompleteOAuthParams): Promise<OAuthSession>;\n\n /**\n * Returns a valid access token for the current session, refreshing it if it\n * is expired or near expiry. This is what you serve to\n * {@link ClientConfig.getAccessToken}.\n *\n * **Writable store**: if the token is expired, the SDK exchanges the refresh\n * token for a new session, persists it, and returns the fresh access token.\n * Returns `null` if there is no session or the refresh fails.\n *\n * **Read-only store** (no `setSession`): refresh is skipped entirely. The\n * stored token is returned as-is, even if it is expired — a non-null return\n * value does **not** guarantee the token is accepted by the API. Before\n * making API calls, check `token.expiresAt > new Date()`. Use a writable\n * store (e.g. in a Route Handler) when you need the SDK to renew the session\n * automatically.\n *\n * @returns the access token, or `null` if there is no session or the session\n * could not be refreshed.\n */\n getAccessToken(): Promise<OAuthAccessToken | null>;\n\n /**\n * Obtains an app-level access token via the OAuth 2.0 `client_credentials`\n * grant (RFC 6749 §4.4). No user is involved: the token authenticates the\n * partner application itself and only grants access to app-level resources\n * such as offers and offer requirements.\n *\n * The token is **not** persisted to the {@link SessionStore} and has no\n * refresh token. It expires at `expiresAt`; once expired, call this method\n * again to obtain a fresh token — the SDK does not renew it automatically.\n *\n * Pass the result to `ServerOffersNamespace` or\n * `ServerRequirementsNamespace.forOffer` to read without a user session.\n */\n clientCredentials(): Promise<ClientCredentialsOAuth>;\n\n /**\n * Revokes the current token via `POST /oauth/revoke` and clears the session.\n *\n * Throws {@link WritableSessionStoreRequiredError} if the session store does\n * not provide `setSession`.\n */\n logout(): Promise<void>;\n}\n\n/** What {@link ServerAuthNamespaceImpl} needs out of `ServerConfig`. */\nexport type ServerAuthConfig = Config & {\n readonly clientSecret: ClientSecret;\n readonly sessionStore: SessionStore;\n /** Seconds before expiry at which a token counts as expired for refresh. */\n readonly accessTokenExpiryBufferSeconds: number;\n /** Whether to rethrow errors the SDK could otherwise swallow (e.g. revoke). */\n readonly strict: boolean;\n};\n\nexport class ServerAuthNamespaceImpl implements ServerAuthNamespace {\n private readonly log: InternalLogger;\n\n constructor(\n private readonly api: Sender,\n private readonly config: ServerAuthConfig\n ) {\n this.log = internalLogger(config.logger ?? null, 'AUTH');\n }\n\n async completeOAuth(params: CompleteOAuthParams): Promise<OAuthSession> {\n return this.log.wrap('completeOAuth', undefined, async () => {\n const setSession = this.writableSessionStore();\n const sessionDto = await this.api.send<OAuthSessionDto>({\n method: 'POST',\n url: `/oauth/token`,\n body: {\n grant_type: 'authorization_code',\n code: params.code,\n redirect_uri: this.config.redirectUri,\n client_id: this.config.clientId,\n client_secret: this.config.clientSecret,\n code_verifier: params.codeVerifier,\n },\n });\n const session = OAuthSession.fromDto(sessionDto);\n await setSession(session);\n return session;\n });\n }\n\n async getAccessToken(): Promise<OAuthAccessToken | null> {\n // Wrapped despite running on every request: `sessionStore.getSession` is\n // host code, and when it throws there is nothing else between the failure\n // and the host's own catch to say which SDK call it came out of.\n return this.log.wrap('getAccessToken', undefined, () =>\n this.readAccessToken()\n );\n }\n\n private async readAccessToken(): Promise<OAuthAccessToken | null> {\n const sessionStore = this.config.sessionStore;\n const session = await sessionStore.getSession();\n if (session == null) return null;\n\n const now = Date.now();\n const expiresAt = session.accessToken.expiresAt.getTime();\n const bufferMs = this.config.accessTokenExpiryBufferSeconds * 1000;\n if (expiresAt > now + bufferMs) {\n // Valid access token, return it regardless\n return session.accessToken;\n }\n\n const setSession = sessionStore.setSession?.bind(sessionStore);\n if (!setSession) {\n // No write session capabilities => can't refresh!\n // Return the access token as-is\n this.log.child({ op: 'getAccessToken' }).warn(() => ({\n msg: 'serving an expired token: the session store is read-only, so it cannot be refreshed',\n }));\n return session.accessToken;\n }\n return this.refreshSession(session.refreshToken, setSession);\n }\n\n private async refreshSession(\n refreshToken: OAuthRefreshToken | undefined,\n setSession: (session: OAuthSession | null) => Promise<void>\n ): Promise<OAuthAccessToken | null> {\n const log = this.log.child({ op: 'refresh' });\n if (!refreshToken) {\n log.warn(() => ({\n msg: 'clearing the session: it carries no refresh token',\n }));\n await setSession(null);\n return null;\n }\n\n try {\n const sessionDto = await this.api.send<OAuthSessionDto>({\n method: 'POST',\n url: `/oauth/token`,\n body: {\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n client_id: this.config.clientId,\n client_secret: this.config.clientSecret,\n },\n });\n const newSession = OAuthSession.fromDto(sessionDto);\n await setSession(newSession);\n log.info(() => ({ msg: 'session renewed' }));\n return newSession.accessToken;\n } catch (error) {\n // The user is logged out by this line, and nothing above sees why:\n // `getAccessToken` answers `null` either way.\n log.failure(\n () => ({ msg: 'refresh failed; clearing the session' }),\n error\n );\n await setSession(null);\n return null;\n }\n }\n\n async clientCredentials(): Promise<ClientCredentialsOAuth> {\n return this.log.wrap('clientCredentials', undefined, async () => {\n const sessionDto = await this.api.send<OAuthSessionDto>({\n method: 'POST',\n url: `/oauth/token`,\n body: {\n grant_type: 'client_credentials',\n client_id: this.config.clientId,\n client_secret: this.config.clientSecret,\n },\n });\n const session = OAuthSession.fromDto(sessionDto);\n return ClientCredentialsOAuth(session.accessToken);\n });\n }\n\n async logout(): Promise<void> {\n return this.log.wrap('logout', undefined, () => this.revokeAndClear());\n }\n\n private async revokeAndClear(): Promise<void> {\n const setSession = this.writableSessionStore();\n const session = await this.config.sessionStore.getSession();\n if (session == null) return;\n\n try {\n await this.api.send({\n method: 'POST',\n url: `/oauth/revoke`,\n body: {\n token: session.accessToken.value,\n client_id: this.config.clientId,\n client_secret: this.config.clientSecret,\n },\n });\n } catch (err) {\n // A failed revoke still leaves the local session invalid, so only strict\n // callers care; anything that is not an HTTP failure is a real bug.\n if (!(err instanceof HttpError) || this.config.strict) {\n throw err;\n }\n this.log.child({ op: 'logout' }).warn(() => ({\n msg: 'the token was not revoked upstream; the local session is cleared regardless',\n }));\n }\n await setSession(null);\n }\n\n /**\n * Returns the store's `setSession`, or throws — the guard every\n * session-writing operation shares.\n */\n private writableSessionStore(): (\n session: OAuthSession | null\n ) => Promise<void> {\n const sessionStore = this.config.sessionStore;\n const setSession = sessionStore.setSession?.bind(sessionStore);\n if (!setSession) {\n throw new WritableSessionStoreRequiredError();\n }\n return setSession;\n }\n}\n","import type { ServerNamespaceContext } from '@/server/core/server-namespace-context';\nimport * as offersApi from '@/universal/api/frontline/offers';\nimport type { OffersNamespace } from '@/universal/core/offers/offers-namespace';\nimport {\n type InternalLogger,\n internalLogger,\n} from '@/universal/core/shared/observability/internal-logger';\nimport type { ClientCredentialsOAuth } from '@/universal/types/oauth-session';\nimport type { Offer, OfferId } from '@/universal/types/offer';\nimport type { OfferDetail } from '@/universal/types/offer-detail';\nimport type {\n PaginatedResponse,\n PaginationParams,\n} from '@/universal/types/pagination';\n\n/**\n * The server-side offers namespace: the same reads as the shared\n * {@link OffersNamespace}, each additionally callable with an app-level token\n * from `ServerAuthNamespace.clientCredentials` instead of a user session.\n *\n * When a user session exists it takes precedence and `clientCreds` acts as a\n * fallback. Without either, the reads throw {@link NotAuthenticatedError}.\n */\nexport interface ServerOffersNamespace extends OffersNamespace {\n /** @param clientCreds app-level token to read without a user session. */\n list(clientCreds?: ClientCredentialsOAuth): Promise<Offer[]>;\n\n /** @param clientCreds app-level token to read without a user session. */\n listPage(\n params: PaginationParams,\n clientCreds?: ClientCredentialsOAuth\n ): Promise<PaginatedResponse<Offer>>;\n\n /** @param clientCreds app-level token to read without a user session. */\n get(id: OfferId, clientCreds?: ClientCredentialsOAuth): Promise<OfferDetail>;\n}\n\nexport class ServerOffersNamespaceImpl implements ServerOffersNamespace {\n private readonly log: InternalLogger;\n\n constructor(private readonly ctx: ServerNamespaceContext) {\n this.log = internalLogger(ctx.logger, 'OFFERS');\n }\n\n async list(clientCreds?: ClientCredentialsOAuth): Promise<Offer[]> {\n return this.log.wrap('list', clientCreds, async () => {\n await this.ctx.ensureAuthenticated(clientCreds);\n return offersApi.fetchOffers(this.ctx.api, clientCreds);\n });\n }\n\n async listPage(\n params: PaginationParams,\n clientCreds?: ClientCredentialsOAuth\n ): Promise<PaginatedResponse<Offer>> {\n return this.log.wrap('listPage', { params, clientCreds }, async () => {\n await this.ctx.ensureAuthenticated(clientCreds);\n return offersApi.fetchOffersPage(this.ctx.api, params, clientCreds);\n });\n }\n\n async get(\n id: OfferId,\n clientCreds?: ClientCredentialsOAuth\n ): Promise<OfferDetail> {\n return this.log.wrap('get', { id, clientCreds }, async () => {\n await this.ctx.ensureAuthenticated(clientCreds);\n return offersApi.fetchOfferDetails(this.ctx.api, id, clientCreds);\n });\n }\n}\n","import type { ServerNamespaceContext } from '@/server/core/server-namespace-context';\nimport * as requirementsApi from '@/universal/api/frontline/requirements';\nimport {\n type RequirementsNamespace,\n RequirementsNamespaceImpl,\n} from '@/universal/core/requirements/requirements-namespace';\nimport type { UniversalNamespaceContext } from '@/universal/core/shared/namespace-context';\nimport type { ClientCredentialsOAuth } from '@/universal/types/oauth-session';\nimport type { OfferId } from '@/universal/types/offer';\nimport type { OfferOptionId } from '@/universal/types/offer-detail';\nimport type { Requirement } from '@/universal/types/requirement';\n\n/**\n * The server-side requirements namespace: the same surface as the shared\n * {@link RequirementsNamespace}, except {@link forOffer} — the offer's\n * requirement definitions are app-level data, so it is additionally callable\n * with a token from `ServerAuthNamespace.clientCredentials`.\n *\n * Everything else is per-user data and needs a user session. `handle` is\n * client-only: there is no browser tab to open on a server.\n */\nexport interface ServerRequirementsNamespace extends RequirementsNamespace {\n /** @param clientCreds app-level token to read without a user session. */\n forOffer(\n offerId: OfferId,\n clientCreds?: ClientCredentialsOAuth\n ): Promise<Record<OfferOptionId, Requirement[]>>;\n}\n\nexport class ServerRequirementsNamespaceImpl\n extends RequirementsNamespaceImpl\n implements ServerRequirementsNamespace\n{\n constructor(\n private readonly serverCtx: UniversalNamespaceContext &\n ServerNamespaceContext\n ) {\n super(serverCtx);\n }\n\n async forOffer(\n offerId: OfferId,\n clientCreds?: ClientCredentialsOAuth\n ): Promise<Record<OfferOptionId, Requirement[]>> {\n return this.log.wrap('forOffer', { offerId, clientCreds }, async () => {\n await this.serverCtx.ensureAuthenticated(clientCreds);\n return requirementsApi.fetchOfferRequirements(\n this.serverCtx.api,\n offerId,\n clientCreds\n );\n });\n }\n}\n","import { ApiClient } from '@/server/core/api/api-client';\nimport {\n type ServerAuthNamespace,\n ServerAuthNamespaceImpl,\n type SessionStore,\n} from '@/server/core/server-auth-namespace';\nimport type { ServerNamespaceContext } from '@/server/core/server-namespace-context';\nimport {\n type ServerOffersNamespace,\n ServerOffersNamespaceImpl,\n} from '@/server/core/server-offers-namespace';\nimport {\n type ServerRequirementsNamespace,\n ServerRequirementsNamespaceImpl,\n} from '@/server/core/server-requirements-namespace';\nimport {\n API_VERSION,\n PUBLIC_API_BASE_URL,\n} from '@/universal/api/frontline/config';\nimport { NABU_BASE_URL } from '@/universal/api/nabu/config';\nimport { publicClients } from '@/universal/api/rpc/public-clients';\nimport {\n type CoinListTokenSaleNamespace,\n CoinListTokenSaleNamespaceImpl,\n} from '@/universal/core/checkout/coin-list/token-sale-namespace';\nimport {\n type OndoNamespace,\n OndoNamespaceImpl,\n} from '@/universal/core/checkout/ondo/ondo-namespace';\nimport {\n type SuperstateSwapNamespace,\n SuperstateSwapNamespaceImpl,\n} from '@/universal/core/checkout/superstate/swap-namespace';\nimport {\n type Erc20Namespace,\n Erc20NamespaceImpl,\n} from '@/universal/core/shared/blockchain/erc20/erc20-namespace';\nimport type { UniversalNamespaceContext } from '@/universal/core/shared/namespace-context';\nimport {\n type TokensNamespace,\n TokensNamespaceImpl,\n} from '@/universal/core/tokens/tokens-namespace';\nimport {\n type WalletsNamespace,\n WalletsNamespaceImpl,\n} from '@/universal/core/wallets/wallets-namespace';\nimport type { Config } from '@/universal/types/config';\nimport { NotAuthenticatedError } from '@/universal/types/errors';\nimport type { ClientSecret } from '@/universal/types/oauth';\nimport type { ClientCredentialsOAuth } from '@/universal/types/oauth-session';\n\n/** Buffer in seconds before expiry to consider token expired for refresh. */\nconst ACCESS_TOKEN_EXPIRY_BUFFER_SECONDS = 60;\n\nexport interface ServerConfig extends Config {\n readonly clientSecret: ClientSecret;\n readonly sessionStore: SessionStore;\n /** Buffer in seconds before expiry to consider token expired for refresh. */\n readonly accessTokenExpiryBufferSeconds?: number;\n /**\n * Whether SDK will throw an exception in cases it can be silent.\n * For example, if token revokation on logout fails.\n */\n readonly strict?: boolean;\n}\n\n/**\n * Server-side CoinList SDK client.\n *\n * Functionality is grouped into namespaces — `coinlist.auth.getAccessToken()`,\n * `coinlist.offers.list()`, `coinlist.requirements.statuses(offerId)`.\n *\n * Operates in one of two modes depending on whether {@link SessionStore}\n * includes a `setSession` implementation:\n *\n * - **Writable store** (`setSession` provided) — full functionality: token\n * refresh, `auth.completeOAuth`, and `auth.logout` all work normally.\n *\n * - **Read-only store** (no `setSession`) — token refresh is skipped entirely,\n * meaning no network call is made and no refresh token is consumed.\n * `auth.completeOAuth` and `auth.logout` throw\n * {@link WritableSessionStoreRequiredError}. `auth.getAccessToken` may\n * return an expired token (see its docs). Use this mode in execution\n * contexts that can read the session but cannot write it back, such as\n * Next.js Server Components.\n *\n * Unless a namespace says otherwise, its methods require a user session and\n * throw {@link NotAuthenticatedError} when there is none.\n */\nexport interface CoinListServer {\n /**\n * OAuth session lifecycle: exchanging an authorization code, serving a valid\n * access token to the browser, minting app-level tokens, and logging out —\n * e.g. `coinlist.auth.getAccessToken()`.\n */\n readonly auth: ServerAuthNamespace;\n\n /**\n * The offer catalogue — e.g. `coinlist.offers.list()`. Every read also\n * accepts an app-level token from {@link ServerAuthNamespace.clientCredentials}\n * so it can run without a user session.\n */\n readonly offers: ServerOffersNamespace;\n\n /**\n * Offer requirements and the operations that satisfy them — e.g.\n * `coinlist.requirements.statuses(offerId)`. `forOffer` also accepts an\n * app-level token; the rest is per-user data and needs a user session.\n */\n readonly requirements: ServerRequirementsNamespace;\n\n /**\n * The user's external wallets: ownership proofs and offer-option bindings —\n * e.g. `coinlist.wallets.list({ offerId, offerOptionId })`.\n */\n readonly wallets: WalletsNamespace;\n\n /**\n * Generic ERC-20 reads (token allowance and balance) — e.g.\n * `coinlist.erc20.getBalance({ ... })`.\n */\n readonly erc20: Erc20Namespace;\n\n /**\n * Token-sale operations: listing, reading, and recording participations —\n * e.g. `coinlist.tokenSale.list()`. The on-chain `execute`\n * flow is client-only and is not exposed here.\n */\n readonly tokenSale: CoinListTokenSaleNamespace;\n\n /**\n * On-chain swap operations: quoting a swap, reading swap-contract state, and\n * allow-listing a proven wallet — e.g.\n * `coinlist.superstate.getOutputToken({ contractAddress, chain })`.\n */\n readonly superstate: SuperstateSwapNamespace;\n\n /**\n * Ondo swap reads: trading status and quoting. Both are free to poll.\n *\n * No CoinList fee is applied to a quote; see {@link OndoNamespace}.\n *\n * This is Ondo's whole surface for now — the wallet-driven half arrives with\n * ENG-1680 and will be client-only, since it needs a wallet to sign with.\n */\n readonly ondo: OndoNamespace;\n\n /**\n * Token display metadata (name, symbol, decimals, logos) from CoinList's\n * public token registry, keyed by chain + contract address — e.g.\n * `coinlist.tokens.get({ chain, address })` for an entry of\n * `Offer.tokens`, or `coinlist.tokens.list()` for the whole\n * catalogue in one request.\n *\n * Public and unauthenticated: unlike the other namespaces, its methods never\n * require a session, so it also works with a read-only store.\n */\n readonly tokens: TokensNamespace;\n}\n\nclass CoinListServerImpl implements CoinListServer {\n private readonly api: ApiClient;\n readonly auth: ServerAuthNamespace;\n readonly offers: ServerOffersNamespace;\n readonly requirements: ServerRequirementsNamespace;\n readonly wallets: WalletsNamespace;\n readonly erc20: Erc20Namespace;\n readonly tokenSale: CoinListTokenSaleNamespace;\n readonly superstate: SuperstateSwapNamespace;\n readonly ondo: OndoNamespace;\n readonly tokens: TokensNamespace;\n\n constructor(private readonly _config: ServerConfig) {\n const logger = _config.logger ?? null;\n this.api = new ApiClient(\n {\n baseUrl: _config.baseUrl ?? PUBLIC_API_BASE_URL,\n xApiVersion: API_VERSION,\n },\n // When refresh=true the renewal middleware has received a 401 and wants a\n // fresh token. A read-only store cannot persist a new session, so return\n // null immediately — this tells the middleware to skip the retry rather\n // than re-sending with the same expired token and wasting a round-trip.\n (refresh) =>\n refresh && !this._config.sessionStore.setSession\n ? Promise.resolve(null)\n : this.auth.getAccessToken(),\n logger\n );\n this.auth = new ServerAuthNamespaceImpl(this.api, {\n ..._config,\n accessTokenExpiryBufferSeconds:\n _config.accessTokenExpiryBufferSeconds ??\n ACCESS_TOKEN_EXPIRY_BUFFER_SECONDS,\n strict: _config.strict ?? false,\n });\n\n const ctx: UniversalNamespaceContext & ServerNamespaceContext = {\n api: this.api,\n rpc: publicClients(this.api, _config.rpc, _config.logger ?? null),\n logger,\n ensureUserAuthenticated: () => this.ensureAuthenticated(undefined),\n ensureAuthenticated: (clientCreds) =>\n this.ensureAuthenticated(clientCreds),\n };\n this.offers = new ServerOffersNamespaceImpl(ctx);\n this.requirements = new ServerRequirementsNamespaceImpl(ctx);\n this.wallets = new WalletsNamespaceImpl(ctx);\n this.erc20 = new Erc20NamespaceImpl(ctx);\n this.tokenSale = new CoinListTokenSaleNamespaceImpl(ctx);\n this.superstate = new SuperstateSwapNamespaceImpl(ctx);\n this.ondo = new OndoNamespaceImpl(ctx);\n this.tokens = new TokensNamespaceImpl(\n _config.tokensBaseUrl ?? NABU_BASE_URL,\n logger\n );\n }\n\n /**\n * An app-level token authenticates a request on its own; without one the\n * caller needs a user session.\n */\n private async ensureAuthenticated(\n clientCreds: ClientCredentialsOAuth | undefined\n ): Promise<void> {\n if (clientCreds) return;\n const token = await this.auth.getAccessToken();\n if (token === null) {\n throw new NotAuthenticatedError();\n }\n }\n}\n\nexport function createCoinListServer(config: ServerConfig): CoinListServer {\n return new CoinListServerImpl(config);\n}\n","import { pino } from 'pino';\nimport {\n loggerOverPino,\n PINO_LEVEL,\n SDK_LOGGER_NAME,\n} from '@/universal/core/shared/observability/pino-logger';\nimport type { Logger, PinoLoggerOptions } from '@/universal/types/logger';\n\n/**\n * A {@link Logger} that writes newline-delimited JSON to stdout through pino.\n *\n * ```ts\n * createCoinListServer({\n * ...config,\n * logger: pinoServerLogger({ isDev: false, level: 'info' }),\n * });\n * ```\n *\n * The Node counterpart of {@link pinoClientLogger}, for a route handler, a BFF\n * or SSR. One line per record, which is what every log aggregator ingests\n * without configuration.\n *\n * ## What it deliberately does not do\n *\n * **No transport, and no `pino-pretty`.** A pino transport runs on a worker\n * thread through `thread-stream`, which every bundler has to be told about\n * (`serverExternalPackages` in Next) and which edge runtimes cannot run at\n * all. Pretty-printing is a pipe the host owns rather than a dependency the\n * SDK takes on their behalf:\n *\n * ```sh\n * node server.js | npx pino-pretty\n * ```\n *\n * **No environment-dependent formatting.** `isDev` decides which levels are\n * legal and nothing else, so a development record and a production record are\n * the same shape - what you debug is what you ship.\n *\n * If you already run pino, or want transports, redaction or `destination`,\n * implement {@link Logger} yourself: it is four methods over an event, and\n * `@opentelemetry/instrumentation-pino` patches the pino module rather than an\n * instance, so trace correlation reaches this logger either way.\n *\n * ## Production\n *\n * **Not advised in production**, the same as everywhere else this seam is\n * documented: the SDK's default answer is to leave {@link Config.logger}\n * undefined outside development, staging and incident reproduction. A backend\n * is the least bad place to disregard that - the records go to your process\n * and your sink rather than to a page the end user can read - but it is still\n * a disregard, and the retention and access questions become yours.\n *\n * If you run one, `isDev: false` restricts you to `'error'`, `'warn'` and\n * `'info'` - `{ isDev: false, level: 'debug' }` does not compile, see\n * {@link PinoLoggerOptions}. Those levels are redacted by construction, which\n * is a mechanism the SDK holds itself to; whether that clears your bar is a\n * judgement the SDK is not in a position to make for you.\n *\n * Holds no module-level state: every call builds its own pino instance, and\n * the level is fixed at construction, so two loggers never interfere. Fixed is\n * this implementation's choice, not the seam's - the SDK re-reads\n * {@link Logger.level} before every log call - so if you want a level you can\n * change at runtime, implement {@link Logger} over your own pino instance\n * rather than calling this.\n */\nexport function pinoServerLogger(options: PinoLoggerOptions): Logger {\n return loggerOverPino(\n // `name` as a child binding rather than pino's `name` option: the option\n // is honoured by pino's node build and silently dropped by its browser\n // build, so a binding is the only spelling that identifies the SDK in\n // both environments.\n pino({\n level: PINO_LEVEL[options.level],\n }).child({ name: SDK_LOGGER_NAME }),\n options.level\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKO,IAAM,YAAN,MAAgB;AAAA,EAGrB,YACE,QACA,kBACA,SAAwB,MACxB;AACA,SAAK,SAAS,IAAI;AAAA,MAChB;AAAA,MACA;AAAA,MACA,CAAC;AAAA,MACD;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,KAAgB,SAA0C;AAC9D,WAAO,KAAK,OAAO,KAAgB,OAAO;AAAA,EAC5C;AACF;;;ACxBO,IAAM,oCAAN,cAAgD,MAAM;AAAA,EAC3D,YACE,UAAU,mJACV;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;;;ACiDO,SAAS,oBAAkC;AAChD,SAAO,EAAE,YAAY,YAAY,KAAK;AACxC;AAkFO,IAAM,0BAAN,MAA6D;AAAA,EAGlE,YACmB,KACA,QACjB;AAFiB;AACA;AAEjB,SAAK,MAAM,eAAe,OAAO,UAAU,MAAM,MAAM;AAAA,EACzD;AAAA,EAEA,MAAM,cAAc,QAAoD;AACtE,WAAO,KAAK,IAAI,KAAK,iBAAiB,QAAW,YA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