@secondlayer/shared 15.3.4 → 15.4.1

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 (61) hide show
  1. package/dist/src/archive/range-digest.d.ts +2 -0
  2. package/dist/src/archive/semantic-digest-builder.d.ts +2 -0
  3. package/dist/src/classify/index.js +16 -2
  4. package/dist/src/classify/index.js.map +3 -3
  5. package/dist/src/coverage/index.d.ts +2 -0
  6. package/dist/src/coverage/index.js +35 -1
  7. package/dist/src/coverage/index.js.map +3 -3
  8. package/dist/src/crypto/secondlayer-webhook.js +16 -2
  9. package/dist/src/crypto/secondlayer-webhook.js.map +3 -3
  10. package/dist/src/crypto/secrets.d.ts +8 -2
  11. package/dist/src/crypto/secrets.js +21 -7
  12. package/dist/src/crypto/secrets.js.map +3 -3
  13. package/dist/src/db/index.d.ts +10 -1
  14. package/dist/src/db/index.js +29 -7
  15. package/dist/src/db/index.js.map +5 -5
  16. package/dist/src/db/queries/chain-reorgs.d.ts +2 -0
  17. package/dist/src/db/queries/chain-reorgs.js +27 -7
  18. package/dist/src/db/queries/chain-reorgs.js.map +5 -5
  19. package/dist/src/db/queries/contracts.d.ts +13 -1
  20. package/dist/src/db/queries/contracts.js +13 -1
  21. package/dist/src/db/queries/contracts.js.map +4 -4
  22. package/dist/src/db/queries/instance.d.ts +28 -5
  23. package/dist/src/db/queries/instance.js +224 -14
  24. package/dist/src/db/queries/instance.js.map +6 -5
  25. package/dist/src/db/queries/integrity.d.ts +15 -1
  26. package/dist/src/db/queries/integrity.js +244 -14
  27. package/dist/src/db/queries/integrity.js.map +7 -6
  28. package/dist/src/db/queries/subgraph-gaps.d.ts +2 -0
  29. package/dist/src/db/queries/subgraph-operations.d.ts +2 -0
  30. package/dist/src/db/queries/subgraphs.d.ts +2 -0
  31. package/dist/src/db/queries/sync-scope.d.ts +2 -0
  32. package/dist/src/db/queries/webhook-replays.d.ts +2 -0
  33. package/dist/src/db/queries/webhook-replays.js +20 -7
  34. package/dist/src/db/queries/webhook-replays.js.map +3 -3
  35. package/dist/src/db/queries/webhooks.d.ts +2 -0
  36. package/dist/src/db/queries/webhooks.js +20 -7
  37. package/dist/src/db/queries/webhooks.js.map +3 -3
  38. package/dist/src/db/schema.d.ts +2 -0
  39. package/dist/src/db/schema.js.map +2 -2
  40. package/dist/src/email/index.js +16 -2
  41. package/dist/src/email/index.js.map +3 -3
  42. package/dist/src/env.d.ts +8 -1
  43. package/dist/src/env.js +18 -3
  44. package/dist/src/env.js.map +3 -3
  45. package/dist/src/index.d.ts +54 -1
  46. package/dist/src/index.js +68 -7
  47. package/dist/src/index.js.map +7 -7
  48. package/dist/src/insights/index.d.ts +2 -0
  49. package/dist/src/insights/index.js +16 -2
  50. package/dist/src/insights/index.js.map +3 -3
  51. package/dist/src/leader.js +915 -27
  52. package/dist/src/leader.js.map +13 -6
  53. package/dist/src/logger.js +16 -2
  54. package/dist/src/logger.js.map +3 -3
  55. package/dist/src/node/local-client.d.ts +2 -0
  56. package/dist/src/node/tx-summary.js +16 -2
  57. package/dist/src/node/tx-summary.js.map +3 -3
  58. package/dist/src/queue/listener.js +27 -7
  59. package/dist/src/queue/listener.js.map +5 -5
  60. package/migrations/0202_instances_secrets_key_canary.ts +36 -0
  61. package/package.json +2 -2
