@secondlayer/shared 7.11.2 → 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/src/archive/range-digest.d.ts +0 -169
  2. package/dist/src/archive/semantic-digest-builder.d.ts +0 -169
  3. package/dist/src/coverage/index.d.ts +0 -169
  4. package/dist/src/crypto/secrets.js +22 -3
  5. package/dist/src/crypto/secrets.js.map +3 -3
  6. package/dist/src/db/index.d.ts +1 -211
  7. package/dist/src/db/index.js +22 -16
  8. package/dist/src/db/index.js.map +4 -4
  9. package/dist/src/db/queries/chain-reorgs.d.ts +0 -169
  10. package/dist/src/db/queries/chain-reorgs.js +22 -16
  11. package/dist/src/db/queries/chain-reorgs.js.map +4 -4
  12. package/dist/src/db/queries/contracts.d.ts +0 -169
  13. package/dist/src/db/queries/instance.d.ts +0 -169
  14. package/dist/src/db/queries/integrity.d.ts +0 -169
  15. package/dist/src/db/queries/subgraph-gaps.d.ts +0 -169
  16. package/dist/src/db/queries/subgraph-operations.d.ts +1 -170
  17. package/dist/src/db/queries/subgraph-operations.js +1 -15
  18. package/dist/src/db/queries/subgraph-operations.js.map +3 -3
  19. package/dist/src/db/queries/subgraphs.d.ts +1 -191
  20. package/dist/src/db/queries/subgraphs.js +30 -1068
  21. package/dist/src/db/queries/subgraphs.js.map +5 -12
  22. package/dist/src/db/queries/subscriptions.d.ts +0 -169
  23. package/dist/src/db/queries/subscriptions.js +22 -3
  24. package/dist/src/db/queries/subscriptions.js.map +3 -3
  25. package/dist/src/db/schema.d.ts +1 -198
  26. package/dist/src/errors.d.ts +1 -22
  27. package/dist/src/errors.js +2 -4
  28. package/dist/src/errors.js.map +3 -3
  29. package/dist/src/index.d.ts +5 -256
  30. package/dist/src/index.js +23 -20
  31. package/dist/src/index.js.map +6 -6
  32. package/dist/src/mode.d.ts +16 -2
  33. package/dist/src/mode.js +25 -4
  34. package/dist/src/mode.js.map +3 -3
  35. package/dist/src/node/local-client.d.ts +0 -169
  36. package/dist/src/schemas/index.d.ts +5 -25
  37. package/dist/src/schemas/index.js +1 -2
  38. package/dist/src/schemas/index.js.map +3 -3
  39. package/dist/src/schemas/subgraphs.d.ts +5 -25
  40. package/dist/src/schemas/subgraphs.js +1 -2
  41. package/dist/src/schemas/subgraphs.js.map +3 -3
  42. package/dist/src/streams-rows/index.d.ts +399 -0
  43. package/dist/src/streams-rows/index.js +336 -0
  44. package/dist/src/streams-rows/index.js.map +17 -0
  45. package/dist/src/subgraphs/spec.d.ts +0 -9
  46. package/migrations/0118_drop_retired_control_tables.ts +53 -0
  47. package/migrations/0119_drop_accounts_plan.ts +29 -0
  48. package/package.json +5 -1
