@dontcode2/backend 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/auth.ts","../src/db.ts","../src/errors.ts","../src/http.ts","../src/storage.ts","../src/client.ts"],"sourcesContent":["export { dontcode } from './client'\nexport type { DontCodeClient, DontCodeClientOptions } from './client'\n\nexport { DontCodeError, isDontCodeError } from './errors'\nexport type { DontCodeErrorBody } from './errors'\n\nexport { AuthApi, MfaApi } from './auth'\nexport { TableQuery, type DbClient } from './db'\nexport { BucketClient, PublicBucketClient, createStorage, type StorageClient } from './storage'\n\nexport type * from './types'\n","import { Transport } from './http'\nimport type {\n ForgotPasswordInput,\n LoginInput,\n LoginResult,\n MeResult,\n MfaChallengeInput,\n MfaDisableInput,\n MfaEnrollConfirmInput,\n MfaEnrollResult,\n ResetPasswordInput,\n SignupInput,\n SignupResult,\n SimpleResult,\n VerifyEmailInput,\n} from './types'\n\nconst AUTH_BASE = '/api/v1/auth'\n\n/**\n * MFA is per-user and opt-in. `enroll`/`enrollConfirm`/`disable` act as the\n * signed-in user, so they need the end-user access token. `challenge` does\n * not; it completes a login that returned `mfa_required`, exchanging the\n * short-lived challenge token for real session tokens.\n */\nexport class MfaApi {\n constructor(private readonly transport: Transport) {}\n\n /** Complete an MFA login. Pass the `challenge_token` from `login`, plus\n * either the authenticator `code` or a `recoveryCode`. */\n challenge(input: MfaChallengeInput): Promise<LoginResult> {\n return this.transport.json<LoginResult>(`${AUTH_BASE}/mfa/challenge`, {\n challenge_token: input.challengeToken,\n code: input.code,\n recovery_code: input.recoveryCode,\n })\n }\n\n /** Begin enrollment. Render the returned `otpauth_url` as a QR code.\n * Enrollment stays pending until `enrollConfirm`. */\n enroll(input: { accessToken: string }): Promise<MfaEnrollResult> {\n return this.transport.json<MfaEnrollResult>(\n `${AUTH_BASE}/mfa/enroll`,\n {},\n { accessToken: input.accessToken }\n )\n }\n\n /** Confirm enrollment with the first authenticator code. The returned\n * `recovery_codes` are shown once and never again. */\n enrollConfirm(input: MfaEnrollConfirmInput): Promise<SimpleResult> {\n return this.transport.json<SimpleResult>(\n `${AUTH_BASE}/mfa/enroll/confirm`,\n { code: input.code },\n { accessToken: input.accessToken }\n )\n }\n\n /** Turn MFA off. Proves possession of the second factor via `code` or\n * `recoveryCode`. */\n disable(input: MfaDisableInput): Promise<SimpleResult> {\n return this.transport.json<SimpleResult>(\n `${AUTH_BASE}/mfa/disable`,\n { code: input.code, recovery_code: input.recoveryCode },\n { accessToken: input.accessToken }\n )\n }\n}\n\n/**\n * Fronts DontCode Auth with the same shapes as the gateway. Two behaviours are\n * project settings (not API flags) and your code must handle both states:\n * email verification (signup may not return tokens) and MFA (login may be two\n * steps). Branch on the resolved value; never assume one round-trip.\n */\nexport class AuthApi {\n readonly mfa: MfaApi\n\n constructor(private readonly transport: Transport) {\n this.mfa = new MfaApi(transport)\n }\n\n /** Create an account. If the project requires email verification the\n * response has `verification_required: true` and NO tokens; collect a\n * code and call `verifyEmail`, then `login`. */\n signup(input: SignupInput): Promise<SignupResult> {\n return this.transport.json<SignupResult>(`${AUTH_BASE}/signup`, {\n email: input.email,\n password: input.password,\n name: input.name,\n role: input.role,\n })\n }\n\n /** Authenticate. Branch on `mfa_required`: when true you hold only a\n * challenge (finish via `mfa.challenge`); otherwise `tokens` is your\n * session. A 403 `EmailNotVerified` means the email step isn't done. */\n login(input: LoginInput): Promise<LoginResult> {\n return this.transport.json<LoginResult>(`${AUTH_BASE}/login`, {\n email: input.email,\n password: input.password,\n })\n }\n\n /** Resolve the signed-in user from their access token, or `{ user: null }`. */\n me(input: { accessToken: string }): Promise<MeResult> {\n return this.transport.json<MeResult>(`${AUTH_BASE}/me`, {}, { accessToken: input.accessToken })\n }\n\n /** Confirm the 6-digit code emailed at signup. */\n verifyEmail(input: VerifyEmailInput): Promise<SimpleResult> {\n return this.transport.json<SimpleResult>(`${AUTH_BASE}/verify-email`, {\n code: input.code,\n email: input.email,\n })\n }\n\n forgotPassword(input: ForgotPasswordInput): Promise<SimpleResult> {\n return this.transport.json<SimpleResult>(`${AUTH_BASE}/forgot-password`, {\n email: input.email,\n })\n }\n\n resetPassword(input: ResetPasswordInput): Promise<SimpleResult> {\n return this.transport.json<SimpleResult>(`${AUTH_BASE}/reset-password`, {\n code: input.code,\n password: input.password,\n email: input.email,\n })\n }\n}\n","import { Transport } from './http'\nimport type {\n DeleteInput,\n MigrateInput,\n MigrateResult,\n QueryOptions,\n UpdateInput,\n} from './types'\n\nconst DB_PATH = '/api/v1/db'\nconst MIGRATE_PATH = '/api/v1/db/migrate'\n\n/** The gateway wraps every DB result in `{ data }`; we unwrap it. */\ninterface DbEnvelope<T> {\n data: T\n}\n\n/**\n * A handle to one table. Structured queries only; there is no raw-SQL escape\n * hatch (schema changes go through `db.migrate`). `update` and `delete`\n * require a `where` clause server-side, so the types make it mandatory.\n */\nexport class TableQuery {\n constructor(\n private readonly transport: Transport,\n private readonly tableName: string\n ) {}\n\n private async run<T>(operation: string, options: unknown): Promise<T> {\n const res = await this.transport.json<DbEnvelope<T>>(DB_PATH, {\n operation,\n tableName: this.tableName,\n options,\n })\n return res.data\n }\n\n /** Rows matching the query (max 1000 per call). */\n find<T = Record<string, unknown>>(options: QueryOptions = {}): Promise<T[]> {\n return this.run<T[]>('find', options)\n }\n\n /** Alias of `find`. */\n findMany<T = Record<string, unknown>>(options: QueryOptions = {}): Promise<T[]> {\n return this.run<T[]>('findMany', options)\n }\n\n /** The first matching row, or `null`. */\n findFirst<T = Record<string, unknown>>(options: QueryOptions = {}): Promise<T | null> {\n return this.run<T | null>('findFirst', options)\n }\n\n /** Alias of `findFirst`. */\n findOne<T = Record<string, unknown>>(options: QueryOptions = {}): Promise<T | null> {\n return this.run<T | null>('findOne', options)\n }\n\n /** Insert one row. Returns `{ id }`. Unique/FK conflicts throw a 409\n * DontCodeError, the supported idempotency signal. */\n insert(data: Record<string, unknown>): Promise<{ id: unknown }> {\n return this.run<{ id: unknown }>('insert', { data })\n }\n\n /** Update rows matching `where`. Returns `{ count }`. */\n update(input: UpdateInput): Promise<{ count: number }> {\n return this.run<{ count: number }>('update', { where: input.where, data: input.data })\n }\n\n /** Delete rows matching `where`. Returns `{ count }`. */\n delete(input: DeleteInput): Promise<{ count: number }> {\n return this.run<{ count: number }>('delete', { where: input.where })\n }\n\n /** Count matching rows. */\n count(options: Pick<QueryOptions, 'where'> = {}): Promise<number> {\n return this.run<number>('count', options)\n }\n}\n\n/**\n * `db.users.find()` and `db('users').find()` both work; the bracket/callable\n * form is there for table names that aren't valid identifiers. `db.migrate()`\n * applies schema DDL (the one place migrations enter from outside).\n */\nexport type DbClient = {\n readonly [tableName: string]: TableQuery\n} & {\n (tableName: string): TableQuery\n migrate(input: MigrateInput): Promise<MigrateResult>\n}\n\nexport function createDb(transport: Transport): DbClient {\n const table = (tableName: string): TableQuery => new TableQuery(transport, tableName)\n const migrate = (input: MigrateInput): Promise<MigrateResult> =>\n transport.json<MigrateResult>(MIGRATE_PATH, { sql: input.sql })\n\n return new Proxy(table, {\n get(target, prop, receiver) {\n if (prop === 'migrate') return migrate\n // Don't manufacture a TableQuery for symbols or promise-unwrapping\n // probes (`then`) or the function's own members.\n if (typeof prop !== 'string' || prop === 'then' || prop in target) {\n return Reflect.get(target, prop, receiver)\n }\n return new TableQuery(transport, prop)\n },\n apply(_target, _thisArg, args: [string]) {\n return table(args[0])\n },\n }) as unknown as DbClient\n}\n","/**\n * Every non-2xx response from the gateway surfaces as a DontCodeError. The\n * platform's error envelope is `{ error, ... }`, sometimes with a machine\n * `code` (e.g. `EmailNotVerified`, `ChallengeExpired`, `MfaNotOffered`) or\n * rate-limit fields. We preserve the whole body so callers can branch on it.\n *\n * Note: many \"one more step\" auth states (signup needing email verification,\n * login returning `mfa_required`) are 2xx successes, NOT errors; inspect the\n * resolved value for those. Errors are reserved for actual failures.\n */\nexport interface DontCodeErrorBody {\n error?: string\n /** Stable machine code, when the platform sends one. */\n code?: string\n /** Present on 429 responses. */\n rate_limit?: boolean\n /** Seconds until the rate limit resets, on 429 responses. */\n timeleft?: number\n [key: string]: unknown\n}\n\nexport class DontCodeError extends Error {\n /** HTTP status code of the failing response. */\n readonly status: number\n /** Stable machine code, when present (e.g. `EmailNotVerified`). */\n readonly code?: string\n /** The raw parsed response body. */\n readonly body: DontCodeErrorBody\n\n constructor(status: number, body: DontCodeErrorBody) {\n const message =\n typeof body?.error === 'string' && body.error.length > 0\n ? body.error\n : `DontCode request failed with status ${status}`\n super(message)\n this.name = 'DontCodeError'\n this.status = status\n this.code = typeof body?.code === 'string' ? body.code : undefined\n this.body = body ?? {}\n }\n\n /** True when the request was rejected by the per-key rate limiter. */\n get rateLimited(): boolean {\n return this.status === 429\n }\n}\n\n/** Cross-bundle-safe check; works even if two copies of the SDK are loaded. */\nexport function isDontCodeError(err: unknown): err is DontCodeError {\n if (err instanceof DontCodeError) return true\n return (\n typeof err === 'object' &&\n err !== null &&\n (err as { name?: unknown }).name === 'DontCodeError'\n )\n}\n","import { DontCodeError, type DontCodeErrorBody } from './errors'\n\nexport interface TransportConfig {\n /** Project API key. When absent, no Authorization header is sent and the\n * gateway responds with its own \"Missing API key\" 401. */\n apiKey?: string\n /** Gateway origin, already normalized (no trailing slash). */\n baseUrl: string\n}\n\nexport interface RequestOptions {\n /** End-user access token, sent as `X-Access-Token` (separate from the\n * project API key). Required by signed-in auth calls. */\n accessToken?: string\n}\n\n/**\n * The single place network requests are made. Everything else in the SDK is a\n * typed shape around `json()` / `multipart()`. No retries, no caching, just a\n * faithful proxy of the v1 gateway.\n */\nexport class Transport {\n constructor(private readonly config: TransportConfig) {}\n\n private headers(opts?: RequestOptions): Record<string, string> {\n const headers: Record<string, string> = {}\n if (this.config.apiKey) headers['Authorization'] = `Bearer ${this.config.apiKey}`\n if (opts?.accessToken) headers['X-Access-Token'] = opts.accessToken\n return headers\n }\n\n private url(path: string): string {\n return `${this.config.baseUrl}${path}`\n }\n\n /** POST a JSON body and parse the JSON response. */\n async json<T>(path: string, body?: unknown, opts?: RequestOptions): Promise<T> {\n const res = await fetch(this.url(path), {\n method: 'POST',\n headers: { ...this.headers(opts), 'Content-Type': 'application/json' },\n body: JSON.stringify(body ?? {}),\n })\n return this.parse<T>(res)\n }\n\n /** PUT a multipart form (file uploads). The runtime sets the boundary. */\n async multipart<T>(path: string, form: FormData, opts?: RequestOptions): Promise<T> {\n const res = await fetch(this.url(path), {\n method: 'PUT',\n headers: this.headers(opts),\n body: form,\n })\n return this.parse<T>(res)\n }\n\n private async parse<T>(res: Response): Promise<T> {\n const raw = await res.text()\n let data: unknown = null\n if (raw) {\n try {\n data = JSON.parse(raw)\n } catch {\n data = { error: raw }\n }\n }\n if (!res.ok) {\n const body: DontCodeErrorBody =\n data && typeof data === 'object'\n ? (data as DontCodeErrorBody)\n : { error: res.statusText || 'Request failed' }\n throw new DontCodeError(res.status, body)\n }\n return data as T\n }\n}\n","import { Transport } from './http'\nimport type {\n DownloadResult,\n ListResult,\n PresignResult,\n StorageBucket,\n StorageObject,\n TemporaryUrlResult,\n UploadBody,\n} from './types'\n\nconst STORAGE_PATH = '/api/v1/storage'\n\nconst DEFAULT_CONTENT_TYPE = 'application/octet-stream'\n\n/** Normalize whatever the caller hands us into a Blob for multipart upload. */\nfunction toBlob(body: UploadBody, contentType: string): Blob {\n if (body instanceof Blob) return body\n if (typeof body === 'string') return new Blob([body], { type: contentType })\n if (body instanceof ArrayBuffer) return new Blob([body], { type: contentType })\n if (ArrayBuffer.isView(body)) {\n return new Blob([body as unknown as BlobPart], { type: contentType })\n }\n throw new TypeError('upload expects a Blob, ArrayBuffer, typed array, or string')\n}\n\nfunction fileName(path: string): string {\n return path.split('/').filter(Boolean).pop() ?? path\n}\n\n/** Operations available on both buckets. */\nexport class BucketClient {\n constructor(\n protected readonly transport: Transport,\n protected readonly bucket: StorageBucket\n ) {}\n\n protected op<T>(operation: string, params: Record<string, unknown> = {}): Promise<T> {\n return this.transport.json<T>(STORAGE_PATH, { operation, bucket: this.bucket, ...params })\n }\n\n /** List objects under `prefix`. */\n list(prefix?: string): Promise<ListResult> {\n return this.op<ListResult>('list', { prefix })\n }\n\n /** Delete one or more objects. Returns `{ deleted }`. */\n remove(paths: string[]): Promise<{ deleted: number }> {\n return this.op<{ deleted: number }>('remove', { paths })\n }\n\n /** Move/rename an object within the bucket. */\n move(from: string, to: string): Promise<{ object: StorageObject }> {\n return this.op<{ object: StorageObject }>('move', { from, to })\n }\n\n createFolder(path: string): Promise<{ created: string }> {\n return this.op<{ created: string }>('createFolder', { path })\n }\n\n /** Download an object inline (≤ 8 MB). Use `getTemporaryUrl` for larger files. */\n download(path: string): Promise<DownloadResult> {\n return this.op<DownloadResult>('download', { path })\n }\n\n /** A short-lived signed URL (default 300s, max 7 days). */\n getTemporaryUrl(path: string, expiresIn?: number): Promise<TemporaryUrlResult> {\n return this.op<TemporaryUrlResult>('getTemporaryUrl', { path, expiresIn })\n }\n\n /** A presigned PUT URL for direct, large uploads (≤ no inline limit). */\n presignUpload(path: string, contentType?: string): Promise<PresignResult> {\n return this.op<PresignResult>('presignUpload', { path, contentType })\n }\n\n /** Upload bytes directly (≤ 100 MB). For larger files, `presignUpload`\n * then PUT to the returned URL yourself. */\n upload(\n path: string,\n body: UploadBody,\n contentType: string = DEFAULT_CONTENT_TYPE\n ): Promise<{ object: StorageObject }> {\n const form = new FormData()\n form.append('file', toBlob(body, contentType), fileName(path))\n form.append('bucket', this.bucket)\n form.append('path', path)\n form.append('contentType', contentType)\n return this.transport.multipart<{ object: StorageObject }>(STORAGE_PATH, form)\n }\n}\n\n/** The public bucket additionally exposes stable public URLs. */\nexport class PublicBucketClient extends BucketClient {\n constructor(transport: Transport) {\n super(transport, 'public')\n }\n\n /** The permanent public URL for an object. */\n getUrl(path: string): Promise<{ url: string }> {\n return this.op<{ url: string }>('getUrl', { path })\n }\n}\n\nexport interface StorageClient {\n public: PublicBucketClient\n private: BucketClient\n}\n\nexport function createStorage(transport: Transport): StorageClient {\n return {\n public: new PublicBucketClient(transport),\n private: new BucketClient(transport, 'private'),\n }\n}\n","import { AuthApi } from './auth'\nimport { createDb, type DbClient } from './db'\nimport { Transport } from './http'\nimport { createStorage, type StorageClient } from './storage'\n\nconst DEFAULT_BASE_URL = 'https://backend.dontcode.co'\n\nexport interface DontCodeClientOptions {\n /** Project API key (`dc_…`). Defaults to `process.env.DONTCODE_API_KEY`.\n * If neither is set, requests fail naturally with the gateway's\n * \"Missing API key\" 401. */\n apiKey?: string\n /** Gateway origin. Defaults to `process.env.DONTCODE_API_URL`, then to\n * `https://backend.dontcode.co`. */\n baseUrl?: string\n}\n\nexport interface DontCodeClient {\n auth: AuthApi\n db: DbClient\n storage: StorageClient\n}\n\n/** Read an env var without assuming `process` exists (e.g. in the browser). */\nfunction fromEnv(name: string): string | undefined {\n if (typeof process === 'undefined' || !process.env) return undefined\n return process.env[name]\n}\n\n/**\n * Create a DontCode backend client. A thin, typed proxy over the v1 HTTP\n * gateway: auth, database, and storage. The API key scopes every request to\n * a single project; there is nothing else to configure.\n *\n * ```ts\n * import { dontcode } from '@dontcode2/backend'\n * const client = dontcode() // reads DONTCODE_API_KEY\n * await client.auth.signup({ email, password, role: 'editor' })\n * ```\n */\nexport function dontcode(options: DontCodeClientOptions = {}): DontCodeClient {\n const apiKey = options.apiKey ?? fromEnv('DONTCODE_API_KEY')\n const baseUrl = (options.baseUrl ?? fromEnv('DONTCODE_API_URL') ?? DEFAULT_BASE_URL).replace(\n /\\/+$/,\n ''\n )\n\n const transport = new Transport({ apiKey, baseUrl })\n\n return {\n auth: new AuthApi(transport),\n db: createDb(transport),\n storage: createStorage(transport),\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACiBA,IAAM,YAAY;AAQX,IAAM,SAAN,MAAa;AAAA,EAChB,YAA6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AA,IACxC,SAAS,IAAI,aAAa,WAAW,SAAS;AAAA,EAClD;AACJ;;;AC5GA,IAAM,mBAAmB;AAmBzB,SAAS,QAAQ,MAAkC;AAC/C,MAAI,OAAO,YAAY,eAAe,CAAC,QAAQ,IAAK,QAAO;AAC3D,SAAO,QAAQ,IAAI,IAAI;AAC3B;AAaO,SAAS,SAAS,UAAiC,CAAC,GAAmB;AAC1E,QAAM,SAAS,QAAQ,UAAU,QAAQ,kBAAkB;AAC3D,QAAM,WAAW,QAAQ,WAAW,QAAQ,kBAAkB,KAAK,kBAAkB;AAAA,IACjF;AAAA,IACA;AAAA,EACJ;AAEA,QAAM,YAAY,IAAI,UAAU,EAAE,QAAQ,QAAQ,CAAC;AAEnD,SAAO;AAAA,IACH,MAAM,IAAI,QAAQ,SAAS;AAAA,IAC3B,IAAI,SAAS,SAAS;AAAA,IACtB,SAAS,cAAc,SAAS;AAAA,EACpC;AACJ;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts","../src/cookies.ts","../src/errors.ts","../src/session.ts","../src/auth.ts","../src/db.ts","../src/http.ts","../src/storage.ts","../src/client.ts"],"sourcesContent":["export { dontcode } from './client'\nexport type { DontCodeClient, DontCodeClientOptions } from './client'\n\nexport { DontCodeError, isDontCodeError } from './errors'\nexport type { DontCodeErrorBody } from './errors'\n\nexport { AuthApi, MfaApi } from './auth'\nexport { TableQuery, type DbClient } from './db'\nexport { BucketClient, PublicBucketClient, createStorage, type StorageClient } from './storage'\n\nexport {\n decodeAccessToken,\n isSessionExpired,\n InMemorySessionCache,\n} from './session'\nexport type {\n DecodedSession,\n GetSessionInput,\n SessionCache,\n SessionOptions,\n SessionResult,\n SessionStatus,\n} from './session'\n\nexport {\n DEFAULT_SESSION_COOKIE_NAME,\n clearSessionCookie,\n readSessionToken,\n serializeSessionCookie,\n} from './cookies'\nexport type { SessionCookieOptions } from './cookies'\n\nexport type * from './types'\n","/**\n * Cookie helpers, framework-agnostic by design. They return strings: a\n * `Set-Cookie` header value to write, or a parsed token to read. Your framework\n * applies them (`headers.append('Set-Cookie', …)`, SvelteKit `cookies.set`, a\n * Next `Response` cookie, etc.). The SDK never owns a request or response.\n *\n * Defaults match how DontCode's own apps store the session: an httpOnly cookie\n * so JavaScript can't read the token, `Secure`, `SameSite=Lax`, path `/`, and a\n * 7-day max age. Cross-site setups (your app and the gateway on different sites)\n * need `sameSite: 'none'`, which forces `Secure` on.\n */\n\n/** Default cookie name for the end-user access token. */\nexport const DEFAULT_SESSION_COOKIE_NAME = 'dc_access_token'\n\n/** One week, in seconds. Matches the default session lifetime DontCode issues. */\nconst DEFAULT_MAX_AGE_SECONDS = 60 * 60 * 24 * 7\n\nexport interface SessionCookieOptions {\n /** Cookie name. Default `dc_access_token`. */\n name?: string\n /** Lifetime in seconds. Default one week. Pass the token's `ExpiresIn` to\n * keep the cookie and the token in lockstep. */\n maxAge?: number\n /** Default `/`. */\n path?: string\n domain?: string\n /** Default `true`. */\n secure?: boolean\n /** Default `true`. Keep the token unreadable from client JavaScript. */\n httpOnly?: boolean\n /** Default `'lax'`. Use `'none'` for cross-site (it forces `Secure`). */\n sameSite?: 'lax' | 'strict' | 'none'\n}\n\nfunction serialize(name: string, value: string, options: SessionCookieOptions, maxAge: number): string {\n const sameSite = options.sameSite ?? 'lax'\n // SameSite=None is meaningless without Secure (browsers drop it), so force\n // Secure on there; otherwise it defaults on and the caller can opt out.\n const secure = sameSite === 'none' ? true : (options.secure ?? true)\n const httpOnly = options.httpOnly ?? true\n const path = options.path ?? '/'\n\n const parts = [`${name}=${encodeURIComponent(value)}`, `Path=${path}`, `Max-Age=${maxAge}`]\n if (options.domain) parts.push(`Domain=${options.domain}`)\n parts.push(`SameSite=${sameSite.charAt(0).toUpperCase()}${sameSite.slice(1)}`)\n if (httpOnly) parts.push('HttpOnly')\n if (secure) parts.push('Secure')\n return parts.join('; ')\n}\n\n/** Build a `Set-Cookie` value that stores the access token. */\nexport function serializeSessionCookie(token: string, options: SessionCookieOptions = {}): string {\n const name = options.name ?? DEFAULT_SESSION_COOKIE_NAME\n const maxAge = options.maxAge ?? DEFAULT_MAX_AGE_SECONDS\n return serialize(name, token, options, maxAge)\n}\n\n/** Build a `Set-Cookie` value that clears the access token (logout). */\nexport function clearSessionCookie(options: SessionCookieOptions = {}): string {\n const name = options.name ?? DEFAULT_SESSION_COOKIE_NAME\n return serialize(name, '', options, 0)\n}\n\n/** Read the access token out of a `Cookie` request header, or `null`. Pass the\n * raw header string (`name=value; name2=value2`). */\nexport function readSessionToken(\n cookieHeader: string | null | undefined,\n name: string = DEFAULT_SESSION_COOKIE_NAME\n): string | null {\n if (!cookieHeader) return null\n for (const pair of cookieHeader.split(';')) {\n const eq = pair.indexOf('=')\n if (eq === -1) continue\n if (pair.slice(0, eq).trim() !== name) continue\n const raw = pair.slice(eq + 1).trim()\n if (!raw) return null\n try {\n return decodeURIComponent(raw)\n } catch {\n return raw\n }\n }\n return null\n}\n","/**\n * Every non-2xx response from the gateway surfaces as a DontCodeError. The\n * platform's error envelope is `{ error, ... }`, sometimes with a machine\n * `code` (e.g. `EmailNotVerified`, `ChallengeExpired`, `MfaNotOffered`) or\n * rate-limit fields. We preserve the whole body so callers can branch on it.\n *\n * Note: many \"one more step\" auth states (signup needing email verification,\n * login returning `mfa_required`) are 2xx successes, NOT errors; inspect the\n * resolved value for those. Errors are reserved for actual failures.\n *\n * Transport failures (no HTTP response at all) also surface as a DontCodeError\n * so callers have one error type: a timeout is status 408 / code `Timeout`, and\n * any other network failure is status 0 / code `NetworkError`. Neither is a\n * `401`, so a guard can distinguish \"backend unavailable\" from \"signed out\".\n */\nexport interface DontCodeErrorBody {\n error?: string\n /** Stable machine code, when the platform sends one. */\n code?: string\n /** Present on 429 responses. */\n rate_limit?: boolean\n /** Seconds until the rate limit resets, on 429 responses. */\n timeleft?: number\n [key: string]: unknown\n}\n\nexport class DontCodeError extends Error {\n /** HTTP status code of the failing response. */\n readonly status: number\n /** Stable machine code, when present (e.g. `EmailNotVerified`). */\n readonly code?: string\n /** The raw parsed response body. */\n readonly body: DontCodeErrorBody\n\n constructor(status: number, body: DontCodeErrorBody) {\n const message =\n typeof body?.error === 'string' && body.error.length > 0\n ? body.error\n : `DontCode request failed with status ${status}`\n super(message)\n this.name = 'DontCodeError'\n this.status = status\n this.code = typeof body?.code === 'string' ? body.code : undefined\n this.body = body ?? {}\n }\n\n /** True when the request was rejected by the per-key rate limiter. */\n get rateLimited(): boolean {\n return this.status === 429\n }\n}\n\n/** Cross-bundle-safe check; works even if two copies of the SDK are loaded. */\nexport function isDontCodeError(err: unknown): err is DontCodeError {\n if (err instanceof DontCodeError) return true\n return (\n typeof err === 'object' &&\n err !== null &&\n (err as { name?: unknown }).name === 'DontCodeError'\n )\n}\n","import { isDontCodeError } from './errors'\nimport type { AuthApi } from './auth'\nimport type { CurrentUser } from './types'\n\n/**\n * Session helpers, framework-agnostic by design. They never touch a request or\n * response object; they take a token (or a cookie header) and return plain\n * data, so they slot into any framework's guard (Next middleware, SvelteKit\n * hooks, Express, a worker) without an adapter.\n *\n * The point of the module: an auth guard must not make a network round-trip on\n * every navigation, or a slow gateway stalls the page and a swallowed timeout\n * reads as \"signed out\". So there are two modes:\n *\n * - optimistic — decode the token locally (no signature check, no network)\n * and trust its claims for routing. Instant. Used for the common gate.\n * - verified — call the gateway's `me` once, cache the result for a short\n * TTL, and hard-timeout the request. Used for sensitive actions.\n *\n * The trade-offs (no signature verification, revocation lag) are documented on\n * `getSession` and in the public BYOC docs; read them before choosing a mode.\n */\n\n/** A JWT payload decoded WITHOUT verifying its signature. Trust accordingly. */\nexport interface DecodedSession {\n /** Subject — the user id. */\n sub: string\n email?: string\n role?: string\n claims?: Record<string, unknown>\n /** Expiry, seconds since the epoch (standard JWT `exp`). */\n exp?: number\n /** Issued-at, seconds since the epoch (standard JWT `iat`). */\n iat?: number\n [key: string]: unknown\n}\n\nexport type SessionStatus =\n /** A usable session: a present, unexpired token (verified or optimistic). */\n | 'active'\n /** The token is present but past its `exp`. */\n | 'expired'\n /** No token, or an unparseable one. */\n | 'anonymous'\n /** Verified mode could not reach the gateway (timeout/network/5xx). The\n * optimistically-decoded `user` is still returned so the caller can choose\n * to fail open during an outage instead of logging everyone out. */\n | 'unavailable'\n\nexport interface SessionResult {\n status: SessionStatus\n /** The signed-in user, or `null` when anonymous/expired. In `verified` mode\n * this came from the gateway; in `optimistic` (or `unavailable`) it was\n * decoded from the token's own claims. */\n user: CurrentUser | null\n /** True only when `user` was confirmed by a gateway `me` call this request\n * (or from a fresh cache entry of one). False for optimistic decodes. */\n verified: boolean\n /** The token's `exp` (seconds since epoch), when present. */\n expiresAt?: number\n}\n\nexport interface GetSessionInput {\n accessToken: string\n /** `optimistic` (default): decode locally, zero network. `verified`: confirm\n * against the gateway with caching + a hard timeout. */\n mode?: 'optimistic' | 'verified'\n}\n\n/** A place to cache verified sessions. Swap the default in-memory store for a\n * shared one (Redis, KV) when running multiple instances. */\nexport interface SessionCache {\n get(token: string): SessionResult | undefined\n set(token: string, value: SessionResult, ttlMs: number): void\n delete?(token: string): void\n}\n\nexport interface SessionOptions {\n /** Cache for verified sessions. Defaults to a per-process `InMemorySessionCache`. */\n cache?: SessionCache\n /** How long a verified session stays cached. Default 60_000 (60s). Keep it\n * short: a cached session can outlive a server-side revocation by up to\n * this long. */\n ttlMs?: number\n /** Timeout for the `me` call made by `verified` mode (ms). Default 5_000. */\n verifyTimeoutMs?: number\n}\n\nconst DEFAULT_TTL_MS = 60_000\nconst DEFAULT_VERIFY_TIMEOUT_MS = 5_000\n\n/** Default cache: a `Map` with per-entry TTL. Lives for the life of the process\n * (and is shared across requests on a reused serverless instance). */\nexport class InMemorySessionCache implements SessionCache {\n private readonly store = new Map<string, { value: SessionResult; expiresAtMs: number }>()\n\n get(token: string): SessionResult | undefined {\n const hit = this.store.get(token)\n if (!hit) return undefined\n if (Date.now() >= hit.expiresAtMs) {\n this.store.delete(token)\n return undefined\n }\n return hit.value\n }\n\n set(token: string, value: SessionResult, ttlMs: number): void {\n this.store.set(token, { value, expiresAtMs: Date.now() + ttlMs })\n }\n\n delete(token: string): void {\n this.store.delete(token)\n }\n}\n\nfunction base64UrlDecode(segment: string): string {\n const base64 = segment.replace(/-/g, '+').replace(/_/g, '/')\n const padded = base64.length % 4 === 0 ? base64 : base64 + '='.repeat(4 - (base64.length % 4))\n if (typeof atob === 'function') {\n const binary = atob(padded)\n const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0))\n return new TextDecoder().decode(bytes)\n }\n // Node without a global atob (older runtimes); Buffer is always present there.\n return Buffer.from(padded, 'base64').toString('utf8')\n}\n\n/**\n * Decode a JWT access token's payload WITHOUT verifying its signature, or\n * return `null` if it is not a parseable JWT. This is deliberately cheap and\n * offline; it is not proof the token is genuine. DontCode tokens are signed\n * with a secret the gateway never shares, so the only authority on a token is\n * the gateway's `me` endpoint — use `getSession({ mode: 'verified' })` when you\n * need that authority.\n */\nexport function decodeAccessToken(token: string): DecodedSession | null {\n if (!token || typeof token !== 'string') return null\n const parts = token.split('.')\n if (parts.length < 2) return null\n try {\n const payload = JSON.parse(base64UrlDecode(parts[1])) as Record<string, unknown>\n if (!payload || typeof payload.sub !== 'string') return null\n return payload as DecodedSession\n } catch {\n return null\n }\n}\n\n/** True when a token (or already-decoded payload) is past its `exp`. A token\n * with no `exp` is treated as not expired (the caller cannot prove otherwise\n * offline). `skewSeconds` widens the window to absorb clock drift. */\nexport function isSessionExpired(\n input: string | DecodedSession | null,\n opts: { skewSeconds?: number } = {}\n): boolean {\n const decoded = typeof input === 'string' ? decodeAccessToken(input) : input\n if (!decoded || typeof decoded.exp !== 'number') return false\n const nowSeconds = Date.now() / 1000\n return nowSeconds >= decoded.exp - (opts.skewSeconds ?? 0)\n}\n\nfunction userFromClaims(decoded: DecodedSession): CurrentUser {\n return {\n id: decoded.sub,\n email: typeof decoded.email === 'string' ? decoded.email : '',\n role: decoded.role,\n claims: decoded.claims,\n }\n}\n\n/**\n * Resolves access tokens into sessions for `AuthApi`. Holds the verified-session\n * cache and timeout policy. Not exported directly; reach it via\n * `client.auth.getSession` / `client.auth.sessionFromCookies`.\n */\nexport class SessionVerifier {\n private readonly cache: SessionCache\n private readonly ttlMs: number\n private readonly verifyTimeoutMs: number\n\n constructor(\n private readonly auth: AuthApi,\n options: SessionOptions = {}\n ) {\n this.cache = options.cache ?? new InMemorySessionCache()\n this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS\n this.verifyTimeoutMs = options.verifyTimeoutMs ?? DEFAULT_VERIFY_TIMEOUT_MS\n }\n\n async getSession({ accessToken, mode = 'optimistic' }: GetSessionInput): Promise<SessionResult> {\n const decoded = decodeAccessToken(accessToken)\n if (!decoded) return { status: 'anonymous', user: null, verified: false }\n if (isSessionExpired(decoded)) {\n return { status: 'expired', user: null, verified: false, expiresAt: decoded.exp }\n }\n\n const optimistic: SessionResult = {\n status: 'active',\n user: userFromClaims(decoded),\n verified: false,\n expiresAt: decoded.exp,\n }\n if (mode === 'optimistic') return optimistic\n\n const cached = this.cache.get(accessToken)\n if (cached) return cached\n\n try {\n const { user } = await this.auth.me({\n accessToken,\n timeoutMs: this.verifyTimeoutMs,\n })\n const result: SessionResult = user\n ? { status: 'active', user, verified: true, expiresAt: decoded.exp }\n : { status: 'anonymous', user: null, verified: true }\n this.cache.set(accessToken, result, this.ttlMs)\n return result\n } catch (err) {\n // A real 401 means the gateway rejected the token: the user is out.\n if (isDontCodeError(err) && err.status === 401) {\n return { status: 'anonymous', user: null, verified: true }\n }\n // Timeout / network / 5xx: the backend is unreachable, not a verdict\n // on the user. Hand back the optimistic session marked unavailable so\n // the caller decides whether to fail open. Not cached.\n return { ...optimistic, status: 'unavailable' }\n }\n }\n}\n","import { Transport } from './http'\nimport { readSessionToken } from './cookies'\nimport {\n SessionVerifier,\n decodeAccessToken,\n type DecodedSession,\n type GetSessionInput,\n type SessionOptions,\n type SessionResult,\n} from './session'\nimport type {\n ForgotPasswordInput,\n LoginInput,\n LoginResult,\n MeResult,\n MfaChallengeInput,\n MfaDisableInput,\n MfaEnrollConfirmInput,\n MfaEnrollResult,\n ResetPasswordInput,\n SignupInput,\n SignupResult,\n SimpleResult,\n VerifyEmailInput,\n} from './types'\n\nconst AUTH_BASE = '/api/v1/auth'\n\n/**\n * MFA is per-user and opt-in. `enroll`/`enrollConfirm`/`disable` act as the\n * signed-in user, so they need the end-user access token. `challenge` does\n * not; it completes a login that returned `mfa_required`, exchanging the\n * short-lived challenge token for real session tokens.\n */\nexport class MfaApi {\n constructor(private readonly transport: Transport) {}\n\n /** Complete an MFA login. Pass the `challenge_token` from `login`, plus\n * either the authenticator `code` or a `recoveryCode`. */\n challenge(input: MfaChallengeInput): Promise<LoginResult> {\n return this.transport.json<LoginResult>(`${AUTH_BASE}/mfa/challenge`, {\n challenge_token: input.challengeToken,\n code: input.code,\n recovery_code: input.recoveryCode,\n })\n }\n\n /** Begin enrollment. Render the returned `otpauth_url` as a QR code.\n * Enrollment stays pending until `enrollConfirm`. */\n enroll(input: { accessToken: string }): Promise<MfaEnrollResult> {\n return this.transport.json<MfaEnrollResult>(\n `${AUTH_BASE}/mfa/enroll`,\n {},\n { accessToken: input.accessToken }\n )\n }\n\n /** Confirm enrollment with the first authenticator code. The returned\n * `recovery_codes` are shown once and never again. */\n enrollConfirm(input: MfaEnrollConfirmInput): Promise<SimpleResult> {\n return this.transport.json<SimpleResult>(\n `${AUTH_BASE}/mfa/enroll/confirm`,\n { code: input.code },\n { accessToken: input.accessToken }\n )\n }\n\n /** Turn MFA off. Proves possession of the second factor via `code` or\n * `recoveryCode`. */\n disable(input: MfaDisableInput): Promise<SimpleResult> {\n return this.transport.json<SimpleResult>(\n `${AUTH_BASE}/mfa/disable`,\n { code: input.code, recovery_code: input.recoveryCode },\n { accessToken: input.accessToken }\n )\n }\n}\n\n/**\n * Fronts DontCode Auth with the same shapes as the gateway. Two behaviours are\n * project settings (not API flags) and your code must handle both states:\n * email verification (signup may not return tokens) and MFA (login may be two\n * steps). Branch on the resolved value; never assume one round-trip.\n */\nexport class AuthApi {\n readonly mfa: MfaApi\n private readonly sessions: SessionVerifier\n\n constructor(\n private readonly transport: Transport,\n sessionOptions?: SessionOptions\n ) {\n this.mfa = new MfaApi(transport)\n this.sessions = new SessionVerifier(this, sessionOptions)\n }\n\n /** Create an account. If the project requires email verification the\n * response has `verification_required: true` and NO tokens; collect a\n * code and call `verifyEmail`, then `login`. */\n signup(input: SignupInput): Promise<SignupResult> {\n return this.transport.json<SignupResult>(`${AUTH_BASE}/signup`, {\n email: input.email,\n password: input.password,\n name: input.name,\n role: input.role,\n })\n }\n\n /** Authenticate. Branch on `mfa_required`: when true you hold only a\n * challenge (finish via `mfa.challenge`); otherwise `tokens` is your\n * session. A 403 `EmailNotVerified` means the email step isn't done. */\n login(input: LoginInput): Promise<LoginResult> {\n return this.transport.json<LoginResult>(`${AUTH_BASE}/login`, {\n email: input.email,\n password: input.password,\n })\n }\n\n /** Resolve the signed-in user from their access token, or `{ user: null }`.\n * This is a network round-trip; for a per-navigation guard prefer\n * `getSession`, which can answer offline and caches verified results. */\n me(input: { accessToken: string; timeoutMs?: number }): Promise<MeResult> {\n return this.transport.json<MeResult>(\n `${AUTH_BASE}/me`,\n {},\n { accessToken: input.accessToken, timeoutMs: input.timeoutMs }\n )\n }\n\n /**\n * Resolve an access token into a session for a route guard, the one call\n * that replaces \"hit `me` on every navigation\". Two modes:\n *\n * - `'optimistic'` (default): decode the token locally and trust its\n * claims. Zero network, zero stall. The right default for gating page\n * loads. It does NOT verify the signature and will not notice a\n * server-side revocation until the token's own `exp`.\n * - `'verified'`: confirm against the gateway's `me`, cached for a short\n * TTL with a hard timeout. Use it before sensitive actions. On a\n * timeout/outage it returns `status: 'unavailable'` with the optimistic\n * user, so you choose whether to fail open rather than the SDK guessing.\n *\n * See the BYOC docs (\"Sessions\") for the full reasoning and best practices.\n */\n getSession(input: GetSessionInput): Promise<SessionResult> {\n return this.sessions.getSession(input)\n }\n\n /** Read the access token from a `Cookie` request header and resolve it, in\n * one call. `name` defaults to `dc_access_token`. Returns the anonymous\n * session when no cookie is present. */\n sessionFromCookies(\n cookieHeader: string | null | undefined,\n options: { mode?: GetSessionInput['mode']; cookieName?: string } = {}\n ): Promise<SessionResult> {\n const token = readSessionToken(cookieHeader, options.cookieName)\n if (!token) return Promise.resolve({ status: 'anonymous', user: null, verified: false })\n return this.sessions.getSession({ accessToken: token, mode: options.mode })\n }\n\n /** Decode an access token's claims locally without a network call or any\n * signature check. Convenience re-export of `decodeAccessToken`. */\n decodeToken(token: string): DecodedSession | null {\n return decodeAccessToken(token)\n }\n\n /** Confirm the 6-digit code emailed at signup. */\n verifyEmail(input: VerifyEmailInput): Promise<SimpleResult> {\n return this.transport.json<SimpleResult>(`${AUTH_BASE}/verify-email`, {\n code: input.code,\n email: input.email,\n })\n }\n\n forgotPassword(input: ForgotPasswordInput): Promise<SimpleResult> {\n return this.transport.json<SimpleResult>(`${AUTH_BASE}/forgot-password`, {\n email: input.email,\n })\n }\n\n resetPassword(input: ResetPasswordInput): Promise<SimpleResult> {\n return this.transport.json<SimpleResult>(`${AUTH_BASE}/reset-password`, {\n code: input.code,\n password: input.password,\n email: input.email,\n })\n }\n}\n","import { Transport } from './http'\nimport type {\n DeleteInput,\n MigrateInput,\n MigrateResult,\n QueryOptions,\n UpdateInput,\n} from './types'\n\nconst DB_PATH = '/api/v1/db'\nconst MIGRATE_PATH = '/api/v1/db/migrate'\n\n/** The gateway wraps every DB result in `{ data }`; we unwrap it. */\ninterface DbEnvelope<T> {\n data: T\n}\n\n/**\n * A handle to one table. Structured queries only; there is no raw-SQL escape\n * hatch (schema changes go through `db.migrate`). `update` and `delete`\n * require a `where` clause server-side, so the types make it mandatory.\n */\nexport class TableQuery {\n constructor(\n private readonly transport: Transport,\n private readonly tableName: string\n ) {}\n\n private async run<T>(operation: string, options: unknown): Promise<T> {\n const res = await this.transport.json<DbEnvelope<T>>(DB_PATH, {\n operation,\n tableName: this.tableName,\n options,\n })\n return res.data\n }\n\n /** Rows matching the query (max 1000 per call). */\n find<T = Record<string, unknown>>(options: QueryOptions = {}): Promise<T[]> {\n return this.run<T[]>('find', options)\n }\n\n /** Alias of `find`. */\n findMany<T = Record<string, unknown>>(options: QueryOptions = {}): Promise<T[]> {\n return this.run<T[]>('findMany', options)\n }\n\n /** The first matching row, or `null`. */\n findFirst<T = Record<string, unknown>>(options: QueryOptions = {}): Promise<T | null> {\n return this.run<T | null>('findFirst', options)\n }\n\n /** Alias of `findFirst`. */\n findOne<T = Record<string, unknown>>(options: QueryOptions = {}): Promise<T | null> {\n return this.run<T | null>('findOne', options)\n }\n\n /** Insert one row. Returns `{ id }`. Unique/FK conflicts throw a 409\n * DontCodeError, the supported idempotency signal. */\n insert(data: Record<string, unknown>): Promise<{ id: unknown }> {\n return this.run<{ id: unknown }>('insert', { data })\n }\n\n /** Update rows matching `where`. Returns `{ count }`. */\n update(input: UpdateInput): Promise<{ count: number }> {\n return this.run<{ count: number }>('update', { where: input.where, data: input.data })\n }\n\n /** Delete rows matching `where`. Returns `{ count }`. */\n delete(input: DeleteInput): Promise<{ count: number }> {\n return this.run<{ count: number }>('delete', { where: input.where })\n }\n\n /** Count matching rows. */\n count(options: Pick<QueryOptions, 'where'> = {}): Promise<number> {\n return this.run<number>('count', options)\n }\n}\n\n/**\n * `db.users.find()` and `db('users').find()` both work; the bracket/callable\n * form is there for table names that aren't valid identifiers. `db.migrate()`\n * applies schema DDL (the one place migrations enter from outside).\n */\nexport type DbClient = {\n readonly [tableName: string]: TableQuery\n} & {\n (tableName: string): TableQuery\n migrate(input: MigrateInput): Promise<MigrateResult>\n}\n\nexport function createDb(transport: Transport): DbClient {\n const table = (tableName: string): TableQuery => new TableQuery(transport, tableName)\n const migrate = (input: MigrateInput): Promise<MigrateResult> =>\n transport.json<MigrateResult>(MIGRATE_PATH, { sql: input.sql })\n\n return new Proxy(table, {\n get(target, prop, receiver) {\n if (prop === 'migrate') return migrate\n // Don't manufacture a TableQuery for symbols or promise-unwrapping\n // probes (`then`) or the function's own members.\n if (typeof prop !== 'string' || prop === 'then' || prop in target) {\n return Reflect.get(target, prop, receiver)\n }\n return new TableQuery(transport, prop)\n },\n apply(_target, _thisArg, args: [string]) {\n return table(args[0])\n },\n }) as unknown as DbClient\n}\n","import { DontCodeError, type DontCodeErrorBody } from './errors'\n\n/** Default per-request timeout. Without one, a slow or unreachable gateway can\n * hang a request for the platform's full socket timeout (tens of seconds),\n * which is the single worst failure mode for an auth guard on the hot path. */\nexport const DEFAULT_TIMEOUT_MS = 10_000\n\nexport interface TransportConfig {\n /** Project API key. When absent, no Authorization header is sent and the\n * gateway responds with its own \"Missing API key\" 401. */\n apiKey?: string\n /** Gateway origin, already normalized (no trailing slash). */\n baseUrl: string\n /** Per-request timeout in ms. Defaults to `DEFAULT_TIMEOUT_MS`; `0` (or any\n * non-positive value) disables it. */\n timeoutMs?: number\n}\n\nexport interface RequestOptions {\n /** End-user access token, sent as `X-Access-Token` (separate from the\n * project API key). Required by signed-in auth calls. */\n accessToken?: string\n /** Override the client's timeout for this one call (ms). `0` disables it. */\n timeoutMs?: number\n}\n\n/**\n * The single place network requests are made. Everything else in the SDK is a\n * typed shape around `json()` / `multipart()`. No retries, no caching, just a\n * faithful proxy of the v1 gateway.\n */\nexport class Transport {\n constructor(private readonly config: TransportConfig) {}\n\n private headers(opts?: RequestOptions): Record<string, string> {\n const headers: Record<string, string> = {}\n if (this.config.apiKey) headers['Authorization'] = `Bearer ${this.config.apiKey}`\n if (opts?.accessToken) headers['X-Access-Token'] = opts.accessToken\n return headers\n }\n\n private url(path: string): string {\n return `${this.config.baseUrl}${path}`\n }\n\n private timeout(opts?: RequestOptions): number {\n const value = opts?.timeoutMs ?? this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS\n return value > 0 ? value : 0\n }\n\n /**\n * One fetch, with a timeout that turns \"hung socket\" into a fast, typed\n * failure. A timeout surfaces as `DontCodeError` with status 408 / code\n * `Timeout`; any other transport failure (DNS, refused, offline) as status\n * 0 / code `NetworkError`. Both are distinct from a real `401`, so an auth\n * guard can tell \"backend is down\" apart from \"user is signed out\".\n */\n private async send(path: string, init: RequestInit, opts?: RequestOptions): Promise<Response> {\n const timeoutMs = this.timeout(opts)\n const controller = timeoutMs > 0 ? new AbortController() : undefined\n const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : undefined\n try {\n return await fetch(this.url(path), { ...init, signal: controller?.signal })\n } catch (err) {\n if (controller?.signal.aborted) {\n throw new DontCodeError(408, {\n error: `Request to ${path} timed out after ${timeoutMs}ms`,\n code: 'Timeout',\n })\n }\n throw new DontCodeError(0, {\n error: err instanceof Error ? err.message : 'Network request failed',\n code: 'NetworkError',\n })\n } finally {\n if (timer) clearTimeout(timer)\n }\n }\n\n /** POST a JSON body and parse the JSON response. */\n async json<T>(path: string, body?: unknown, opts?: RequestOptions): Promise<T> {\n const res = await this.send(\n path,\n {\n method: 'POST',\n headers: { ...this.headers(opts), 'Content-Type': 'application/json' },\n body: JSON.stringify(body ?? {}),\n },\n opts\n )\n return this.parse<T>(res)\n }\n\n /** PUT a multipart form (file uploads). The runtime sets the boundary. */\n async multipart<T>(path: string, form: FormData, opts?: RequestOptions): Promise<T> {\n const res = await this.send(path, { method: 'PUT', headers: this.headers(opts), body: form }, opts)\n return this.parse<T>(res)\n }\n\n private async parse<T>(res: Response): Promise<T> {\n const raw = await res.text()\n let data: unknown = null\n if (raw) {\n try {\n data = JSON.parse(raw)\n } catch {\n data = { error: raw }\n }\n }\n if (!res.ok) {\n const body: DontCodeErrorBody =\n data && typeof data === 'object'\n ? (data as DontCodeErrorBody)\n : { error: res.statusText || 'Request failed' }\n throw new DontCodeError(res.status, body)\n }\n return data as T\n }\n}\n","import { Transport } from './http'\nimport type {\n DownloadResult,\n ListResult,\n PresignResult,\n StorageBucket,\n StorageObject,\n TemporaryUrlResult,\n UploadBody,\n} from './types'\n\nconst STORAGE_PATH = '/api/v1/storage'\n\nconst DEFAULT_CONTENT_TYPE = 'application/octet-stream'\n\n/** Normalize whatever the caller hands us into a Blob for multipart upload. */\nfunction toBlob(body: UploadBody, contentType: string): Blob {\n if (body instanceof Blob) return body\n if (typeof body === 'string') return new Blob([body], { type: contentType })\n if (body instanceof ArrayBuffer) return new Blob([body], { type: contentType })\n if (ArrayBuffer.isView(body)) {\n return new Blob([body as unknown as BlobPart], { type: contentType })\n }\n throw new TypeError('upload expects a Blob, ArrayBuffer, typed array, or string')\n}\n\nfunction fileName(path: string): string {\n return path.split('/').filter(Boolean).pop() ?? path\n}\n\n/** Operations available on both buckets. */\nexport class BucketClient {\n constructor(\n protected readonly transport: Transport,\n protected readonly bucket: StorageBucket\n ) {}\n\n protected op<T>(operation: string, params: Record<string, unknown> = {}): Promise<T> {\n return this.transport.json<T>(STORAGE_PATH, { operation, bucket: this.bucket, ...params })\n }\n\n /** List objects under `prefix`. */\n list(prefix?: string): Promise<ListResult> {\n return this.op<ListResult>('list', { prefix })\n }\n\n /** Delete one or more objects. Returns `{ deleted }`. */\n remove(paths: string[]): Promise<{ deleted: number }> {\n return this.op<{ deleted: number }>('remove', { paths })\n }\n\n /** Move/rename an object within the bucket. */\n move(from: string, to: string): Promise<{ object: StorageObject }> {\n return this.op<{ object: StorageObject }>('move', { from, to })\n }\n\n createFolder(path: string): Promise<{ created: string }> {\n return this.op<{ created: string }>('createFolder', { path })\n }\n\n /** Download an object inline (≤ 8 MB). Use `getTemporaryUrl` for larger files. */\n download(path: string): Promise<DownloadResult> {\n return this.op<DownloadResult>('download', { path })\n }\n\n /** A short-lived signed URL (default 300s, max 7 days). */\n getTemporaryUrl(path: string, expiresIn?: number): Promise<TemporaryUrlResult> {\n return this.op<TemporaryUrlResult>('getTemporaryUrl', { path, expiresIn })\n }\n\n /** A presigned PUT URL for direct, large uploads (≤ no inline limit). */\n presignUpload(path: string, contentType?: string): Promise<PresignResult> {\n return this.op<PresignResult>('presignUpload', { path, contentType })\n }\n\n /** Upload bytes directly (≤ 100 MB). For larger files, `presignUpload`\n * then PUT to the returned URL yourself. */\n upload(\n path: string,\n body: UploadBody,\n contentType: string = DEFAULT_CONTENT_TYPE\n ): Promise<{ object: StorageObject }> {\n const form = new FormData()\n form.append('file', toBlob(body, contentType), fileName(path))\n form.append('bucket', this.bucket)\n form.append('path', path)\n form.append('contentType', contentType)\n return this.transport.multipart<{ object: StorageObject }>(STORAGE_PATH, form)\n }\n}\n\n/** The public bucket additionally exposes stable public URLs. */\nexport class PublicBucketClient extends BucketClient {\n constructor(transport: Transport) {\n super(transport, 'public')\n }\n\n /** The permanent public URL for an object. */\n getUrl(path: string): Promise<{ url: string }> {\n return this.op<{ url: string }>('getUrl', { path })\n }\n}\n\nexport interface StorageClient {\n public: PublicBucketClient\n private: BucketClient\n}\n\nexport function createStorage(transport: Transport): StorageClient {\n return {\n public: new PublicBucketClient(transport),\n private: new BucketClient(transport, 'private'),\n }\n}\n","import { AuthApi } from './auth'\nimport { createDb, type DbClient } from './db'\nimport { Transport } from './http'\nimport type { SessionOptions } from './session'\nimport { createStorage, type StorageClient } from './storage'\n\nconst DEFAULT_BASE_URL = 'https://backend.dontcode.co'\n\nexport interface DontCodeClientOptions {\n /** Project API key (`dc_…`). Defaults to `process.env.DONTCODE_API_KEY`.\n * If neither is set, requests fail naturally with the gateway's\n * \"Missing API key\" 401. */\n apiKey?: string\n /** Gateway origin. Defaults to `process.env.DONTCODE_API_URL`, then to\n * `https://backend.dontcode.co`. */\n baseUrl?: string\n /** Per-request network timeout in ms. Defaults to 10_000; `0` disables it.\n * Without one, a slow gateway can hang a request for the full socket\n * timeout, the worst case for an auth guard. */\n timeoutMs?: number\n /** Caching + timeout policy for `auth.getSession` / `auth.sessionFromCookies`. */\n session?: SessionOptions\n}\n\nexport interface DontCodeClient {\n auth: AuthApi\n db: DbClient\n storage: StorageClient\n}\n\n/** Read an env var without assuming `process` exists (e.g. in the browser). */\nfunction fromEnv(name: string): string | undefined {\n if (typeof process === 'undefined' || !process.env) return undefined\n return process.env[name]\n}\n\n/**\n * Create a DontCode backend client. A thin, typed proxy over the v1 HTTP\n * gateway: auth, database, and storage. The API key scopes every request to\n * a single project; there is nothing else to configure.\n *\n * ```ts\n * import { dontcode } from '@dontcode2/backend'\n * const client = dontcode() // reads DONTCODE_API_KEY\n * await client.auth.signup({ email, password, role: 'editor' })\n * ```\n */\nexport function dontcode(options: DontCodeClientOptions = {}): DontCodeClient {\n const apiKey = options.apiKey ?? fromEnv('DONTCODE_API_KEY')\n const baseUrl = (options.baseUrl ?? fromEnv('DONTCODE_API_URL') ?? DEFAULT_BASE_URL).replace(\n /\\/+$/,\n ''\n )\n\n const transport = new Transport({ apiKey, baseUrl, timeoutMs: options.timeoutMs })\n\n return {\n auth: new AuthApi(transport, options.session),\n db: createDb(transport),\n storage: createStorage(transport),\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaO,IAAM,8BAA8B;AAG3C,IAAM,0BAA0B,KAAK,KAAK,KAAK;AAmB/C,SAAS,UAAU,MAAc,OAAe,SAA+B,QAAwB;AACnG,QAAM,WAAW,QAAQ,YAAY;AAGrC,QAAM,SAAS,aAAa,SAAS,OAAQ,QAAQ,UAAU;AAC/D,QAAM,WAAW,QAAQ,YAAY;AACrC,QAAM,OAAO,QAAQ,QAAQ;AAE7B,QAAM,QAAQ,CAAC,GAAG,IAAI,IAAI,mBAAmB,KAAK,CAAC,IAAI,QAAQ,IAAI,IAAI,WAAW,MAAM,EAAE;AAC1F,MAAI,QAAQ,OAAQ,OAAM,KAAK,UAAU,QAAQ,MAAM,EAAE;AACzD,QAAM,KAAK,YAAY,SAAS,OAAO,CAAC,EAAE,YAAY,CAAC,GAAG,SAAS,MAAM,CAAC,CAAC,EAAE;AAC7E,MAAI,SAAU,OAAM,KAAK,UAAU;AACnC,MAAI,OAAQ,OAAM,KAAK,QAAQ;AAC/B,SA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AO,eAAe,WAAW;AACtC,WAAO,KAAK,UAAU,UAAqC,cAAc,IAAI;AAAA,EACjF;AACJ;AAGO,IAAM,qBAAN,cAAiC,aAAa;AAAA,EACjD,YAAY,WAAsB;AAC9B,UAAM,WAAW,QAAQ;AAAA,EAC7B;AAAA;AAAA,EAGA,OAAO,MAAwC;AAC3C,WAAO,KAAK,GAAoB,UAAU,EAAE,KAAK,CAAC;AAAA,EACtD;AACJ;AAOO,SAAS,cAAc,WAAqC;AAC/D,SAAO;AAAA,IACH,QAAQ,IAAI,mBAAmB,SAAS;AAAA,IACxC,SAAS,IAAI,aAAa,WAAW,SAAS;AAAA,EAClD;AACJ;;;AC3GA,IAAM,mBAAmB;AAyBzB,SAAS,QAAQ,MAAkC;AAC/C,MAAI,OAAO,YAAY,eAAe,CAAC,QAAQ,IAAK,QAAO;AAC3D,SAAO,QAAQ,IAAI,IAAI;AAC3B;AAaO,SAAS,SAAS,UAAiC,CAAC,GAAmB;AAC1E,QAAM,SAAS,QAAQ,UAAU,QAAQ,kBAAkB;AAC3D,QAAM,WAAW,QAAQ,WAAW,QAAQ,kBAAkB,KAAK,kBAAkB;AAAA,IACjF;AAAA,IACA;AAAA,EACJ;AAEA,QAAM,YAAY,IAAI,UAAU,EAAE,QAAQ,SAAS,WAAW,QAAQ,UAAU,CAAC;AAEjF,SAAO;AAAA,IACH,MAAM,IAAI,QAAQ,WAAW,QAAQ,OAAO;AAAA,IAC5C,IAAI,SAAS,SAAS;AAAA,IACtB,SAAS,cAAc,SAAS;AAAA,EACpC;AACJ;","names":[]}
package/dist/index.d.cts CHANGED
@@ -4,11 +4,16 @@ interface TransportConfig {
4
4
  apiKey?: string;
5
5
  /** Gateway origin, already normalized (no trailing slash). */
6
6
  baseUrl: string;
7
+ /** Per-request timeout in ms. Defaults to `DEFAULT_TIMEOUT_MS`; `0` (or any
8
+ * non-positive value) disables it. */
9
+ timeoutMs?: number;
7
10
  }
8
11
  interface RequestOptions {
9
12
  /** End-user access token, sent as `X-Access-Token` (separate from the
10
13
  * project API key). Required by signed-in auth calls. */
11
14
  accessToken?: string;
15
+ /** Override the client's timeout for this one call (ms). `0` disables it. */
16
+ timeoutMs?: number;
12
17
  }
13
18
  /**
14
19
  * The single place network requests are made. Everything else in the SDK is a
@@ -20,6 +25,15 @@ declare class Transport {
20
25
  constructor(config: TransportConfig);
21
26
  private headers;
22
27
  private url;
28
+ private timeout;
29
+ /**
30
+ * One fetch, with a timeout that turns "hung socket" into a fast, typed
31
+ * failure. A timeout surfaces as `DontCodeError` with status 408 / code
32
+ * `Timeout`; any other transport failure (DNS, refused, offline) as status
33
+ * 0 / code `NetworkError`. Both are distinct from a real `401`, so an auth
34
+ * guard can tell "backend is down" apart from "user is signed out".
35
+ */
36
+ private send;
23
37
  /** POST a JSON body and parse the JSON response. */
24
38
  json<T>(path: string, body?: unknown, opts?: RequestOptions): Promise<T>;
25
39
  /** PUT a multipart form (file uploads). The runtime sets the boundary. */
@@ -188,6 +202,107 @@ interface TemporaryUrlResult {
188
202
  /** Bytes the SDK can turn into an upload body. */
189
203
  type UploadBody = Blob | ArrayBuffer | ArrayBufferView | string;
190
204
 
205
+ /**
206
+ * Session helpers, framework-agnostic by design. They never touch a request or
207
+ * response object; they take a token (or a cookie header) and return plain
208
+ * data, so they slot into any framework's guard (Next middleware, SvelteKit
209
+ * hooks, Express, a worker) without an adapter.
210
+ *
211
+ * The point of the module: an auth guard must not make a network round-trip on
212
+ * every navigation, or a slow gateway stalls the page and a swallowed timeout
213
+ * reads as "signed out". So there are two modes:
214
+ *
215
+ * - optimistic — decode the token locally (no signature check, no network)
216
+ * and trust its claims for routing. Instant. Used for the common gate.
217
+ * - verified — call the gateway's `me` once, cache the result for a short
218
+ * TTL, and hard-timeout the request. Used for sensitive actions.
219
+ *
220
+ * The trade-offs (no signature verification, revocation lag) are documented on
221
+ * `getSession` and in the public BYOC docs; read them before choosing a mode.
222
+ */
223
+ /** A JWT payload decoded WITHOUT verifying its signature. Trust accordingly. */
224
+ interface DecodedSession {
225
+ /** Subject — the user id. */
226
+ sub: string;
227
+ email?: string;
228
+ role?: string;
229
+ claims?: Record<string, unknown>;
230
+ /** Expiry, seconds since the epoch (standard JWT `exp`). */
231
+ exp?: number;
232
+ /** Issued-at, seconds since the epoch (standard JWT `iat`). */
233
+ iat?: number;
234
+ [key: string]: unknown;
235
+ }
236
+ type SessionStatus =
237
+ /** A usable session: a present, unexpired token (verified or optimistic). */
238
+ 'active'
239
+ /** The token is present but past its `exp`. */
240
+ | 'expired'
241
+ /** No token, or an unparseable one. */
242
+ | 'anonymous'
243
+ /** Verified mode could not reach the gateway (timeout/network/5xx). The
244
+ * optimistically-decoded `user` is still returned so the caller can choose
245
+ * to fail open during an outage instead of logging everyone out. */
246
+ | 'unavailable';
247
+ interface SessionResult {
248
+ status: SessionStatus;
249
+ /** The signed-in user, or `null` when anonymous/expired. In `verified` mode
250
+ * this came from the gateway; in `optimistic` (or `unavailable`) it was
251
+ * decoded from the token's own claims. */
252
+ user: CurrentUser | null;
253
+ /** True only when `user` was confirmed by a gateway `me` call this request
254
+ * (or from a fresh cache entry of one). False for optimistic decodes. */
255
+ verified: boolean;
256
+ /** The token's `exp` (seconds since epoch), when present. */
257
+ expiresAt?: number;
258
+ }
259
+ interface GetSessionInput {
260
+ accessToken: string;
261
+ /** `optimistic` (default): decode locally, zero network. `verified`: confirm
262
+ * against the gateway with caching + a hard timeout. */
263
+ mode?: 'optimistic' | 'verified';
264
+ }
265
+ /** A place to cache verified sessions. Swap the default in-memory store for a
266
+ * shared one (Redis, KV) when running multiple instances. */
267
+ interface SessionCache {
268
+ get(token: string): SessionResult | undefined;
269
+ set(token: string, value: SessionResult, ttlMs: number): void;
270
+ delete?(token: string): void;
271
+ }
272
+ interface SessionOptions {
273
+ /** Cache for verified sessions. Defaults to a per-process `InMemorySessionCache`. */
274
+ cache?: SessionCache;
275
+ /** How long a verified session stays cached. Default 60_000 (60s). Keep it
276
+ * short: a cached session can outlive a server-side revocation by up to
277
+ * this long. */
278
+ ttlMs?: number;
279
+ /** Timeout for the `me` call made by `verified` mode (ms). Default 5_000. */
280
+ verifyTimeoutMs?: number;
281
+ }
282
+ /** Default cache: a `Map` with per-entry TTL. Lives for the life of the process
283
+ * (and is shared across requests on a reused serverless instance). */
284
+ declare class InMemorySessionCache implements SessionCache {
285
+ private readonly store;
286
+ get(token: string): SessionResult | undefined;
287
+ set(token: string, value: SessionResult, ttlMs: number): void;
288
+ delete(token: string): void;
289
+ }
290
+ /**
291
+ * Decode a JWT access token's payload WITHOUT verifying its signature, or
292
+ * return `null` if it is not a parseable JWT. This is deliberately cheap and
293
+ * offline; it is not proof the token is genuine. DontCode tokens are signed
294
+ * with a secret the gateway never shares, so the only authority on a token is
295
+ * the gateway's `me` endpoint — use `getSession({ mode: 'verified' })` when you
296
+ * need that authority.
297
+ */
298
+ declare function decodeAccessToken(token: string): DecodedSession | null;
299
+ /** True when a token (or already-decoded payload) is past its `exp`. A token
300
+ * with no `exp` is treated as not expired (the caller cannot prove otherwise
301
+ * offline). `skewSeconds` widens the window to absorb clock drift. */
302
+ declare function isSessionExpired(input: string | DecodedSession | null, opts?: {
303
+ skewSeconds?: number;
304
+ }): boolean;
305
+
191
306
  /**
192
307
  * MFA is per-user and opt-in. `enroll`/`enrollConfirm`/`disable` act as the
193
308
  * signed-in user, so they need the end-user access token. `challenge` does
@@ -221,7 +336,8 @@ declare class MfaApi {
221
336
  declare class AuthApi {
222
337
  private readonly transport;
223
338
  readonly mfa: MfaApi;
224
- constructor(transport: Transport);
339
+ private readonly sessions;
340
+ constructor(transport: Transport, sessionOptions?: SessionOptions);
225
341
  /** Create an account. If the project requires email verification the
226
342
  * response has `verification_required: true` and NO tokens; collect a
227
343
  * code and call `verifyEmail`, then `login`. */
@@ -230,10 +346,39 @@ declare class AuthApi {
230
346
  * challenge (finish via `mfa.challenge`); otherwise `tokens` is your
231
347
  * session. A 403 `EmailNotVerified` means the email step isn't done. */
232
348
  login(input: LoginInput): Promise<LoginResult>;
233
- /** Resolve the signed-in user from their access token, or `{ user: null }`. */
349
+ /** Resolve the signed-in user from their access token, or `{ user: null }`.
350
+ * This is a network round-trip; for a per-navigation guard prefer
351
+ * `getSession`, which can answer offline and caches verified results. */
234
352
  me(input: {
235
353
  accessToken: string;
354
+ timeoutMs?: number;
236
355
  }): Promise<MeResult>;
356
+ /**
357
+ * Resolve an access token into a session for a route guard, the one call
358
+ * that replaces "hit `me` on every navigation". Two modes:
359
+ *
360
+ * - `'optimistic'` (default): decode the token locally and trust its
361
+ * claims. Zero network, zero stall. The right default for gating page
362
+ * loads. It does NOT verify the signature and will not notice a
363
+ * server-side revocation until the token's own `exp`.
364
+ * - `'verified'`: confirm against the gateway's `me`, cached for a short
365
+ * TTL with a hard timeout. Use it before sensitive actions. On a
366
+ * timeout/outage it returns `status: 'unavailable'` with the optimistic
367
+ * user, so you choose whether to fail open rather than the SDK guessing.
368
+ *
369
+ * See the BYOC docs ("Sessions") for the full reasoning and best practices.
370
+ */
371
+ getSession(input: GetSessionInput): Promise<SessionResult>;
372
+ /** Read the access token from a `Cookie` request header and resolve it, in
373
+ * one call. `name` defaults to `dc_access_token`. Returns the anonymous
374
+ * session when no cookie is present. */
375
+ sessionFromCookies(cookieHeader: string | null | undefined, options?: {
376
+ mode?: GetSessionInput['mode'];
377
+ cookieName?: string;
378
+ }): Promise<SessionResult>;
379
+ /** Decode an access token's claims locally without a network call or any
380
+ * signature check. Convenience re-export of `decodeAccessToken`. */
381
+ decodeToken(token: string): DecodedSession | null;
237
382
  /** Confirm the 6-digit code emailed at signup. */
238
383
  verifyEmail(input: VerifyEmailInput): Promise<SimpleResult>;
239
384
  forgotPassword(input: ForgotPasswordInput): Promise<SimpleResult>;
@@ -339,6 +484,12 @@ interface DontCodeClientOptions {
339
484
  /** Gateway origin. Defaults to `process.env.DONTCODE_API_URL`, then to
340
485
  * `https://backend.dontcode.co`. */
341
486
  baseUrl?: string;
487
+ /** Per-request network timeout in ms. Defaults to 10_000; `0` disables it.
488
+ * Without one, a slow gateway can hang a request for the full socket
489
+ * timeout, the worst case for an auth guard. */
490
+ timeoutMs?: number;
491
+ /** Caching + timeout policy for `auth.getSession` / `auth.sessionFromCookies`. */
492
+ session?: SessionOptions;
342
493
  }
343
494
  interface DontCodeClient {
344
495
  auth: AuthApi;
@@ -367,6 +518,11 @@ declare function dontcode(options?: DontCodeClientOptions): DontCodeClient;
367
518
  * Note: many "one more step" auth states (signup needing email verification,
368
519
  * login returning `mfa_required`) are 2xx successes, NOT errors; inspect the
369
520
  * resolved value for those. Errors are reserved for actual failures.
521
+ *
522
+ * Transport failures (no HTTP response at all) also surface as a DontCodeError
523
+ * so callers have one error type: a timeout is status 408 / code `Timeout`, and
524
+ * any other network failure is status 0 / code `NetworkError`. Neither is a
525
+ * `401`, so a guard can distinguish "backend unavailable" from "signed out".
370
526
  */
371
527
  interface DontCodeErrorBody {
372
528
  error?: string;
@@ -392,4 +548,41 @@ declare class DontCodeError extends Error {
392
548
  /** Cross-bundle-safe check; works even if two copies of the SDK are loaded. */
393
549
  declare function isDontCodeError(err: unknown): err is DontCodeError;
394
550
 
395
- export { AuthApi, type AuthTokens, BucketClient, type CurrentUser, type DbClient, type DeleteInput, type DontCodeClient, type DontCodeClientOptions, DontCodeError, type DontCodeErrorBody, type DownloadResult, type ForgotPasswordInput, type ListResult, type LoginInput, type LoginResult, type MeResult, MfaApi, type MfaChallengeInput, type MfaDisableInput, type MfaEnrollConfirmInput, type MfaEnrollResult, type MigrateInput, type MigrateResult, type OrderByClause, type PresignResult, PublicBucketClient, type QueryOptions, type ResetPasswordInput, type SignupInput, type SignupResult, type SimpleResult, type StorageBucket, type StorageClient, type StorageObject, TableQuery, type TemporaryUrlResult, type UpdateInput, type UploadBody, type VerifyEmailInput, type WhereClause, type WhereOperator, createStorage, dontcode, isDontCodeError };
551
+ /**
552
+ * Cookie helpers, framework-agnostic by design. They return strings: a
553
+ * `Set-Cookie` header value to write, or a parsed token to read. Your framework
554
+ * applies them (`headers.append('Set-Cookie', …)`, SvelteKit `cookies.set`, a
555
+ * Next `Response` cookie, etc.). The SDK never owns a request or response.
556
+ *
557
+ * Defaults match how DontCode's own apps store the session: an httpOnly cookie
558
+ * so JavaScript can't read the token, `Secure`, `SameSite=Lax`, path `/`, and a
559
+ * 7-day max age. Cross-site setups (your app and the gateway on different sites)
560
+ * need `sameSite: 'none'`, which forces `Secure` on.
561
+ */
562
+ /** Default cookie name for the end-user access token. */
563
+ declare const DEFAULT_SESSION_COOKIE_NAME = "dc_access_token";
564
+ interface SessionCookieOptions {
565
+ /** Cookie name. Default `dc_access_token`. */
566
+ name?: string;
567
+ /** Lifetime in seconds. Default one week. Pass the token's `ExpiresIn` to
568
+ * keep the cookie and the token in lockstep. */
569
+ maxAge?: number;
570
+ /** Default `/`. */
571
+ path?: string;
572
+ domain?: string;
573
+ /** Default `true`. */
574
+ secure?: boolean;
575
+ /** Default `true`. Keep the token unreadable from client JavaScript. */
576
+ httpOnly?: boolean;
577
+ /** Default `'lax'`. Use `'none'` for cross-site (it forces `Secure`). */
578
+ sameSite?: 'lax' | 'strict' | 'none';
579
+ }
580
+ /** Build a `Set-Cookie` value that stores the access token. */
581
+ declare function serializeSessionCookie(token: string, options?: SessionCookieOptions): string;
582
+ /** Build a `Set-Cookie` value that clears the access token (logout). */
583
+ declare function clearSessionCookie(options?: SessionCookieOptions): string;
584
+ /** Read the access token out of a `Cookie` request header, or `null`. Pass the
585
+ * raw header string (`name=value; name2=value2`). */
586
+ declare function readSessionToken(cookieHeader: string | null | undefined, name?: string): string | null;
587
+
588
+ export { AuthApi, type AuthTokens, BucketClient, type CurrentUser, DEFAULT_SESSION_COOKIE_NAME, type DbClient, type DecodedSession, type DeleteInput, type DontCodeClient, type DontCodeClientOptions, DontCodeError, type DontCodeErrorBody, type DownloadResult, type ForgotPasswordInput, type GetSessionInput, InMemorySessionCache, type ListResult, type LoginInput, type LoginResult, type MeResult, MfaApi, type MfaChallengeInput, type MfaDisableInput, type MfaEnrollConfirmInput, type MfaEnrollResult, type MigrateInput, type MigrateResult, type OrderByClause, type PresignResult, PublicBucketClient, type QueryOptions, type ResetPasswordInput, type SessionCache, type SessionCookieOptions, type SessionOptions, type SessionResult, type SessionStatus, type SignupInput, type SignupResult, type SimpleResult, type StorageBucket, type StorageClient, type StorageObject, TableQuery, type TemporaryUrlResult, type UpdateInput, type UploadBody, type VerifyEmailInput, type WhereClause, type WhereOperator, clearSessionCookie, createStorage, decodeAccessToken, dontcode, isDontCodeError, isSessionExpired, readSessionToken, serializeSessionCookie };