@@ -2,9 +2,9 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/db/types.ts"],
4
4
  "sourcesContent": [
5
- "import type {\n\tColumnType,\n\tGenerated,\n\tInsertable,\n\tSelectable,\n\tUpdateable,\n} from \"kysely\";\nimport type {\n\tFailureClass,\n\tFailureUnit,\n\tNativeClock,\n\tRepairMode,\n\tRetryState,\n\tRunStatus,\n\tStageKind,\n} from \"../coverage/constraints.ts\";\nimport type { BootstrapSource } from \"../coverage/evaluate.ts\";\nimport type {\n\tSubgraphStatus,\n\tSubgraphVerification,\n} from \"../schemas/subgraphs.ts\";\nimport type { WebhookPauseReason } from \"../webhooks/health.ts\";\n\nexport type {\n\tFailureClass,\n\tFailureUnit,\n\tNativeClock,\n\tRepairMode,\n\tRetryState,\n\tRunStatus,\n\tStageKind,\n} from \"../coverage/constraints.ts\";\n\n// ── Table interfaces ──────────────────────────────────────────────────\n\nexport interface BlocksTable {\n\theight: number;\n\thash: string;\n\tparent_hash: string;\n\tburn_block_height: number;\n\tburn_block_hash: ColumnType<\n\t\tstring | null,\n\t\tstring | null | undefined,\n\t\tstring | null\n\t>;\n\t/** Nakamoto StacksBlockId. Null on rows ingested before it was persisted. */\n\tindex_block_hash: ColumnType<\n\t\tstring | null,\n\t\tstring | null | undefined,\n\t\tstring | null\n\t>;\n\ttimestamp: number;\n\tcanonical: Generated<boolean>;\n\t/** Tx count `persistBlock` was handed for this height. Null on rows\n\t * ingested before this column existed. */\n\ttx_count: ColumnType<number | null, number | null | undefined, number | null>;\n\t/** Event count `persistBlock` was handed for this height. Null on rows\n\t * ingested before this column existed. */\n\tevent_count: ColumnType<\n\t\tnumber | null,\n\t\tnumber | null | undefined,\n\t\tnumber | null\n\t>;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface TransactionsTable {\n\ttx_id: string;\n\tblock_height: number;\n\ttx_index: Generated<number>;\n\ttype: string;\n\tsender: string;\n\tstatus: string;\n\tcontract_id: string | null;\n\tfunction_name: string | null;\n\tfunction_args: Generated<unknown | null>;\n\traw_result: Generated<string | null>;\n\traw_tx: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface EventsTable {\n\tid: Generated<string>;\n\ttx_id: string;\n\tblock_height: number;\n\tevent_index: number;\n\ttype: string;\n\tdata: unknown;\n\tcreated_at: Generated<Date>;\n}\n\n// Reorg archive (see migration 0084): orphaned transactions/events copied here\n// before a reused height is replaced, preserving the raw log instead of\n// deleting it.\nexport interface TransactionsArchiveTable {\n\tarchive_id: Generated<string>;\n\ttx_id: string;\n\tblock_height: number;\n\ttx_index: number;\n\ttype: string;\n\tsender: string;\n\tstatus: string;\n\tcontract_id: string | null;\n\tfunction_name: string | null;\n\tfunction_args: unknown | null;\n\traw_result: string | null;\n\traw_tx: string;\n\tcreated_at: Date;\n\torphaned_block_hash: string | null;\n\tarchived_at: Generated<Date>;\n}\n\nexport interface EventsArchiveTable {\n\tarchive_id: Generated<string>;\n\tid: string;\n\ttx_id: string;\n\tblock_height: number;\n\tevent_index: number;\n\ttype: string;\n\tdata: unknown;\n\tcreated_at: Date;\n\torphaned_block_hash: string | null;\n\tarchived_at: Generated<Date>;\n}\n\n// Opt-in VM traces (migration 0131). Second clock: `ordinal` (array position\n// in `/new_block.vm_events`). Never mixed into `events.event_index`. Primary\n// key `(block_height, ordinal)` (migration 0153).\nexport interface VmEventsTable {\n\ttx_id: string;\n\tblock_height: number;\n\tordinal: number;\n\ttype: string;\n\tdata: unknown;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface VmEventsArchiveTable {\n\tarchive_id: Generated<string>;\n\t/** `block_height:ordinal`; rows archived before migration 0153 hold the old uuid. */\n\tid: string;\n\ttx_id: string;\n\tblock_height: number;\n\tordinal: number;\n\ttype: string;\n\tdata: unknown;\n\tcreated_at: Date;\n\torphaned_block_hash: string | null;\n\tarchived_at: Generated<Date>;\n}\n\n// Opt-in node storage-layer writes (migration 0154): the exact MARF writes a\n// block committed, in node order. `tx_index` is null for block-level writes.\n// Primary key `(block_height, ordinal)`.\nexport interface StateWritesTable {\n\tblock_height: number;\n\tordinal: number;\n\ttx_index: number | null;\n\tkey: string;\n\tvalue_hex: string;\n}\n\nexport interface StateWritesArchiveTable {\n\tarchive_id: Generated<string>;\n\t/** `block_height:ordinal`. */\n\tid: string;\n\tblock_height: number;\n\tordinal: number;\n\ttx_index: number | null;\n\tkey: string;\n\tvalue_hex: string;\n\torphaned_block_hash: string | null;\n\tarchived_at: Generated<Date>;\n}\n\n// Dead-letter log (see migration 0085): events whose decoded payload failed\n// schema validation on ingest. Append-only diagnostic; the event still lands in\n// `events`, so chain data is never lost.\nexport interface DeadLetterEventsTable {\n\tid: Generated<string>;\n\tblock_height: number;\n\ttx_id: string;\n\tevent_index: number;\n\tevent_type: string;\n\tdata: unknown;\n\treason: string;\n\tcreated_at: Generated<Date>;\n}\n\n// Pending (unconfirmed) transactions (see migration 0086). Pre-chain, so no\n// block_height/tx_index/result/events and never canonical. tx_id is derived\n// from raw_tx; function_args holds hex-encoded ClarityValues (jsonb), like\n// `transactions`.\nexport interface MempoolTransactionsTable {\n\tseq: Generated<string>;\n\ttx_id: string;\n\traw_tx: string;\n\ttype: string;\n\tsender: string;\n\tcontract_id: string | null;\n\tfunction_name: string | null;\n\tfunction_args: unknown | null;\n\treceived_at: Generated<Date>;\n}\n\nexport interface IndexProgressTable {\n\tnetwork: string;\n\tlast_indexed_block: Generated<number>;\n\tlast_contiguous_block: Generated<number>;\n\thighest_seen_block: Generated<number>;\n\tupdated_at: Generated<Date>;\n}\n\nexport interface SubgraphsTable {\n\tid: Generated<string>;\n\tname: string;\n\tversion: Generated<string>;\n\tstatus: Generated<SubgraphStatus>;\n\tdefinition: Record<string, unknown>;\n\tschema_hash: string;\n\thandler_path: string;\n\tschema_name: string | null;\n\tstart_block: Generated<number>;\n\tlast_processed_block: Generated<number>;\n\t/** Hash of the block at `last_processed_block`; NULL = unknown (see 0197). */\n\tlast_processed_block_hash: Generated<string | null>;\n\treindex_from_block: number | null;\n\treindex_to_block: number | null;\n\tlast_error: string | null;\n\tlast_error_at: Date | null;\n\ttotal_processed: Generated<number>;\n\ttotal_errors: Generated<number>;\n\taccount_id: string;\n\thandler_code: string | null;\n\tsource_code: string | null;\n\tproject_id: string | null;\n\t/** Set while the account's metered reads are refused (spend cap, credits).\n\t * Both columns are set or both null; `last_error` stays for real errors. */\n\tbilling_paused_at: Date | null;\n\tbilling_paused_code: string | null;\n\t/** (event type, contract) probe pairs persisted at deploy for weight classification. */\n\tsparse_probe_targets: unknown | null;\n\t/** sha256 over everything that shapes rows (schema, handler bundle,\n\t * startBlock, network, runtime). NULL for unbundled or older deploys. */\n\tpin: string | null;\n\t/** The canonical JSON `pin` hashes, so a client can recompute it. NULL\n\t * wherever `pin` is, and for deploys before migration 0158. */\n\tpin_preimage: string | null;\n\t/** Level derived at deploy. NULL (older deploys) = not verifiable. */\n\tverification: SubgraphVerification | null;\n\tcreated_at: Generated<Date>;\n\tupdated_at: Generated<Date>;\n}\n\n/** Mirrored by the CHECK on `contracts.abi_status`. */\nexport const ABI_STATUSES = [\n\t\"pending\",\n\t\"fetched\",\n\t\"unparseable\",\n\t\"failed\",\n] as const;\nexport type AbiStatus = (typeof ABI_STATUSES)[number];\n\nexport interface ContractsTable {\n\tcontract_id: string;\n\tdeployer: string;\n\tblock_height: number;\n\tcanonical: Generated<boolean>;\n\tabi: unknown | null;\n\tdeclared_traits: Generated<string[]>;\n\tinferred_standards: Generated<string[]>;\n\tabi_status: Generated<AbiStatus>;\n\tabi_fetched_at: Date | null;\n\t/** Failed fetches so far; `failed` re-polls until the registry's attempt cap. */\n\tabi_attempts: Generated<number>;\n\t/** When a `failed` row is next due; NULL once attempts are exhausted. */\n\tabi_next_attempt_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\n/** The only reasons the runtime records; mirrored by a CHECK on `subgraph_gaps.reason`. */\nexport type GapReason = \"block_missing\" | \"processing_error\";\n\nexport interface SubgraphGapsTable {\n\tid: Generated<string>;\n\tsubgraph_id: string;\n\tsubgraph_name: string;\n\tgap_start: number;\n\tgap_end: number;\n\treason: GapReason;\n\tdetected_at: Generated<Date>;\n\tresolved_at: Date | null;\n}\n\n/** Print-validate skips persisted for the authed violations GET. Cap 100/subgraph. */\nexport interface SubgraphViolationsTable {\n\tid: Generated<string>;\n\tsubgraph_name: string;\n\tsource_name: string;\n\tblock_height: number;\n\ttx_id: string;\n\treason: string;\n\tsample_payload: Record<string, unknown>;\n\tseen_at: Generated<Date>;\n}\n\nexport type SubgraphOperationKind = \"reindex\" | \"backfill\";\nexport type SubgraphOperationStatus =\n\t| \"queued\"\n\t| \"running\"\n\t| \"completed\"\n\t| \"failed\"\n\t| \"cancelled\";\n\nexport interface SubgraphOperationsTable {\n\tid: Generated<string>;\n\tsubgraph_id: string;\n\tsubgraph_name: string;\n\taccount_id: string | null;\n\tkind: ColumnType<\n\t\tSubgraphOperationKind,\n\t\tSubgraphOperationKind,\n\t\tSubgraphOperationKind\n\t>;\n\tstatus: ColumnType<\n\t\tSubgraphOperationStatus,\n\t\tSubgraphOperationStatus | undefined,\n\t\tSubgraphOperationStatus\n\t>;\n\tfrom_block: number | null;\n\tto_block: number | null;\n\tcancel_requested: Generated<boolean>;\n\tlocked_by: string | null;\n\tlocked_until: Date | null;\n\tstarted_at: Date | null;\n\tfinished_at: Date | null;\n\tprocessed_blocks: number | null;\n\terror: string | null;\n\tcreated_at: Generated<Date>;\n\tupdated_at: Generated<Date>;\n\t/** 'light' (contract-scoped sparse) | 'heavy' (broad). Claim budgets heavy. */\n\tweight: Generated<string>;\n\t/** Candidate-event denominator computed at enqueue (sparse ops only). */\n\testimated_events: string | number | bigint | null;\n\t/** Events processed so far — written by the progress flush. */\n\tprocessed_events: string | number | bigint | null;\n\t/** Backfill ops' own crash checkpoint — advanced conditionally in-tx with\n\t * each written block; replays skip at/below it. NULL for reindex ops\n\t * (those checkpoint on subgraphs.last_processed_block). */\n\tcursor_block: string | number | bigint | null;\n}\n\nexport type ApiKeyStatus = \"active\" | \"revoked\";\n\nexport interface ApiKeysTable {\n\tid: Generated<string>;\n\tkey_hash: string;\n\tkey_prefix: string;\n\tname: string | null;\n\tstatus: Generated<ApiKeyStatus>;\n\trate_limit: Generated<number>;\n\tip_address: string;\n\taccount_id: string;\n\tproduct: Generated<\n\t\t\"account\" | \"streams\" | \"index\" | \"sentinel\" | \"docs\" | \"tenant\"\n\t>;\n\t/** Sentinel permission areas; set only on `product = 'sentinel'` keys. */\n\tareas: unknown | null;\n\ttier: \"free\" | \"internal\" | null;\n\tlast_used_at: Date | null;\n\trevoked_at: Date | null;\n\t/** Set only on `docs` keys (24h). A key past this instant never authenticates. */\n\texpires_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\n/** Singleton self-host / publisher identity. Network is immutable. */\nexport interface InstancesTable {\n\tid: Generated<string>;\n\tnetwork: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface AccountsTable {\n\tid: Generated<string>;\n\t/** NULL for unclaimed ghost accounts (anonymous self-serve keys). */\n\temail: string | null;\n\t/** True for anonymous self-serve accounts until claimed via magic link. */\n\tghost: Generated<boolean>;\n\t/** First-party service account: usage priced at $0, never gated on\n\t * credits. Set by ops only. */\n\tinternal: Generated<boolean>;\n\t/** Stacks principal owning a wallet-ghost account. */\n\twallet_principal: string | null;\n\tdisplay_name: string | null;\n\tbio: string | null;\n\tavatar_url: string | null;\n\tstripe_customer_id: string | null;\n\t/** Opt-out toggle for the subgraph reindex-completion email. Defaults true. */\n\tnotify_reindex_complete: Generated<boolean>;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface SessionsTable {\n\tid: Generated<string>;\n\ttoken_hash: string;\n\ttoken_prefix: string;\n\taccount_id: string;\n\tip_address: string;\n\texpires_at: Generated<Date>;\n\trevoked_at: Date | null;\n\tlast_used_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface MagicLinksTable {\n\tid: Generated<string>;\n\temail: string;\n\ttoken: string;\n\tcode: string | null;\n\texpires_at: Date;\n\tused_at: Date | null;\n\tfailed_attempts: Generated<number>;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface SubgraphProcessingStatsTable {\n\tid: Generated<string>;\n\tsubgraph_name: string;\n\tapi_key_id: string | null;\n\tbucket_start: Date | null;\n\tbucket_end: Date | null;\n\tblocks_processed: number | null;\n\ttotal_time_ms: number | null;\n\thandler_time_ms: number | null;\n\tflush_time_ms: number | null;\n\tmax_block_time_ms: number | null;\n\tmax_handler_time_ms: number | null;\n\tavg_ops_per_block: number | null;\n\tis_catchup: Generated<boolean>;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface SubgraphHealthSnapshotsTable {\n\tid: Generated<string>;\n\tsubgraph_id: string;\n\ttotal_processed: number;\n\ttotal_errors: number;\n\tlast_processed_block: number | null;\n\tchain_tip: string | number | null;\n\trows_written_total: string | number | null;\n\tstorage_bytes: string | number | null;\n\tcaptured_at: Generated<Date>;\n}\n\n/** Handler errors grouped by fingerprint. Cap 50/subgraph. */\nexport interface SubgraphErrorGroupsTable {\n\tid: Generated<string>;\n\tsubgraph_name: string;\n\tfingerprint: string;\n\tsource_name: string;\n\tevent_type: string | null;\n\tmessage: string;\n\tframe: string | null;\n\tcount: Generated<string | number>;\n\tsample_tx_id: string | null;\n\tsample_block_height: string | number | null;\n\tfirst_seen: Generated<Date>;\n\tlast_seen: Generated<Date>;\n}\n\n/**\n * One ranked dashboard insight. `account_id` is NULL on tenant and self-host\n * databases. `severity` is never \"recovered\": that is derived on read from\n * `resolved_at`.\n */\nexport interface InsightsTable {\n\tid: Generated<string>;\n\taccount_id: string | null;\n\tresource_kind: string;\n\tresource_id: string;\n\trule: string;\n\tseverity: string;\n\timpact: Generated<number>;\n\t/** resource, line, meta, lead, body, evidence, handoff, how. */\n\tpayload: unknown;\n\tfirst_seen_at: Generated<Date>;\n\tlast_seen_at: Generated<Date>;\n\tclear_streak: Generated<number>;\n\tresolved_at: Date | null;\n\tdismissed_at: Date | null;\n\tsnoozed_until: Date | null;\n}\n\n/** \"Expected\": mutes one rule for one resource until removed. */\nexport interface InsightMutesTable {\n\taccount_id: string | null;\n\tresource_kind: string;\n\tresource_id: string;\n\trule: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface ProcessedStripeEventsTable {\n\tevent_id: string;\n\tevent_type: string;\n\tprocessed_at: Generated<Date>;\n}\n\nexport interface DecodedEventsTable {\n\tcursor: string;\n\tblock_height: number;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\tevent_type: string;\n\tmicroblock_hash: string | null;\n\tcanonical: Generated<boolean>;\n\tcontract_id: string | null;\n\tsender: string | null;\n\trecipient: string | null;\n\tamount: string | null;\n\tasset_identifier: string | null;\n\tvalue: string | null;\n\tmemo: string | null;\n\t/** Decoded payload for event types that don't fit the flat columns\n\t * (e.g. `print`: { topic, value, raw_value }). Null for transfer types. */\n\tpayload: unknown | null;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface DecoderCheckpointsTable {\n\tdecoder_name: string;\n\tlast_cursor: string | null;\n\tupdated_at: Generated<Date>;\n}\n\nexport interface ChainReorgsTable {\n\tid: Generated<string>;\n\tdetected_at: Generated<Date>;\n\tfork_point_height: number;\n\told_index_block_hash: string | null;\n\tnew_index_block_hash: string | null;\n\torphaned_from_height: number;\n\torphaned_from_event_index: number;\n\torphaned_to_height: number;\n\torphaned_to_event_index: number;\n\tnew_canonical_height: number;\n\tnew_canonical_event_index: number;\n\tcreated_at: Generated<Date>;\n}\n\n// ── L2 decoded tables: PoX-4 / sBTC / BNS ────────────────────────────\n\nexport type Pox4FunctionName =\n\t| \"stack-stx\"\n\t| \"delegate-stx\"\n\t| \"stack-extend\"\n\t| \"stack-increase\"\n\t| \"revoke-delegate-stx\"\n\t| \"delegate-stack-stx\"\n\t| \"delegate-stack-extend\"\n\t| \"delegate-stack-increase\"\n\t| \"stack-aggregation-commit\"\n\t| \"stack-aggregation-commit-indexed\"\n\t| \"stack-aggregation-increase\"\n\t| \"set-signer-key-authorization\";\n\nexport interface Pox4CallsTable {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time: Date;\n\tburn_block_height: number;\n\ttx_id: string;\n\ttx_index: number;\n\tfunction_name: Pox4FunctionName;\n\tcaller: string;\n\tstacker: string | null;\n\tdelegate_to: string | null;\n\tamount_ustx: string | null;\n\tlock_period: number | null;\n\tpox_addr_version: number | null;\n\tpox_addr_hashbytes: string | null;\n\tpox_addr_btc: string | null;\n\tstart_cycle: number | null;\n\tend_cycle: number | null;\n\tsigner_key: string | null;\n\tsigner_signature: string | null;\n\tauth_id: string | null;\n\tmax_amount: string | null;\n\treward_cycle: number | null;\n\taggregated_amount_ustx: string | null;\n\taggregated_signer_index: number | null;\n\tauth_period: number | null;\n\tauth_topic: string | null;\n\tauth_allowed: boolean | null;\n\tresult_ok: boolean;\n\tresult_raw: string;\n\tcanonical: Generated<boolean>;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport type Pox5EventTopic =\n\t| \"set-bond-admin\"\n\t| \"set-pause-admin\"\n\t| \"pause-rewards\"\n\t| \"setup-bond\"\n\t| \"add-to-allowlist\"\n\t| \"register-for-bond\"\n\t| \"update-bond-registration\"\n\t| \"register-signer\"\n\t| \"stake\"\n\t| \"stake-update\"\n\t| \"announce-l1-early-exit\"\n\t| \"unstake-sbtc\"\n\t| \"unstake\"\n\t| \"calculate-rewards\"\n\t| \"bond-distribution\"\n\t| \"claim-rewards\"\n\t| \"claim-staker-rewards-for-signer\"\n\t| \"grant-signer-key\"\n\t| \"revoke-signer-grant\";\n\n// PoX-5 print events (SIP-045). Promoted columns cover hot query paths; the\n// full decoded tuple always lands in `data` (nested shapes: btc-lockup,\n// bond-rewards lists, bond-periods).\nexport interface Pox5EventsTable {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time: Date;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\ttopic: Pox5EventTopic;\n\tstaker: string | null;\n\tsigner: string | null;\n\tsigner_manager: string | null;\n\tbond_index: number | null;\n\tamount_ustx: string | null;\n\tamount_sats: string | null;\n\treward_cycle: number | null;\n\tfirst_reward_cycle: number | null;\n\tunlock_cycle: number | null;\n\tunlock_burn_height: number | null;\n\tis_l1_lock: boolean | null;\n\tsigner_key: string | null;\n\tdata: unknown;\n\tcanonical: Generated<boolean>;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\n// Materialized per-cycle PoX-5 rollup (`rollupPox5Cycles`), maintained after\n// every committed pox5 decoder batch and after a pox5 reorg. Fully\n// rebuildable from `pox5_events` via `rebuild-pox5-cycles.ts --apply`.\nexport interface Pox5CyclesTable {\n\treward_cycle: number;\n\tstart_burn_height: number;\n\tprepare_start_burn_height: number;\n\tend_burn_height: number;\n\ttotal_stacked_ustx: string;\n\treward_eligible_ustx: string;\n\tstakers: number;\n\tsigners_in_set: number;\n\t/** bond index (as string) -> sats staked for this cycle. */\n\tbond_sats: unknown;\n\tbond_total_sats: string;\n\tsbtc_custodied_sats: string;\n\trewards_allocated_stx: string;\n\trewards_allocated_bond: string;\n\treserve_deposit: string;\n\trewards_per_token_stx: string | null;\n\t/** bond index (as string) -> cumulative rewards-per-sat for this cycle. */\n\trewards_per_token_bond: unknown;\n\tdistributions: number;\n\trewards_claimed: string;\n\tcomputed_through_height: number;\n\tupdated_at: Generated<Date>;\n}\n\n// Per-signer half of the pox-5 cycle rollup.\nexport interface Pox5CycleSignersTable {\n\treward_cycle: number;\n\tsigner: string;\n\tdelegated_ustx: string;\n\tstx_only_ustx: string;\n\treward_shares_ustx: string;\n\tin_set: boolean;\n\trewards_claimed: string;\n}\n\n// Actual BTC PoX payout — one row per reward slot (≤2 per burn block), from the\n// /new_burn_block reward_recipients array. `amount_sats`/`burn_amount` are sats.\nexport interface BurnBlockRewardsTable {\n\tcursor: string;\n\tburn_block_height: number;\n\tburn_block_hash: string;\n\treward_index: number;\n\trecipient_btc: string;\n\t// sats; TEXT to match the dataset amount convention (BIGINT returns as string).\n\tamount_sats: string;\n\tburn_amount: Generated<string>;\n\tcreated_at: Generated<Date>;\n}\n\n// Reward-set membership per burn block, from /new_burn_block reward_slot_holders.\nexport interface BurnBlockRewardSlotsTable {\n\tcursor: string;\n\tburn_block_height: number;\n\tburn_block_hash: string;\n\tslot_index: number;\n\tholder_btc: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport type SbtcEventTopic =\n\t| \"completed-deposit\"\n\t| \"withdrawal-create\"\n\t| \"withdrawal-accept\"\n\t| \"withdrawal-reject\"\n\t| \"key-rotation\"\n\t| \"update-protocol-contract\";\n\nexport interface SbtcEventsTable {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time: Date;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\ttopic: SbtcEventTopic;\n\trequest_id: number | null;\n\tamount: string | null;\n\tsender: string | null;\n\trecipient_btc_version: number | null;\n\trecipient_btc_hashbytes: string | null;\n\tbitcoin_txid: string | null;\n\toutput_index: number | null;\n\tsweep_txid: string | null;\n\tburn_hash: string | null;\n\tburn_height: number | null;\n\tsigner_bitmap: string | null;\n\tmax_fee: string | null;\n\tfee: string | null;\n\tblock_height_at_request: number | null;\n\tgovernance_contract_type: number | null;\n\tgovernance_new_contract: string | null;\n\tsigner_aggregate_pubkey: string | null;\n\tsigner_threshold: number | null;\n\tsigner_address: string | null;\n\tsigner_keys_count: number | null;\n\tcanonical: Generated<boolean>;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport type SbtcTokenEventType = \"transfer\" | \"mint\" | \"burn\";\n\nexport interface SbtcTokenEventsTable {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time: Date;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\tevent_type: SbtcTokenEventType;\n\tsender: string | null;\n\trecipient: string | null;\n\tamount: string;\n\tmemo: string | null;\n\tcanonical: Generated<boolean>;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\n/**\n * BTC L1 settlement status for sBTC withdrawal sweeps. Filled by the indexer's\n * settlement-confirmer worker, which polls our own bitcoind for confirmations of\n * each `withdrawal-accept`'s `sweep_txid` and surfaces real settlement on the\n * withdrawal lifecycle (the API's `settlement.{btc_confirmations,\n * settlement_confirmed}` placeholder). Keyed on `sweep_txid` (not `request_id`):\n * a request can produce more than one sweep over its life (RBF/rebroadcast), so\n * each broadcast keeps its own confirmation history.\n */\nexport interface SbtcSettlementsTable {\n\tsweep_txid: string;\n\trequest_id: number;\n\tbtc_confirmations: Generated<number>;\n\tsettlement_confirmed: Generated<boolean>;\n\t/** Confirming Bitcoin block — null while the sweep is unconfirmed. */\n\tblock_hash: string | null;\n\tblock_height: number | null;\n\tfirst_seen_at: Generated<Date>;\n\tlast_checked_at: Generated<Date>;\n\t/** Set once, when `settlement_confirmed` first flips true. */\n\tconfirmed_at: Date | null;\n\t/** Monotonic stamp from `sbtc_settlements_seq`, retaken each time the sweep\n\t * becomes confirmed. The webhook scan's watermark. BIGINT: a string at\n\t * runtime. */\n\tseq: Generated<number | string>;\n\tupdated_at: Generated<Date>;\n}\n\nexport type BnsNameEventTopic =\n\t| \"new-name\"\n\t| \"transfer-name\"\n\t| \"renew-name\"\n\t| \"burn-name\"\n\t| \"new-airdrop\";\n\nexport interface BnsNameEventsTable {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time: Date;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\ttopic: BnsNameEventTopic;\n\tnamespace: string;\n\tname: string;\n\tfqn: string;\n\towner: string | null;\n\tbns_id: string;\n\tregistered_at: number | null;\n\timported_at: number | null;\n\trenewal_height: number | null;\n\tstx_burn: string | null;\n\tpreordered_by: string | null;\n\thashed_salted_fqn_preorder: string | null;\n\tcanonical: Generated<boolean>;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport type BnsNamespaceEventStatus =\n\t| \"launch\"\n\t| \"transfer-manager\"\n\t| \"freeze-manager\"\n\t| \"update-price-manager\"\n\t| \"freeze-price-manager\"\n\t| \"turn-off-manager-transfers\";\n\nexport interface BnsNamespaceEventsTable {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time: Date;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\tstatus: BnsNamespaceEventStatus;\n\tnamespace: string;\n\tmanager: string | null;\n\tmanager_frozen: boolean | null;\n\tmanager_transfers_disabled: boolean | null;\n\tprice_function: string | null;\n\tprice_frozen: boolean | null;\n\tlifetime: number | null;\n\trevealed_at: number | null;\n\tlaunched_at: number | null;\n\tcanonical: Generated<boolean>;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport type BnsMarketplaceAction =\n\t| \"list-in-ustx\"\n\t| \"unlist-in-ustx\"\n\t| \"buy-in-ustx\";\n\nexport interface BnsMarketplaceEventsTable {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time: Date;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\taction: BnsMarketplaceAction;\n\tbns_id: string;\n\tprice_ustx: string | null;\n\tcommission: string | null;\n\tcanonical: Generated<boolean>;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface BnsNamesTable {\n\tfqn: string;\n\tnamespace: string;\n\tname: string;\n\towner: string;\n\tbns_id: string;\n\tregistered_at: number | null;\n\trenewal_height: number | null;\n\tlast_event_cursor: string;\n\tlast_event_at: Date;\n\tupdated_at: Generated<Date>;\n}\n\nexport interface BnsNamespacesTable {\n\tnamespace: string;\n\tmanager: string | null;\n\tmanager_frozen: Generated<boolean>;\n\tprice_frozen: Generated<boolean>;\n\tlifetime: number | null;\n\tlaunched_at: number | null;\n\tlast_event_cursor: string;\n\tlast_event_at: Date;\n\tname_count: Generated<number>;\n\tupdated_at: Generated<Date>;\n}\n\n// ── Database interface ────────────────────────────────────────────────\n\n/**\n * Memoized `ctx.client.readOnly()` results. Keyed on `index_block_hash` so a\n * reorg-replaced block never inherits the orphaned fork's answer; a NULL\n * `index_block_hash` marks a caller-declared contract-constant value, cached\n * once per contract+args instead of once per block.\n */\nexport interface ChainReadCacheTable {\n\tid: Generated<number>;\n\tcontract_id: string;\n\tfunction_name: string;\n\targs_hash: string;\n\tindex_block_hash: string | null;\n\tblock_height: ColumnType<\n\t\tnumber | null,\n\t\tnumber | null | undefined,\n\t\tnumber | null\n\t>;\n\tresult_hex: string;\n\tcreated_at: Generated<Date>;\n}\n\n/**\n * A block that arrived for a height we already hold, staged until a later\n * block's `parent_hash` says which of the two the chain kept. See migration\n * 0112 — adopting on first sight picked the losing fork twice.\n */\nexport interface PendingForkBlocksTable {\n\theight: number;\n\tblock_hash: string;\n\tparent_hash: string;\n\t/** The canonical hash we held at this height when the contender arrived. */\n\tincumbent_hash: string;\n\t/** The raw observer payload, replayed verbatim if this fork wins. */\n\tpayload: ColumnType<unknown, unknown, unknown>;\n\treceived_at: Generated<Date>;\n}\n\n/** Mirrored by the CHECK on `observer_journal.status`. */\nexport const OBSERVER_JOURNAL_STATUSES = [\n\t\"received\",\n\t\"processed\",\n\t\"failed\",\n\t\"retried\",\n\t\"poisoned\",\n\t\"skipped\",\n] as const;\nexport type ObserverJournalStatus = (typeof OBSERVER_JOURNAL_STATUSES)[number];\n\n/**\n * Exact observer callback receipt. `raw_body` is immutable evidence; the\n * processing columns are updated only after the current derived-state write\n * succeeds or fails.\n */\nexport interface ObserverJournalTable {\n\tsequence: Generated<string>;\n\tnetwork: string;\n\tpath: string;\n\tsource: string | null;\n\treceived_at: Generated<Date>;\n\traw_body: ColumnType<Buffer, Buffer, Buffer>;\n\traw_body_sha256: string;\n\tstatus: ColumnType<\n\t\tObserverJournalStatus,\n\t\tObserverJournalStatus | undefined,\n\t\tObserverJournalStatus\n\t>;\n\tsemantic_sha256: string | null;\n\tblock_height: number | null;\n\tblock_hash: string | null;\n\tburn_block_height: number | null;\n\tburn_block_hash: string | null;\n\tresult: unknown | null;\n\terror: string | null;\n\tprocessed_at: Date | null;\n}\n\n/** Declared coverage stage. Identity is the `id` string (`raw`, `decode:stx`, …). */\nexport interface StageRegistryTable {\n\tid: string;\n\tkind: StageKind;\n\tdepends_on: string | null;\n\tnative_clock: NativeClock;\n\tproducer_version: string;\n\trepair_mode: RepairMode;\n\tenabled: Generated<boolean>;\n\tcreated_at: Generated<Date>;\n}\n\n/** One versioned sweep of a stage. Nothing writes this table yet; kept because the receipts and failures tables reference it. */\nexport interface StageRunsTable {\n\tid: Generated<string>;\n\tstage_id: string;\n\tcode_hash: string;\n\tconfig_hash: string;\n\thandler_hash: string | null;\n\ttarget_height: number | null;\n\ttarget_cursor: string | null;\n\tstatus: RunStatus;\n\tcomplete_through: number | null;\n\tstarted_at: Generated<Date>;\n\tfinished_at: Date | null;\n}\n\n/** Per-block acknowledgement. Unique on (stage, height, hash). */\nexport interface StageBlockReceiptsTable {\n\tid: Generated<string>;\n\tstage_id: string;\n\trun_id: string | null;\n\tblock_height: number;\n\tblock_hash: string;\n\tinput_count: number;\n\tinput_digest: string;\n\teffect_digest: string;\n\tfinalized: Generated<boolean>;\n\tcompacted_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\n/** Compacted finalized range. Only sealed after receipts in the range finalize. */\nexport interface CoverageSegmentsTable {\n\tid: Generated<string>;\n\tstage_id: string;\n\tfrom_height: number;\n\tto_height: number;\n\tchain_digest: string;\n\tinput_digest: string;\n\toutput_digest: string;\n\tsealed_at: Generated<Date>;\n}\n\n/** Exact unit or range that failed, plus retry/retention state. */\nexport interface StageFailuresTable {\n\tid: Generated<string>;\n\tstage_id: string;\n\trun_id: string | null;\n\tunit_kind: FailureUnit;\n\tfrom_height: number | null;\n\tto_height: number | null;\n\tclass: FailureClass;\n\tretry_state: RetryState;\n\tretry_count: Generated<number>;\n\tlast_error: string | null;\n\tcreated_at: Generated<Date>;\n\tresolved_at: Date | null;\n\tretain_until: Generated<Date>;\n}\n\n/**\n * The instance's declared scope — one row per network. `start_height` is what\n * makes missing history below it deliberate rather than a gap.\n */\nexport interface SyncScopesTable {\n\tnetwork: string;\n\tstart_height: number;\n\ttarget_height: number | null;\n\tbootstrap_source: BootstrapSource;\n\tbootstrap_manifest_digest: string | null;\n\tgenesis_hash: string | null;\n\tcreated_at: Generated<Date>;\n\tupdated_at: Generated<Date>;\n}\n\nexport interface Database {\n\tblocks: BlocksTable;\n\ttransactions: TransactionsTable;\n\tevents: EventsTable;\n\tvm_events: VmEventsTable;\n\tstate_writes: StateWritesTable;\n\ttransactions_archive: TransactionsArchiveTable;\n\tevents_archive: EventsArchiveTable;\n\tvm_events_archive: VmEventsArchiveTable;\n\tstate_writes_archive: StateWritesArchiveTable;\n\tdead_letter_events: DeadLetterEventsTable;\n\tmempool_transactions: MempoolTransactionsTable;\n\tindex_progress: IndexProgressTable;\n\tcontracts: ContractsTable;\n\tsubgraphs: SubgraphsTable;\n\tapi_keys: ApiKeysTable;\n\tinstances: InstancesTable;\n\taccounts: AccountsTable;\n\tsessions: SessionsTable;\n\tmagic_links: MagicLinksTable;\n\tsubgraph_health_snapshots: SubgraphHealthSnapshotsTable;\n\tsubgraph_processing_stats: SubgraphProcessingStatsTable;\n\tsubgraph_gaps: SubgraphGapsTable;\n\tsubgraph_violations: SubgraphViolationsTable;\n\tsubgraph_error_groups: SubgraphErrorGroupsTable;\n\tsubgraph_operations: SubgraphOperationsTable;\n\tprocessed_stripe_events: ProcessedStripeEventsTable;\n\taccount_spend_caps: AccountSpendCapsTable;\n\taccount_credits: AccountCreditsTable;\n\twebhooks: WebhooksTable;\n\twebhook_outbox: WebhookOutboxTable;\n\twebhook_deliveries: WebhookDeliveriesTable;\n\twebhook_delivery_hours: WebhookDeliveryHoursTable;\n\twebhook_replays: WebhookReplaysTable;\n\ttrigger_evaluator_state: TriggerEvaluatorStateTable;\n\tdecoded_events: DecodedEventsTable;\n\tdecoder_checkpoints: DecoderCheckpointsTable;\n\tchain_reorgs: ChainReorgsTable;\n\tpox4_calls: Pox4CallsTable;\n\tpox5_events: Pox5EventsTable;\n\tpox5_cycles: Pox5CyclesTable;\n\tpox5_cycle_signers: Pox5CycleSignersTable;\n\tburn_block_rewards: BurnBlockRewardsTable;\n\tburn_block_reward_slots: BurnBlockRewardSlotsTable;\n\tsbtc_events: SbtcEventsTable;\n\tsbtc_token_events: SbtcTokenEventsTable;\n\tsbtc_settlements: SbtcSettlementsTable;\n\tbns_name_events: BnsNameEventsTable;\n\tbns_namespace_events: BnsNamespaceEventsTable;\n\tbns_marketplace_events: BnsMarketplaceEventsTable;\n\tbns_names: BnsNamesTable;\n\tbns_namespaces: BnsNamespacesTable;\n\tservice_heartbeats: ServiceHeartbeatsTable;\n\tchain_read_cache: ChainReadCacheTable;\n\tpending_fork_blocks: PendingForkBlocksTable;\n\tobserver_journal: ObserverJournalTable;\n\tsync_scopes: SyncScopesTable;\n\tstage_registry: StageRegistryTable;\n\tstage_runs: StageRunsTable;\n\tstage_block_receipts: StageBlockReceiptsTable;\n\tcoverage_segments: CoverageSegmentsTable;\n\tstage_failures: StageFailuresTable;\n\tarchive_fetches: ArchiveFetchesTable;\n\tusage_ledger: UsageLedgerTable;\n\taccount_balance_alerts: AccountBalanceAlertsTable;\n\thosted_stack_state: HostedStackStateTable;\n\twebhook_incident_alerts: WebhookIncidentAlertsTable;\n\tcli_device_logins: CliDeviceLoginsTable;\n\toauth_clients: OauthClientsTable;\n\toauth_requests: OauthRequestsTable;\n\toauth_codes: OauthCodesTable;\n\toauth_grants: OauthGrantsTable;\n\toauth_tokens: OauthTokensTable;\n\toauth_refresh_retired: OauthRefreshRetiredTable;\n\tsentinel_accounts: SentinelAccountsTable;\n\twaitlists: WaitlistsTable;\n\twaitlist_signups: WaitlistSignupsTable;\n\tcontact_requests: ContactRequestsTable;\n\tupdate_subscribers: UpdateSubscribersTable;\n\tupdate_sends: UpdateSendsTable;\n\tapi_failed_requests: ApiFailedRequestsTable;\n\tapi_request_log: ApiRequestLogTable;\n\tinsights: InsightsTable;\n\tinsight_mutes: InsightMutesTable;\n\tfeedback_tickets: FeedbackTicketsTable;\n\tpush_subscriptions: PushSubscriptionsTable;\n\tpush_prefs: PushPrefsTable;\n\tpush_sent: PushSentTable;\n}\n\nexport interface ServiceHeartbeatsTable {\n\tname: string;\n\tupdated_at: Generated<Date>;\n}\n\n// --- Account spend caps (soft cap + threshold alerts) ---\n//\n// One row per account. Null caps = \"no cap\" for that dimension.\n// `monthly_cap_cents` caps this calendar month's pay-as-you-go credit spend.\n// The hard stop is enforced in real time on the read path (read-credits.ts);\n// `frozen_at` is a display/alert mirror set by the daily cron when the cap is\n// hit, and cleared on month rollover, on invoice.paid, or when the cap is raised.\n\nexport interface AccountSpendCapsTable {\n\taccount_id: string;\n\tmonthly_cap_cents: number | null;\n\tcompute_cap_cents: number | null;\n\tstorage_cap_cents: number | null;\n\talert_threshold_pct: Generated<number>;\n\talert_sent_at: Date | null;\n\tfrozen_at: Date | null;\n\tupdated_at: Generated<Date>;\n}\n\nexport type AccountSpendCap = Selectable<AccountSpendCapsTable>;\nexport type InsertAccountSpendCap = Insertable<AccountSpendCapsTable>;\nexport type UpdateAccountSpendCap = Updateable<AccountSpendCapsTable>;\n\n/** Prepaid dev credits — card-funded balance per account. */\nexport interface AccountCreditsTable {\n\taccount_id: string;\n\tbalance_usd_micros: Generated<string | number | bigint>;\n\t/** Month bucket (\"YYYY-MM\") the spend counter applies to. */\n\tspent_month: string | null;\n\tspent_month_usd_micros: Generated<string | number | bigint>;\n\t/** Null = auto-refill off. */\n\trefill_below_usd_micros: string | number | bigint | null;\n\trefill_pack_usd: number | null;\n\trefill_last_at: Date | null;\n\tupdated_at: Generated<Date>;\n}\n\nexport type AccountCredits = Selectable<AccountCreditsTable>;\nexport type InsertAccountCredits = Insertable<AccountCreditsTable>;\nexport type UpdateAccountCredits = Updateable<AccountCreditsTable>;\n\n/**\n * Archive fetch charge log. Append-only: one row per\n * priced attempt to fetch a partition object. `usd_micros` is 0 for\n * free rows (24h re-issue, monthly repair allowance).\n */\nexport interface ArchiveFetchesTable {\n\tid: Generated<string>;\n\taccount_id: string;\n\tpath: string;\n\tdataset: string;\n\tusd_micros: string | number | bigint;\n\tvia_allowance: Generated<boolean>;\n\tcharged_at: Generated<Date>;\n}\n\nexport type ArchiveFetch = Selectable<ArchiveFetchesTable>;\nexport type InsertArchiveFetch = Insertable<ArchiveFetchesTable>;\nexport type UpdateArchiveFetch = Updateable<ArchiveFetchesTable>;\n\n/**\n * One metered ledger for every billable unit (archive partitions, hosted\n * Index/Streams rows, and future hosted-stack meters). Append-only, written\n * only by `meter()`. `idempotency_key` is UNIQUE so a retried submission\n * no-ops instead of double-charging. `debited` is false when the balance\n * (or a spend cap) refused the charge — the row still exists so the gap is\n * visible, never silently dropped. `usd_micros` is negative for a Stripe\n * top-up (`unit: \"topup\"`).\n */\nexport interface UsageLedgerTable {\n\tid: Generated<string>;\n\taccount_id: string;\n\tunit: string;\n\tquantity: string | number | bigint;\n\t/** Raw sampled quantity before any floor (e.g. `memory.gb_hour`'s actual\n\t * RAM, before the 0.5 GB minimum). NULL for every unit that has no\n\t * floor to observe past. */\n\tobserved_quantity: string | number | null;\n\tusd_micros: string | number | bigint;\n\t/** True when the whole price was taken; derived from `debited_usd_micros`. */\n\tdebited: Generated<boolean>;\n\t/** Amount actually taken from the balance, `0..usd_micros` (bounded the\n\t * other way for a negative top-up/grant row). Unpaid = price - this. */\n\tdebited_usd_micros: Generated<string | number | bigint>;\n\tsource: string;\n\t/** API key behind a metered read; null for non-read units and older rows. */\n\tapi_key_id: string | null;\n\tidempotency_key: string;\n\toccurred_at: Generated<Date>;\n\trecorded_at: Generated<Date>;\n}\n\nexport type UsageLedgerRow = Selectable<UsageLedgerTable>;\nexport type InsertUsageLedgerRow = Insertable<UsageLedgerTable>;\nexport type UpdateUsageLedgerRow = Updateable<UsageLedgerTable>;\n\n/** Preferences + debounce state for the balance-runway email alerts. One\n * row per account; a missing row means both alerts are on (defaults). */\nexport interface AccountBalanceAlertsTable {\n\taccount_id: string;\n\tnotify_7d: Generated<boolean>;\n\tnotify_2d: Generated<boolean>;\n\tsent_7d_at: Date | null;\n\tsent_2d_at: Date | null;\n\tsent_stopped_at: Date | null;\n}\n\n/** The workload host's report of one account's hosted stack. Written only by\n * `POST /internal/stack-state`; `reported_at` is the host's observation time. */\nexport interface HostedStackStateTable {\n\taccount_id: string;\n\tstate: \"provisioning\" | \"running\" | \"stopped\" | \"destroyed\";\n\tstop_reason: \"credits\" | \"cap\" | \"idle\" | null;\n\treported_at: Date;\n}\n\n/** Debounce state for the webhook-down email: one row per incident, open\n * while `resolved_at` is null. No preference columns by design. */\nexport interface WebhookIncidentAlertsTable {\n\tid: Generated<string>;\n\taccount_id: string;\n\twebhook_id: string;\n\twebhook_name: string;\n\tfailing_since: Date;\n\topened_at: Generated<Date>;\n\temailed_at: Date | null;\n\temail_attempts: Generated<number>;\n\tresolved_at: Date | null;\n}\n\nexport type WebhookIncidentAlert = Selectable<WebhookIncidentAlertsTable>;\n\n/** One browser/device push subscription; the endpoint is unique. */\nexport interface PushSubscriptionsTable {\n\tid: Generated<string>;\n\taccount_id: string;\n\tendpoint: string;\n\tp256dh: string;\n\tauth: string;\n\tuser_agent: string | null;\n\tcreated_at: Generated<Date>;\n\tlast_success_at: Date | null;\n\tfailed_count: Generated<number>;\n}\n\nexport type PushSubscription = Selectable<PushSubscriptionsTable>;\n\n/** Per-account push toggles. A missing row means the column defaults. */\nexport interface PushPrefsTable {\n\taccount_id: string;\n\twebhook_failing: Generated<boolean>;\n\tsubgraph_stopped: Generated<boolean>;\n\tsubgraph_not_serving: Generated<boolean>;\n\treplay_done: Generated<boolean>;\n\tspend_cap: Generated<boolean>;\n\tkey_repeat: Generated<boolean>;\n\tupdated_at: Generated<Date>;\n}\n\nexport type PushPrefs = Selectable<PushPrefsTable>;\n\n/** A push already sent, keyed by what it was about; debounces repeat signals. */\nexport interface PushSentTable {\n\taccount_id: string;\n\tkey: string;\n\tkind: string;\n\tsent_at: Generated<Date>;\n}\n\nexport type CliDeviceLoginStatus =\n\t| \"pending\"\n\t| \"approved\"\n\t| \"denied\"\n\t| \"consumed\";\n\n/** The product that started a CLI sign-in; null is `sl login`. */\nexport type CliDeviceProduct = \"sentinel\";\n\n/** One browser sign-in attempt from `sl login` (or `sentinel login`). Only the\n * hash of the CLI's device code is stored; the session is opened when the CLI\n * polls after approval. */\nexport interface CliDeviceLoginsTable {\n\tid: Generated<string>;\n\tdevice_code_hash: string;\n\tuser_code: string;\n\tclient_name: string;\n\tproduct: CliDeviceProduct | null;\n\tstatus: Generated<CliDeviceLoginStatus>;\n\taccount_id: string | null;\n\tkey_name: string | null;\n\tcreated_at: Generated<Date>;\n\texpires_at: Date;\n\tapproved_at: Date | null;\n\tconsumed_at: Date | null;\n}\n\nexport type CliDeviceLogin = Selectable<CliDeviceLoginsTable>;\n\n// --- OAuth for the hosted MCP endpoint ---\n//\n// Codes and tokens are stored as SHA-256 hashes only. See migration\n// `0177_oauth_mcp` and `@secondlayer/platform/db/queries/oauth`.\n\n/** An app that registered itself (RFC 7591). Public clients only: no secret. */\nexport interface OauthClientsTable {\n\tid: string;\n\t/** The app's own claim, validated at registration; shown quoted. */\n\tname: string;\n\tredirect_uris: string[];\n\tcreated_ip: string | null;\n\tcreated_at: Generated<Date>;\n\t/** Set when it first gets tokens; never-used clients are purged. */\n\tlast_used_at: Date | null;\n}\n\nexport type OauthRequestStatus = \"pending\" | \"approved\" | \"denied\";\n\n/** One authorize request waiting for (or answered on) the consent page. */\nexport interface OauthRequestsTable {\n\tid: string;\n\tclient_id: string;\n\tredirect_uri: string;\n\tstate: string | null;\n\tcode_challenge: string;\n\tresource: string;\n\tstatus: Generated<OauthRequestStatus>;\n\taccount_id: string | null;\n\tcreated_at: Generated<Date>;\n\texpires_at: Date;\n\tanswered_at: Date | null;\n}\n\n/** A one-time authorization code, bound to its client, redirect, PKCE\n * challenge, resource and account. */\nexport interface OauthCodesTable {\n\tcode_hash: string;\n\tclient_id: string;\n\taccount_id: string;\n\tredirect_uri: string;\n\tcode_challenge: string;\n\tresource: string;\n\t/** The grant its one use made, so a replay can revoke it. */\n\tgrant_id: string | null;\n\tcreated_at: Generated<Date>;\n\texpires_at: Date;\n\tused_at: Date | null;\n}\n\n/** What a person allowed one app to do: use the hosted MCP as them. */\nexport interface OauthGrantsTable {\n\tid: Generated<string>;\n\taccount_id: string;\n\tclient_id: string;\n\tscope: Generated<string>;\n\tresource: string;\n\tcreated_at: Generated<Date>;\n\tlast_used_at: Date | null;\n\trevoked_at: Date | null;\n}\n\nexport type OauthTokenKind = \"access\" | \"refresh\";\n\nexport interface OauthTokensTable {\n\ttoken_hash: string;\n\tgrant_id: string;\n\tkind: OauthTokenKind;\n\tcreated_at: Generated<Date>;\n\texpires_at: Date;\n}\n\n/** A refresh token a rotation replaced: presented again, it revokes the grant. */\nexport interface OauthRefreshRetiredTable {\n\ttoken_hash: string;\n\tgrant_id: string;\n\tretired_at: Generated<Date>;\n}\n\nexport type OauthClient = Selectable<OauthClientsTable>;\nexport type OauthGrant = Selectable<OauthGrantsTable>;\n\n/** Accounts Sentinel's service key may touch: created by Sentinel, or the\n * owner opted in. */\nexport interface SentinelAccountsTable {\n\taccount_id: string;\n\tlinked_at: Generated<Date>;\n\tvia: \"created\" | \"consent\";\n}\n\nexport type SentinelAccount = Selectable<SentinelAccountsTable>;\n\nexport type AccountBalanceAlerts = Selectable<AccountBalanceAlertsTable>;\nexport type InsertAccountBalanceAlerts = Insertable<AccountBalanceAlertsTable>;\nexport type UpdateAccountBalanceAlerts = Updateable<AccountBalanceAlertsTable>;\n\n// ── Convenience types ─────────────────────────────────────────────────\n\nexport type Block = Selectable<BlocksTable>;\nexport type InsertBlock = Insertable<BlocksTable>;\nexport type UpdateBlock = Updateable<BlocksTable>;\n\nexport type Transaction = Selectable<TransactionsTable>;\nexport type InsertTransaction = Insertable<TransactionsTable>;\nexport type UpdateTransaction = Updateable<TransactionsTable>;\n\nexport type MempoolTransaction = Selectable<MempoolTransactionsTable>;\nexport type InsertMempoolTransaction = Insertable<MempoolTransactionsTable>;\n\nexport type Event = Selectable<EventsTable>;\nexport type InsertEvent = Insertable<EventsTable>;\nexport type UpdateEvent = Updateable<EventsTable>;\n\nexport type VmEvent = Selectable<VmEventsTable>;\nexport type InsertVmEvent = Insertable<VmEventsTable>;\nexport type UpdateVmEvent = Updateable<VmEventsTable>;\nexport type StateWrite = Selectable<StateWritesTable>;\nexport type InsertStateWrite = Insertable<StateWritesTable>;\n\nexport type IndexProgress = Selectable<IndexProgressTable>;\nexport type InsertIndexProgress = Insertable<IndexProgressTable>;\nexport type UpdateIndexProgress = Updateable<IndexProgressTable>;\n\nexport type Subgraph = Selectable<SubgraphsTable>;\nexport type InsertSubgraph = Insertable<SubgraphsTable>;\nexport type UpdateSubgraph = Updateable<SubgraphsTable>;\n\nexport type Contract = Selectable<ContractsTable>;\nexport type InsertContract = Insertable<ContractsTable>;\nexport type UpdateContract = Updateable<ContractsTable>;\n\nexport type SubgraphOperation = Selectable<SubgraphOperationsTable>;\nexport type InsertSubgraphOperation = Insertable<SubgraphOperationsTable>;\nexport type UpdateSubgraphOperation = Updateable<SubgraphOperationsTable>;\n\nexport type ApiKey = Selectable<ApiKeysTable>;\nexport type InsertApiKey = Insertable<ApiKeysTable>;\nexport type UpdateApiKey = Updateable<ApiKeysTable>;\n\nexport type Account = Selectable<AccountsTable>;\nexport type InsertAccount = Insertable<AccountsTable>;\n\nexport type MagicLink = Selectable<MagicLinksTable>;\nexport type InsertMagicLink = Insertable<MagicLinksTable>;\n\nexport type Session = Selectable<SessionsTable>;\nexport type InsertSession = Insertable<SessionsTable>;\n\nexport type SubgraphHealthSnapshot = Selectable<SubgraphHealthSnapshotsTable>;\nexport type InsertSubgraphHealthSnapshot =\n\tInsertable<SubgraphHealthSnapshotsTable>;\n\nexport type SubgraphGap = Selectable<SubgraphGapsTable>;\nexport type InsertSubgraphGap = Insertable<SubgraphGapsTable>;\n\n// ── Webhooks (chain event webhooks) ─────────────────────\n\nexport type WebhookStatus = \"active\" | \"paused\";\nexport type { WebhookPauseReason };\n\n/** Webhooks react to raw chain events matched directly off the Index/Streams\n * clock. `chain` is the only kind since migration 0159 removed subgraph-row\n * webhooks; the column stays as the discriminator. */\nexport type WebhookKind = \"chain\";\nexport type WebhookFormat =\n\t| \"standard-webhooks\"\n\t| \"inngest\"\n\t| \"trigger\"\n\t| \"cloudflare\"\n\t| \"cloudevents\"\n\t| \"raw\";\n\nexport interface WebhooksTable {\n\tid: Generated<string>;\n\taccount_id: string;\n\tproject_id: string | null;\n\tname: string;\n\tstatus: ColumnType<WebhookStatus, WebhookStatus | undefined, WebhookStatus>;\n\tkind: ColumnType<WebhookKind, WebhookKind | undefined, WebhookKind>;\n\t/** Chain-trigger filter array (the `SubgraphFilter` shape, JSON). Typed\n\t * loosely here to avoid a shared→subgraphs import cycle; the Zod schema in\n\t * schemas/webhooks.ts owns the shape. */\n\ttriggers: unknown;\n\tformat: ColumnType<WebhookFormat, WebhookFormat | undefined, WebhookFormat>;\n\turl: string;\n\tsigning_secret_enc: Buffer;\n\tauth_config: Generated<unknown>;\n\tmax_retries: Generated<number>;\n\ttimeout_ms: Generated<number>;\n\tconcurrency: Generated<number>;\n\tcircuit_failures: Generated<number>;\n\tcircuit_opened_at: Date | null;\n\t/** Why a paused webhook is paused. Set exactly while `status` is `paused`. */\n\tpause_reason: WebhookPauseReason | null;\n\tlast_delivery_at: Date | null;\n\tlast_success_at: Date | null;\n\tlast_error: string | null;\n\t/** Receiver TLS leaf certificate expiry, from the emitter's periodic probe. */\n\treceiver_cert_expires_at: Date | null;\n\treceiver_cert_checked_at: Date | null;\n\tcreated_at: Generated<Date>;\n\tupdated_at: Generated<Date>;\n}\n\nexport type Webhook = Selectable<WebhooksTable>;\nexport type InsertWebhook = Insertable<WebhooksTable>;\nexport type UpdateWebhook = Updateable<WebhooksTable>;\n\nexport type OutboxStatus = \"pending\" | \"delivered\" | \"dead\";\n/** Why a row is dead: retries ran out, or a reorg removed its event. An\n * orphaned row stays dead; requeueing it would resend an event the chain no\n * longer contains. */\nexport type DeadReason = \"exhausted\" | \"orphaned\";\n\nexport interface WebhookOutboxTable {\n\tid: Generated<string>;\n\twebhook_id: string;\n\tkind: ColumnType<WebhookKind, WebhookKind | undefined, WebhookKind>;\n\tblock_height: number | bigint;\n\ttx_id: string | null;\n\trow_pk: unknown;\n\tevent_type: string;\n\tpayload: unknown;\n\tdedup_key: string;\n\tattempt: Generated<number>;\n\tnext_attempt_at: Generated<Date>;\n\tstatus: ColumnType<OutboxStatus, OutboxStatus | undefined, OutboxStatus>;\n\tis_replay: Generated<boolean>;\n\t/** The replay that created this row; null for live rows. */\n\treplay_id: string | null;\n\t/** The chain block_time of the matched event/tx. Null for rows written\n\t * before this column existed, and for the settlement scan path (not yet\n\t * wired). Lets `delivered_at - block_time` measure end-to-end webhook\n\t * latency without a join to SOURCE-plane `blocks`. */\n\tblock_time: Date | null;\n\tdelivered_at: Date | null;\n\tfailed_at: Date | null;\n\tlocked_by: string | null;\n\tlocked_until: Date | null;\n\t/** Set when a reorg marks an in-flight row `dead` instead of retrying it\n\t * into an orphaned fork. Null otherwise — delivery failures track their\n\t * history on `webhooks.last_error`, not per-row. */\n\tlast_error: string | null;\n\t/** Set exactly while `status` is `dead`. */\n\tdead_reason: DeadReason | null;\n\t/** Hash of the block a chain apply row was emitted for. Null on rows\n\t * written before the column existed (the payload carries it too). */\n\tblock_hash: string | null;\n\t/** Set when a reorg rollback recalled this delivered apply row, so a\n\t * later rollback for the same reorg skips it. */\n\trolled_back_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\nexport type WebhookReplayStatus = \"scanning\" | \"running\" | \"done\" | \"failed\";\n\nexport interface WebhookReplaysTable {\n\tid: string;\n\twebhook_id: string;\n\tfrom_block: number | bigint;\n\tto_block: number | bigint;\n\tstatus: WebhookReplayStatus;\n\tscanned_count: Generated<number>;\n\tenqueued_count: Generated<number>;\n\ttotal: number | null;\n\tdelivered: number | null;\n\tgave_up: number | null;\n\terror: string | null;\n\tstarted_at: Generated<Date>;\n\tfinished_at: Date | null;\n}\nexport type WebhookReplay = Selectable<WebhookReplaysTable>;\n\n/** `replay_id` is optional on the row type so hand-built rows (the test\n * delivery, fixtures) need not carry it; reads still return it. */\nexport type WebhookOutbox = Omit<\n\tSelectable<WebhookOutboxTable>,\n\t\"replay_id\"\n> & {\n\treplay_id?: string | null;\n};\nexport type InsertWebhookOutbox = Insertable<WebhookOutboxTable>;\nexport type UpdateWebhookOutbox = Updateable<WebhookOutboxTable>;\n\nexport interface WebhookDeliveriesTable {\n\tid: Generated<string>;\n\t/** Nullable after migration 0077 — outbox row may be cleaned up while\n\t * delivery telemetry is retained. */\n\toutbox_id: string | null;\n\twebhook_id: string;\n\tattempt: number;\n\tstatus_code: number | null;\n\tresponse_headers: unknown | null;\n\tresponse_body: string | null;\n\terror_message: string | null;\n\tduration_ms: number | null;\n\tdispatched_at: Generated<Date>;\n}\n\n/** Attempts per UTC hour, counted by a trigger on `webhook_deliveries`. */\nexport interface WebhookDeliveryHoursTable {\n\twebhook_id: string;\n\thour: Date;\n\t/** 2xx attempts. */\n\tdelivered: Generated<number>;\n\t/** Every other attempt. */\n\tfailed: Generated<number>;\n}\n\nexport type WebhookDelivery = Selectable<WebhookDeliveriesTable>;\nexport type InsertWebhookDelivery = Insertable<WebhookDeliveriesTable>;\n\n/** Single-row (id always TRUE) high-water mark for the chain-trigger evaluator.\n * One loop serves all chain webhooks, so the cursor is global. */\nexport interface TriggerEvaluatorStateTable {\n\tid: Generated<boolean>;\n\tlast_processed_block: ColumnType<\n\t\tbigint,\n\t\tbigint | number | undefined,\n\t\tbigint | number\n\t>;\n\t/** Watermark for the async sBTC settlement-confirmed webhook scan; null until\n\t * the evaluator fast-forwards it on first run. */\n\tlast_settlement_scan_at: ColumnType<\n\t\tDate | null,\n\t\tDate | null | undefined,\n\t\tDate | null\n\t>;\n\t/** `sbtc_settlements.seq` watermark. Null until the first settlement row is\n\t * scanned; `last_settlement_scan_at` is the forward-only floor until then. */\n\tlast_settlement_scan_seq: ColumnType<\n\t\tbigint | null,\n\t\tbigint | number | null | undefined,\n\t\tbigint | number | null\n\t>;\n\t/** Counts reorg rewinds. The evaluator checks it under the row lock in the\n\t * transaction that emits a batch and advances the cursor, so a reorg that\n\t * lands mid-tick rolls the batch back. */\n\treorg_generation: ColumnType<\n\t\tbigint,\n\t\tbigint | number | undefined,\n\t\tbigint | number\n\t>;\n\t/** Streams cursor (`<block_height>:<event_index>`) for the Bitcoin (Runes)\n\t * chain-trigger evaluator (plan 060) — a separate clock from\n\t * `last_processed_block` (Stacks). Null until the evaluator fast-forwards\n\t * it to the Bitcoin Streams tip on first run. */\n\tbitcoin_last_cursor: ColumnType<\n\t\tstring | null,\n\t\tstring | null | undefined,\n\t\tstring | null\n\t>;\n\tupdated_at: Generated<Date>;\n}\n\nexport type TriggerEvaluatorState = Selectable<TriggerEvaluatorStateTable>;\n\n/** A public waitlist page: what it is for and whether it takes signups. */\nexport interface WaitlistsTable {\n\tslug: string;\n\ttitle: string;\n\tdescription: string;\n\turl: string;\n\topened_at: Generated<Date>;\n\t/** Null while the list is open. */\n\tclosed_at: Date | null;\n}\n\n/**\n * One signup per (list, contact, token). `answers` holds the list's own\n * questions, validated per list by the API before insert.\n */\nexport interface WaitlistSignupsTable {\n\tid: Generated<string>;\n\tlist: string;\n\tcontact: string;\n\tanswers: Record<string, unknown>;\n\tcreated_at: Generated<Date>;\n}\n\n/**\n * A \"Talk to us\" message. Stored before the operator is emailed;\n * `notified_at` stays null until the email goes out.\n */\nexport interface ContactRequestsTable {\n\tid: Generated<string>;\n\tname: string;\n\temail: string;\n\tcompany: string | null;\n\tvolume: \"lt10m\" | \"10m-100m\" | \"100m-1b\" | \"gt1b\" | \"unsure\" | null;\n\tmessage: string;\n\tsource_page: string | null;\n\taccount_id: string | null;\n\t/** Hex sha256 of the client IP, never the address. */\n\tip_hash: string | null;\n\tnotified_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\n/**\n * A member of the email updates list. `pending` until the emailed link is\n * confirmed (`confirm_sent_at` starts the 7-day window), `confirmed` while\n * subscribed, `unsubscribed` after an opt-out. `token` is the secret in\n * confirm and unsubscribe links.\n */\nexport interface UpdateSubscribersTable {\n\tid: Generated<string>;\n\temail: string;\n\tstatus: Generated<\"pending\" | \"confirmed\" | \"unsubscribed\">;\n\ttoken: string;\n\tsource_page: string | null;\n\t/** Hex sha256 of the client IP, never the address. */\n\tip_hash: string | null;\n\tconfirm_sent_at: Date | null;\n\tconfirmed_at: Date | null;\n\tunsubscribed_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\n/** One broadcast (`send_key`) delivered to one subscriber. */\nexport interface UpdateSendsTable {\n\tsend_key: string;\n\tsubscriber_id: string;\n\tsent_at: Generated<Date>;\n}\n\n/**\n * 24h hosted record of a failed API request, keyed by `request_id` and\n * scoped to the account that made it. `query` is redacted before insert.\n */\nexport interface ApiFailedRequestsTable {\n\trequest_id: string;\n\taccount_id: string;\n\tmethod: string;\n\tpath: string;\n\tstatus: number;\n\tcode: string;\n\tmessage: Generated<string>;\n\tquery: Record<string, unknown>;\n\torigin: string | null;\n\t/** Revoked account key the request presented (`KEY_REVOKED` only). */\n\tapi_key_id: string | null;\n\tcreated_at: Generated<Date>;\n}\n\nexport type ApiFailedRequest = Selectable<ApiFailedRequestsTable>;\nexport type InsertApiFailedRequest = Insertable<ApiFailedRequestsTable>;\n\n/**\n * 7-day hosted log of account-attributed Index/Streams reads. Query values\n * are stored only as hashes; never bodies, headers or tokens.\n */\nexport interface ApiRequestLogTable {\n\tid: Generated<string>;\n\trequest_id: string | null;\n\taccount_id: string;\n\tapi_key_id: string | null;\n\tmethod: string;\n\tpath: string;\n\tpath_template: string;\n\tparams_hash: string | null;\n\tcursor_hash: string | null;\n\tpage_size: number | null;\n\trows: number | null;\n\tstatus: number;\n\tduration_ms: number;\n\tcreated_at: Generated<Date>;\n}\n\nexport type ApiRequestLogRow = Selectable<ApiRequestLogTable>;\nexport type InsertApiRequestLogRow = Insertable<ApiRequestLogTable>;\n\n/**\n * Hosted problem report. `attempted` is the server's own copy of the failed\n * request (never caller-supplied); `status` starts `new` until classified.\n */\nexport interface FeedbackTicketsTable {\n\tid: Generated<string>;\n\taccount_id: string;\n\tidempotency_key: string | null;\n\trequest_id: string | null;\n\tintent: string;\n\t/** Any JSON value the caller sent: a sentence or a shape. */\n\texpected: unknown;\n\tkind_hint: string | null;\n\tevidence: Record<string, unknown> | null;\n\tattempted: Record<string, unknown> | null;\n\torigin: string;\n\tstatus: Generated<\"new\" | \"classified\">;\n\troute: string | null;\n\tclassification: Record<string, unknown> | null;\n\tclassified_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\nexport type FeedbackTicket = Selectable<FeedbackTicketsTable>;\nexport type InsertFeedbackTicket = Insertable<FeedbackTicketsTable>;\n\nexport type Waitlist = Selectable<WaitlistsTable>;\nexport type WaitlistSignup = Selectable<WaitlistSignupsTable>;\nexport type InsertWaitlistSignup = Insertable<WaitlistSignupsTable>;\n\nexport type ContactRequest = Selectable<ContactRequestsTable>;\nexport type InsertContactRequest = Insertable<ContactRequestsTable>;\n\nexport type UpdateSubscriber = Selectable<UpdateSubscribersTable>;\nexport type InsertUpdateSubscriber = Insertable<UpdateSubscribersTable>;\n"
5
+ "import type {\n\tColumnType,\n\tGenerated,\n\tInsertable,\n\tSelectable,\n\tUpdateable,\n} from \"kysely\";\nimport type {\n\tFailureClass,\n\tFailureUnit,\n\tNativeClock,\n\tRepairMode,\n\tRetryState,\n\tRunStatus,\n\tStageKind,\n} from \"../coverage/constraints.ts\";\nimport type { BootstrapSource } from \"../coverage/evaluate.ts\";\nimport type {\n\tSubgraphStatus,\n\tSubgraphVerification,\n} from \"../schemas/subgraphs.ts\";\nimport type { WebhookPauseReason } from \"../webhooks/health.ts\";\n\nexport type {\n\tFailureClass,\n\tFailureUnit,\n\tNativeClock,\n\tRepairMode,\n\tRetryState,\n\tRunStatus,\n\tStageKind,\n} from \"../coverage/constraints.ts\";\n\n// ── Table interfaces ──────────────────────────────────────────────────\n\nexport interface BlocksTable {\n\theight: number;\n\thash: string;\n\tparent_hash: string;\n\tburn_block_height: number;\n\tburn_block_hash: ColumnType<\n\t\tstring | null,\n\t\tstring | null | undefined,\n\t\tstring | null\n\t>;\n\t/** Nakamoto StacksBlockId. Null on rows ingested before it was persisted. */\n\tindex_block_hash: ColumnType<\n\t\tstring | null,\n\t\tstring | null | undefined,\n\t\tstring | null\n\t>;\n\ttimestamp: number;\n\tcanonical: Generated<boolean>;\n\t/** Tx count `persistBlock` was handed for this height. Null on rows\n\t * ingested before this column existed. */\n\ttx_count: ColumnType<number | null, number | null | undefined, number | null>;\n\t/** Event count `persistBlock` was handed for this height. Null on rows\n\t * ingested before this column existed. */\n\tevent_count: ColumnType<\n\t\tnumber | null,\n\t\tnumber | null | undefined,\n\t\tnumber | null\n\t>;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface TransactionsTable {\n\ttx_id: string;\n\tblock_height: number;\n\ttx_index: Generated<number>;\n\ttype: string;\n\tsender: string;\n\tstatus: string;\n\tcontract_id: string | null;\n\tfunction_name: string | null;\n\tfunction_args: Generated<unknown | null>;\n\traw_result: Generated<string | null>;\n\traw_tx: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface EventsTable {\n\tid: Generated<string>;\n\ttx_id: string;\n\tblock_height: number;\n\tevent_index: number;\n\ttype: string;\n\tdata: unknown;\n\tcreated_at: Generated<Date>;\n}\n\n// Reorg archive (see migration 0084): orphaned transactions/events copied here\n// before a reused height is replaced, preserving the raw log instead of\n// deleting it.\nexport interface TransactionsArchiveTable {\n\tarchive_id: Generated<string>;\n\ttx_id: string;\n\tblock_height: number;\n\ttx_index: number;\n\ttype: string;\n\tsender: string;\n\tstatus: string;\n\tcontract_id: string | null;\n\tfunction_name: string | null;\n\tfunction_args: unknown | null;\n\traw_result: string | null;\n\traw_tx: string;\n\tcreated_at: Date;\n\torphaned_block_hash: string | null;\n\tarchived_at: Generated<Date>;\n}\n\nexport interface EventsArchiveTable {\n\tarchive_id: Generated<string>;\n\tid: string;\n\ttx_id: string;\n\tblock_height: number;\n\tevent_index: number;\n\ttype: string;\n\tdata: unknown;\n\tcreated_at: Date;\n\torphaned_block_hash: string | null;\n\tarchived_at: Generated<Date>;\n}\n\n// Opt-in VM traces (migration 0131). Second clock: `ordinal` (array position\n// in `/new_block.vm_events`). Never mixed into `events.event_index`. Primary\n// key `(block_height, ordinal)` (migration 0153).\nexport interface VmEventsTable {\n\ttx_id: string;\n\tblock_height: number;\n\tordinal: number;\n\ttype: string;\n\tdata: unknown;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface VmEventsArchiveTable {\n\tarchive_id: Generated<string>;\n\t/** `block_height:ordinal`; rows archived before migration 0153 hold the old uuid. */\n\tid: string;\n\ttx_id: string;\n\tblock_height: number;\n\tordinal: number;\n\ttype: string;\n\tdata: unknown;\n\tcreated_at: Date;\n\torphaned_block_hash: string | null;\n\tarchived_at: Generated<Date>;\n}\n\n// Opt-in node storage-layer writes (migration 0154): the exact MARF writes a\n// block committed, in node order. `tx_index` is null for block-level writes.\n// Primary key `(block_height, ordinal)`.\nexport interface StateWritesTable {\n\tblock_height: number;\n\tordinal: number;\n\ttx_index: number | null;\n\tkey: string;\n\tvalue_hex: string;\n}\n\nexport interface StateWritesArchiveTable {\n\tarchive_id: Generated<string>;\n\t/** `block_height:ordinal`. */\n\tid: string;\n\tblock_height: number;\n\tordinal: number;\n\ttx_index: number | null;\n\tkey: string;\n\tvalue_hex: string;\n\torphaned_block_hash: string | null;\n\tarchived_at: Generated<Date>;\n}\n\n// Dead-letter log (see migration 0085): events whose decoded payload failed\n// schema validation on ingest. Append-only diagnostic; the event still lands in\n// `events`, so chain data is never lost.\nexport interface DeadLetterEventsTable {\n\tid: Generated<string>;\n\tblock_height: number;\n\ttx_id: string;\n\tevent_index: number;\n\tevent_type: string;\n\tdata: unknown;\n\treason: string;\n\tcreated_at: Generated<Date>;\n}\n\n// Pending (unconfirmed) transactions (see migration 0086). Pre-chain, so no\n// block_height/tx_index/result/events and never canonical. tx_id is derived\n// from raw_tx; function_args holds hex-encoded ClarityValues (jsonb), like\n// `transactions`.\nexport interface MempoolTransactionsTable {\n\tseq: Generated<string>;\n\ttx_id: string;\n\traw_tx: string;\n\ttype: string;\n\tsender: string;\n\tcontract_id: string | null;\n\tfunction_name: string | null;\n\tfunction_args: unknown | null;\n\treceived_at: Generated<Date>;\n}\n\nexport interface IndexProgressTable {\n\tnetwork: string;\n\tlast_indexed_block: Generated<number>;\n\tlast_contiguous_block: Generated<number>;\n\thighest_seen_block: Generated<number>;\n\tupdated_at: Generated<Date>;\n}\n\nexport interface SubgraphsTable {\n\tid: Generated<string>;\n\tname: string;\n\tversion: Generated<string>;\n\tstatus: Generated<SubgraphStatus>;\n\tdefinition: Record<string, unknown>;\n\tschema_hash: string;\n\thandler_path: string;\n\tschema_name: string | null;\n\tstart_block: Generated<number>;\n\tlast_processed_block: Generated<number>;\n\t/** Hash of the block at `last_processed_block`; NULL = unknown (see 0197). */\n\tlast_processed_block_hash: Generated<string | null>;\n\treindex_from_block: number | null;\n\treindex_to_block: number | null;\n\tlast_error: string | null;\n\tlast_error_at: Date | null;\n\ttotal_processed: Generated<number>;\n\ttotal_errors: Generated<number>;\n\taccount_id: string;\n\thandler_code: string | null;\n\tsource_code: string | null;\n\tproject_id: string | null;\n\t/** Set while the account's metered reads are refused (spend cap, credits).\n\t * Both columns are set or both null; `last_error` stays for real errors. */\n\tbilling_paused_at: Date | null;\n\tbilling_paused_code: string | null;\n\t/** (event type, contract) probe pairs persisted at deploy for weight classification. */\n\tsparse_probe_targets: unknown | null;\n\t/** sha256 over everything that shapes rows (schema, handler bundle,\n\t * startBlock, network, runtime). NULL for unbundled or older deploys. */\n\tpin: string | null;\n\t/** The canonical JSON `pin` hashes, so a client can recompute it. NULL\n\t * wherever `pin` is, and for deploys before migration 0158. */\n\tpin_preimage: string | null;\n\t/** Level derived at deploy. NULL (older deploys) = not verifiable. */\n\tverification: SubgraphVerification | null;\n\tcreated_at: Generated<Date>;\n\tupdated_at: Generated<Date>;\n}\n\n/** Mirrored by the CHECK on `contracts.abi_status`. */\nexport const ABI_STATUSES = [\n\t\"pending\",\n\t\"fetched\",\n\t\"unparseable\",\n\t\"failed\",\n] as const;\nexport type AbiStatus = (typeof ABI_STATUSES)[number];\n\nexport interface ContractsTable {\n\tcontract_id: string;\n\tdeployer: string;\n\tblock_height: number;\n\tcanonical: Generated<boolean>;\n\tabi: unknown | null;\n\tdeclared_traits: Generated<string[]>;\n\tinferred_standards: Generated<string[]>;\n\tabi_status: Generated<AbiStatus>;\n\tabi_fetched_at: Date | null;\n\t/** Failed fetches so far; `failed` re-polls until the registry's attempt cap. */\n\tabi_attempts: Generated<number>;\n\t/** When a `failed` row is next due; NULL once attempts are exhausted. */\n\tabi_next_attempt_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\n/** The only reasons the runtime records; mirrored by a CHECK on `subgraph_gaps.reason`. */\nexport type GapReason = \"block_missing\" | \"processing_error\";\n\nexport interface SubgraphGapsTable {\n\tid: Generated<string>;\n\tsubgraph_id: string;\n\tsubgraph_name: string;\n\tgap_start: number;\n\tgap_end: number;\n\treason: GapReason;\n\tdetected_at: Generated<Date>;\n\tresolved_at: Date | null;\n}\n\n/** Print-validate skips persisted for the authed violations GET. Cap 100/subgraph. */\nexport interface SubgraphViolationsTable {\n\tid: Generated<string>;\n\tsubgraph_name: string;\n\tsource_name: string;\n\tblock_height: number;\n\ttx_id: string;\n\treason: string;\n\tsample_payload: Record<string, unknown>;\n\tseen_at: Generated<Date>;\n}\n\nexport type SubgraphOperationKind = \"reindex\" | \"backfill\";\nexport type SubgraphOperationStatus =\n\t| \"queued\"\n\t| \"running\"\n\t| \"completed\"\n\t| \"failed\"\n\t| \"cancelled\";\n\nexport interface SubgraphOperationsTable {\n\tid: Generated<string>;\n\tsubgraph_id: string;\n\tsubgraph_name: string;\n\taccount_id: string | null;\n\tkind: ColumnType<\n\t\tSubgraphOperationKind,\n\t\tSubgraphOperationKind,\n\t\tSubgraphOperationKind\n\t>;\n\tstatus: ColumnType<\n\t\tSubgraphOperationStatus,\n\t\tSubgraphOperationStatus | undefined,\n\t\tSubgraphOperationStatus\n\t>;\n\tfrom_block: number | null;\n\tto_block: number | null;\n\tcancel_requested: Generated<boolean>;\n\tlocked_by: string | null;\n\tlocked_until: Date | null;\n\tstarted_at: Date | null;\n\tfinished_at: Date | null;\n\tprocessed_blocks: number | null;\n\terror: string | null;\n\tcreated_at: Generated<Date>;\n\tupdated_at: Generated<Date>;\n\t/** 'light' (contract-scoped sparse) | 'heavy' (broad). Claim budgets heavy. */\n\tweight: Generated<string>;\n\t/** Candidate-event denominator computed at enqueue (sparse ops only). */\n\testimated_events: string | number | bigint | null;\n\t/** Events processed so far — written by the progress flush. */\n\tprocessed_events: string | number | bigint | null;\n\t/** Backfill ops' own crash checkpoint — advanced conditionally in-tx with\n\t * each written block; replays skip at/below it. NULL for reindex ops\n\t * (those checkpoint on subgraphs.last_processed_block). */\n\tcursor_block: string | number | bigint | null;\n}\n\nexport type ApiKeyStatus = \"active\" | \"revoked\";\n\nexport interface ApiKeysTable {\n\tid: Generated<string>;\n\tkey_hash: string;\n\tkey_prefix: string;\n\tname: string | null;\n\tstatus: Generated<ApiKeyStatus>;\n\trate_limit: Generated<number>;\n\tip_address: string;\n\taccount_id: string;\n\tproduct: Generated<\n\t\t\"account\" | \"streams\" | \"index\" | \"sentinel\" | \"docs\" | \"tenant\"\n\t>;\n\t/** Sentinel permission areas; set only on `product = 'sentinel'` keys. */\n\tareas: unknown | null;\n\ttier: \"free\" | \"internal\" | null;\n\tlast_used_at: Date | null;\n\trevoked_at: Date | null;\n\t/** Set only on `docs` keys (24h). A key past this instant never authenticates. */\n\texpires_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\n/** Singleton self-host / publisher identity. Network is immutable. */\nexport interface InstancesTable {\n\tid: Generated<string>;\n\tnetwork: string;\n\t/** `SECONDLAYER_SECRETS_KEY` sealed under itself; see `ensureSecretsKeyCanary`. */\n\tsecrets_key_canary: ColumnType<\n\t\tstring | null,\n\t\tstring | null | undefined,\n\t\tstring | null\n\t>;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface AccountsTable {\n\tid: Generated<string>;\n\t/** NULL for unclaimed ghost accounts (anonymous self-serve keys). */\n\temail: string | null;\n\t/** True for anonymous self-serve accounts until claimed via magic link. */\n\tghost: Generated<boolean>;\n\t/** First-party service account: usage priced at $0, never gated on\n\t * credits. Set by ops only. */\n\tinternal: Generated<boolean>;\n\t/** Stacks principal owning a wallet-ghost account. */\n\twallet_principal: string | null;\n\tdisplay_name: string | null;\n\tbio: string | null;\n\tavatar_url: string | null;\n\tstripe_customer_id: string | null;\n\t/** Opt-out toggle for the subgraph reindex-completion email. Defaults true. */\n\tnotify_reindex_complete: Generated<boolean>;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface SessionsTable {\n\tid: Generated<string>;\n\ttoken_hash: string;\n\ttoken_prefix: string;\n\taccount_id: string;\n\tip_address: string;\n\texpires_at: Generated<Date>;\n\trevoked_at: Date | null;\n\tlast_used_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface MagicLinksTable {\n\tid: Generated<string>;\n\temail: string;\n\ttoken: string;\n\tcode: string | null;\n\texpires_at: Date;\n\tused_at: Date | null;\n\tfailed_attempts: Generated<number>;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface SubgraphProcessingStatsTable {\n\tid: Generated<string>;\n\tsubgraph_name: string;\n\tapi_key_id: string | null;\n\tbucket_start: Date | null;\n\tbucket_end: Date | null;\n\tblocks_processed: number | null;\n\ttotal_time_ms: number | null;\n\thandler_time_ms: number | null;\n\tflush_time_ms: number | null;\n\tmax_block_time_ms: number | null;\n\tmax_handler_time_ms: number | null;\n\tavg_ops_per_block: number | null;\n\tis_catchup: Generated<boolean>;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface SubgraphHealthSnapshotsTable {\n\tid: Generated<string>;\n\tsubgraph_id: string;\n\ttotal_processed: number;\n\ttotal_errors: number;\n\tlast_processed_block: number | null;\n\tchain_tip: string | number | null;\n\trows_written_total: string | number | null;\n\tstorage_bytes: string | number | null;\n\tcaptured_at: Generated<Date>;\n}\n\n/** Handler errors grouped by fingerprint. Cap 50/subgraph. */\nexport interface SubgraphErrorGroupsTable {\n\tid: Generated<string>;\n\tsubgraph_name: string;\n\tfingerprint: string;\n\tsource_name: string;\n\tevent_type: string | null;\n\tmessage: string;\n\tframe: string | null;\n\tcount: Generated<string | number>;\n\tsample_tx_id: string | null;\n\tsample_block_height: string | number | null;\n\tfirst_seen: Generated<Date>;\n\tlast_seen: Generated<Date>;\n}\n\n/**\n * One ranked dashboard insight. `account_id` is NULL on tenant and self-host\n * databases. `severity` is never \"recovered\": that is derived on read from\n * `resolved_at`.\n */\nexport interface InsightsTable {\n\tid: Generated<string>;\n\taccount_id: string | null;\n\tresource_kind: string;\n\tresource_id: string;\n\trule: string;\n\tseverity: string;\n\timpact: Generated<number>;\n\t/** resource, line, meta, lead, body, evidence, handoff, how. */\n\tpayload: unknown;\n\tfirst_seen_at: Generated<Date>;\n\tlast_seen_at: Generated<Date>;\n\tclear_streak: Generated<number>;\n\tresolved_at: Date | null;\n\tdismissed_at: Date | null;\n\tsnoozed_until: Date | null;\n}\n\n/** \"Expected\": mutes one rule for one resource until removed. */\nexport interface InsightMutesTable {\n\taccount_id: string | null;\n\tresource_kind: string;\n\tresource_id: string;\n\trule: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface ProcessedStripeEventsTable {\n\tevent_id: string;\n\tevent_type: string;\n\tprocessed_at: Generated<Date>;\n}\n\nexport interface DecodedEventsTable {\n\tcursor: string;\n\tblock_height: number;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\tevent_type: string;\n\tmicroblock_hash: string | null;\n\tcanonical: Generated<boolean>;\n\tcontract_id: string | null;\n\tsender: string | null;\n\trecipient: string | null;\n\tamount: string | null;\n\tasset_identifier: string | null;\n\tvalue: string | null;\n\tmemo: string | null;\n\t/** Decoded payload for event types that don't fit the flat columns\n\t * (e.g. `print`: { topic, value, raw_value }). Null for transfer types. */\n\tpayload: unknown | null;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface DecoderCheckpointsTable {\n\tdecoder_name: string;\n\tlast_cursor: string | null;\n\tupdated_at: Generated<Date>;\n}\n\nexport interface ChainReorgsTable {\n\tid: Generated<string>;\n\tdetected_at: Generated<Date>;\n\tfork_point_height: number;\n\told_index_block_hash: string | null;\n\tnew_index_block_hash: string | null;\n\torphaned_from_height: number;\n\torphaned_from_event_index: number;\n\torphaned_to_height: number;\n\torphaned_to_event_index: number;\n\tnew_canonical_height: number;\n\tnew_canonical_event_index: number;\n\tcreated_at: Generated<Date>;\n}\n\n// ── L2 decoded tables: PoX-4 / sBTC / BNS ────────────────────────────\n\nexport type Pox4FunctionName =\n\t| \"stack-stx\"\n\t| \"delegate-stx\"\n\t| \"stack-extend\"\n\t| \"stack-increase\"\n\t| \"revoke-delegate-stx\"\n\t| \"delegate-stack-stx\"\n\t| \"delegate-stack-extend\"\n\t| \"delegate-stack-increase\"\n\t| \"stack-aggregation-commit\"\n\t| \"stack-aggregation-commit-indexed\"\n\t| \"stack-aggregation-increase\"\n\t| \"set-signer-key-authorization\";\n\nexport interface Pox4CallsTable {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time: Date;\n\tburn_block_height: number;\n\ttx_id: string;\n\ttx_index: number;\n\tfunction_name: Pox4FunctionName;\n\tcaller: string;\n\tstacker: string | null;\n\tdelegate_to: string | null;\n\tamount_ustx: string | null;\n\tlock_period: number | null;\n\tpox_addr_version: number | null;\n\tpox_addr_hashbytes: string | null;\n\tpox_addr_btc: string | null;\n\tstart_cycle: number | null;\n\tend_cycle: number | null;\n\tsigner_key: string | null;\n\tsigner_signature: string | null;\n\tauth_id: string | null;\n\tmax_amount: string | null;\n\treward_cycle: number | null;\n\taggregated_amount_ustx: string | null;\n\taggregated_signer_index: number | null;\n\tauth_period: number | null;\n\tauth_topic: string | null;\n\tauth_allowed: boolean | null;\n\tresult_ok: boolean;\n\tresult_raw: string;\n\tcanonical: Generated<boolean>;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport type Pox5EventTopic =\n\t| \"set-bond-admin\"\n\t| \"set-pause-admin\"\n\t| \"pause-rewards\"\n\t| \"setup-bond\"\n\t| \"add-to-allowlist\"\n\t| \"register-for-bond\"\n\t| \"update-bond-registration\"\n\t| \"register-signer\"\n\t| \"stake\"\n\t| \"stake-update\"\n\t| \"announce-l1-early-exit\"\n\t| \"unstake-sbtc\"\n\t| \"unstake\"\n\t| \"calculate-rewards\"\n\t| \"bond-distribution\"\n\t| \"claim-rewards\"\n\t| \"claim-staker-rewards-for-signer\"\n\t| \"grant-signer-key\"\n\t| \"revoke-signer-grant\";\n\n// PoX-5 print events (SIP-045). Promoted columns cover hot query paths; the\n// full decoded tuple always lands in `data` (nested shapes: btc-lockup,\n// bond-rewards lists, bond-periods).\nexport interface Pox5EventsTable {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time: Date;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\ttopic: Pox5EventTopic;\n\tstaker: string | null;\n\tsigner: string | null;\n\tsigner_manager: string | null;\n\tbond_index: number | null;\n\tamount_ustx: string | null;\n\tamount_sats: string | null;\n\treward_cycle: number | null;\n\tfirst_reward_cycle: number | null;\n\tunlock_cycle: number | null;\n\tunlock_burn_height: number | null;\n\tis_l1_lock: boolean | null;\n\tsigner_key: string | null;\n\tdata: unknown;\n\tcanonical: Generated<boolean>;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\n// Materialized per-cycle PoX-5 rollup (`rollupPox5Cycles`), maintained after\n// every committed pox5 decoder batch and after a pox5 reorg. Fully\n// rebuildable from `pox5_events` via `rebuild-pox5-cycles.ts --apply`.\nexport interface Pox5CyclesTable {\n\treward_cycle: number;\n\tstart_burn_height: number;\n\tprepare_start_burn_height: number;\n\tend_burn_height: number;\n\ttotal_stacked_ustx: string;\n\treward_eligible_ustx: string;\n\tstakers: number;\n\tsigners_in_set: number;\n\t/** bond index (as string) -> sats staked for this cycle. */\n\tbond_sats: unknown;\n\tbond_total_sats: string;\n\tsbtc_custodied_sats: string;\n\trewards_allocated_stx: string;\n\trewards_allocated_bond: string;\n\treserve_deposit: string;\n\trewards_per_token_stx: string | null;\n\t/** bond index (as string) -> cumulative rewards-per-sat for this cycle. */\n\trewards_per_token_bond: unknown;\n\tdistributions: number;\n\trewards_claimed: string;\n\tcomputed_through_height: number;\n\tupdated_at: Generated<Date>;\n}\n\n// Per-signer half of the pox-5 cycle rollup.\nexport interface Pox5CycleSignersTable {\n\treward_cycle: number;\n\tsigner: string;\n\tdelegated_ustx: string;\n\tstx_only_ustx: string;\n\treward_shares_ustx: string;\n\tin_set: boolean;\n\trewards_claimed: string;\n}\n\n// Actual BTC PoX payout — one row per reward slot (≤2 per burn block), from the\n// /new_burn_block reward_recipients array. `amount_sats`/`burn_amount` are sats.\nexport interface BurnBlockRewardsTable {\n\tcursor: string;\n\tburn_block_height: number;\n\tburn_block_hash: string;\n\treward_index: number;\n\trecipient_btc: string;\n\t// sats; TEXT to match the dataset amount convention (BIGINT returns as string).\n\tamount_sats: string;\n\tburn_amount: Generated<string>;\n\tcreated_at: Generated<Date>;\n}\n\n// Reward-set membership per burn block, from /new_burn_block reward_slot_holders.\nexport interface BurnBlockRewardSlotsTable {\n\tcursor: string;\n\tburn_block_height: number;\n\tburn_block_hash: string;\n\tslot_index: number;\n\tholder_btc: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport type SbtcEventTopic =\n\t| \"completed-deposit\"\n\t| \"withdrawal-create\"\n\t| \"withdrawal-accept\"\n\t| \"withdrawal-reject\"\n\t| \"key-rotation\"\n\t| \"update-protocol-contract\";\n\nexport interface SbtcEventsTable {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time: Date;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\ttopic: SbtcEventTopic;\n\trequest_id: number | null;\n\tamount: string | null;\n\tsender: string | null;\n\trecipient_btc_version: number | null;\n\trecipient_btc_hashbytes: string | null;\n\tbitcoin_txid: string | null;\n\toutput_index: number | null;\n\tsweep_txid: string | null;\n\tburn_hash: string | null;\n\tburn_height: number | null;\n\tsigner_bitmap: string | null;\n\tmax_fee: string | null;\n\tfee: string | null;\n\tblock_height_at_request: number | null;\n\tgovernance_contract_type: number | null;\n\tgovernance_new_contract: string | null;\n\tsigner_aggregate_pubkey: string | null;\n\tsigner_threshold: number | null;\n\tsigner_address: string | null;\n\tsigner_keys_count: number | null;\n\tcanonical: Generated<boolean>;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport type SbtcTokenEventType = \"transfer\" | \"mint\" | \"burn\";\n\nexport interface SbtcTokenEventsTable {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time: Date;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\tevent_type: SbtcTokenEventType;\n\tsender: string | null;\n\trecipient: string | null;\n\tamount: string;\n\tmemo: string | null;\n\tcanonical: Generated<boolean>;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\n/**\n * BTC L1 settlement status for sBTC withdrawal sweeps. Filled by the indexer's\n * settlement-confirmer worker, which polls our own bitcoind for confirmations of\n * each `withdrawal-accept`'s `sweep_txid` and surfaces real settlement on the\n * withdrawal lifecycle (the API's `settlement.{btc_confirmations,\n * settlement_confirmed}` placeholder). Keyed on `sweep_txid` (not `request_id`):\n * a request can produce more than one sweep over its life (RBF/rebroadcast), so\n * each broadcast keeps its own confirmation history.\n */\nexport interface SbtcSettlementsTable {\n\tsweep_txid: string;\n\trequest_id: number;\n\tbtc_confirmations: Generated<number>;\n\tsettlement_confirmed: Generated<boolean>;\n\t/** Confirming Bitcoin block — null while the sweep is unconfirmed. */\n\tblock_hash: string | null;\n\tblock_height: number | null;\n\tfirst_seen_at: Generated<Date>;\n\tlast_checked_at: Generated<Date>;\n\t/** Set once, when `settlement_confirmed` first flips true. */\n\tconfirmed_at: Date | null;\n\t/** Monotonic stamp from `sbtc_settlements_seq`, retaken each time the sweep\n\t * becomes confirmed. The webhook scan's watermark. BIGINT: a string at\n\t * runtime. */\n\tseq: Generated<number | string>;\n\tupdated_at: Generated<Date>;\n}\n\nexport type BnsNameEventTopic =\n\t| \"new-name\"\n\t| \"transfer-name\"\n\t| \"renew-name\"\n\t| \"burn-name\"\n\t| \"new-airdrop\";\n\nexport interface BnsNameEventsTable {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time: Date;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\ttopic: BnsNameEventTopic;\n\tnamespace: string;\n\tname: string;\n\tfqn: string;\n\towner: string | null;\n\tbns_id: string;\n\tregistered_at: number | null;\n\timported_at: number | null;\n\trenewal_height: number | null;\n\tstx_burn: string | null;\n\tpreordered_by: string | null;\n\thashed_salted_fqn_preorder: string | null;\n\tcanonical: Generated<boolean>;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport type BnsNamespaceEventStatus =\n\t| \"launch\"\n\t| \"transfer-manager\"\n\t| \"freeze-manager\"\n\t| \"update-price-manager\"\n\t| \"freeze-price-manager\"\n\t| \"turn-off-manager-transfers\";\n\nexport interface BnsNamespaceEventsTable {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time: Date;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\tstatus: BnsNamespaceEventStatus;\n\tnamespace: string;\n\tmanager: string | null;\n\tmanager_frozen: boolean | null;\n\tmanager_transfers_disabled: boolean | null;\n\tprice_function: string | null;\n\tprice_frozen: boolean | null;\n\tlifetime: number | null;\n\trevealed_at: number | null;\n\tlaunched_at: number | null;\n\tcanonical: Generated<boolean>;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport type BnsMarketplaceAction =\n\t| \"list-in-ustx\"\n\t| \"unlist-in-ustx\"\n\t| \"buy-in-ustx\";\n\nexport interface BnsMarketplaceEventsTable {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time: Date;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\taction: BnsMarketplaceAction;\n\tbns_id: string;\n\tprice_ustx: string | null;\n\tcommission: string | null;\n\tcanonical: Generated<boolean>;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface BnsNamesTable {\n\tfqn: string;\n\tnamespace: string;\n\tname: string;\n\towner: string;\n\tbns_id: string;\n\tregistered_at: number | null;\n\trenewal_height: number | null;\n\tlast_event_cursor: string;\n\tlast_event_at: Date;\n\tupdated_at: Generated<Date>;\n}\n\nexport interface BnsNamespacesTable {\n\tnamespace: string;\n\tmanager: string | null;\n\tmanager_frozen: Generated<boolean>;\n\tprice_frozen: Generated<boolean>;\n\tlifetime: number | null;\n\tlaunched_at: number | null;\n\tlast_event_cursor: string;\n\tlast_event_at: Date;\n\tname_count: Generated<number>;\n\tupdated_at: Generated<Date>;\n}\n\n// ── Database interface ────────────────────────────────────────────────\n\n/**\n * Memoized `ctx.client.readOnly()` results. Keyed on `index_block_hash` so a\n * reorg-replaced block never inherits the orphaned fork's answer; a NULL\n * `index_block_hash` marks a caller-declared contract-constant value, cached\n * once per contract+args instead of once per block.\n */\nexport interface ChainReadCacheTable {\n\tid: Generated<number>;\n\tcontract_id: string;\n\tfunction_name: string;\n\targs_hash: string;\n\tindex_block_hash: string | null;\n\tblock_height: ColumnType<\n\t\tnumber | null,\n\t\tnumber | null | undefined,\n\t\tnumber | null\n\t>;\n\tresult_hex: string;\n\tcreated_at: Generated<Date>;\n}\n\n/**\n * A block that arrived for a height we already hold, staged until a later\n * block's `parent_hash` says which of the two the chain kept. See migration\n * 0112 — adopting on first sight picked the losing fork twice.\n */\nexport interface PendingForkBlocksTable {\n\theight: number;\n\tblock_hash: string;\n\tparent_hash: string;\n\t/** The canonical hash we held at this height when the contender arrived. */\n\tincumbent_hash: string;\n\t/** The raw observer payload, replayed verbatim if this fork wins. */\n\tpayload: ColumnType<unknown, unknown, unknown>;\n\treceived_at: Generated<Date>;\n}\n\n/** Mirrored by the CHECK on `observer_journal.status`. */\nexport const OBSERVER_JOURNAL_STATUSES = [\n\t\"received\",\n\t\"processed\",\n\t\"failed\",\n\t\"retried\",\n\t\"poisoned\",\n\t\"skipped\",\n] as const;\nexport type ObserverJournalStatus = (typeof OBSERVER_JOURNAL_STATUSES)[number];\n\n/**\n * Exact observer callback receipt. `raw_body` is immutable evidence; the\n * processing columns are updated only after the current derived-state write\n * succeeds or fails.\n */\nexport interface ObserverJournalTable {\n\tsequence: Generated<string>;\n\tnetwork: string;\n\tpath: string;\n\tsource: string | null;\n\treceived_at: Generated<Date>;\n\traw_body: ColumnType<Buffer, Buffer, Buffer>;\n\traw_body_sha256: string;\n\tstatus: ColumnType<\n\t\tObserverJournalStatus,\n\t\tObserverJournalStatus | undefined,\n\t\tObserverJournalStatus\n\t>;\n\tsemantic_sha256: string | null;\n\tblock_height: number | null;\n\tblock_hash: string | null;\n\tburn_block_height: number | null;\n\tburn_block_hash: string | null;\n\tresult: unknown | null;\n\terror: string | null;\n\tprocessed_at: Date | null;\n}\n\n/** Declared coverage stage. Identity is the `id` string (`raw`, `decode:stx`, …). */\nexport interface StageRegistryTable {\n\tid: string;\n\tkind: StageKind;\n\tdepends_on: string | null;\n\tnative_clock: NativeClock;\n\tproducer_version: string;\n\trepair_mode: RepairMode;\n\tenabled: Generated<boolean>;\n\tcreated_at: Generated<Date>;\n}\n\n/** One versioned sweep of a stage. Nothing writes this table yet; kept because the receipts and failures tables reference it. */\nexport interface StageRunsTable {\n\tid: Generated<string>;\n\tstage_id: string;\n\tcode_hash: string;\n\tconfig_hash: string;\n\thandler_hash: string | null;\n\ttarget_height: number | null;\n\ttarget_cursor: string | null;\n\tstatus: RunStatus;\n\tcomplete_through: number | null;\n\tstarted_at: Generated<Date>;\n\tfinished_at: Date | null;\n}\n\n/** Per-block acknowledgement. Unique on (stage, height, hash). */\nexport interface StageBlockReceiptsTable {\n\tid: Generated<string>;\n\tstage_id: string;\n\trun_id: string | null;\n\tblock_height: number;\n\tblock_hash: string;\n\tinput_count: number;\n\tinput_digest: string;\n\teffect_digest: string;\n\tfinalized: Generated<boolean>;\n\tcompacted_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\n/** Compacted finalized range. Only sealed after receipts in the range finalize. */\nexport interface CoverageSegmentsTable {\n\tid: Generated<string>;\n\tstage_id: string;\n\tfrom_height: number;\n\tto_height: number;\n\tchain_digest: string;\n\tinput_digest: string;\n\toutput_digest: string;\n\tsealed_at: Generated<Date>;\n}\n\n/** Exact unit or range that failed, plus retry/retention state. */\nexport interface StageFailuresTable {\n\tid: Generated<string>;\n\tstage_id: string;\n\trun_id: string | null;\n\tunit_kind: FailureUnit;\n\tfrom_height: number | null;\n\tto_height: number | null;\n\tclass: FailureClass;\n\tretry_state: RetryState;\n\tretry_count: Generated<number>;\n\tlast_error: string | null;\n\tcreated_at: Generated<Date>;\n\tresolved_at: Date | null;\n\tretain_until: Generated<Date>;\n}\n\n/**\n * The instance's declared scope — one row per network. `start_height` is what\n * makes missing history below it deliberate rather than a gap.\n */\nexport interface SyncScopesTable {\n\tnetwork: string;\n\tstart_height: number;\n\ttarget_height: number | null;\n\tbootstrap_source: BootstrapSource;\n\tbootstrap_manifest_digest: string | null;\n\tgenesis_hash: string | null;\n\tcreated_at: Generated<Date>;\n\tupdated_at: Generated<Date>;\n}\n\nexport interface Database {\n\tblocks: BlocksTable;\n\ttransactions: TransactionsTable;\n\tevents: EventsTable;\n\tvm_events: VmEventsTable;\n\tstate_writes: StateWritesTable;\n\ttransactions_archive: TransactionsArchiveTable;\n\tevents_archive: EventsArchiveTable;\n\tvm_events_archive: VmEventsArchiveTable;\n\tstate_writes_archive: StateWritesArchiveTable;\n\tdead_letter_events: DeadLetterEventsTable;\n\tmempool_transactions: MempoolTransactionsTable;\n\tindex_progress: IndexProgressTable;\n\tcontracts: ContractsTable;\n\tsubgraphs: SubgraphsTable;\n\tapi_keys: ApiKeysTable;\n\tinstances: InstancesTable;\n\taccounts: AccountsTable;\n\tsessions: SessionsTable;\n\tmagic_links: MagicLinksTable;\n\tsubgraph_health_snapshots: SubgraphHealthSnapshotsTable;\n\tsubgraph_processing_stats: SubgraphProcessingStatsTable;\n\tsubgraph_gaps: SubgraphGapsTable;\n\tsubgraph_violations: SubgraphViolationsTable;\n\tsubgraph_error_groups: SubgraphErrorGroupsTable;\n\tsubgraph_operations: SubgraphOperationsTable;\n\tprocessed_stripe_events: ProcessedStripeEventsTable;\n\taccount_spend_caps: AccountSpendCapsTable;\n\taccount_credits: AccountCreditsTable;\n\twebhooks: WebhooksTable;\n\twebhook_outbox: WebhookOutboxTable;\n\twebhook_deliveries: WebhookDeliveriesTable;\n\twebhook_delivery_hours: WebhookDeliveryHoursTable;\n\twebhook_replays: WebhookReplaysTable;\n\ttrigger_evaluator_state: TriggerEvaluatorStateTable;\n\tdecoded_events: DecodedEventsTable;\n\tdecoder_checkpoints: DecoderCheckpointsTable;\n\tchain_reorgs: ChainReorgsTable;\n\tpox4_calls: Pox4CallsTable;\n\tpox5_events: Pox5EventsTable;\n\tpox5_cycles: Pox5CyclesTable;\n\tpox5_cycle_signers: Pox5CycleSignersTable;\n\tburn_block_rewards: BurnBlockRewardsTable;\n\tburn_block_reward_slots: BurnBlockRewardSlotsTable;\n\tsbtc_events: SbtcEventsTable;\n\tsbtc_token_events: SbtcTokenEventsTable;\n\tsbtc_settlements: SbtcSettlementsTable;\n\tbns_name_events: BnsNameEventsTable;\n\tbns_namespace_events: BnsNamespaceEventsTable;\n\tbns_marketplace_events: BnsMarketplaceEventsTable;\n\tbns_names: BnsNamesTable;\n\tbns_namespaces: BnsNamespacesTable;\n\tservice_heartbeats: ServiceHeartbeatsTable;\n\tchain_read_cache: ChainReadCacheTable;\n\tpending_fork_blocks: PendingForkBlocksTable;\n\tobserver_journal: ObserverJournalTable;\n\tsync_scopes: SyncScopesTable;\n\tstage_registry: StageRegistryTable;\n\tstage_runs: StageRunsTable;\n\tstage_block_receipts: StageBlockReceiptsTable;\n\tcoverage_segments: CoverageSegmentsTable;\n\tstage_failures: StageFailuresTable;\n\tarchive_fetches: ArchiveFetchesTable;\n\tusage_ledger: UsageLedgerTable;\n\taccount_balance_alerts: AccountBalanceAlertsTable;\n\thosted_stack_state: HostedStackStateTable;\n\twebhook_incident_alerts: WebhookIncidentAlertsTable;\n\tcli_device_logins: CliDeviceLoginsTable;\n\toauth_clients: OauthClientsTable;\n\toauth_requests: OauthRequestsTable;\n\toauth_codes: OauthCodesTable;\n\toauth_grants: OauthGrantsTable;\n\toauth_tokens: OauthTokensTable;\n\toauth_refresh_retired: OauthRefreshRetiredTable;\n\tsentinel_accounts: SentinelAccountsTable;\n\twaitlists: WaitlistsTable;\n\twaitlist_signups: WaitlistSignupsTable;\n\tcontact_requests: ContactRequestsTable;\n\tupdate_subscribers: UpdateSubscribersTable;\n\tupdate_sends: UpdateSendsTable;\n\tapi_failed_requests: ApiFailedRequestsTable;\n\tapi_request_log: ApiRequestLogTable;\n\tinsights: InsightsTable;\n\tinsight_mutes: InsightMutesTable;\n\tfeedback_tickets: FeedbackTicketsTable;\n\tpush_subscriptions: PushSubscriptionsTable;\n\tpush_prefs: PushPrefsTable;\n\tpush_sent: PushSentTable;\n}\n\nexport interface ServiceHeartbeatsTable {\n\tname: string;\n\tupdated_at: Generated<Date>;\n}\n\n// --- Account spend caps (soft cap + threshold alerts) ---\n//\n// One row per account. Null caps = \"no cap\" for that dimension.\n// `monthly_cap_cents` caps this calendar month's pay-as-you-go credit spend.\n// The hard stop is enforced in real time on the read path (read-credits.ts);\n// `frozen_at` is a display/alert mirror set by the daily cron when the cap is\n// hit, and cleared on month rollover, on invoice.paid, or when the cap is raised.\n\nexport interface AccountSpendCapsTable {\n\taccount_id: string;\n\tmonthly_cap_cents: number | null;\n\tcompute_cap_cents: number | null;\n\tstorage_cap_cents: number | null;\n\talert_threshold_pct: Generated<number>;\n\talert_sent_at: Date | null;\n\tfrozen_at: Date | null;\n\tupdated_at: Generated<Date>;\n}\n\nexport type AccountSpendCap = Selectable<AccountSpendCapsTable>;\nexport type InsertAccountSpendCap = Insertable<AccountSpendCapsTable>;\nexport type UpdateAccountSpendCap = Updateable<AccountSpendCapsTable>;\n\n/** Prepaid dev credits — card-funded balance per account. */\nexport interface AccountCreditsTable {\n\taccount_id: string;\n\tbalance_usd_micros: Generated<string | number | bigint>;\n\t/** Month bucket (\"YYYY-MM\") the spend counter applies to. */\n\tspent_month: string | null;\n\tspent_month_usd_micros: Generated<string | number | bigint>;\n\t/** Null = auto-refill off. */\n\trefill_below_usd_micros: string | number | bigint | null;\n\trefill_pack_usd: number | null;\n\trefill_last_at: Date | null;\n\tupdated_at: Generated<Date>;\n}\n\nexport type AccountCredits = Selectable<AccountCreditsTable>;\nexport type InsertAccountCredits = Insertable<AccountCreditsTable>;\nexport type UpdateAccountCredits = Updateable<AccountCreditsTable>;\n\n/**\n * Archive fetch charge log. Append-only: one row per\n * priced attempt to fetch a partition object. `usd_micros` is 0 for\n * free rows (24h re-issue, monthly repair allowance).\n */\nexport interface ArchiveFetchesTable {\n\tid: Generated<string>;\n\taccount_id: string;\n\tpath: string;\n\tdataset: string;\n\tusd_micros: string | number | bigint;\n\tvia_allowance: Generated<boolean>;\n\tcharged_at: Generated<Date>;\n}\n\nexport type ArchiveFetch = Selectable<ArchiveFetchesTable>;\nexport type InsertArchiveFetch = Insertable<ArchiveFetchesTable>;\nexport type UpdateArchiveFetch = Updateable<ArchiveFetchesTable>;\n\n/**\n * One metered ledger for every billable unit (archive partitions, hosted\n * Index/Streams rows, and future hosted-stack meters). Append-only, written\n * only by `meter()`. `idempotency_key` is UNIQUE so a retried submission\n * no-ops instead of double-charging. `debited` is false when the balance\n * (or a spend cap) refused the charge — the row still exists so the gap is\n * visible, never silently dropped. `usd_micros` is negative for a Stripe\n * top-up (`unit: \"topup\"`).\n */\nexport interface UsageLedgerTable {\n\tid: Generated<string>;\n\taccount_id: string;\n\tunit: string;\n\tquantity: string | number | bigint;\n\t/** Raw sampled quantity before any floor (e.g. `memory.gb_hour`'s actual\n\t * RAM, before the 0.5 GB minimum). NULL for every unit that has no\n\t * floor to observe past. */\n\tobserved_quantity: string | number | null;\n\tusd_micros: string | number | bigint;\n\t/** True when the whole price was taken; derived from `debited_usd_micros`. */\n\tdebited: Generated<boolean>;\n\t/** Amount actually taken from the balance, `0..usd_micros` (bounded the\n\t * other way for a negative top-up/grant row). Unpaid = price - this. */\n\tdebited_usd_micros: Generated<string | number | bigint>;\n\tsource: string;\n\t/** API key behind a metered read; null for non-read units and older rows. */\n\tapi_key_id: string | null;\n\tidempotency_key: string;\n\toccurred_at: Generated<Date>;\n\trecorded_at: Generated<Date>;\n}\n\nexport type UsageLedgerRow = Selectable<UsageLedgerTable>;\nexport type InsertUsageLedgerRow = Insertable<UsageLedgerTable>;\nexport type UpdateUsageLedgerRow = Updateable<UsageLedgerTable>;\n\n/** Preferences + debounce state for the balance-runway email alerts. One\n * row per account; a missing row means both alerts are on (defaults). */\nexport interface AccountBalanceAlertsTable {\n\taccount_id: string;\n\tnotify_7d: Generated<boolean>;\n\tnotify_2d: Generated<boolean>;\n\tsent_7d_at: Date | null;\n\tsent_2d_at: Date | null;\n\tsent_stopped_at: Date | null;\n}\n\n/** The workload host's report of one account's hosted stack. Written only by\n * `POST /internal/stack-state`; `reported_at` is the host's observation time. */\nexport interface HostedStackStateTable {\n\taccount_id: string;\n\tstate: \"provisioning\" | \"running\" | \"stopped\" | \"destroyed\";\n\tstop_reason: \"credits\" | \"cap\" | \"idle\" | null;\n\treported_at: Date;\n}\n\n/** Debounce state for the webhook-down email: one row per incident, open\n * while `resolved_at` is null. No preference columns by design. */\nexport interface WebhookIncidentAlertsTable {\n\tid: Generated<string>;\n\taccount_id: string;\n\twebhook_id: string;\n\twebhook_name: string;\n\tfailing_since: Date;\n\topened_at: Generated<Date>;\n\temailed_at: Date | null;\n\temail_attempts: Generated<number>;\n\tresolved_at: Date | null;\n}\n\nexport type WebhookIncidentAlert = Selectable<WebhookIncidentAlertsTable>;\n\n/** One browser/device push subscription; the endpoint is unique. */\nexport interface PushSubscriptionsTable {\n\tid: Generated<string>;\n\taccount_id: string;\n\tendpoint: string;\n\tp256dh: string;\n\tauth: string;\n\tuser_agent: string | null;\n\tcreated_at: Generated<Date>;\n\tlast_success_at: Date | null;\n\tfailed_count: Generated<number>;\n}\n\nexport type PushSubscription = Selectable<PushSubscriptionsTable>;\n\n/** Per-account push toggles. A missing row means the column defaults. */\nexport interface PushPrefsTable {\n\taccount_id: string;\n\twebhook_failing: Generated<boolean>;\n\tsubgraph_stopped: Generated<boolean>;\n\tsubgraph_not_serving: Generated<boolean>;\n\treplay_done: Generated<boolean>;\n\tspend_cap: Generated<boolean>;\n\tkey_repeat: Generated<boolean>;\n\tupdated_at: Generated<Date>;\n}\n\nexport type PushPrefs = Selectable<PushPrefsTable>;\n\n/** A push already sent, keyed by what it was about; debounces repeat signals. */\nexport interface PushSentTable {\n\taccount_id: string;\n\tkey: string;\n\tkind: string;\n\tsent_at: Generated<Date>;\n}\n\nexport type CliDeviceLoginStatus =\n\t| \"pending\"\n\t| \"approved\"\n\t| \"denied\"\n\t| \"consumed\";\n\n/** The product that started a CLI sign-in; null is `sl login`. */\nexport type CliDeviceProduct = \"sentinel\";\n\n/** One browser sign-in attempt from `sl login` (or `sentinel login`). Only the\n * hash of the CLI's device code is stored; the session is opened when the CLI\n * polls after approval. */\nexport interface CliDeviceLoginsTable {\n\tid: Generated<string>;\n\tdevice_code_hash: string;\n\tuser_code: string;\n\tclient_name: string;\n\tproduct: CliDeviceProduct | null;\n\tstatus: Generated<CliDeviceLoginStatus>;\n\taccount_id: string | null;\n\tkey_name: string | null;\n\tcreated_at: Generated<Date>;\n\texpires_at: Date;\n\tapproved_at: Date | null;\n\tconsumed_at: Date | null;\n}\n\nexport type CliDeviceLogin = Selectable<CliDeviceLoginsTable>;\n\n// --- OAuth for the hosted MCP endpoint ---\n//\n// Codes and tokens are stored as SHA-256 hashes only. See migration\n// `0177_oauth_mcp` and `@secondlayer/platform/db/queries/oauth`.\n\n/** An app that registered itself (RFC 7591). Public clients only: no secret. */\nexport interface OauthClientsTable {\n\tid: string;\n\t/** The app's own claim, validated at registration; shown quoted. */\n\tname: string;\n\tredirect_uris: string[];\n\tcreated_ip: string | null;\n\tcreated_at: Generated<Date>;\n\t/** Set when it first gets tokens; never-used clients are purged. */\n\tlast_used_at: Date | null;\n}\n\nexport type OauthRequestStatus = \"pending\" | \"approved\" | \"denied\";\n\n/** One authorize request waiting for (or answered on) the consent page. */\nexport interface OauthRequestsTable {\n\tid: string;\n\tclient_id: string;\n\tredirect_uri: string;\n\tstate: string | null;\n\tcode_challenge: string;\n\tresource: string;\n\tstatus: Generated<OauthRequestStatus>;\n\taccount_id: string | null;\n\tcreated_at: Generated<Date>;\n\texpires_at: Date;\n\tanswered_at: Date | null;\n}\n\n/** A one-time authorization code, bound to its client, redirect, PKCE\n * challenge, resource and account. */\nexport interface OauthCodesTable {\n\tcode_hash: string;\n\tclient_id: string;\n\taccount_id: string;\n\tredirect_uri: string;\n\tcode_challenge: string;\n\tresource: string;\n\t/** The grant its one use made, so a replay can revoke it. */\n\tgrant_id: string | null;\n\tcreated_at: Generated<Date>;\n\texpires_at: Date;\n\tused_at: Date | null;\n}\n\n/** What a person allowed one app to do: use the hosted MCP as them. */\nexport interface OauthGrantsTable {\n\tid: Generated<string>;\n\taccount_id: string;\n\tclient_id: string;\n\tscope: Generated<string>;\n\tresource: string;\n\tcreated_at: Generated<Date>;\n\tlast_used_at: Date | null;\n\trevoked_at: Date | null;\n}\n\nexport type OauthTokenKind = \"access\" | \"refresh\";\n\nexport interface OauthTokensTable {\n\ttoken_hash: string;\n\tgrant_id: string;\n\tkind: OauthTokenKind;\n\tcreated_at: Generated<Date>;\n\texpires_at: Date;\n}\n\n/** A refresh token a rotation replaced: presented again, it revokes the grant. */\nexport interface OauthRefreshRetiredTable {\n\ttoken_hash: string;\n\tgrant_id: string;\n\tretired_at: Generated<Date>;\n}\n\nexport type OauthClient = Selectable<OauthClientsTable>;\nexport type OauthGrant = Selectable<OauthGrantsTable>;\n\n/** Accounts Sentinel's service key may touch: created by Sentinel, or the\n * owner opted in. */\nexport interface SentinelAccountsTable {\n\taccount_id: string;\n\tlinked_at: Generated<Date>;\n\tvia: \"created\" | \"consent\";\n}\n\nexport type SentinelAccount = Selectable<SentinelAccountsTable>;\n\nexport type AccountBalanceAlerts = Selectable<AccountBalanceAlertsTable>;\nexport type InsertAccountBalanceAlerts = Insertable<AccountBalanceAlertsTable>;\nexport type UpdateAccountBalanceAlerts = Updateable<AccountBalanceAlertsTable>;\n\n// ── Convenience types ─────────────────────────────────────────────────\n\nexport type Block = Selectable<BlocksTable>;\nexport type InsertBlock = Insertable<BlocksTable>;\nexport type UpdateBlock = Updateable<BlocksTable>;\n\nexport type Transaction = Selectable<TransactionsTable>;\nexport type InsertTransaction = Insertable<TransactionsTable>;\nexport type UpdateTransaction = Updateable<TransactionsTable>;\n\nexport type MempoolTransaction = Selectable<MempoolTransactionsTable>;\nexport type InsertMempoolTransaction = Insertable<MempoolTransactionsTable>;\n\nexport type Event = Selectable<EventsTable>;\nexport type InsertEvent = Insertable<EventsTable>;\nexport type UpdateEvent = Updateable<EventsTable>;\n\nexport type VmEvent = Selectable<VmEventsTable>;\nexport type InsertVmEvent = Insertable<VmEventsTable>;\nexport type UpdateVmEvent = Updateable<VmEventsTable>;\nexport type StateWrite = Selectable<StateWritesTable>;\nexport type InsertStateWrite = Insertable<StateWritesTable>;\n\nexport type IndexProgress = Selectable<IndexProgressTable>;\nexport type InsertIndexProgress = Insertable<IndexProgressTable>;\nexport type UpdateIndexProgress = Updateable<IndexProgressTable>;\n\nexport type Subgraph = Selectable<SubgraphsTable>;\nexport type InsertSubgraph = Insertable<SubgraphsTable>;\nexport type UpdateSubgraph = Updateable<SubgraphsTable>;\n\nexport type Contract = Selectable<ContractsTable>;\nexport type InsertContract = Insertable<ContractsTable>;\nexport type UpdateContract = Updateable<ContractsTable>;\n\nexport type SubgraphOperation = Selectable<SubgraphOperationsTable>;\nexport type InsertSubgraphOperation = Insertable<SubgraphOperationsTable>;\nexport type UpdateSubgraphOperation = Updateable<SubgraphOperationsTable>;\n\nexport type ApiKey = Selectable<ApiKeysTable>;\nexport type InsertApiKey = Insertable<ApiKeysTable>;\nexport type UpdateApiKey = Updateable<ApiKeysTable>;\n\nexport type Account = Selectable<AccountsTable>;\nexport type InsertAccount = Insertable<AccountsTable>;\n\nexport type MagicLink = Selectable<MagicLinksTable>;\nexport type InsertMagicLink = Insertable<MagicLinksTable>;\n\nexport type Session = Selectable<SessionsTable>;\nexport type InsertSession = Insertable<SessionsTable>;\n\nexport type SubgraphHealthSnapshot = Selectable<SubgraphHealthSnapshotsTable>;\nexport type InsertSubgraphHealthSnapshot =\n\tInsertable<SubgraphHealthSnapshotsTable>;\n\nexport type SubgraphGap = Selectable<SubgraphGapsTable>;\nexport type InsertSubgraphGap = Insertable<SubgraphGapsTable>;\n\n// ── Webhooks (chain event webhooks) ─────────────────────\n\nexport type WebhookStatus = \"active\" | \"paused\";\nexport type { WebhookPauseReason };\n\n/** Webhooks react to raw chain events matched directly off the Index/Streams\n * clock. `chain` is the only kind since migration 0159 removed subgraph-row\n * webhooks; the column stays as the discriminator. */\nexport type WebhookKind = \"chain\";\nexport type WebhookFormat =\n\t| \"standard-webhooks\"\n\t| \"inngest\"\n\t| \"trigger\"\n\t| \"cloudflare\"\n\t| \"cloudevents\"\n\t| \"raw\";\n\nexport interface WebhooksTable {\n\tid: Generated<string>;\n\taccount_id: string;\n\tproject_id: string | null;\n\tname: string;\n\tstatus: ColumnType<WebhookStatus, WebhookStatus | undefined, WebhookStatus>;\n\tkind: ColumnType<WebhookKind, WebhookKind | undefined, WebhookKind>;\n\t/** Chain-trigger filter array (the `SubgraphFilter` shape, JSON). Typed\n\t * loosely here to avoid a shared→subgraphs import cycle; the Zod schema in\n\t * schemas/webhooks.ts owns the shape. */\n\ttriggers: unknown;\n\tformat: ColumnType<WebhookFormat, WebhookFormat | undefined, WebhookFormat>;\n\turl: string;\n\tsigning_secret_enc: Buffer;\n\tauth_config: Generated<unknown>;\n\tmax_retries: Generated<number>;\n\ttimeout_ms: Generated<number>;\n\tconcurrency: Generated<number>;\n\tcircuit_failures: Generated<number>;\n\tcircuit_opened_at: Date | null;\n\t/** Why a paused webhook is paused. Set exactly while `status` is `paused`. */\n\tpause_reason: WebhookPauseReason | null;\n\tlast_delivery_at: Date | null;\n\tlast_success_at: Date | null;\n\tlast_error: string | null;\n\t/** Receiver TLS leaf certificate expiry, from the emitter's periodic probe. */\n\treceiver_cert_expires_at: Date | null;\n\treceiver_cert_checked_at: Date | null;\n\tcreated_at: Generated<Date>;\n\tupdated_at: Generated<Date>;\n}\n\nexport type Webhook = Selectable<WebhooksTable>;\nexport type InsertWebhook = Insertable<WebhooksTable>;\nexport type UpdateWebhook = Updateable<WebhooksTable>;\n\nexport type OutboxStatus = \"pending\" | \"delivered\" | \"dead\";\n/** Why a row is dead: retries ran out, or a reorg removed its event. An\n * orphaned row stays dead; requeueing it would resend an event the chain no\n * longer contains. */\nexport type DeadReason = \"exhausted\" | \"orphaned\";\n\nexport interface WebhookOutboxTable {\n\tid: Generated<string>;\n\twebhook_id: string;\n\tkind: ColumnType<WebhookKind, WebhookKind | undefined, WebhookKind>;\n\tblock_height: number | bigint;\n\ttx_id: string | null;\n\trow_pk: unknown;\n\tevent_type: string;\n\tpayload: unknown;\n\tdedup_key: string;\n\tattempt: Generated<number>;\n\tnext_attempt_at: Generated<Date>;\n\tstatus: ColumnType<OutboxStatus, OutboxStatus | undefined, OutboxStatus>;\n\tis_replay: Generated<boolean>;\n\t/** The replay that created this row; null for live rows. */\n\treplay_id: string | null;\n\t/** The chain block_time of the matched event/tx. Null for rows written\n\t * before this column existed, and for the settlement scan path (not yet\n\t * wired). Lets `delivered_at - block_time` measure end-to-end webhook\n\t * latency without a join to SOURCE-plane `blocks`. */\n\tblock_time: Date | null;\n\tdelivered_at: Date | null;\n\tfailed_at: Date | null;\n\tlocked_by: string | null;\n\tlocked_until: Date | null;\n\t/** Set when a reorg marks an in-flight row `dead` instead of retrying it\n\t * into an orphaned fork. Null otherwise — delivery failures track their\n\t * history on `webhooks.last_error`, not per-row. */\n\tlast_error: string | null;\n\t/** Set exactly while `status` is `dead`. */\n\tdead_reason: DeadReason | null;\n\t/** Hash of the block a chain apply row was emitted for. Null on rows\n\t * written before the column existed (the payload carries it too). */\n\tblock_hash: string | null;\n\t/** Set when a reorg rollback recalled this delivered apply row, so a\n\t * later rollback for the same reorg skips it. */\n\trolled_back_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\nexport type WebhookReplayStatus = \"scanning\" | \"running\" | \"done\" | \"failed\";\n\nexport interface WebhookReplaysTable {\n\tid: string;\n\twebhook_id: string;\n\tfrom_block: number | bigint;\n\tto_block: number | bigint;\n\tstatus: WebhookReplayStatus;\n\tscanned_count: Generated<number>;\n\tenqueued_count: Generated<number>;\n\ttotal: number | null;\n\tdelivered: number | null;\n\tgave_up: number | null;\n\terror: string | null;\n\tstarted_at: Generated<Date>;\n\tfinished_at: Date | null;\n}\nexport type WebhookReplay = Selectable<WebhookReplaysTable>;\n\n/** `replay_id` is optional on the row type so hand-built rows (the test\n * delivery, fixtures) need not carry it; reads still return it. */\nexport type WebhookOutbox = Omit<\n\tSelectable<WebhookOutboxTable>,\n\t\"replay_id\"\n> & {\n\treplay_id?: string | null;\n};\nexport type InsertWebhookOutbox = Insertable<WebhookOutboxTable>;\nexport type UpdateWebhookOutbox = Updateable<WebhookOutboxTable>;\n\nexport interface WebhookDeliveriesTable {\n\tid: Generated<string>;\n\t/** Nullable after migration 0077 — outbox row may be cleaned up while\n\t * delivery telemetry is retained. */\n\toutbox_id: string | null;\n\twebhook_id: string;\n\tattempt: number;\n\tstatus_code: number | null;\n\tresponse_headers: unknown | null;\n\tresponse_body: string | null;\n\terror_message: string | null;\n\tduration_ms: number | null;\n\tdispatched_at: Generated<Date>;\n}\n\n/** Attempts per UTC hour, counted by a trigger on `webhook_deliveries`. */\nexport interface WebhookDeliveryHoursTable {\n\twebhook_id: string;\n\thour: Date;\n\t/** 2xx attempts. */\n\tdelivered: Generated<number>;\n\t/** Every other attempt. */\n\tfailed: Generated<number>;\n}\n\nexport type WebhookDelivery = Selectable<WebhookDeliveriesTable>;\nexport type InsertWebhookDelivery = Insertable<WebhookDeliveriesTable>;\n\n/** Single-row (id always TRUE) high-water mark for the chain-trigger evaluator.\n * One loop serves all chain webhooks, so the cursor is global. */\nexport interface TriggerEvaluatorStateTable {\n\tid: Generated<boolean>;\n\tlast_processed_block: ColumnType<\n\t\tbigint,\n\t\tbigint | number | undefined,\n\t\tbigint | number\n\t>;\n\t/** Watermark for the async sBTC settlement-confirmed webhook scan; null until\n\t * the evaluator fast-forwards it on first run. */\n\tlast_settlement_scan_at: ColumnType<\n\t\tDate | null,\n\t\tDate | null | undefined,\n\t\tDate | null\n\t>;\n\t/** `sbtc_settlements.seq` watermark. Null until the first settlement row is\n\t * scanned; `last_settlement_scan_at` is the forward-only floor until then. */\n\tlast_settlement_scan_seq: ColumnType<\n\t\tbigint | null,\n\t\tbigint | number | null | undefined,\n\t\tbigint | number | null\n\t>;\n\t/** Counts reorg rewinds. The evaluator checks it under the row lock in the\n\t * transaction that emits a batch and advances the cursor, so a reorg that\n\t * lands mid-tick rolls the batch back. */\n\treorg_generation: ColumnType<\n\t\tbigint,\n\t\tbigint | number | undefined,\n\t\tbigint | number\n\t>;\n\t/** Streams cursor (`<block_height>:<event_index>`) for the Bitcoin (Runes)\n\t * chain-trigger evaluator (plan 060) — a separate clock from\n\t * `last_processed_block` (Stacks). Null until the evaluator fast-forwards\n\t * it to the Bitcoin Streams tip on first run. */\n\tbitcoin_last_cursor: ColumnType<\n\t\tstring | null,\n\t\tstring | null | undefined,\n\t\tstring | null\n\t>;\n\tupdated_at: Generated<Date>;\n}\n\nexport type TriggerEvaluatorState = Selectable<TriggerEvaluatorStateTable>;\n\n/** A public waitlist page: what it is for and whether it takes signups. */\nexport interface WaitlistsTable {\n\tslug: string;\n\ttitle: string;\n\tdescription: string;\n\turl: string;\n\topened_at: Generated<Date>;\n\t/** Null while the list is open. */\n\tclosed_at: Date | null;\n}\n\n/**\n * One signup per (list, contact, token). `answers` holds the list's own\n * questions, validated per list by the API before insert.\n */\nexport interface WaitlistSignupsTable {\n\tid: Generated<string>;\n\tlist: string;\n\tcontact: string;\n\tanswers: Record<string, unknown>;\n\tcreated_at: Generated<Date>;\n}\n\n/**\n * A \"Talk to us\" message. Stored before the operator is emailed;\n * `notified_at` stays null until the email goes out.\n */\nexport interface ContactRequestsTable {\n\tid: Generated<string>;\n\tname: string;\n\temail: string;\n\tcompany: string | null;\n\tvolume: \"lt10m\" | \"10m-100m\" | \"100m-1b\" | \"gt1b\" | \"unsure\" | null;\n\tmessage: string;\n\tsource_page: string | null;\n\taccount_id: string | null;\n\t/** Hex sha256 of the client IP, never the address. */\n\tip_hash: string | null;\n\tnotified_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\n/**\n * A member of the email updates list. `pending` until the emailed link is\n * confirmed (`confirm_sent_at` starts the 7-day window), `confirmed` while\n * subscribed, `unsubscribed` after an opt-out. `token` is the secret in\n * confirm and unsubscribe links.\n */\nexport interface UpdateSubscribersTable {\n\tid: Generated<string>;\n\temail: string;\n\tstatus: Generated<\"pending\" | \"confirmed\" | \"unsubscribed\">;\n\ttoken: string;\n\tsource_page: string | null;\n\t/** Hex sha256 of the client IP, never the address. */\n\tip_hash: string | null;\n\tconfirm_sent_at: Date | null;\n\tconfirmed_at: Date | null;\n\tunsubscribed_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\n/** One broadcast (`send_key`) delivered to one subscriber. */\nexport interface UpdateSendsTable {\n\tsend_key: string;\n\tsubscriber_id: string;\n\tsent_at: Generated<Date>;\n}\n\n/**\n * 24h hosted record of a failed API request, keyed by `request_id` and\n * scoped to the account that made it. `query` is redacted before insert.\n */\nexport interface ApiFailedRequestsTable {\n\trequest_id: string;\n\taccount_id: string;\n\tmethod: string;\n\tpath: string;\n\tstatus: number;\n\tcode: string;\n\tmessage: Generated<string>;\n\tquery: Record<string, unknown>;\n\torigin: string | null;\n\t/** Revoked account key the request presented (`KEY_REVOKED` only). */\n\tapi_key_id: string | null;\n\tcreated_at: Generated<Date>;\n}\n\nexport type ApiFailedRequest = Selectable<ApiFailedRequestsTable>;\nexport type InsertApiFailedRequest = Insertable<ApiFailedRequestsTable>;\n\n/**\n * 7-day hosted log of account-attributed Index/Streams reads. Query values\n * are stored only as hashes; never bodies, headers or tokens.\n */\nexport interface ApiRequestLogTable {\n\tid: Generated<string>;\n\trequest_id: string | null;\n\taccount_id: string;\n\tapi_key_id: string | null;\n\tmethod: string;\n\tpath: string;\n\tpath_template: string;\n\tparams_hash: string | null;\n\tcursor_hash: string | null;\n\tpage_size: number | null;\n\trows: number | null;\n\tstatus: number;\n\tduration_ms: number;\n\tcreated_at: Generated<Date>;\n}\n\nexport type ApiRequestLogRow = Selectable<ApiRequestLogTable>;\nexport type InsertApiRequestLogRow = Insertable<ApiRequestLogTable>;\n\n/**\n * Hosted problem report. `attempted` is the server's own copy of the failed\n * request (never caller-supplied); `status` starts `new` until classified.\n */\nexport interface FeedbackTicketsTable {\n\tid: Generated<string>;\n\taccount_id: string;\n\tidempotency_key: string | null;\n\trequest_id: string | null;\n\tintent: string;\n\t/** Any JSON value the caller sent: a sentence or a shape. */\n\texpected: unknown;\n\tkind_hint: string | null;\n\tevidence: Record<string, unknown> | null;\n\tattempted: Record<string, unknown> | null;\n\torigin: string;\n\tstatus: Generated<\"new\" | \"classified\">;\n\troute: string | null;\n\tclassification: Record<string, unknown> | null;\n\tclassified_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\nexport type FeedbackTicket = Selectable<FeedbackTicketsTable>;\nexport type InsertFeedbackTicket = Insertable<FeedbackTicketsTable>;\n\nexport type Waitlist = Selectable<WaitlistsTable>;\nexport type WaitlistSignup = Selectable<WaitlistSignupsTable>;\nexport type InsertWaitlistSignup = Insertable<WaitlistSignupsTable>;\n\nexport type ContactRequest = Selectable<ContactRequestsTable>;\nexport type InsertContactRequest = Insertable<ContactRequestsTable>;\n\nexport type UpdateSubscriber = Selectable<UpdateSubscribersTable>;\nexport type InsertUpdateSubscriber = Insertable<UpdateSubscribersTable>;\n"
6
6
  ],