@@ -2,12 +2,12 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/mode.ts", "../src/crypto/hmac.ts", "../src/crypto/secrets.ts", "../src/db/queries/subscriptions.ts"],
4
4
  "sourcesContent": [
5
- "/**\n * Instance modes for the Secondlayer platform.\n *\n * - `oss`: self-hosted, single-tenant. No auth middleware, no platform routes\n * (projects, admin). Everything runs against a single `DATABASE_URL`.\n * Intended for `docker compose up`.\n *\n * - `platform`: control-plane mode. Magic-link auth, API keys, projects,\n * admin. Serves the dashboard + CLI against a single shared DB. Post\n * 2026-05-14 shared-rip this also serves subgraphs + subscriptions.\n */\n\nexport type InstanceMode = \"oss\" | \"platform\";\n\nconst VALID_MODES: readonly InstanceMode[] = [\"oss\", \"platform\"];\n\n/**\n * Resolve the active instance mode from `process.env.INSTANCE_MODE`.\n * Defaults to `\"oss\"` — the safest default for self-hosters who deploy\n * without setting the variable.\n */\nexport function getInstanceMode(): InstanceMode {\n\tconst raw = process.env.INSTANCE_MODE?.trim().toLowerCase();\n\tif (raw && (VALID_MODES as readonly string[]).includes(raw)) {\n\t\treturn raw as InstanceMode;\n\t}\n\treturn \"oss\";\n}\n\n/** True when the active mode is `\"platform\"` (shared multi-tenant). */\nexport function isPlatformMode(): boolean {\n\treturn getInstanceMode() === \"platform\";\n}\n\n/** True when the active mode is `\"oss\"` (self-hosted). */\nexport function isOssMode(): boolean {\n\treturn getInstanceMode() === \"oss\";\n}\n",
5
+ "/**\n * Instance modes for the Secondlayer platform.\n *\n * - `oss`: self-hosted, single-tenant. No auth middleware, no platform routes\n * (projects, admin). Everything runs against a single `DATABASE_URL`.\n * Intended for `docker compose up`.\n *\n * - `platform`: control-plane mode. Magic-link auth, API keys, projects,\n * admin. Serves the dashboard + CLI against a single shared DB. Post\n * 2026-05-14 shared-rip this also serves subgraphs + subscriptions.\n */\n\nexport type InstanceMode = \"oss\" | \"platform\";\n\n/** What the operator wrote in the env — `archive` is the honest name for the\n * metered public-archive deployment and aliases `platform` behaviorally. */\nexport type DeclaredInstanceMode = InstanceMode | \"archive\";\n\nconst VALID_MODES: readonly DeclaredInstanceMode[] = [\n\t\"oss\",\n\t\"platform\",\n\t\"archive\",\n];\n\nfunction declaredMode(): DeclaredInstanceMode {\n\tconst raw = process.env.INSTANCE_MODE?.trim().toLowerCase();\n\tif (raw && (VALID_MODES as readonly string[]).includes(raw)) {\n\t\treturn raw as DeclaredInstanceMode;\n\t}\n\treturn \"oss\";\n}\n\n/**\n * Resolve the active instance mode from `process.env.INSTANCE_MODE`.\n * Defaults to `\"oss\"` — the safest default for self-hosters who deploy\n * without setting the variable. `archive` normalizes to `platform` here so\n * every behavioral branch stays a two-way choice; use\n * `getDeclaredInstanceMode()` for display surfaces.\n */\nexport function getInstanceMode(): InstanceMode {\n\tconst declared = declaredMode();\n\treturn declared === \"archive\" ? \"platform\" : declared;\n}\n\n/** The mode as declared in the env, for status/identity surfaces. */\nexport function getDeclaredInstanceMode(): DeclaredInstanceMode {\n\treturn declaredMode();\n}\n\n/**\n * True when public reads are credit-metered (the free window, retention, and\n * credits gates arm). Platform/archive deployments meter by default;\n * self-host never does unless the operator explicitly sets\n * `METERED_READS=true`. `METERED_READS=false` disarms a metered deployment.\n */\nexport function isMeteredReads(): boolean {\n\tconst override = process.env.METERED_READS?.trim().toLowerCase();\n\tif (override === \"true\") return true;\n\tif (override === \"false\") return false;\n\treturn getInstanceMode() === \"platform\";\n}\n\n/** True when the active mode is `\"platform\"` (shared multi-tenant). */\nexport function isPlatformMode(): boolean {\n\treturn getInstanceMode() === \"platform\";\n}\n\n/** True when the active mode is `\"oss\"` (self-hosted). */\nexport function isOssMode(): boolean {\n\treturn getInstanceMode() === \"oss\";\n}\n",
6
6
  "import { createHmac, randomBytes } from \"node:crypto\";\n\n/**\n * Generate a random secret for delivery signing\n * Returns 32 bytes as a 64-character hex string\n */\nexport function generateSecret(): string {\n\treturn randomBytes(32).toString(\"hex\");\n}\n\n/**\n * Sign a payload with HMAC-SHA256\n * Returns the signature as a hex string\n */\nexport function signPayload(payload: string, secret: string): string {\n\tconst hmac = createHmac(\"sha256\", secret);\n\thmac.update(payload);\n\treturn hmac.digest(\"hex\");\n}\n\n/**\n * Verify an HMAC signature\n * Uses constant-time comparison to prevent timing attacks\n */\nexport function verifySignature(\n\tpayload: string,\n\tsignature: string,\n\tsecret: string,\n): boolean {\n\tconst expectedSignature = signPayload(payload, secret);\n\n\t// Constant-time comparison\n\tif (signature.length !== expectedSignature.length) {\n\t\treturn false;\n\t}\n\n\tlet result = 0;\n\tfor (let i = 0; i < signature.length; i++) {\n\t\tresult |= signature.charCodeAt(i) ^ expectedSignature.charCodeAt(i);\n\t}\n\n\treturn result === 0;\n}\n\n/**\n * Create a Stripe-style signature header\n * Format: t=timestamp,v1=signature\n */\nexport function createSignatureHeader(\n\tpayload: string,\n\tsecret: string,\n\ttimestamp?: number,\n): string {\n\tconst ts = timestamp ?? Math.floor(Date.now() / 1000);\n\tconst signedPayload = `${ts}.${payload}`;\n\tconst signature = signPayload(signedPayload, secret);\n\n\treturn `t=${ts},v1=${signature}`;\n}\n\n/**\n * Parse and verify a Stripe-style signature header\n * Returns true if valid, false otherwise\n */\nexport function verifySignatureHeader(\n\tpayload: string,\n\theader: string,\n\tsecret: string,\n\ttoleranceSeconds = 300, // 5 minutes\n): boolean {\n\t// Parse header\n\tconst parts = header.split(\",\");\n\tconst timestamp = parts.find((p) => p.startsWith(\"t=\"))?.slice(2);\n\tconst signature = parts.find((p) => p.startsWith(\"v1=\"))?.slice(3);\n\n\tif (!timestamp || !signature) {\n\t\treturn false;\n\t}\n\n\tconst ts = Number.parseInt(timestamp, 10);\n\tif (Number.isNaN(ts)) {\n\t\treturn false;\n\t}\n\n\t// Check timestamp is within tolerance\n\tconst now = Math.floor(Date.now() / 1000);\n\tif (Math.abs(now - ts) > toleranceSeconds) {\n\t\treturn false;\n\t}\n\n\t// Verify signature\n\tconst signedPayload = `${ts}.${payload}`;\n\treturn verifySignature(signedPayload, signature, secret);\n}\n",
7
7
  "import { createCipheriv, createDecipheriv, randomBytes } from \"node:crypto\";\nimport {\n\tappendFileSync,\n\tcloseSync,\n\texistsSync,\n\topenSync,\n\treadFileSync,\n\tunlinkSync,\n} from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { getInstanceMode } from \"../mode.ts\";\n\n/**\n * AES-256-GCM symmetric envelope for encrypted secrets at rest (tenant keys,\n * subscription signing secrets, etc.).\n *\n * Ciphertext layout: `iv (12 bytes) || authTag (16 bytes) || ciphertext`\n *\n * The key comes from `SECONDLAYER_SECRETS_KEY` — 32 bytes hex. In OSS mode,\n * if the env var is unset on first use we autogenerate a key and persist it\n * to `.env.local` in the current working directory so subsequent restarts\n * pick it up without user intervention. Dedicated/platform modes throw —\n * those runtimes must provision the key explicitly.\n *\n * Rotation strategy: re-encrypt all rows with the new key and swap the env\n * var. Not zero-downtime, but acceptable at v2 scale. For real KMS (AWS\n * KMS, Vault, GCP KMS), wrap the same byte layout behind an\n * `EncryptSecret`/`DecryptSecret` interface and swap at startup.\n */\n\nconst KEY_ENV = \"SECONDLAYER_SECRETS_KEY\";\nconst IV_LEN = 12;\nconst TAG_LEN = 16;\n\nfunction readExistingKey(envPath: string): string | null {\n\tif (!existsSync(envPath)) return null;\n\tconst contents = readFileSync(envPath, \"utf8\");\n\tconst match = contents.match(/^SECONDLAYER_SECRETS_KEY=([a-fA-F0-9]{64})/m);\n\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\treturn match ? match[1]! : null;\n}\n\n/**\n * Atomic file lock via `openSync(..., \"wx\")` — O_CREAT | O_EXCL. If two\n * processes race on cold-compose start, exactly one creates the lock\n * file; the loser polls until the winner finishes writing `.env.local`,\n * then reads the winner's key. Stale locks (process crashed mid-write)\n * are cleaned after `STALE_LOCK_MS`.\n */\nconst STALE_LOCK_MS = 10_000;\nconst POLL_MS = 25;\n\nfunction bootstrapOssKey(): string {\n\tconst envPath = resolve(process.cwd(), \".env.local\");\n\n\t// Fast path — key already on disk from a prior run.\n\tconst existing = readExistingKey(envPath);\n\tif (existing) {\n\t\tprocess.env[KEY_ENV] = existing;\n\t\treturn existing;\n\t}\n\n\tconst lockPath = `${envPath}.secret-bootstrap.lock`;\n\tlet lockFd: number | null = null;\n\ttry {\n\t\tlockFd = openSync(lockPath, \"wx\", 0o600);\n\t} catch (err) {\n\t\tconst e = err as NodeJS.ErrnoException;\n\t\tif (e.code !== \"EEXIST\") throw err;\n\t}\n\n\tif (lockFd === null) {\n\t\t// Another process is bootstrapping. Poll for its result.\n\t\tconst deadline = Date.now() + STALE_LOCK_MS;\n\t\twhile (Date.now() < deadline) {\n\t\t\tconst key = readExistingKey(envPath);\n\t\t\tif (key) {\n\t\t\t\tprocess.env[KEY_ENV] = key;\n\t\t\t\treturn key;\n\t\t\t}\n\t\t\tBun.sleepSync(POLL_MS);\n\t\t}\n\t\t// Lock holder died mid-write — force-clean and retry once.\n\t\ttry {\n\t\t\tunlinkSync(lockPath);\n\t\t} catch {}\n\t\treturn bootstrapOssKey();\n\t}\n\n\ttry {\n\t\tconst hex = randomBytes(32).toString(\"hex\");\n\t\tconst line = `${existsSync(envPath) ? \"\\n\" : \"\"}${KEY_ENV}=${hex}\\n`;\n\t\tappendFileSync(envPath, line, { mode: 0o600 });\n\t\tprocess.env[KEY_ENV] = hex;\n\t\tconsole.log(\n\t\t\t`[secondlayer] generated ${KEY_ENV}; saved to ${envPath} (mode 0600)`,\n\t\t);\n\t\treturn hex;\n\t} finally {\n\t\tcloseSync(lockFd);\n\t\ttry {\n\t\t\tunlinkSync(lockPath);\n\t\t} catch {}\n\t}\n}\n\nfunction loadKey(): Buffer {\n\tlet hex = process.env[KEY_ENV];\n\tif (!hex) {\n\t\tif (getInstanceMode() === \"oss\") {\n\t\t\thex = bootstrapOssKey();\n\t\t} else {\n\t\t\tthrow new Error(\n\t\t\t\t`${KEY_ENV} not set. Generate one with: openssl rand -hex 32`,\n\t\t\t);\n\t\t}\n\t}\n\tconst key = Buffer.from(hex, \"hex\");\n\tif (key.length !== 32) {\n\t\tthrow new Error(`${KEY_ENV} must be 32 bytes hex (got ${key.length})`);\n\t}\n\treturn key;\n}\n\nlet _cachedKey: Buffer | null = null;\nfunction getKey(): Buffer {\n\tif (!_cachedKey) _cachedKey = loadKey();\n\treturn _cachedKey;\n}\n\n/**\n * Non-throwing check for whether a secrets key is currently resolvable —\n * same resolution order as {@link loadKey} (env var, then the OSS\n * `.env.local` fallback), but never bootstraps a new key (that would\n * generate+persist a key as a side effect of a mere existence check), never\n * throws, and never returns or logs the key itself. Used by callers that\n * need to fail loud on a missing key BEFORE attempting a decrypt (f072).\n */\nexport function secretsKeyAvailable(): boolean {\n\tif (process.env[KEY_ENV]) return true;\n\tif (getInstanceMode() === \"oss\") {\n\t\tconst envPath = resolve(process.cwd(), \".env.local\");\n\t\treturn readExistingKey(envPath) !== null;\n\t}\n\treturn false;\n}\n\nexport function encryptSecret(plaintext: string): Buffer {\n\tconst key = getKey();\n\tconst iv = randomBytes(IV_LEN);\n\tconst cipher = createCipheriv(\"aes-256-gcm\", key, iv);\n\tconst ciphertext = Buffer.concat([\n\t\tcipher.update(plaintext, \"utf8\"),\n\t\tcipher.final(),\n\t]);\n\tconst tag = cipher.getAuthTag();\n\treturn Buffer.concat([iv, tag, ciphertext]);\n}\n\nexport function decryptSecret(envelope: Buffer): string {\n\tconst key = getKey();\n\tconst iv = envelope.subarray(0, IV_LEN);\n\tconst tag = envelope.subarray(IV_LEN, IV_LEN + TAG_LEN);\n\tconst ciphertext = envelope.subarray(IV_LEN + TAG_LEN);\n\tconst decipher = createDecipheriv(\"aes-256-gcm\", key, iv);\n\tdecipher.setAuthTag(tag);\n\treturn decipher.update(ciphertext).toString(\"utf8\") + decipher.final(\"utf8\");\n}\n\n/** Generate a fresh 32-byte hex key suitable for `SECONDLAYER_SECRETS_KEY`. */\nexport function generateSecretsKey(): string {\n\treturn randomBytes(32).toString(\"hex\");\n}\n",
8
8
  "import { type Kysely, sql } from \"kysely\";\nimport { generateSecret } from \"../../crypto/hmac.ts\";\nimport { decryptSecret, encryptSecret } from \"../../crypto/secrets.ts\";\nimport { isPlatformMode } from \"../../mode.ts\";\nimport type {\n\tDatabase,\n\tInsertSubscription,\n\tSubscription,\n\tSubscriptionFormat,\n\tSubscriptionKind,\n\tSubscriptionRuntime,\n\tSubscriptionStatus,\n\tUpdateSubscription,\n} from \"../types.ts\";\n\n/**\n * Subscription CRUD. `signing_secret_enc` is transparently encrypted via\n * `encryptSecret`/`decryptSecret`. Plaintext secrets only leave via the\n * return value of `create` (one-time display) and `rotateSecret`.\n */\n\nexport interface CreateSubscriptionInput {\n\taccountId: string;\n\tprojectId?: string | null;\n\tname: string;\n\t/** Defaults to \"subgraph\". Chain subscriptions set kind=\"chain\" + triggers. */\n\tkind?: SubscriptionKind;\n\t/** Required for subgraph subscriptions; omitted for chain. */\n\tsubgraphName?: string | null;\n\t/** Required for subgraph subscriptions; omitted for chain. */\n\ttableName?: string | null;\n\t/** Chain-trigger filter array. Required for chain subscriptions. */\n\ttriggers?: unknown;\n\tfilter?: unknown;\n\tformat?: SubscriptionFormat;\n\truntime?: SubscriptionRuntime | null;\n\turl: string;\n\tauthConfig?: unknown;\n\tmaxRetries?: number;\n\ttimeoutMs?: number;\n\tconcurrency?: number;\n}\n\nexport interface CreateSubscriptionResult {\n\tsubscription: Subscription;\n\t/** Plaintext signing secret — surfaced once, never stored decrypted. */\n\tsigningSecret: string;\n}\n\nexport async function createSubscription(\n\tdb: Kysely<Database>,\n\tinput: CreateSubscriptionInput,\n): Promise<CreateSubscriptionResult> {\n\tconst signingSecret = generateSecret();\n\tconst kind: SubscriptionKind = input.kind ?? \"subgraph\";\n\tconst row: InsertSubscription = {\n\t\taccount_id: isPlatformMode() ? input.accountId : \"\",\n\t\tproject_id: input.projectId ?? null,\n\t\tname: input.name,\n\t\tstatus: \"active\",\n\t\tkind,\n\t\tsubgraph_name: input.subgraphName ?? null,\n\t\ttable_name: input.tableName ?? null,\n\t\ttriggers: kind === \"chain\" ? ((input.triggers ?? []) as unknown) : null,\n\t\tfilter: input.filter ?? {},\n\t\tformat: input.format ?? \"standard-webhooks\",\n\t\truntime: input.runtime ?? null,\n\t\turl: input.url,\n\t\tsigning_secret_enc: encryptSecret(signingSecret),\n\t\tauth_config: input.authConfig ?? {},\n\t\t...(input.maxRetries !== undefined\n\t\t\t? { max_retries: input.maxRetries }\n\t\t\t: {}),\n\t\t...(input.timeoutMs !== undefined ? { timeout_ms: input.timeoutMs } : {}),\n\t\t...(input.concurrency !== undefined\n\t\t\t? { concurrency: input.concurrency }\n\t\t\t: {}),\n\t};\n\tconst subscription = await db\n\t\t.insertInto(\"subscriptions\")\n\t\t.values(row)\n\t\t.returningAll()\n\t\t.executeTakeFirstOrThrow();\n\treturn { subscription, signingSecret };\n}\n\nexport async function listSubscriptions(\n\tdb: Kysely<Database>,\n\taccountId: string,\n\topts?: { limit?: number; offset?: number },\n): Promise<Subscription[]> {\n\tlet q = db\n\t\t.selectFrom(\"subscriptions\")\n\t\t.selectAll()\n\t\t.orderBy(\"created_at\", \"desc\");\n\tif (isPlatformMode()) q = q.where(\"account_id\", \"=\", accountId);\n\tif (opts?.limit !== undefined) q = q.limit(opts.limit);\n\tif (opts?.offset !== undefined) q = q.offset(opts.offset);\n\treturn q.execute();\n}\n\n/**\n * All active chain subscriptions across every account — the input to the global\n * trigger evaluator (one loop serves them all). Subgraph subscriptions are\n * excluded; they emit via the subgraph flush path.\n */\nexport async function listActiveChainSubscriptions(\n\tdb: Kysely<Database>,\n): Promise<Subscription[]> {\n\treturn db\n\t\t.selectFrom(\"subscriptions\")\n\t\t.selectAll()\n\t\t.where(\"kind\", \"=\", \"chain\")\n\t\t.where(\"status\", \"=\", \"active\")\n\t\t.execute();\n}\n\nexport async function getSubscription(\n\tdb: Kysely<Database>,\n\taccountId: string,\n\tid: string,\n): Promise<Subscription | null> {\n\tlet q = db.selectFrom(\"subscriptions\").selectAll().where(\"id\", \"=\", id);\n\tif (isPlatformMode()) q = q.where(\"account_id\", \"=\", accountId);\n\treturn (await q.executeTakeFirst()) ?? null;\n}\n\nexport async function getSubscriptionByName(\n\tdb: Kysely<Database>,\n\taccountId: string,\n\tname: string,\n): Promise<Subscription | null> {\n\tlet q = db.selectFrom(\"subscriptions\").selectAll().where(\"name\", \"=\", name);\n\tif (isPlatformMode()) q = q.where(\"account_id\", \"=\", accountId);\n\treturn (await q.executeTakeFirst()) ?? null;\n}\n\nexport interface UpdateSubscriptionInput {\n\tname?: string;\n\tfilter?: unknown;\n\tformat?: SubscriptionFormat;\n\truntime?: SubscriptionRuntime | null;\n\turl?: string;\n\tauthConfig?: unknown;\n\tmaxRetries?: number;\n\ttimeoutMs?: number;\n\tconcurrency?: number;\n}\n\nexport async function updateSubscription(\n\tdb: Kysely<Database>,\n\taccountId: string,\n\tid: string,\n\tpatch: UpdateSubscriptionInput,\n): Promise<Subscription | null> {\n\tconst update: UpdateSubscription = { updated_at: new Date() };\n\tif (patch.name !== undefined) update.name = patch.name;\n\tif (patch.filter !== undefined) update.filter = patch.filter;\n\tif (patch.format !== undefined) update.format = patch.format;\n\tif (patch.runtime !== undefined) update.runtime = patch.runtime;\n\tif (patch.url !== undefined) update.url = patch.url;\n\tif (patch.authConfig !== undefined) update.auth_config = patch.authConfig;\n\tif (patch.maxRetries !== undefined) update.max_retries = patch.maxRetries;\n\tif (patch.timeoutMs !== undefined) update.timeout_ms = patch.timeoutMs;\n\tif (patch.concurrency !== undefined) update.concurrency = patch.concurrency;\n\n\tlet q = db.updateTable(\"subscriptions\").set(update).where(\"id\", \"=\", id);\n\tif (isPlatformMode()) q = q.where(\"account_id\", \"=\", accountId);\n\treturn (await q.returningAll().executeTakeFirst()) ?? null;\n}\n\nexport async function toggleSubscriptionStatus(\n\tdb: Kysely<Database>,\n\taccountId: string,\n\tid: string,\n\tstatus: SubscriptionStatus,\n): Promise<Subscription | null> {\n\tlet q = db\n\t\t.updateTable(\"subscriptions\")\n\t\t.set({\n\t\t\tstatus,\n\t\t\tupdated_at: new Date(),\n\t\t\t...(status === \"active\"\n\t\t\t\t? {\n\t\t\t\t\t\tcircuit_failures: 0,\n\t\t\t\t\t\tcircuit_opened_at: null,\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t})\n\t\t.where(\"id\", \"=\", id);\n\tif (isPlatformMode()) q = q.where(\"account_id\", \"=\", accountId);\n\treturn (await q.returningAll().executeTakeFirst()) ?? null;\n}\n\nexport async function deleteSubscription(\n\tdb: Kysely<Database>,\n\taccountId: string,\n\tid: string,\n): Promise<boolean> {\n\tlet q = db.deleteFrom(\"subscriptions\").where(\"id\", \"=\", id);\n\tif (isPlatformMode()) q = q.where(\"account_id\", \"=\", accountId);\n\tconst res = await q.executeTakeFirst();\n\treturn Number(res.numDeletedRows ?? 0) > 0;\n}\n\nexport interface RotateSecretResult {\n\tsubscription: Subscription;\n\tsigningSecret: string;\n}\n\nexport async function rotateSubscriptionSecret(\n\tdb: Kysely<Database>,\n\taccountId: string,\n\tid: string,\n): Promise<RotateSecretResult | null> {\n\tconst signingSecret = generateSecret();\n\tlet q = db\n\t\t.updateTable(\"subscriptions\")\n\t\t.set({\n\t\t\tsigning_secret_enc: encryptSecret(signingSecret),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"id\", \"=\", id);\n\tif (isPlatformMode()) q = q.where(\"account_id\", \"=\", accountId);\n\tconst row = await q.returningAll().executeTakeFirst();\n\tif (!row) return null;\n\treturn { subscription: row, signingSecret };\n}\n\n/** Decrypt a subscription's signing secret for HMAC signing at emit time. */\nexport function getSubscriptionSigningSecret(sub: Subscription): string {\n\treturn decryptSecret(sub.signing_secret_enc);\n}\n\n/** Fire `subscriptions:changed` notify so the emitter hot-reloads its cache. */\nexport async function notifySubscriptionsChanged(\n\tdb: Kysely<Database>,\n\taccountId: string,\n): Promise<void> {\n\tawait sql`SELECT pg_notify('subscriptions:changed', ${accountId})`.execute(\n\t\tdb,\n\t);\n}\n"
9
9
  ],