7
- "mappings": ";AA+PO,IAAM,eAAe;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD;AAqrBO,IAAM,4BAA4B;AAAA,EACxC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD;",
7
+ "mappings": ";AA+PO,IAAM,eAAe;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD;AA2rBO,IAAM,4BAA4B;AAAA,EACxC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD;",
8
8
  "debugId": "6E76A79D8A25C17E64756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -36,11 +36,25 @@ function getEnv() {
36
36
  } else if (result.data.NETWORK) {
37
37
  enabledNetworks = [result.data.NETWORK];
38
38
  } else {
39
- enabledNetworks = ["mainnet"];
39
+ const named = stacksNetwork();
40
+ enabledNetworks = named === "testnet" ? ["testnet"] : ["mainnet"];
40
41
  }
41
42
  cachedEnv = { ...result.data, enabledNetworks };
42
43
  return cachedEnv;
43
44
  }
45
+ var warnedNetworkFallback = false;
46
+ function stacksNetwork(env = process.env) {
47
+ if (env.STACKS_NETWORK)
48
+ return env.STACKS_NETWORK;
49
+ if (env.NETWORK) {
50
+ if (!warnedNetworkFallback) {
51
+ warnedNetworkFallback = true;
52
+ console.warn("NETWORK is deprecated: set STACKS_NETWORK instead");
53
+ }
54
+ return env.NETWORK;
55
+ }
56
+ return "mainnet";
57
+ }
44
58
  function isProductionEnv() {
45
59
  return process.env["NODE_ENV"] === "production";
46
60
  }
@@ -486,5 +500,5 @@ export {
486
500
  unsubscribeFor
487
501
  };
488
502
 
489
- //# debugId=2E00C110C2EE0B8564756E2164756E21
503
+ //# debugId=71D615692693B5AC64756E2164756E21
490
504
  //# sourceMappingURL=index.js.map
@@ -2,14 +2,14 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/env.ts", "../src/logger.ts", "../src/email/render.ts", "../src/email/send.ts", "../src/email/contact.ts", "../src/email/updates.ts"],
4
4
  "sourcesContent": [
5
- "import { z } from \"zod\";\n\n// Parse comma-separated networks\nconst networksSchema = z.string().transform((val) => {\n\tconst networks = val\n\t\t.split(\",\")\n\t\t.map((n) => n.trim())\n\t\t.filter(Boolean);\n\tconst valid = [\"mainnet\", \"testnet\"];\n\tfor (const n of networks) {\n\t\tif (!valid.includes(n)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid network: ${n}. Must be one of: ${valid.join(\", \")}`,\n\t\t\t);\n\t\t}\n\t}\n\treturn networks as (\"mainnet\" | \"testnet\")[];\n});\n\ninterface EnvSchemaOutput {\n\tDATABASE_URL?: string;\n\t/**\n\t * Shared indexer DB (blocks/txs/events). Falls back to DATABASE_URL.\n\t * Set this alongside TARGET_DATABASE_URL to enable dual-DB mode.\n\t */\n\tSOURCE_DATABASE_URL?: string;\n\t/**\n\t * Tenant DB (subgraph schemas + subgraphs table). Falls back to DATABASE_URL.\n\t * Set this alongside SOURCE_DATABASE_URL to enable dual-DB mode.\n\t */\n\tTARGET_DATABASE_URL?: string;\n\tNETWORK?: \"mainnet\" | \"testnet\";\n\tNETWORKS?: (\"mainnet\" | \"testnet\")[];\n\tLOG_LEVEL: \"debug\" | \"info\" | \"warn\" | \"error\";\n\tNODE_ENV: \"development\" | \"production\" | \"test\";\n}\n\n// Cast needed: z.preprocess / z.default create different _input vs _output types\n// that z.ZodType<T> can't represent without explicit input type param\nconst envSchema: z.ZodType<EnvSchemaOutput> = z.object({\n\tDATABASE_URL: z.preprocess(\n\t\t(val) => (typeof val === \"string\" && val.length === 0 ? undefined : val),\n\t\tz.string().url().optional(),\n\t),\n\tSOURCE_DATABASE_URL: z.preprocess(\n\t\t(val) => (typeof val === \"string\" && val.length === 0 ? undefined : val),\n\t\tz.string().url().optional(),\n\t),\n\tTARGET_DATABASE_URL: z.preprocess(\n\t\t(val) => (typeof val === \"string\" && val.length === 0 ? undefined : val),\n\t\tz.string().url().optional(),\n\t),\n\tNETWORK: z.enum([\"mainnet\", \"testnet\"]).optional(),\n\tNETWORKS: networksSchema.optional(),\n\tLOG_LEVEL: z.enum([\"debug\", \"info\", \"warn\", \"error\"]).default(\"info\"),\n\tNODE_ENV: z\n\t\t.enum([\"development\", \"production\", \"test\"])\n\t\t.default(\"development\"),\n}) as unknown as z.ZodType<EnvSchemaOutput>;\n\nexport type Env = EnvSchemaOutput & {\n\tenabledNetworks: (\"mainnet\" | \"testnet\")[];\n};\n\nlet cachedEnv: Env | null = null;\n\nexport function getEnv(): Env {\n\tif (cachedEnv) {\n\t\treturn cachedEnv;\n\t}\n\n\tconst result = envSchema.safeParse(process.env);\n\n\tif (!result.success) {\n\t\tconsole.error(\"❌ Invalid environment configuration:\");\n\t\tconsole.error(z.treeifyError(result.error));\n\t\tthrow new Error(\"Invalid environment configuration\");\n\t}\n\n\t// Compute enabled networks from NETWORKS or NETWORK\n\tlet enabledNetworks: (\"mainnet\" | \"testnet\")[];\n\tif (result.data.NETWORKS && result.data.NETWORKS.length > 0) {\n\t\tenabledNetworks = result.data.NETWORKS;\n\t} else if (result.data.NETWORK) {\n\t\tenabledNetworks = [result.data.NETWORK];\n\t} else {\n\t\tenabledNetworks = [\"mainnet\"]; // Default\n\t}\n\n\tcachedEnv = { ...result.data, enabledNetworks };\n\treturn cachedEnv;\n}\n\n/**\n * True when `NODE_ENV=production`, read at RUNTIME — the single source of truth\n * for prod-vs-dev branching in this package.\n *\n * Why a helper instead of inlining `process.env.NODE_ENV === \"production\"`:\n * bunup/esbuild constant-folds the dot-access `process.env.NODE_ENV` to its\n * BUILD-time value. `@secondlayer/shared` is consumed by other services as its\n * built `dist`, so an inlined check freezes to a literal in the shipped bundle\n * (e.g. `const isProd = false`) and silently ignores the container's real\n * NODE_ENV. The bracket access below is NOT folded, so it stays a runtime read.\n * Route every prod check through here so the footgun lives in exactly one place.\n */\nexport function isProductionEnv(): boolean {\n\t// biome-ignore lint/complexity/useLiteralKeys: bracket access is deliberate — dot-access gets constant-folded by the bundler, freezing this to a build-time literal in the shipped dist.\n\treturn process.env[\"NODE_ENV\"] === \"production\";\n}\n\ntype EnvMap = NodeJS.ProcessEnv;\n\n/**\n * PoX-4 stacking decoder is ON by default — `/v1/index/stacking` is part of the\n * public surface, so the decoder that fills `pox4_calls` runs unless explicitly\n * opted out with `POX4_DECODER_ENABLED=false` (mirrors the sBTC decoder policy).\n */\nexport function isPox4DecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.POX4_DECODER_ENABLED !== \"false\";\n}\n\n/**\n * PoX-5 print-event decoder is ON by default (mirrors pox-4/sBTC policy).\n * No activation gating needed: pox-5 events cannot exist before the Epoch 4.0\n * hard fork (Bitcoin block 960,230), so pre-activation the decoder idles at\n * tip. Opt out with `POX5_DECODER_ENABLED=false`.\n */\nexport function isPox5DecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.POX5_DECODER_ENABLED !== \"false\";\n}\n\n/** Default ON. Opt out with `SBTC_DECODER_ENABLED=false`. */\nexport function isSbtcDecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.SBTC_DECODER_ENABLED !== \"false\";\n}\n\n/** Default OFF. Opt in with `BNS_DECODER_ENABLED=true`. */\nexport function isBnsDecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.BNS_DECODER_ENABLED === \"true\";\n}\n\n// Export for testing\nexport { envSchema };\n",
5
+ "import { z } from \"zod\";\n\n// Parse comma-separated networks\nconst networksSchema = z.string().transform((val) => {\n\tconst networks = val\n\t\t.split(\",\")\n\t\t.map((n) => n.trim())\n\t\t.filter(Boolean);\n\tconst valid = [\"mainnet\", \"testnet\"];\n\tfor (const n of networks) {\n\t\tif (!valid.includes(n)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid network: ${n}. Must be one of: ${valid.join(\", \")}`,\n\t\t\t);\n\t\t}\n\t}\n\treturn networks as (\"mainnet\" | \"testnet\")[];\n});\n\ninterface EnvSchemaOutput {\n\tDATABASE_URL?: string;\n\t/**\n\t * Shared indexer DB (blocks/txs/events). Falls back to DATABASE_URL.\n\t * Set this alongside TARGET_DATABASE_URL to enable dual-DB mode.\n\t */\n\tSOURCE_DATABASE_URL?: string;\n\t/**\n\t * Tenant DB (subgraph schemas + subgraphs table). Falls back to DATABASE_URL.\n\t * Set this alongside SOURCE_DATABASE_URL to enable dual-DB mode.\n\t */\n\tTARGET_DATABASE_URL?: string;\n\tNETWORK?: \"mainnet\" | \"testnet\";\n\tNETWORKS?: (\"mainnet\" | \"testnet\")[];\n\tLOG_LEVEL: \"debug\" | \"info\" | \"warn\" | \"error\";\n\tNODE_ENV: \"development\" | \"production\" | \"test\";\n}\n\n// Cast needed: z.preprocess / z.default create different _input vs _output types\n// that z.ZodType<T> can't represent without explicit input type param\nconst envSchema: z.ZodType<EnvSchemaOutput> = z.object({\n\tDATABASE_URL: z.preprocess(\n\t\t(val) => (typeof val === \"string\" && val.length === 0 ? undefined : val),\n\t\tz.string().url().optional(),\n\t),\n\tSOURCE_DATABASE_URL: z.preprocess(\n\t\t(val) => (typeof val === \"string\" && val.length === 0 ? undefined : val),\n\t\tz.string().url().optional(),\n\t),\n\tTARGET_DATABASE_URL: z.preprocess(\n\t\t(val) => (typeof val === \"string\" && val.length === 0 ? undefined : val),\n\t\tz.string().url().optional(),\n\t),\n\tNETWORK: z.enum([\"mainnet\", \"testnet\"]).optional(),\n\tNETWORKS: networksSchema.optional(),\n\tLOG_LEVEL: z.enum([\"debug\", \"info\", \"warn\", \"error\"]).default(\"info\"),\n\tNODE_ENV: z\n\t\t.enum([\"development\", \"production\", \"test\"])\n\t\t.default(\"development\"),\n}) as unknown as z.ZodType<EnvSchemaOutput>;\n\nexport type Env = EnvSchemaOutput & {\n\tenabledNetworks: (\"mainnet\" | \"testnet\")[];\n};\n\nlet cachedEnv: Env | null = null;\n\nexport function getEnv(): Env {\n\tif (cachedEnv) {\n\t\treturn cachedEnv;\n\t}\n\n\tconst result = envSchema.safeParse(process.env);\n\n\tif (!result.success) {\n\t\tconsole.error(\"❌ Invalid environment configuration:\");\n\t\tconsole.error(z.treeifyError(result.error));\n\t\tthrow new Error(\"Invalid environment configuration\");\n\t}\n\n\t// Compute enabled networks from NETWORKS or NETWORK\n\tlet enabledNetworks: (\"mainnet\" | \"testnet\")[];\n\tif (result.data.NETWORKS && result.data.NETWORKS.length > 0) {\n\t\tenabledNetworks = result.data.NETWORKS;\n\t} else if (result.data.NETWORK) {\n\t\tenabledNetworks = [result.data.NETWORK];\n\t} else {\n\t\tconst named = stacksNetwork();\n\t\tenabledNetworks = named === \"testnet\" ? [\"testnet\"] : [\"mainnet\"];\n\t}\n\n\tcachedEnv = { ...result.data, enabledNetworks };\n\treturn cachedEnv;\n}\n\nlet warnedNetworkFallback = false;\n\n/**\n * The Stacks network this process serves, and the only place that decides it:\n * `STACKS_NETWORK`, else the deprecated `NETWORK` (warned once so a deployment\n * that only sets it is not silently re-keyed), else mainnet. Not validated;\n * `instanceNetworkFromEnv` is the strict form.\n */\nexport function stacksNetwork(env: NodeJS.ProcessEnv = process.env): string {\n\tif (env.STACKS_NETWORK) return env.STACKS_NETWORK;\n\tif (env.NETWORK) {\n\t\tif (!warnedNetworkFallback) {\n\t\t\twarnedNetworkFallback = true;\n\t\t\tconsole.warn(\"NETWORK is deprecated: set STACKS_NETWORK instead\");\n\t\t}\n\t\treturn env.NETWORK;\n\t}\n\treturn \"mainnet\";\n}\n\n/**\n * True when `NODE_ENV=production`, read at RUNTIME — the single source of truth\n * for prod-vs-dev branching in this package.\n *\n * Why a helper instead of inlining `process.env.NODE_ENV === \"production\"`:\n * bunup/esbuild constant-folds the dot-access `process.env.NODE_ENV` to its\n * BUILD-time value. `@secondlayer/shared` is consumed by other services as its\n * built `dist`, so an inlined check freezes to a literal in the shipped bundle\n * (e.g. `const isProd = false`) and silently ignores the container's real\n * NODE_ENV. The bracket access below is NOT folded, so it stays a runtime read.\n * Route every prod check through here so the footgun lives in exactly one place.\n */\nexport function isProductionEnv(): boolean {\n\t// biome-ignore lint/complexity/useLiteralKeys: bracket access is deliberate — dot-access gets constant-folded by the bundler, freezing this to a build-time literal in the shipped dist.\n\treturn process.env[\"NODE_ENV\"] === \"production\";\n}\n\ntype EnvMap = NodeJS.ProcessEnv;\n\n/**\n * PoX-4 stacking decoder is ON by default — `/v1/index/stacking` is part of the\n * public surface, so the decoder that fills `pox4_calls` runs unless explicitly\n * opted out with `POX4_DECODER_ENABLED=false` (mirrors the sBTC decoder policy).\n */\nexport function isPox4DecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.POX4_DECODER_ENABLED !== \"false\";\n}\n\n/**\n * PoX-5 print-event decoder is ON by default (mirrors pox-4/sBTC policy).\n * No activation gating needed: pox-5 events cannot exist before the Epoch 4.0\n * hard fork (Bitcoin block 960,230), so pre-activation the decoder idles at\n * tip. Opt out with `POX5_DECODER_ENABLED=false`.\n */\nexport function isPox5DecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.POX5_DECODER_ENABLED !== \"false\";\n}\n\n/** Default ON. Opt out with `SBTC_DECODER_ENABLED=false`. */\nexport function isSbtcDecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.SBTC_DECODER_ENABLED !== \"false\";\n}\n\n/** Default OFF. Opt in with `BNS_DECODER_ENABLED=true`. */\nexport function isBnsDecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.BNS_DECODER_ENABLED === \"true\";\n}\n\n// Export for testing\nexport { envSchema };\n",
6
6
  "import { getEnv } from \"./env.ts\";\n\ntype LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n\tdebug: 0,\n\tinfo: 1,\n\twarn: 2,\n\terror: 3,\n};\n\nclass Logger {\n\tprivate _level?: LogLevel;\n\tprivate _isProduction?: boolean;\n\tprivate _initialized = false;\n\n\tprivate init() {\n\t\tif (this._initialized) return;\n\t\tthis._initialized = true;\n\t\ttry {\n\t\t\tconst env = getEnv();\n\t\t\tthis._level = env.LOG_LEVEL;\n\t\t\tthis._isProduction = env.NODE_ENV === \"production\";\n\t\t} catch {\n\t\t\t// Fallback when env is unavailable (e.g. tests without DATABASE_URL)\n\t\t\tthis._level = \"info\";\n\t\t\tthis._isProduction = false;\n\t\t}\n\t}\n\n\tprivate get level(): LogLevel {\n\t\tthis.init();\n\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\treturn this._level!;\n\t}\n\n\tprivate get isProduction(): boolean {\n\t\tthis.init();\n\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\treturn this._isProduction!;\n\t}\n\n\tprivate shouldLog(level: LogLevel): boolean {\n\t\treturn LOG_LEVELS[level] >= LOG_LEVELS[this.level];\n\t}\n\n\tprivate formatMessage(\n\t\tlevel: LogLevel,\n\t\tmessage: string,\n\t\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\t\tmeta?: Record<string, any>,\n\t) {\n\t\tconst timestamp = new Date().toISOString();\n\n\t\tif (this.isProduction) {\n\t\t\t// JSON output for production\n\t\t\treturn JSON.stringify({\n\t\t\t\ttimestamp,\n\t\t\t\tlevel,\n\t\t\t\tmessage,\n\t\t\t\t...meta,\n\t\t\t});\n\t\t}\n\n\t\t// Human-readable output for development\n\t\tconst metaStr = meta ? ` ${JSON.stringify(meta)}` : \"\";\n\t\treturn `[${timestamp}] ${level.toUpperCase()}: ${message}${metaStr}`;\n\t}\n\n\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\tdebug(message: string, meta?: Record<string, any>): void {\n\t\tif (this.shouldLog(\"debug\")) {\n\t\t\tconsole.debug(this.formatMessage(\"debug\", message, meta));\n\t\t}\n\t}\n\n\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\tinfo(message: string, meta?: Record<string, any>): void {\n\t\tif (this.shouldLog(\"info\")) {\n\t\t\tconsole.info(this.formatMessage(\"info\", message, meta));\n\t\t}\n\t}\n\n\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\twarn(message: string, meta?: Record<string, any>): void {\n\t\tif (this.shouldLog(\"warn\")) {\n\t\t\tconsole.warn(this.formatMessage(\"warn\", message, meta));\n\t\t}\n\t}\n\n\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\terror(message: string, meta?: Record<string, any>): void {\n\t\tif (this.shouldLog(\"error\")) {\n\t\t\tconsole.error(this.formatMessage(\"error\", message, meta));\n\t\t}\n\t}\n}\n\n// Export singleton instance\nexport const logger: Logger = new Logger();\n",
7
7
  "/**\n * The one HTML/text layout every customer email renders through, in the\n * brand's \"Figure\" look: logo + wordmark, a 24px heading, muted prose, the\n * code or facts inside a hairline code figure whose bar names it and carries\n * a status chip, one blue button, and a hairline footer.\n *\n * Table-based HTML with inline styles (most clients strip <style>). The head\n * <style> only adds dark mode for clients that honor `prefers-color-scheme`\n * (Apple Mail, iOS); everyone else gets the light palette, which Gmail\n * inverts on its own. Geist loads where web fonts work, the system stack\n * elsewhere. Callers pass content; every color lives here.\n */\n\nexport interface FactRow {\n\tlabel: string;\n\tvalue: string;\n}\n\nexport interface EmailCta {\n\tlabel: string;\n\turl: string;\n}\n\n/** `alarm` only for failures and stops, `ok` only for success. */\nexport type EmailTone = \"neutral\" | \"ok\" | \"alarm\";\n\nexport interface EmailStatus {\n\ttone: EmailTone;\n\ttext: string;\n}\n\n/**\n * A post on X, drawn as our own card (X's embeds don't render in email):\n * avatar, name, @handle and date, the text, and an optional image. Without\n * `avatarUrl` the avatar is the Secondlayer tile.\n */\nexport interface XPost {\n\turl: string;\n\tauthor: { name: string; handle: string; avatarUrl?: string };\n\ttext: string;\n\t/** ISO date or timestamp; shown as \"Nov 5, 2026\". */\n\tdate: string;\n\timage?: { url: string; alt?: string };\n}\n\nexport interface RenderEmailInput {\n\theading: string;\n\t/** The inbox preview line after the subject. Not shown in the body. */\n\tpreheader?: string;\n\tparagraphs: string[];\n\t/** Someone else's words, quoted (a contact form message). */\n\tquote?: string;\n\t/** A sign-in code, shown as one selectable run of digits in the figure. */\n\tcode?: string;\n\tfacts?: FactRow[];\n\t/** The figure's title bar. Defaults to \"sign-in code\" or \"details\". */\n\tfigure?: string;\n\t/** A chip in the figure bar, or a status line when there is no figure. */\n\tstatus?: EmailStatus;\n\tcta?: EmailCta;\n\t/** Why the reader got this email and how to stop it. */\n\tfootnote?: string;\n\t/**\n\t * Monospace lines shown in the figure, whitespace kept. `mark`, when set,\n\t * has its first occurrence highlighted.\n\t */\n\texcerpt?: { lines: string; mark?: string };\n\t/** Plain text at the right of the figure bar when there is no `status`. */\n\tfigureNote?: string;\n\t/** A launch that lives on X, shown as a post card after the paragraphs. */\n\txPost?: XPost;\n\t/** Adds an \"Unsubscribe\" link to the footer (list emails only). */\n\tunsubscribeUrl?: string;\n}\n\nexport interface RenderedEmail {\n\thtml: string;\n\ttext: string;\n}\n\n// www directly: the apex 307s there, and every image fetch would pay for it.\nconst LOGO_URL = \"https://www.secondlayer.tools/email/logo.png\";\nconst LOGO_WHITE_URL = \"https://www.secondlayer.tools/email/logo-white.png\";\nconst TAGLINE = \"Instant data for apps on Bitcoin\";\n\nconst SANS =\n\t\"Geist, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif\";\nconst MONO =\n\t\"'Geist Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace\";\n\n// DESIGN.md roles. Light inline; dark via the head <style> classes below.\nconst LIGHT = {\n\tpaper: \"#fbfaf7\",\n\tink: \"#14110d\",\n\tsub: \"#63605c\",\n\tfaint: \"#9d9b97\",\n\tline: \"#e8e6e3\",\n\tpri: \"#1f45e0\",\n\tonPri: \"#fbfaf7\",\n\tok: \"#128a43\",\n\talarm: \"#e3301e\",\n};\n\nconst DARK_STYLE = `\n@media (prefers-color-scheme: dark) {\n .sl-paper { background: #1e1b17 !important; }\n .sl-ink { color: #e8e6e3 !important; }\n .sl-sub { color: #b3b1ad !important; }\n .sl-faint { color: #7c7a76 !important; }\n .sl-line { border-color: #393632 !important; }\n .sl-pri { background: #3a5bff !important; }\n .sl-pri-text { color: #7f96ff !important; }\n .sl-ok { color: #5cc28f !important; }\n .sl-alarm { color: #ff5a47 !important; }\n .sl-dot-neutral { background: #7c7a76 !important; }\n .sl-dot-ok { background: #5cc28f !important; }\n .sl-dot-alarm { background: #ff5a47 !important; }\n}`.trim();\n\nfunction escapeHtml(value: string): string {\n\treturn value\n\t\t.replace(/&/g, \"&amp;\")\n\t\t.replace(/</g, \"&lt;\")\n\t\t.replace(/>/g, \"&gt;\")\n\t\t.replace(/\"/g, \"&quot;\")\n\t\t.replace(/'/g, \"&#39;\");\n}\n\nconst TONE_COLOR: Record<EmailTone, string> = {\n\tneutral: LIGHT.sub,\n\tok: LIGHT.ok,\n\talarm: LIGHT.alarm,\n};\nconst DOT_COLOR: Record<EmailTone, string> = {\n\tneutral: LIGHT.faint,\n\tok: LIGHT.ok,\n\talarm: LIGHT.alarm,\n};\nconst TONE_CLASS: Record<EmailTone, string> = {\n\tneutral: \"sl-sub\",\n\tok: \"sl-ok\",\n\talarm: \"sl-alarm\",\n};\n\nfunction dot(tone: EmailTone): string {\n\treturn `<span class=\"sl-dot-${tone}\" style=\"display: inline-block; width: 7px; height: 7px; border-radius: 999px; background: ${DOT_COLOR[tone]}; margin-right: 6px; vertical-align: 1px;\"></span>`;\n}\n\nfunction statusChip(status: EmailStatus): string {\n\treturn `<span class=\"sl-line ${TONE_CLASS[status.tone]}\" style=\"display: inline-block; border: 1px solid ${LIGHT.line}; border-radius: 999px; padding: 2px 8px; font-family: ${MONO}; font-size: 12px; line-height: 16px; color: ${TONE_COLOR[status.tone]}; white-space: nowrap;\">${dot(status.tone)}${escapeHtml(status.text)}</span>`;\n}\n\nfunction preheaderHtml(preheader: string | undefined): string {\n\tif (!preheader) return \"\";\n\t// Trailing joiners keep body text from leaking into the preview line.\n\tconst filler = \"&#847;&zwnj;&nbsp;\".repeat(60);\n\treturn `<div style=\"display: none; max-height: 0; overflow: hidden; mso-hide: all; opacity: 0; color: transparent;\">${escapeHtml(preheader)}${filler}</div>`;\n}\n\nfunction hasFigure(input: RenderEmailInput): boolean {\n\treturn Boolean(input.code || input.facts?.length || input.excerpt);\n}\n\nfunction excerptHtml(excerpt: { lines: string; mark?: string }): string {\n\tlet lines = escapeHtml(excerpt.lines);\n\tif (excerpt.mark) {\n\t\tconst mark = escapeHtml(excerpt.mark);\n\t\tconst at = lines.indexOf(mark);\n\t\tif (at !== -1) {\n\t\t\tlines = `${lines.slice(0, at)}<span style=\"background: #ffd200; color: #14110d; padding: 0 2px;\">${mark}</span>${lines.slice(at + mark.length)}`;\n\t\t}\n\t}\n\treturn `<tr><td colspan=\"2\" style=\"padding: 0;\"><pre class=\"sl-ink\" style=\"margin: 0; padding: 12px 14px; font-family: ${MONO}; font-size: 12.5px; line-height: 20px; white-space: pre; overflow-x: auto; color: ${LIGHT.ink};\">${lines}</pre></td></tr>`;\n}\n\nfunction figureHtml(input: RenderEmailInput): string {\n\tif (!hasFigure(input)) return \"\";\n\tconst title =\n\t\tinput.figure ??\n\t\t(input.code ? \"sign-in code\" : input.excerpt ? \"excerpt\" : \"details\");\n\tconst line = `border-color: ${LIGHT.line}; border-style: solid; border-width: 0`;\n\n\tconst bar = `<tr>\n <td class=\"sl-faint sl-line\" style=\"padding: 8px 14px; ${line}; border-bottom-width: 1px; font-family: ${MONO}; font-size: 12px; line-height: 18px; color: ${LIGHT.faint};\">${escapeHtml(title)}</td>\n <td class=\"sl-line\" align=\"right\" style=\"padding: 8px 14px; ${line}; border-bottom-width: 1px;\">${input.status ? statusChip(input.status) : input.figureNote ? `<span class=\"sl-faint\" style=\"font-family: ${MONO}; font-size: 12px; line-height: 18px; color: ${LIGHT.faint};\">${escapeHtml(input.figureNote)}</span>` : \"\"}</td>\n </tr>`;\n\n\tlet body: string;\n\tif (input.code) {\n\t\tbody = `<tr><td colspan=\"2\" align=\"center\" class=\"sl-ink\" style=\"padding: 24px 14px 8px; font-family: ${MONO}; font-size: 36px; line-height: 40px; font-weight: 500; letter-spacing: 0.3em; color: ${LIGHT.ink}; -webkit-user-select: all; user-select: all;\">${escapeHtml(input.code)}</td></tr>\n <tr><td colspan=\"2\" align=\"center\" class=\"sl-faint\" style=\"padding: 0 14px 16px; font-family: ${MONO}; font-size: 12px; line-height: 18px; color: ${LIGHT.faint};\">tap or double-click to select</td></tr>`;\n\t} else if (input.excerpt && !input.facts?.length) {\n\t\tbody = excerptHtml(input.excerpt);\n\t} else {\n\t\tconst facts = input.facts ?? [];\n\t\tbody = facts\n\t\t\t.map((fact, i) => {\n\t\t\t\tconst top = i === 0 ? 12 : 2;\n\t\t\t\tconst bottom = i === facts.length - 1 ? 12 : 2;\n\t\t\t\tconst cell = `padding: ${top}px 14px ${bottom}px; font-family: ${MONO}; font-size: 13px; line-height: 20px; vertical-align: top;`;\n\t\t\t\treturn `<tr>\n <td class=\"sl-faint\" style=\"${cell} padding-right: 24px; width: 1%; color: ${LIGHT.faint}; white-space: nowrap;\">${escapeHtml(fact.label.toLowerCase())}</td>\n <td class=\"sl-ink\" style=\"${cell} color: ${LIGHT.ink}; word-break: break-word;\">${escapeHtml(fact.value)}</td>\n </tr>`;\n\t\t\t})\n\t\t\t.join(\"\\n \");\n\t}\n\n\treturn `<table role=\"presentation\" cellpadding=\"0\" cellspacing=\"0\" class=\"sl-line\" style=\"width: 100%; border: 1px solid ${LIGHT.line}; border-radius: 8px; border-collapse: separate; border-spacing: 0; margin: 8px 0 24px;\">\n ${bar}\n ${body}\n </table>`;\n}\n\nexport function xPostDate(date: string): string {\n\tconst d = new Date(date);\n\tif (Number.isNaN(d.getTime())) return date;\n\treturn d.toLocaleDateString(\"en-US\", {\n\t\tmonth: \"short\",\n\t\tday: \"numeric\",\n\t\tyear: \"numeric\",\n\t\ttimeZone: \"UTC\",\n\t});\n}\n\nfunction xPostHtml(post: XPost): string {\n\tconst avatar = post.author.avatarUrl\n\t\t? `<img src=\"${escapeHtml(post.author.avatarUrl)}\" width=\"36\" height=\"36\" alt=\"\" style=\"display: block; width: 36px; height: 36px; border-radius: 999px; border: 0;\">`\n\t\t: `<div class=\"sl-pri\" style=\"width: 36px; height: 36px; border-radius: 6px; background: ${LIGHT.pri}; text-align: center;\"><img src=\"${LOGO_WHITE_URL}\" width=\"21\" height=\"14\" alt=\"\" style=\"display: inline-block; margin-top: 11px; border: 0;\"></div>`;\n\tconst paragraphs = post.text\n\t\t.split(/\\n{2,}/)\n\t\t.map((p) => {\n\t\t\tconst linked = escapeHtml(p).replace(\n\t\t\t\t/@(\\w{1,15})/g,\n\t\t\t\t`<a href=\"https://x.com/$1\" class=\"sl-pri-text\" style=\"color: ${LIGHT.pri}; text-decoration: none;\">@$1</a>`,\n\t\t\t);\n\t\t\treturn `<p class=\"sl-ink\" style=\"margin: 0 0 10px; font-size: 15px; line-height: 23px; color: ${LIGHT.ink}; white-space: pre-line;\">${linked}</p>`;\n\t\t})\n\t\t.join(\"\");\n\tconst image = post.image\n\t\t? `<tr><td style=\"padding: 4px 14px 14px;\"><a href=\"${escapeHtml(post.url)}\"><img src=\"${escapeHtml(post.image.url)}\" width=\"100%\" alt=\"${escapeHtml(post.image.alt ?? \"\")}\" class=\"sl-line\" style=\"display: block; width: 100%; height: auto; border: 1px solid ${LIGHT.line}; border-radius: 6px; box-sizing: border-box;\"></a></td></tr>`\n\t\t: \"\";\n\treturn `<table role=\"presentation\" cellpadding=\"0\" cellspacing=\"0\" class=\"sl-line\" style=\"width: 100%; border: 1px solid ${LIGHT.line}; border-radius: 8px; border-collapse: separate; border-spacing: 0; margin: 8px 0 24px;\">\n <tr><td style=\"padding: 14px 14px 10px;\">\n <table role=\"presentation\" cellpadding=\"0\" cellspacing=\"0\"><tr>\n <td style=\"padding-right: 10px; vertical-align: middle;\">${avatar}</td>\n <td style=\"vertical-align: middle;\">\n <div class=\"sl-ink\" style=\"font-size: 14px; line-height: 18px; font-weight: 500; color: ${LIGHT.ink};\">${escapeHtml(post.author.name)}</div>\n <div class=\"sl-faint\" style=\"font-family: ${MONO}; font-size: 12px; line-height: 18px; color: ${LIGHT.faint};\">@${escapeHtml(post.author.handle)} &middot; ${escapeHtml(xPostDate(post.date))}</div>\n </td>\n </tr></table>\n </td></tr>\n <tr><td style=\"padding: 0 14px 4px;\">${paragraphs}</td></tr>\n ${image}\n </table>`;\n}\n\nfunction renderHtml(input: RenderEmailInput): string {\n\tconst figure = hasFigure(input);\n\n\tconst statusLine =\n\t\tinput.status && !figure\n\t\t\t? `<p class=\"${TONE_CLASS[input.status.tone]}\" style=\"margin: 0 0 12px; font-size: 13px; line-height: 20px; color: ${TONE_COLOR[input.status.tone]};\">${dot(input.status.tone)}${escapeHtml(input.status.text)}</p>`\n\t\t\t: \"\";\n\n\tconst paragraphsHtml = input.paragraphs\n\t\t.map(\n\t\t\t(p) =>\n\t\t\t\t`<p class=\"sl-sub\" style=\"margin: 0 0 14px; font-size: 15px; line-height: 24px; color: ${LIGHT.sub};\">${escapeHtml(p)}</p>`,\n\t\t)\n\t\t.join(\"\\n \");\n\n\tconst quoteHtml = input.quote\n\t\t? `<p class=\"sl-ink\" style=\"margin: 0 0 14px; font-size: 15px; line-height: 24px; color: ${LIGHT.ink};\">&ldquo;${escapeHtml(input.quote)}&rdquo;</p>`\n\t\t: \"\";\n\n\tconst ctaHtml = input.cta\n\t\t? `<table role=\"presentation\" cellpadding=\"0\" cellspacing=\"0\" style=\"margin: 10px 0 0;\"><tr><td class=\"sl-pri\" style=\"background: ${LIGHT.pri}; border-radius: 4px;\"><a href=\"${escapeHtml(input.cta.url)}\" style=\"display: inline-block; padding: 0 18px; height: 42px; line-height: 42px; font-family: ${SANS}; font-size: 15px; font-weight: 500; color: ${LIGHT.onPri}; text-decoration: none;\">${escapeHtml(input.cta.label)}</a></td></tr></table>`\n\t\t: \"\";\n\n\tconst unsubscribeLink = input.unsubscribeUrl\n\t\t? `<a href=\"${escapeHtml(input.unsubscribeUrl)}\" class=\"sl-sub\" style=\"color: ${LIGHT.sub}; text-decoration: underline;\">Unsubscribe</a>`\n\t\t: \"\";\n\tconst footnoteText = input.footnote ? escapeHtml(input.footnote) : \"\";\n\tconst footnoteHtml =\n\t\tfootnoteText || unsubscribeLink\n\t\t\t? `<p class=\"sl-faint\" style=\"margin: 0 0 6px;\">${[footnoteText, unsubscribeLink].filter(Boolean).join(\" \")}</p>`\n\t\t\t: \"\";\n\n\treturn `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<meta name=\"color-scheme\" content=\"light dark\">\n<meta name=\"supported-color-schemes\" content=\"light dark\">\n<link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css2?family=Geist:wght@400;500&family=Geist+Mono:wght@400;500&display=swap\">\n<style>\n${DARK_STYLE}\n</style>\n</head>\n<body class=\"sl-paper\" style=\"margin: 0; padding: 0; background: ${LIGHT.paper};\">\n${preheaderHtml(input.preheader)}\n<table role=\"presentation\" cellpadding=\"0\" cellspacing=\"0\" class=\"sl-paper\" style=\"width: 100%; background: ${LIGHT.paper};\">\n <tr>\n <td align=\"center\">\n <table role=\"presentation\" cellpadding=\"0\" cellspacing=\"0\" style=\"width: 100%; max-width: 560px; font-family: ${SANS}; padding: 40px 20px;\">\n <tr>\n <td>\n <table role=\"presentation\" cellpadding=\"0\" cellspacing=\"0\" style=\"margin: 0 0 32px;\"><tr>\n <td style=\"padding-right: 8px; vertical-align: middle;\"><img src=\"${LOGO_URL}\" width=\"30\" height=\"20\" alt=\"\" style=\"display: block; border: 0;\"></td>\n <td class=\"sl-ink\" style=\"vertical-align: middle; font-size: 15px; font-weight: 500; letter-spacing: -0.01em; color: ${LIGHT.ink};\">secondlayer</td>\n </tr></table>\n ${statusLine}\n <h1 class=\"sl-ink\" style=\"margin: 0 0 14px; font-size: 24px; line-height: 29px; font-weight: 500; letter-spacing: -0.025em; color: ${LIGHT.ink};\">${escapeHtml(input.heading)}</h1>\n ${paragraphsHtml}\n ${quoteHtml}\n ${input.xPost ? xPostHtml(input.xPost) : \"\"}\n ${figureHtml(input)}\n ${ctaHtml}\n <div class=\"sl-line sl-faint\" style=\"margin: 32px 0 0; padding: 16px 0 0; border-top: 1px solid ${LIGHT.line}; font-size: 12px; line-height: 18px; color: ${LIGHT.faint};\">\n ${footnoteHtml}\n <p class=\"sl-faint\" style=\"margin: 0;\"><span class=\"sl-sub\" style=\"color: ${LIGHT.sub}; font-weight: 500;\">Secondlayer</span> &middot; ${TAGLINE}</p>\n </div>\n </td>\n </tr>\n </table>\n </td>\n </tr>\n</table>\n</body>\n</html>`;\n}\n\nfunction renderText(input: RenderEmailInput): string {\n\tconst lines: string[] = [input.heading, \"\"];\n\tfor (const p of input.paragraphs) lines.push(p, \"\");\n\tif (input.quote) lines.push(`\"${input.quote}\"`, \"\");\n\tif (input.xPost) {\n\t\tconst { author, date, text, url } = input.xPost;\n\t\tlines.push(\n\t\t\t`${author.name} (@${author.handle}) · ${xPostDate(date)}`,\n\t\t\ttext,\n\t\t\turl,\n\t\t\t\"\",\n\t\t);\n\t}\n\tif (input.status) lines.push(input.status.text, \"\");\n\tif (input.code) lines.push(`Code: ${input.code}`, \"\");\n\tif (input.facts?.length) {\n\t\tfor (const fact of input.facts) lines.push(`${fact.label}: ${fact.value}`);\n\t\tlines.push(\"\");\n\t}\n\tif (input.excerpt) lines.push(input.excerpt.lines, \"\");\n\tif (input.cta) lines.push(`${input.cta.label}: ${input.cta.url}`, \"\");\n\tlines.push(\"--\");\n\tif (input.footnote) lines.push(input.footnote);\n\tif (input.unsubscribeUrl) lines.push(`Unsubscribe: ${input.unsubscribeUrl}`);\n\tlines.push(`Secondlayer · ${TAGLINE}`);\n\treturn lines.join(\"\\n\");\n}\n\nexport function renderEmail(input: RenderEmailInput): RenderedEmail {\n\treturn { html: renderHtml(input), text: renderText(input) };\n}\n",
8
8
  "import { logger } from \"../logger.ts\";\n\n/**\n * The one Resend call every customer email goes through. Never throws when\n * `RESEND_API_KEY` is unset — that's a dev/CI/self-host state, not a send\n * failure — it logs a warning and reports `{ skipped: true }` so a caller\n * can still record its own \"notification sent\" bookkeeping accurately.\n */\n\nexport interface SendEmailInput {\n\tto: string;\n\tsubject: string;\n\thtml: string;\n\ttext: string;\n\t/** Where a reply goes; omitted, replies go to the From address. */\n\treplyTo?: string;\n\t/** Overrides the `EMAIL_FROM` default. */\n\tfrom?: string;\n\t/** Extra message headers, e.g. RFC 8058 `List-Unsubscribe`. */\n\theaders?: Record<string, string>;\n}\n\nexport type SendEmailResult = { skipped: true } | { skipped: false };\n\nexport async function sendEmail(\n\tinput: SendEmailInput,\n): Promise<SendEmailResult> {\n\tconst apiKey = process.env.RESEND_API_KEY;\n\tif (!apiKey) {\n\t\tlogger.warn(\"RESEND_API_KEY unset — skipping email\", {\n\t\t\tsubject: input.subject,\n\t\t});\n\t\treturn { skipped: true };\n\t}\n\n\tconst from =\n\t\tinput.from ??\n\t\tprocess.env.EMAIL_FROM ??\n\t\t\"secondlayer <noreply@secondlayer.tools>\";\n\n\tconst response = await fetch(\"https://api.resend.com/emails\", {\n\t\tmethod: \"POST\",\n\t\theaders: {\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t},\n\t\tbody: JSON.stringify({\n\t\t\tfrom,\n\t\t\tto: [input.to],\n\t\t\tsubject: input.subject,\n\t\t\thtml: input.html,\n\t\t\ttext: input.text,\n\t\t\t...(input.replyTo ? { reply_to: [input.replyTo] } : {}),\n\t\t\t...(input.headers && Object.keys(input.headers).length > 0\n\t\t\t\t? { headers: input.headers }\n\t\t\t\t: {}),\n\t\t}),\n\t});\n\n\tif (!response.ok) {\n\t\tconst body = await response.text().catch(() => \"\");\n\t\tthrow new Error(\n\t\t\t`Resend API error (${response.status}): ${body.slice(0, 200)}`,\n\t\t);\n\t}\n\n\treturn { skipped: false };\n}\n",
9
9
  "import { logger } from \"../logger.ts\";\nimport { renderEmail } from \"./render.ts\";\nimport { sendEmail } from \"./send.ts\";\n\nexport type ContactVolume =\n\t| \"lt10m\"\n\t| \"10m-100m\"\n\t| \"100m-1b\"\n\t| \"gt1b\"\n\t| \"unsure\";\n\nconst VOLUME_LABELS: Record<ContactVolume, string> = {\n\tlt10m: \"under 10M rows/mo\",\n\t\"10m-100m\": \"10M–100M rows/mo\",\n\t\"100m-1b\": \"100M–1B rows/mo\",\n\tgt1b: \"over 1B rows/mo\",\n\tunsure: \"volume not sure\",\n};\n\nexport interface ContactMessage {\n\tname: string;\n\temail: string;\n\tcompany: string | null;\n\tvolume: ContactVolume | null;\n\tmessage: string;\n\tsource_page: string | null;\n}\n\n/**\n * Emails the operator (`CONTACT_NOTIFY_EMAIL`) about a stored contact\n * request and reports whether the message went out. Used by the route that\n * stores the row and by the worker that retries rows still unnotified.\n */\nexport async function notifyContact(\n\tid: string,\n\trow: ContactMessage,\n): Promise<boolean> {\n\tconst to = process.env.CONTACT_NOTIFY_EMAIL?.trim();\n\tif (!to) {\n\t\tlogger.info(\"contact.notify_skipped\", { id, reason: \"no notify address\" });\n\t\treturn false;\n\t}\n\tconst volumeLabel = row.volume\n\t\t? VOLUME_LABELS[row.volume]\n\t\t: \"volume not given\";\n\tconst reference = `ctc_${id.slice(0, 6)}`;\n\tconst { html, text } = renderEmail({\n\t\theading: \"New contact request\",\n\t\tpreheader: row.message.slice(0, 90),\n\t\tparagraphs: [],\n\t\tquote: row.message,\n\t\tfigure: `contact · ${reference}`,\n\t\tfacts: [\n\t\t\t{ label: \"Name\", value: row.name },\n\t\t\t{ label: \"Email\", value: row.email },\n\t\t\t{ label: \"Company\", value: row.company ?? \"not given\" },\n\t\t\t{ label: \"Volume\", value: volumeLabel },\n\t\t\t{ label: \"From page\", value: row.source_page ?? \"not given\" },\n\t\t\t{ label: \"Reference\", value: reference },\n\t\t],\n\t\tfootnote: `Reply to this email to answer ${row.name.split(/\\s+/)[0]}.`,\n\t});\n\ttry {\n\t\tconst result = await sendEmail({\n\t\t\tto,\n\t\t\treplyTo: row.email,\n\t\t\tsubject: `Contact: ${row.company ?? row.name} · ${volumeLabel}`,\n\t\t\thtml,\n\t\t\ttext,\n\t\t});\n\t\tif (result.skipped) {\n\t\t\tlogger.info(\"contact.notify_skipped\", { id, reason: \"no email key\" });\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t} catch (err) {\n\t\tlogger.error(\"contact.notify_failed\", {\n\t\t\tid,\n\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t});\n\t\treturn false;\n\t}\n}\n",
10
10
  "import { renderEmail } from \"./render.ts\";\n\n/**\n * The email updates list: sender, links and the double opt-in email. Every\n * list email must carry `unsubscribeFor(token)` (footer link plus the\n * RFC 8058 headers Gmail and Yahoo require from bulk senders).\n */\n\nexport const UPDATES_FROM = \"Secondlayer <dev@secondlayer.tools>\";\nexport const UPDATES_SITE_URL = \"https://www.secondlayer.tools\";\nexport const UPDATES_API_URL = \"https://api.secondlayer.tools\";\n\n/** Footer link (a web page that unsubscribes on load) and one-click headers. */\nexport function unsubscribeFor(token: string): {\n\turl: string;\n\theaders: Record<string, string>;\n} {\n\tconst t = encodeURIComponent(token);\n\treturn {\n\t\turl: `${UPDATES_SITE_URL}/updates/unsubscribe?t=${t}`,\n\t\theaders: {\n\t\t\t\"List-Unsubscribe\": `<${UPDATES_API_URL}/api/public/updates/unsubscribe?t=${t}>`,\n\t\t\t\"List-Unsubscribe-Post\": \"List-Unsubscribe=One-Click\",\n\t\t},\n\t};\n}\n\n/**\n * The double opt-in email. No unsubscribe link or headers: the address is\n * not on the list until it confirms.\n */\nexport function confirmEmail(token: string): {\n\tsubject: string;\n\thtml: string;\n\ttext: string;\n} {\n\tconst subject = \"Confirm your secondlayer subscription\";\n\tconst { html, text } = renderEmail({\n\t\theading: \"Confirm your email\",\n\t\tpreheader: \"One click and new posts and launches come to this inbox.\",\n\t\tparagraphs: [\n\t\t\t\"Confirm and we'll email you when we publish a post or ship something new. Nothing else, and every email has a one-click unsubscribe.\",\n\t\t],\n\t\tcta: {\n\t\t\tlabel: \"Confirm subscription\",\n\t\t\turl: `${UPDATES_SITE_URL}/updates/confirm?t=${encodeURIComponent(token)}`,\n\t\t},\n\t\tfootnote:\n\t\t\t\"Someone entered this address at secondlayer.tools/blog. If it wasn't you, ignore this email and you won't hear from us. The link works for 7 days.\",\n\t});\n\treturn { subject, html, text };\n}\n"
11
11
  ],