10
- "mappings": ";;;;;;;;;;;;;;;;;AAcA,IAAM,cAAuC,CAAC,OAAO,UAAU;AAOxD,SAAS,eAAe,GAAiB;AAAA,EAC/C,MAAM,MAAM,QAAQ,IAAI,eAAe,KAAK,EAAE,YAAY;AAAA,EAC1D,IAAI,OAAQ,YAAkC,SAAS,GAAG,GAAG;AAAA,IAC5D,OAAO;AAAA,EACR;AAAA,EACA,OAAO;AAAA;AAID,SAAS,cAAc,GAAY;AAAA,EACzC,OAAO,gBAAgB,MAAM;AAAA;AAIvB,SAAS,SAAS,GAAY;AAAA,EACpC,OAAO,gBAAgB,MAAM;AAAA;;;;;;;;;;;ACpC9B;AAMO,SAAS,cAAc,GAAW;AAAA,EACxC,OAAO,YAAY,EAAE,EAAE,SAAS,KAAK;AAAA;AAO/B,SAAS,WAAW,CAAC,SAAiB,QAAwB;AAAA,EACpE,MAAM,OAAO,WAAW,UAAU,MAAM;AAAA,EACxC,KAAK,OAAO,OAAO;AAAA,EACnB,OAAO,KAAK,OAAO,KAAK;AAAA;AAOlB,SAAS,eAAe,CAC9B,SACA,WACA,QACU;AAAA,EACV,MAAM,oBAAoB,YAAY,SAAS,MAAM;AAAA,EAGrD,IAAI,UAAU,WAAW,kBAAkB,QAAQ;AAAA,IAClD,OAAO;AAAA,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IAAI,EAAE,MAAM,cAAc,KAAK,SAAS;AAAA,EAC9D,OAAQ,MAAM,EAAE,aAAa,EAAE,iBAAiB,KAAM;AAAA;AAGvD,eAAsB,kBAAkB,CACvC,IACA,WACA,IACmB;AAAA,EACnB,IAAI,IAAI,GAAG,WAAW,eAAe,EAAE,MAAM,MAAM,KAAK,EAAE;AAAA,EAC1D,IAAI,eAAe;AAAA,IAAG,IAAI,EAAE,MAAM,cAAc,KAAK,SAAS;AAAA,EAC9D,MAAM,MAAM,MAAM,EAAE,iBAAiB;AAAA,EACrC,OAAO,OAAO,IAAI,kBAAkB,CAAC,IAAI;AAAA;AAQ1C,eAAsB,wBAAwB,CAC7C,IACA,WACA,IACqC;AAAA,EACrC,MAAM,gBAAgB,eAAe;AAAA,EACrC,IAAI,IAAI,GACN,YAAY,eAAe,EAC3B,IAAI;AAAA,IACJ,oBAAoB,cAAc,aAAa;AAAA,IAC/C,YAAY,IAAI;AAAA,EACjB,CAAC,EACA,MAAM,MAAM,KAAK,EAAE;AAAA,EACrB,IAAI,eAAe;AAAA,IAAG,IAAI,EAAE,MAAM,cAAc,KAAK,SAAS;AAAA,EAC9D,MAAM,MAAM,MAAM,EAAE,aAAa,EAAE,iBAAiB;AAAA,EACpD,IAAI,CAAC;AAAA,IAAK,OAAO;AAAA,EACjB,OAAO,EAAE,cAAc,KAAK,cAAc;AAAA;AAIpC,SAAS,4BAA4B,CAAC,KAA2B;AAAA,EACvE,OAAO,cAAc,IAAI,kBAAkB;AAAA;AAI5C,eAAsB,0BAA0B,CAC/C,IACA,WACgB;AAAA,EAChB,MAAM,gDAAgD,aAAa,QAClE,EACD;AAAA;",
11
+ "debugId": "A468DA6DE7BBDD4564756E2164756E21",
12
12
  "names": []