12
- "mappings": ";AAAA;AAGA,IAAM,iBAAiB,EAAE,OAAO,EAAE,UAAU,CAAC,QAAQ;AAAA,EACpD,MAAM,WAAW,IACf,MAAM,GAAG,EACT,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EACnB,OAAO,OAAO;AAAA,EAChB,MAAM,QAAQ,CAAC,WAAW,SAAS;AAAA,EACnC,WAAW,KAAK,UAAU;AAAA,IACzB,IAAI,CAAC,MAAM,SAAS,CAAC,GAAG;AAAA,MACvB,MAAM,IAAI,MACT,oBAAoB,sBAAsB,MAAM,KAAK,IAAI,GAC1D;AAAA,IACD;AAAA,EACD;AAAA,EACA,OAAO;AAAA,CACP;AAsBD,IAAM,YAAwC,EAAE,OAAO;AAAA,EACtD,cAAc,EAAE,WACf,CAAC,QAAS,OAAO,QAAQ,YAAY,IAAI,WAAW,IAAI,YAAY,KACpE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,CAC3B;AAAA,EACA,qBAAqB,EAAE,WACtB,CAAC,QAAS,OAAO,QAAQ,YAAY,IAAI,WAAW,IAAI,YAAY,KACpE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,CAC3B;AAAA,EACA,qBAAqB,EAAE,WACtB,CAAC,QAAS,OAAO,QAAQ,YAAY,IAAI,WAAW,IAAI,YAAY,KACpE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,CAC3B;AAAA,EACA,SAAS,EAAE,KAAK,CAAC,WAAW,SAAS,CAAC,EAAE,SAAS;AAAA,EACjD,UAAU,eAAe,SAAS;AAAA,EAClC,WAAW,EAAE,KAAK,CAAC,SAAS,Q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yB;AAAA,MACrC;AAAA,MACA,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA,IACvD,CAAC;AAAA,IACD,OAAO;AAAA;AAAA;;ACxEF,IAAM,eAAe;AACrB,IAAM,mBAAmB;AACzB,IAAM,kBAAkB;AAGxB,SAAS,cAAc,CAAC,OAG7B;AAAA,EACD,MAAM,IAAI,mBAAmB,KAAK;AAAA,EAClC,OAAO;AAAA,IACN,KAAK,GAAG,0CAA0C;AAAA,IAClD,SAAS;AAAA,MACR,oBAAoB,IAAI,oDAAoD;AAAA,MAC5E,yBAAyB;AAAA,IAC1B;AAAA,EACD;AAAA;AAOM,SAAS,YAAY,CAAC,OAI3B;AAAA,EACD,MAAM,UAAU;AAAA,EAChB,QAAQ,MAAM,SAAS,YAAY;AAAA,IAClC,SAAS;AAAA,IACT,WAAW;AAAA,IACX,YAAY;AAAA,MACX;AAAA,IACD;AAAA,IACA,KAAK;AAAA,MACJ,OAAO;AAAA,MACP,KAAK,GAAG,sCAAsC,mBAAmB,KAAK;AAAA,IACvE;AAAA,IACA,UACC;AAAA,EACF,CAAC;AAAA,EACD,OAAO,EAAE,SAAS,MAAM,KAAK;AAAA;",
13
+ "debugId": "71D615692693B5AC64756E2164756E21",
14
14
  "names": []