13
13
  }
@@ -222,11 +222,9 @@ interface AccountsTable {
222
222
  ghost: Generated<boolean>;
223
223
  /** Stacks principal owning a wallet-ghost account (x402-paid deploys). */
224
224
  wallet_principal: string | null;
225
- plan: Generated<string>;
226
225
  display_name: string | null;
227
226
  bio: string | null;
228
227
  avatar_url: string | null;
229
- slug: string | null;
230
228
  stripe_customer_id: string | null;
231
229
  /** Opt-out toggle for the subgraph reindex-completion email. Defaults true. */
232
230
  notify_reindex_complete: Generated<boolean>;
@@ -243,19 +241,6 @@ interface SessionsTable {
243
241
  last_used_at: Date | null;
244
242
  created_at: Generated<Date>;
245
243
  }
246
- /**
247
- * One-time claim tokens for ghost accounts. The raw token only ever appears in
248
- * the claim URL returned at mint time; we store its sha256. A used token marks
249
- * the account as claimed (or merged into an existing account).
250
- */
251
- interface ClaimTokensTable {
252
- id: Generated<string>;
253
- account_id: string;
254
- token_hash: string;
255
- created_at: Generated<Date>;
256
- expires_at: Date;
257
- used_at: Date | null;
258
- }
259
244
  interface MagicLinksTable {
260
245
  id: Generated<string>;
261
246
  email: string;
@@ -266,47 +251,6 @@ interface MagicLinksTable {
266
251
  failed_attempts: Generated<number>;
267
252
  created_at: Generated<Date>;
268
253
  }
269
- interface UsageDailyTable {
270
- account_id: string;
271
- tenant_id: string | null;
272
- date: string;
273
- api_requests: Generated<number>;
274
- deliveries: Generated<number>;
275
- streams_events_returned: Generated<number>;
276
- index_decoded_events_returned: Generated<number>;
277
- }
278
- interface UsageSnapshotsTable {
279
- id: Generated<string>;
280
- account_id: string;
281
- measured_at: Generated<Date>;
282
- storage_bytes: Generated<number>;
283
- }
284
- interface AccountInsightsTable {
285
- id: Generated<string>;
286
- account_id: string;
287
- category: string;
288
- insight_type: string;
289
- resource_id: string | null;
290
- severity: string;
291
- title: string;
292
- body: string;
293
- data: unknown;
294
- dismissed_at: Date | null;
295
- expires_at: Date | null;
296
- created_at: Generated<Date>;
297
- }
298
- interface AccountAgentRunsTable {
299
- id: Generated<string>;
300
- account_id: string;
301
- started_at: Generated<Date>;
302
- completed_at: Date | null;
303
- status: Generated<string>;
304
- input_tokens: Generated<number>;
305
- output_tokens: Generated<number>;
306
- cost_usd: Generated<number>;
307
- insights_created: Generated<number>;
308
- error: string | null;
309
- }
310
254
  interface SubgraphProcessingStatsTable {
311
255
  id: Generated<string>;
312
256
  subgraph_name: string;
@@ -339,41 +283,6 @@ interface SubgraphHealthSnapshotsTable {
339
283
  last_processed_block: number | null;
340
284
  captured_at: Generated<Date>;
341
285
  }
342
- interface SubgraphUsageDailyTable {
343
- subgraph_id: string;
344
- date: string;
345
- query_count: Generated<number>;
346
- }
347
- interface ProjectsTable {
348
- id: Generated<string>;
349
- name: string;
350
- slug: string;
351
- account_id: string;
352
- settings: Generated<Record<string, unknown>>;
353
- network: Generated<string>;
354
- node_rpc: string | null;
355
- created_at: Generated<Date>;
356
- updated_at: Generated<Date>;
357
- }
358
- interface TeamMembersTable {
359
- id: Generated<string>;
360
- project_id: string;
361
- account_id: string;
362
- role: Generated<string>;
363
- invited_by: string | null;
364
- created_at: Generated<Date>;
365
- }
366
- interface TeamInvitationsTable {
367
- id: Generated<string>;
368
- project_id: string;
369
- email: string;
370
- role: Generated<string>;
371
- token: string;
372
- invited_by: string | null;
373
- expires_at: Date;
374
- accepted_at: Date | null;
375
- created_at: Generated<Date>;
376
- }
377
286
  interface ProcessedStripeEventsTable {
378
287
  event_id: string;
379
288
  event_type: string;
@@ -826,27 +735,14 @@ interface Database {
826
735
  accounts: AccountsTable;
827
736
  sessions: SessionsTable;
828
737
  magic_links: MagicLinksTable;
829
- claim_tokens: ClaimTokensTable;
830
- usage_daily: UsageDailyTable;
831
- usage_snapshots: UsageSnapshotsTable;
832
- account_insights: AccountInsightsTable;
833
- account_agent_runs: AccountAgentRunsTable;
834
738
  subgraph_health_snapshots: SubgraphHealthSnapshotsTable;
835
739
  subgraph_processing_stats: SubgraphProcessingStatsTable;
836
740
  subgraph_table_snapshots: SubgraphTableSnapshotsTable;
837
741
  subgraph_gaps: SubgraphGapsTable;
838
742
  subgraph_operations: SubgraphOperationsTable;
839
- subgraph_usage_daily: SubgraphUsageDailyTable;
840
- projects: ProjectsTable;
841
- team_members: TeamMembersTable;
842
- team_invitations: TeamInvitationsTable;
843
743
  processed_stripe_events: ProcessedStripeEventsTable;
844
- tenants: TenantsTable;
845
- tenant_usage_monthly: TenantUsageMonthlyTable;
846
- tenant_compute_addons: TenantComputeAddonsTable;
847
744
  account_spend_caps: AccountSpendCapsTable;
848
745
  account_credits: AccountCreditsTable;
849
- provisioning_audit_log: ProvisioningAuditLogTable;
850
746
  subscriptions: SubscriptionsTable;
851
747
  subscription_outbox: SubscriptionOutboxTable;
852
748
  subscription_deliveries: SubscriptionDeliveriesTable;
@@ -921,66 +817,6 @@ interface X402PaymentsTable {
921
817
  * reconciler's heal path can never double-credit them. */
922
818
  credited_at: Generated<Date> | null;
923
819
  }
924
- type TenantStatus = "provisioning" | "active" | "limit_warning" | "paused_limit" | "suspended" | "error" | "deleted";
925
- interface TenantsTable {
926
- id: Generated<string>;
927
- account_id: string;
928
- slug: string;
929
- status: ColumnType<TenantStatus, TenantStatus | undefined, TenantStatus>;
930
- plan: string;
931
- cpus: ColumnType<number, number | string, number | string>;
932
- memory_mb: number;
933
- storage_limit_mb: number;
934
- storage_used_mb: number | null;
935
- pg_container_id: string | null;
936
- api_container_id: string | null;
937
- processor_container_id: string | null;
938
- target_database_url_enc: Buffer;
939
- tenant_jwt_secret_enc: Buffer;
940
- anon_key_enc: Buffer;
941
- service_key_enc: Buffer;
942
- api_url_internal: string;
943
- api_url_public: string;
944
- suspended_at: Date | null;
945
- last_health_check_at: Date | null;
946
- last_active_at: Generated<Date>;
947
- service_gen: Generated<number>;
948
- anon_gen: Generated<number>;
949
- project_id: string | null;
950
- created_at: Generated<Date>;
951
- updated_at: Generated<Date>;
952
- }
953
- type Tenant = Selectable<TenantsTable>;
954
- type InsertTenant = Insertable<TenantsTable>;
955
- type UpdateTenant = Updateable<TenantsTable>;
956
- interface TenantUsageMonthlyTable {
957
- id: Generated<string>;
958
- tenant_id: string;
959
- period_month: Date;
960
- storage_peak_mb: Generated<number>;
961
- storage_avg_mb: Generated<number>;
962
- storage_last_mb: Generated<number>;
963
- measurements: Generated<number>;
964
- first_at: Generated<Date>;
965
- last_at: Generated<Date>;
966
- }
967
- type TenantUsageMonthly = Selectable<TenantUsageMonthlyTable>;
968
- type InsertTenantUsageMonthly = Insertable<TenantUsageMonthlyTable>;
969
- type UpdateTenantUsageMonthly = Updateable<TenantUsageMonthlyTable>;
970
- interface TenantComputeAddonsTable {
971
- id: Generated<string>;
972
- tenant_id: string;
973
- memory_mb_delta: Generated<number>;
974
- cpu_delta: Generated<number | string>;
975
- storage_mb_delta: Generated<number>;
976
- effective_from: Generated<Date>;
977
- effective_until: Date | null;
978
- stripe_subscription_item_id: string | null;
979
- created_at: Generated<Date>;
980
- }
981
- type TenantComputeAddon = Selectable<TenantComputeAddonsTable>;
982
- type InsertTenantComputeAddon = Insertable<TenantComputeAddonsTable>;
983
- type UpdateTenantComputeAddon = Updateable<TenantComputeAddonsTable>;
984
820
  interface AccountSpendCapsTable {
985
821
  account_id: string;
986
822
  monthly_cap_cents: number | null;
@@ -1010,22 +846,6 @@ interface AccountCreditsTable {
1010
846
  type AccountCredits = Selectable<AccountCreditsTable>;
1011
847
  type InsertAccountCredits = Insertable<AccountCreditsTable>;
1012
848
  type UpdateAccountCredits = Updateable<AccountCreditsTable>;
1013
- type ProvisioningAuditEvent = "provision.start" | "provision.success" | "provision.failure" | "suspend" | "resume" | "resize" | "keys.rotate" | "bastion.key.upload" | "bastion.key.revoke" | "teardown";
1014
- type ProvisioningAuditStatus = "ok" | "error";
1015
- interface ProvisioningAuditLogTable {
1016
- id: Generated<string>;
1017
- tenant_id: string | null;
1018
- tenant_slug: string | null;
1019
- account_id: string | null;
1020
- actor: string;
1021
- event: ProvisioningAuditEvent;
1022
- status: ProvisioningAuditStatus;
1023
- detail: unknown | null;
1024
- error: string | null;
1025
- created_at: Generated<Date>;
1026
- }
1027
- type ProvisioningAuditLog = Selectable<ProvisioningAuditLogTable>;
1028
- type InsertProvisioningAuditLog = Insertable<ProvisioningAuditLogTable>;
1029
849
  type Block = Selectable<BlocksTable>;
1030
850
  type InsertBlock = Insertable<BlocksTable>;
1031
851
  type UpdateBlock = Updateable<BlocksTable>;
@@ -1056,29 +876,12 @@ type Account = Selectable<AccountsTable>;
1056
876
  type InsertAccount = Insertable<AccountsTable>;
1057
877
  type MagicLink = Selectable<MagicLinksTable>;
1058
878
  type InsertMagicLink = Insertable<MagicLinksTable>;
1059
- type ClaimToken = Selectable<ClaimTokensTable>;
1060
- type InsertClaimToken = Insertable<ClaimTokensTable>;
1061
879
  type Session = Selectable<SessionsTable>;
1062
880
  type InsertSession = Insertable<SessionsTable>;
1063
- type UsageDaily = Selectable<UsageDailyTable>;
1064
- type UsageSnapshot = Selectable<UsageSnapshotsTable>;
1065
- type AccountInsight = Selectable<AccountInsightsTable>;
1066
- type InsertAccountInsight = Insertable<AccountInsightsTable>;
1067
- type AccountAgentRun = Selectable<AccountAgentRunsTable>;
1068
- type InsertAccountAgentRun = Insertable<AccountAgentRunsTable>;
1069
881
  type SubgraphHealthSnapshot = Selectable<SubgraphHealthSnapshotsTable>;
1070
882
  type InsertSubgraphHealthSnapshot = Insertable<SubgraphHealthSnapshotsTable>;
1071
883
  type SubgraphGap = Selectable<SubgraphGapsTable>;
1072
884
  type InsertSubgraphGap = Insertable<SubgraphGapsTable>;
1073
- type SubgraphUsageDaily = Selectable<SubgraphUsageDailyTable>;
1074
- type InsertSubgraphUsageDaily = Insertable<SubgraphUsageDailyTable>;
1075
- type Project = Selectable<ProjectsTable>;
1076
- type InsertProject = Insertable<ProjectsTable>;
1077
- type UpdateProject = Updateable<ProjectsTable>;
1078
- type TeamMember = Selectable<TeamMembersTable>;
1079
- type InsertTeamMember = Insertable<TeamMembersTable>;
1080
- type TeamInvitation = Selectable<TeamInvitationsTable>;
1081
- type InsertTeamInvitation = Insertable<TeamInvitationsTable>;
1082
885
  type SubscriptionStatus = "active" | "paused" | "error";
1083
886
  /** Polymorphic subscription mode: `subgraph` reacts to processed table rows;
1084
887
  * `chain` reacts to raw chain events matched directly off the Index/Streams
@@ -1176,4 +979,4 @@ interface TriggerEvaluatorStateTable {
1176
979
  updated_at: Generated<Date>;
1177
980
  }
1178
981
  type TriggerEvaluatorState = Selectable<TriggerEvaluatorStateTable>;
1179
- export { X402PaymentsTable, X402BalancesTable, UsageSnapshotsTable, UsageSnapshot, UsageDailyTable, UsageDaily, UpdateTransaction, UpdateTenantUsageMonthly, UpdateTenantComputeAddon, UpdateTenant, UpdateSubscriptionOutbox, UpdateSubscription, UpdateSubgraphOperation, UpdateSubgraph, UpdateProject, UpdateIndexProgress, UpdateEvent, UpdateContract, UpdateBlock, UpdateApiKey, UpdateAccountSpendCap, UpdateAccountCredits, TriggerEvaluatorStateTable, TriggerEvaluatorState, TransactionsTable, TransactionsArchiveTable, Transaction, TenantsTable, TenantUsageMonthlyTable, TenantUsageMonthly, TenantStatus, TenantComputeAddonsTable, TenantComputeAddon, Tenant, TeamMembersTable, TeamMember, TeamInvitationsTable, TeamInvitation, SubscriptionsTable, SubscriptionStatus, SubscriptionRuntime, SubscriptionOutboxTable, SubscriptionOutbox, SubscriptionKind, SubscriptionFormat, SubscriptionDelivery, SubscriptionDeliveriesTable, Subscription, SubgraphsTable, SubgraphUsageDailyTable, SubgraphUsageDaily, SubgraphTableSnapshotsTable, SubgraphProcessingStatsTable, SubgraphOperationsTable, SubgraphOperationStatus, SubgraphOperationKind, SubgraphOperation, SubgraphHealthSnapshotsTable, SubgraphHealthSnapshot, SubgraphGapsTable, SubgraphGap, Subgraph, StageRunsTable, StageRegistryTable, StageKind, StageFailuresTable, StageBlockReceiptsTable, SessionsTable, Session, ServiceHeartbeatsTable, SbtcTokenEventsTable, SbtcTokenEventType, SbtcSupplySnapshotsTable, SbtcSettlementsTable, SbtcEventsTable, SbtcEventTopic, RunStatus, RetryState, RepairMode, ProvisioningAuditStatus, ProvisioningAuditLogTable, ProvisioningAuditLog, ProvisioningAuditEvent, ProjectsTable, Project, ProcessedStripeEventsTable, Pox5EventsTable, Pox5EventTopic, Pox4SignersDailyTable, Pox4FunctionName, Pox4CyclesDailyTable, Pox4CallsTable, PendingForkBlocksTable, OutboxStatus, ObserverJournalTable, ObserverJournalStatus, NativeClock, MempoolTransactionsTable, MempoolTransaction, MagicLinksTable, MagicLink, InstancesTable, InsertTransaction, InsertTenantUsageMonthly, InsertTenantComputeAddon, InsertTenant, InsertTeamMember, InsertTeamInvitation, InsertSubscriptionOutbox, InsertSubscriptionDelivery, InsertSubscription, InsertSubgraphUsageDaily, InsertSubgraphOperation, InsertSubgraphHealthSnapshot, InsertSubgraphGap, InsertSubgraph, InsertSession, InsertProvisioningAuditLog, InsertProject, InsertMempoolTransaction, InsertMagicLink, InsertIndexProgress, InsertEvent, InsertContract, InsertClaimToken, InsertBlock, InsertApiKey, InsertAccountSpendCap, InsertAccountInsight, InsertAccountCredits, InsertAccountAgentRun, InsertAccount, IndexProgressTable, IndexProgress, FailureUnit, FailureClass, EventsTable, EventsArchiveTable, Event, DecoderCheckpointsTable, DecodedEventsTable, DeadLetterEventsTable, Database, CoverageSegmentsTable, ContractsTable, Contract, ClaimTokensTable, ClaimToken, ChainReorgsTable, ChainReadCacheTable, BurnBlockRewardsTable, BurnBlockRewardSlotsTable, BnsNamespacesTable, BnsNamespaceEventsTable, BnsNamespaceEventStatus, BnsNamesTable, BnsNameEventsTable, BnsNameEventTopic, BnsMarketplaceEventsTable, BnsMarketplaceAction, BlocksTable, Block, ApiKeysTable, ApiKey, AccountsTable, AccountSpendCapsTable, AccountSpendCap, AccountInsightsTable, AccountInsight, AccountCreditsTable, AccountCredits, AccountAgentRunsTable, AccountAgentRun, Account };
982
+ export { X402PaymentsTable, X402BalancesTable, UpdateTransaction, UpdateSubscriptionOutbox, UpdateSubscription, UpdateSubgraphOperation, UpdateSubgraph, UpdateIndexProgress, UpdateEvent, UpdateContract, UpdateBlock, UpdateApiKey, UpdateAccountSpendCap, UpdateAccountCredits, TriggerEvaluatorStateTable, TriggerEvaluatorState, TransactionsTable, TransactionsArchiveTable, Transaction, SubscriptionsTable, SubscriptionStatus, SubscriptionRuntime, SubscriptionOutboxTable, SubscriptionOutbox, SubscriptionKind, SubscriptionFormat, SubscriptionDelivery, SubscriptionDeliveriesTable, Subscription, SubgraphsTable, SubgraphTableSnapshotsTable, SubgraphProcessingStatsTable, SubgraphOperationsTable, SubgraphOperationStatus, SubgraphOperationKind, SubgraphOperation, SubgraphHealthSnapshotsTable, SubgraphHealthSnapshot, SubgraphGapsTable, SubgraphGap, Subgraph, StageRunsTable, StageRegistryTable, StageKind, StageFailuresTable, StageBlockReceiptsTable, SessionsTable, Session, ServiceHeartbeatsTable, SbtcTokenEventsTable, SbtcTokenEventType, SbtcSupplySnapshotsTable, SbtcSettlementsTable, SbtcEventsTable, SbtcEventTopic, RunStatus, RetryState, RepairMode, ProcessedStripeEventsTable, Pox5EventsTable, Pox5EventTopic, Pox4SignersDailyTable, Pox4FunctionName, Pox4CyclesDailyTable, Pox4CallsTable, PendingForkBlocksTable, OutboxStatus, ObserverJournalTable, ObserverJournalStatus, NativeClock, MempoolTransactionsTable, MempoolTransaction, MagicLinksTable, MagicLink, InstancesTable, InsertTransaction, InsertSubscriptionOutbox, InsertSubscriptionDelivery, InsertSubscription, InsertSubgraphOperation, InsertSubgraphHealthSnapshot, InsertSubgraphGap, InsertSubgraph, InsertSession, InsertMempoolTransaction, InsertMagicLink, InsertIndexProgress, InsertEvent, InsertContract, InsertBlock, InsertApiKey, InsertAccountSpendCap, InsertAccountCredits, InsertAccount, IndexProgressTable, IndexProgress, FailureUnit, FailureClass, EventsTable, EventsArchiveTable, Event, DecoderCheckpointsTable, DecodedEventsTable, DeadLetterEventsTable, Database, CoverageSegmentsTable, ContractsTable, Contract, ChainReorgsTable, ChainReadCacheTable, BurnBlockRewardsTable, BurnBlockRewardSlotsTable, BnsNamespacesTable, BnsNamespaceEventsTable, BnsNamespaceEventStatus, BnsNamesTable, BnsNameEventsTable, BnsNameEventTopic, BnsMarketplaceEventsTable, BnsMarketplaceAction, BlocksTable, Block, ApiKeysTable, ApiKey, AccountsTable, AccountSpendCapsTable, AccountSpendCap, AccountCreditsTable, AccountCredits, Account };
@@ -14,27 +14,6 @@ declare const ErrorCodes: {
14
14
  readonly INSTANCE_EXISTS: "INSTANCE_EXISTS"
15
15
  };
16
16
  type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];
17
- /**
18
- * Structured payload carried on a refused BYO breaking-change deploy. Single-sourced
19
- * here so subgraphs (thrower), api (body), sdk (typed error), and cli (renderer) all
20
- * agree on shape. The deploy is still refused — this only describes the manual
21
- * DROP + rebuild the user must run themselves.
22
- */
23
- interface ByoBreakingChangeDetails {
24
- reasons: string[];
25
- diff: {
26
- addedTables: string[]
27
- removedTables: string[]
28
- addedColumns: Record<string, string[]>
29
- breakingChanges: string[]
30
- };
31
- plan: {
32
- schemaName: string
33
- dropStatement: string
34
- statements: string[]
35
- grantScript: string
36
- };
37
- }
38
17
  /** Base error class for all Secondlayer errors. */
39
18
  declare class SecondLayerError extends Error {
40
19
  code: ErrorCode;
@@ -95,4 +74,4 @@ declare class TenantSuspendedError extends SecondLayerError {
95
74
  * (avoids cross-bundle instanceof failures from bunup class duplication). */
96
75
  declare const CODE_TO_STATUS: Record<string, 400 | 401 | 402 | 403 | 404 | 409 | 422 | 423 | 429 | 503>;
97
76
  declare function getErrorMessage(err: unknown): string;
98
- export { getErrorMessage, VersionConflictError, ValidationError, TenantSuspendedError, SecondLayerError, RateLimitError, PaymentRequiredError, NotFoundError, KeyRotatedError, ForbiddenError, ErrorCodes, ErrorCode, DatabaseError, CODE_TO_STATUS, ByoBreakingChangeDetails, AuthorizationError, AuthenticationError };
77
+ export { getErrorMessage, VersionConflictError, ValidationError, TenantSuspendedError, SecondLayerError, RateLimitError, PaymentRequiredError, NotFoundError, KeyRotatedError, ForbiddenError, ErrorCodes, ErrorCode, DatabaseError, CODE_TO_STATUS, AuthorizationError, AuthenticationError };
@@ -138,10 +138,8 @@ var CODE_TO_STATUS = {
138
138
  NO_TENANT_FOR_PROJECT: 404,
139
139
  INSTANCE_EXISTS: 409,
140
140
  SUBGRAPH_NOT_FOUND: 404,
141
- BYO_BREAKING_CHANGE: 422,
142
141
  PUBLIC_NAME_TAKEN: 409,
143
- GHOST_KEY_READ_ONLY: 403,
144
- GENESIS_BACKFILL_REQUIRES_PLAN: 403
142
+ GHOST_KEY_READ_ONLY: 403
145
143
  };
146
144
  function getErrorMessage(err) {
147
145
  return err instanceof Error ? err.message : String(err);
@@ -164,5 +162,5 @@ export {
164
162
  AuthenticationError
165
163
  };
166
164
 
167
- //# debugId=7FB861FAC1CC3EBE64756E2164756E21
165
+ //# debugId=5807B9DB95B688C664756E2164756E21
168
166
  //# sourceMappingURL=errors.js.map
@@ -2,9 +2,9 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/errors.ts"],
4
4
  "sourcesContent": [
5
- "export const ErrorCodes = {\n\tVALIDATION_ERROR: \"VALIDATION_ERROR\",\n\tDATABASE_ERROR: \"DATABASE_ERROR\",\n\tAUTHENTICATION_ERROR: \"AUTHENTICATION_ERROR\",\n\tAUTHORIZATION_ERROR: \"AUTHORIZATION_ERROR\",\n\tRATE_LIMIT_ERROR: \"RATE_LIMIT_ERROR\",\n\tPAYMENT_REQUIRED: \"PAYMENT_REQUIRED\",\n\tFORBIDDEN: \"FORBIDDEN\",\n\tVERSION_CONFLICT: \"VERSION_CONFLICT\",\n\tNOT_FOUND: \"NOT_FOUND\",\n\t// Tenant lifecycle (CLI surfaces these verbatim)\n\tKEY_ROTATED: \"KEY_ROTATED\",\n\tTENANT_SUSPENDED: \"TENANT_SUSPENDED\",\n\tNO_TENANT_FOR_PROJECT: \"NO_TENANT_FOR_PROJECT\",\n\tINSTANCE_EXISTS: \"INSTANCE_EXISTS\",\n} as const;\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];\n\n/**\n * Structured payload carried on a refused BYO breaking-change deploy. Single-sourced\n * here so subgraphs (thrower), api (body), sdk (typed error), and cli (renderer) all\n * agree on shape. The deploy is still refused — this only describes the manual\n * DROP + rebuild the user must run themselves.\n */\nexport interface ByoBreakingChangeDetails {\n\treasons: string[];\n\tdiff: {\n\t\taddedTables: string[];\n\t\tremovedTables: string[];\n\t\taddedColumns: Record<string, string[]>;\n\t\tbreakingChanges: string[];\n\t};\n\tplan: {\n\t\tschemaName: string;\n\t\tdropStatement: string;\n\t\tstatements: string[];\n\t\tgrantScript: string;\n\t};\n}\n\n/** Base error class for all Secondlayer errors. */\nexport class SecondLayerError extends Error {\n\tpublic code: ErrorCode;\n\tpublic override cause?: unknown;\n\t/** Optional structured payload merged into the HTTP error body (machine-readable hints). */\n\tpublic details?: Record<string, unknown>;\n\n\tconstructor(\n\t\tcode: ErrorCode,\n\t\tmessage: string,\n\t\tcause?: unknown,\n\t\tdetails?: Record<string, unknown>,\n\t) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\t\tthis.cause = cause;\n\t\tthis.details = details;\n\t\tthis.name = this.constructor.name;\n\t\tError.captureStackTrace?.(this, this.constructor);\n\t}\n\n\ttoJSON(): {\n\t\tname: string;\n\t\tcode: string;\n\t\tmessage: string;\n\t\tstack: string | undefined;\n\t\tcause: unknown;\n\t\tdetails: Record<string, unknown> | undefined;\n\t} {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tcode: this.code,\n\t\t\tmessage: this.message,\n\t\t\tstack: this.stack,\n\t\t\tcause: this.cause,\n\t\t\tdetails: this.details,\n\t\t};\n\t}\n}\n\nexport class NotFoundError extends SecondLayerError {\n\tconstructor(message: string) {\n\t\tsuper(\"NOT_FOUND\", message);\n\t}\n}\n\nexport class ValidationError extends SecondLayerError {\n\tconstructor(message: string, cause?: unknown) {\n\t\tsuper(\"VALIDATION_ERROR\", message, cause);\n\t}\n}\n\nexport class DatabaseError extends SecondLayerError {\n\tconstructor(message: string, cause?: unknown) {\n\t\tsuper(\"DATABASE_ERROR\", message, cause);\n\t}\n}\n\nexport class AuthenticationError extends SecondLayerError {\n\tconstructor(message: string) {\n\t\tsuper(\"AUTHENTICATION_ERROR\", message);\n\t}\n}\n\nexport class AuthorizationError extends SecondLayerError {\n\tconstructor(message: string, details?: Record<string, unknown>) {\n\t\tsuper(\"AUTHORIZATION_ERROR\", message, undefined, details);\n\t}\n}\n\nexport class RateLimitError extends SecondLayerError {\n\tconstructor(message: string) {\n\t\tsuper(\"RATE_LIMIT_ERROR\", message);\n\t}\n}\n\n/**\n * HTTP 402. Carries the x402 challenge (or a retry-later reason) in `details` so\n * the global error handler emits it in the body. The wire `PAYMENT-REQUIRED`\n * header is set separately by the x402 middleware on the challenge path.\n */\nexport class PaymentRequiredError extends SecondLayerError {\n\tconstructor(message: string, details?: Record<string, unknown>) {\n\t\tsuper(\"PAYMENT_REQUIRED\", message, undefined, details);\n\t}\n}\n\nexport class ForbiddenError extends SecondLayerError {\n\tconstructor(message = \"Forbidden\") {\n\t\tsuper(\"FORBIDDEN\", message);\n\t}\n}\n\nexport class VersionConflictError extends SecondLayerError {\n\tpublic currentVersion: string;\n\tpublic expectedVersion: string;\n\n\tconstructor(currentVersion: string, expectedVersion: string) {\n\t\tsuper(\n\t\t\t\"VERSION_CONFLICT\",\n\t\t\t`Version conflict: expected ${expectedVersion}, current ${currentVersion}`,\n\t\t);\n\t\tthis.currentVersion = currentVersion;\n\t\tthis.expectedVersion = expectedVersion;\n\t}\n}\n\nexport class KeyRotatedError extends SecondLayerError {\n\tconstructor(message = \"Token has been rotated\") {\n\t\tsuper(\"KEY_ROTATED\", message);\n\t}\n}\n\nexport class TenantSuspendedError extends SecondLayerError {\n\tconstructor(message = \"Instance is suspended\") {\n\t\tsuper(\"TENANT_SUSPENDED\", message);\n\t}\n}\n\n/** Error code → HTTP status. Used by API middleware for code-based matching\n * (avoids cross-bundle instanceof failures from bunup class duplication). */\n// String literal map — codes don't have to be in the central ErrorCode\n// enum (route-local error classes can supply any code; we just map the\n// HTTP status here). This keeps cross-bundle instanceof failures out of\n// the equation.\nexport const CODE_TO_STATUS: Record<\n\tstring,\n\t400 | 401 | 402 | 403 | 404 | 409 | 422 | 423 | 429 | 503\n> = {\n\t// The chain plane has no data yet — a fresh self-host install before the\n\t// first block lands. Retryable, and not the operator's mistake, so it is a\n\t// 503 with a name rather than an opaque 500.\n\tCHAIN_DATA_UNAVAILABLE: 503,\n\tAUTHENTICATION_ERROR: 401,\n\tAUTHORIZATION_ERROR: 403,\n\tPAYMENT_REQUIRED: 402,\n\tRATE_LIMIT_ERROR: 429,\n\tFORBIDDEN: 403,\n\tNOT_FOUND: 404,\n\tVALIDATION_ERROR: 400,\n\tKEY_ROTATED: 401,\n\tTENANT_SUSPENDED: 423,\n\tNO_TENANT_FOR_PROJECT: 404,\n\tINSTANCE_EXISTS: 409,\n\tSUBGRAPH_NOT_FOUND: 404,\n\tBYO_BREAKING_CHANGE: 422,\n\tPUBLIC_NAME_TAKEN: 409,\n\tGHOST_KEY_READ_ONLY: 403,\n\tGENESIS_BACKFILL_REQUIRES_PLAN: 403,\n} as const;\n\nexport function getErrorMessage(err: unknown): string {\n\treturn err instanceof Error ? err.message : String(err);\n}\n"
5
+ "export const ErrorCodes = {\n\tVALIDATION_ERROR: \"VALIDATION_ERROR\",\n\tDATABASE_ERROR: \"DATABASE_ERROR\",\n\tAUTHENTICATION_ERROR: \"AUTHENTICATION_ERROR\",\n\tAUTHORIZATION_ERROR: \"AUTHORIZATION_ERROR\",\n\tRATE_LIMIT_ERROR: \"RATE_LIMIT_ERROR\",\n\tPAYMENT_REQUIRED: \"PAYMENT_REQUIRED\",\n\tFORBIDDEN: \"FORBIDDEN\",\n\tVERSION_CONFLICT: \"VERSION_CONFLICT\",\n\tNOT_FOUND: \"NOT_FOUND\",\n\t// Tenant lifecycle (CLI surfaces these verbatim)\n\tKEY_ROTATED: \"KEY_ROTATED\",\n\tTENANT_SUSPENDED: \"TENANT_SUSPENDED\",\n\tNO_TENANT_FOR_PROJECT: \"NO_TENANT_FOR_PROJECT\",\n\tINSTANCE_EXISTS: \"INSTANCE_EXISTS\",\n} as const;\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];\n\n/** Base error class for all Secondlayer errors. */\nexport class SecondLayerError extends Error {\n\tpublic code: ErrorCode;\n\tpublic override cause?: unknown;\n\t/** Optional structured payload merged into the HTTP error body (machine-readable hints). */\n\tpublic details?: Record<string, unknown>;\n\n\tconstructor(\n\t\tcode: ErrorCode,\n\t\tmessage: string,\n\t\tcause?: unknown,\n\t\tdetails?: Record<string, unknown>,\n\t) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\t\tthis.cause = cause;\n\t\tthis.details = details;\n\t\tthis.name = this.constructor.name;\n\t\tError.captureStackTrace?.(this, this.constructor);\n\t}\n\n\ttoJSON(): {\n\t\tname: string;\n\t\tcode: string;\n\t\tmessage: string;\n\t\tstack: string | undefined;\n\t\tcause: unknown;\n\t\tdetails: Record<string, unknown> | undefined;\n\t} {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tcode: this.code,\n\t\t\tmessage: this.message,\n\t\t\tstack: this.stack,\n\t\t\tcause: this.cause,\n\t\t\tdetails: this.details,\n\t\t};\n\t}\n}\n\nexport class NotFoundError extends SecondLayerError {\n\tconstructor(message: string) {\n\t\tsuper(\"NOT_FOUND\", message);\n\t}\n}\n\nexport class ValidationError extends SecondLayerError {\n\tconstructor(message: string, cause?: unknown) {\n\t\tsuper(\"VALIDATION_ERROR\", message, cause);\n\t}\n}\n\nexport class DatabaseError extends SecondLayerError {\n\tconstructor(message: string, cause?: unknown) {\n\t\tsuper(\"DATABASE_ERROR\", message, cause);\n\t}\n}\n\nexport class AuthenticationError extends SecondLayerError {\n\tconstructor(message: string) {\n\t\tsuper(\"AUTHENTICATION_ERROR\", message);\n\t}\n}\n\nexport class AuthorizationError extends SecondLayerError {\n\tconstructor(message: string, details?: Record<string, unknown>) {\n\t\tsuper(\"AUTHORIZATION_ERROR\", message, undefined, details);\n\t}\n}\n\nexport class RateLimitError extends SecondLayerError {\n\tconstructor(message: string) {\n\t\tsuper(\"RATE_LIMIT_ERROR\", message);\n\t}\n}\n\n/**\n * HTTP 402. Carries the x402 challenge (or a retry-later reason) in `details` so\n * the global error handler emits it in the body. The wire `PAYMENT-REQUIRED`\n * header is set separately by the x402 middleware on the challenge path.\n */\nexport class PaymentRequiredError extends SecondLayerError {\n\tconstructor(message: string, details?: Record<string, unknown>) {\n\t\tsuper(\"PAYMENT_REQUIRED\", message, undefined, details);\n\t}\n}\n\nexport class ForbiddenError extends SecondLayerError {\n\tconstructor(message = \"Forbidden\") {\n\t\tsuper(\"FORBIDDEN\", message);\n\t}\n}\n\nexport class VersionConflictError extends SecondLayerError {\n\tpublic currentVersion: string;\n\tpublic expectedVersion: string;\n\n\tconstructor(currentVersion: string, expectedVersion: string) {\n\t\tsuper(\n\t\t\t\"VERSION_CONFLICT\",\n\t\t\t`Version conflict: expected ${expectedVersion}, current ${currentVersion}`,\n\t\t);\n\t\tthis.currentVersion = currentVersion;\n\t\tthis.expectedVersion = expectedVersion;\n\t}\n}\n\nexport class KeyRotatedError extends SecondLayerError {\n\tconstructor(message = \"Token has been rotated\") {\n\t\tsuper(\"KEY_ROTATED\", message);\n\t}\n}\n\nexport class TenantSuspendedError extends SecondLayerError {\n\tconstructor(message = \"Instance is suspended\") {\n\t\tsuper(\"TENANT_SUSPENDED\", message);\n\t}\n}\n\n/** Error code → HTTP status. Used by API middleware for code-based matching\n * (avoids cross-bundle instanceof failures from bunup class duplication). */\n// String literal map — codes don't have to be in the central ErrorCode\n// enum (route-local error classes can supply any code; we just map the\n// HTTP status here). This keeps cross-bundle instanceof failures out of\n// the equation.\nexport const CODE_TO_STATUS: Record<\n\tstring,\n\t400 | 401 | 402 | 403 | 404 | 409 | 422 | 423 | 429 | 503\n> = {\n\t// The chain plane has no data yet — a fresh self-host install before the\n\t// first block lands. Retryable, and not the operator's mistake, so it is a\n\t// 503 with a name rather than an opaque 500.\n\tCHAIN_DATA_UNAVAILABLE: 503,\n\tAUTHENTICATION_ERROR: 401,\n\tAUTHORIZATION_ERROR: 403,\n\tPAYMENT_REQUIRED: 402,\n\tRATE_LIMIT_ERROR: 429,\n\tFORBIDDEN: 403,\n\tNOT_FOUND: 404,\n\tVALIDATION_ERROR: 400,\n\tKEY_ROTATED: 401,\n\tTENANT_SUSPENDED: 423,\n\tNO_TENANT_FOR_PROJECT: 404,\n\tINSTANCE_EXISTS: 409,\n\tSUBGRAPH_NOT_FOUND: 404,\n\tPUBLIC_NAME_TAKEN: 409,\n\tGHOST_KEY_READ_ONLY: 403,\n} as const;\n\nexport function getErrorMessage(err: unknown): string {\n\treturn err instanceof Error ? err.message : String(err);\n}\n"
6
6
  ],
7
- "mappings": ";;;;;;;;;;;;;;;;;AAAO,IAAM,aAAa;AAAA,EACzB,kBAAkB;AAAA,EAClB,gBAAgB;AAAA,EAChB,sBAAsB;AAAA,EACtB,qBAAqB;AAAA,EACrB,kBAAkB;AAAA,EAClB,kBAAkB;AAAA,EAClB,WAAW;AAAA,EACX,kBAAkB;AAAA,EAClB,WAAW;AAAA,EAEX,aAAa;AAAA,EACb,kBAAkB;AAAA,EAClB,uBAAuB;AAAA,EACvB,iBAAiB;AAClB;AAAA;AA2BO,MAAM,yBAAyB,MAAM;AAAA,EACpC;AAAA,EACS;AAAA,EAET;AAAA,EAEP,WAAW,CACV,MACA,SACA,OACA,SACC;AAAA,IACD,MAAM,OAAO;AAAA,IACb,KAAK,OAAO;AAAA,IACZ,KAAK,QAAQ;AAAA,IACb,KAAK,UAAU;AAAA,IACf,KAAK,OAAO,KAAK,YAAY;AAAA,IAC7B,MAAM,oBAAoB,MAAM,KAAK,WAAW;AAAA;AAAA,EAGjD,MAAM,GAOJ;AAAA,IACD,OAAO;AAAA,MACN,MAAM,KAAK;AAAA,MACX,MAAM,KAAK;AAAA,MACX,SAAS,KAAK;AAAA,MACd,OAAO,KAAK;AAAA,MACZ,OAAO,KAAK;AAAA,MACZ,SAAS,KAAK;AAAA,IACf;AAAA;AAEF;AAAA;AAEO,MAAM,sBAAsB,iBAAi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