15
15
  }
package/dist/src/env.d.ts CHANGED
@@ -22,6 +22,13 @@ type Env = EnvSchemaOutput & {
22
22
  };
23
23
  declare function getEnv(): Env;
24
24
  /**
25
+ * The Stacks network this process serves, and the only place that decides it:
26
+ * `STACKS_NETWORK`, else the deprecated `NETWORK` (warned once so a deployment
27
+ * that only sets it is not silently re-keyed), else mainnet. Not validated;
28
+ * `instanceNetworkFromEnv` is the strict form.
29
+ */
30
+ declare function stacksNetwork(env?: NodeJS.ProcessEnv): string;
31
+ /**
25
32
  * True when `NODE_ENV=production`, read at RUNTIME — the single source of truth
26
33
  * for prod-vs-dev branching in this package.
27
34
  *
@@ -52,4 +59,4 @@ declare function isPox5DecoderEnabled(env?: EnvMap): boolean;
52
59
  declare function isSbtcDecoderEnabled(env?: EnvMap): boolean;
53
60
  /** Default OFF. Opt in with `BNS_DECODER_ENABLED=true`. */
54
61
  declare function isBnsDecoderEnabled(env?: EnvMap): boolean;
55
- export { Env, envSchema, getEnv, isBnsDecoderEnabled, isPox4DecoderEnabled, isPox5DecoderEnabled, isProductionEnv, isSbtcDecoderEnabled };
62
+ export { Env, envSchema, getEnv, isBnsDecoderEnabled, isPox4DecoderEnabled, isPox5DecoderEnabled, isProductionEnv, isSbtcDecoderEnabled, stacksNetwork };
package/dist/src/env.js CHANGED
@@ -36,11 +36,25 @@ function getEnv() {
36
36
  } else if (result.data.NETWORK) {
37
37
  enabledNetworks = [result.data.NETWORK];
38
38
  } else {
39
- enabledNetworks = ["mainnet"];
39
+ const named = stacksNetwork();
40
+ enabledNetworks = named === "testnet" ? ["testnet"] : ["mainnet"];
40
41
  }
41
42
  cachedEnv = { ...result.data, enabledNetworks };
42
43
  return cachedEnv;
43
44
  }
45
+ var warnedNetworkFallback = false;
46
+ function stacksNetwork(env = process.env) {
47
+ if (env.STACKS_NETWORK)
48
+ return env.STACKS_NETWORK;
49
+ if (env.NETWORK) {
50
+ if (!warnedNetworkFallback) {
51
+ warnedNetworkFallback = true;
52
+ console.warn("NETWORK is deprecated: set STACKS_NETWORK instead");
53
+ }
54
+ return env.NETWORK;
55
+ }
56
+ return "mainnet";
57
+ }
44
58
  function isProductionEnv() {
45
59
  return process.env["NODE_ENV"] === "production";
46
60
  }
@@ -63,8 +77,9 @@ export {
63
77
  isPox4DecoderEnabled,
64
78
  isPox5DecoderEnabled,
65
79
  isProductionEnv,
66
- isSbtcDecoderEnabled
80
+ isSbtcDecoderEnabled,
81
+ stacksNetwork
67
82
  };
68
83
 
69
- //# debugId=09269FBBCC4C7B6B64756E2164756E21
84
+ //# debugId=5CAECF233D46AD1C64756E2164756E21
70
85
  //# sourceMappingURL=env.js.map