@secondlayer/sdk 10.0.0 → 10.1.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.
@@ -1,4 +1,3 @@
1
- import { Kysely, Transaction } from "kysely";
2
1
  /**
3
2
  * A consumer sink: the destination adapter a consume loop writes through.
4
3
  *
@@ -121,6 +120,14 @@ interface ConsumerSink<Tx = unknown> {
121
120
  */
122
121
  rollback(forkPointHeight: number, rewindCursor: string | null): Promise<void>;
123
122
  }
123
+ /** Context handed to {@link CreateSinkOptions.onRollback}. `forkPointHeight`
124
+ * is the undo range (inclusive `>=`); `rewindCursor` is what the checkpoint
125
+ * will become after this transaction — `null` only for a fork at genesis. */
126
+ type SinkRollbackContext = {
127
+ forkPointHeight: number;
128
+ rewindCursor: string | null;
129
+ };
130
+ import { Kysely, Transaction } from "kysely";
124
131
  /**
125
132
  * Column present on EVERY declared table — `keyof` a union of row types is
126
133
  * the intersection of their keys, so a column missing from any one table is
@@ -144,18 +151,22 @@ interface KyselySinkOptions<
144
151
  id: string;
145
152
  /** Rollback scope. On a reorg, rows AT OR ABOVE the fork point are deleted
146
153
  * from exactly these tables (inclusive `>=` — the new chain re-supplies
147
- * the fork block). A table you write but don't declare keeps orphaned
148
- * rows forever, so declare everything the handler touches. */
154
+ * the fork block). Fact tables only: a fold (balances, counters) does
155
+ * not belong here — invert it in `onRollback`. A table you write but
156
+ * don't declare keeps orphaned rows forever. */
149
157
  tables: readonly T[];
150
158
  /** The block-height stamp column, present on every declared table (compile
151
159
  * and first-use checked). Height-stamp rollback is correct for
152
- * APPEND-ONLY projections (one row per event/call); aggregates that
153
- * mutate rows (balances, counters) can't be rolled back this way — use a
154
- * subgraph for those. */
160
+ * append-only projections (one row per event/call). */
155
161
  height: CommonColumn<DB, T>;
156
162
  /** Checkpoint table name. Default `sl_consumer_checkpoints` (created on
157
163
  * first use). */
158
164
  checkpointTable?: string;
165
+ /** Same transaction as the fact-table delete, before it. Doomed rows are
166
+ * still visible; remaining facts are `height < forkPointHeight`. A throw
167
+ * aborts the rewind. Derive undo from the doomed rows so a re-applied
168
+ * rollback is a no-op. */
169
+ onRollback?: (tx: Transaction<DB>, ctx: SinkRollbackContext) => Promise<void> | void;
159
170
  }
160
171
  /**
161
172
  * A {@link ConsumerSink} over a Kysely Postgres database — keyed on the
@@ -168,9 +179,10 @@ interface KyselySinkOptions<
168
179
  * - rows AND cursor committed in ONE transaction per batch — a handler
169
180
  * throw aborts both, so a crashed batch is re-read on restart with no
170
181
  * gaps and no double-writes;
171
- * - reorg rollback: delete `>= fork_point_height` from every declared table
172
- * and commit the rewound cursor atomically (the crash-between-the-two-
173
- * writes gap is unrepresentable);
182
+ * - reorg rollback: `onRollback` (doomed facts still visible), then delete
183
+ * `>= fork_point_height` from every declared table, then the rewound
184
+ * cursor — one transaction (the crash-between-the-two-writes gap is
185
+ * unrepresentable);
174
186
  * - a per-id advisory lock, so two replicas of the same consumer can't
175
187
  * interleave commits.
176
188
  *
@@ -193,4 +205,4 @@ declare function kyselySink<
193
205
  DB,
194
206
  T extends keyof DB & string
195
207
  >(db: Kysely<DB>, options: KyselySinkOptions<DB, T>): ConsumerSink<Transaction<DB>>;
196
- export { kyselySink, KyselySinkOptions };
208
+ export { kyselySink, SinkRollbackContext, KyselySinkOptions };
@@ -163,6 +163,7 @@ function createSink(driver, options) {
163
163
  async rollback(forkPointHeight, rewindCursor) {
164
164
  await driver.transact(async (tx) => {
165
165
  await driver.acquireLock?.(tx);
166
+ await options.onRollback?.(tx, { forkPointHeight, rewindCursor });
166
167
  for (const table of options.tables) {
167
168
  await driver.deleteAtOrAbove(tx, table, forkPointHeight);
168
169
  }
@@ -240,12 +241,13 @@ function kyselySink(db, options) {
240
241
  id: options.id,
241
242
  tables: options.tables,
242
243
  height: options.height,
243
- checkpointTable
244
+ checkpointTable,
245
+ onRollback: options.onRollback
244
246
  });
245
247
  }
246
248
  export {
247
249
  kyselySink
248
250
  };
249
251
 
250
- //# debugId=0DA2509BB96D9F1A64756E2164756E21
252
+ //# debugId=4C5BB7B77B93BD5664756E2164756E21
251
253
  //# sourceMappingURL=kysely.js.map
@@ -3,10 +3,10 @@
3
3
  "sources": ["src/errors.ts", "src/sinks/core.ts", "src/sinks/kysely.ts"],
4
4
  "sourcesContent": [
5
5
  "const DOCS_BASE = \"https://www.secondlayer.tools\";\n\n/** Options accepted by every error in the family. */\nexport interface SecondLayerErrorOptions {\n\tcause?: Error;\n\tdetails?: string;\n\t/** Stable machine-readable code (e.g. `UPGRADE_REQUIRED`). */\n\tcode?: string;\n\t/** Docs page that explains this failure and its fix. */\n\tdocsUrl?: string;\n\t/** Extra context lines appended to the message (DDL to run, next steps). */\n\tmetaMessages?: string[];\n\t/** Whether retrying the SAME request can succeed (429/5xx/network). */\n\tretryable?: boolean;\n\t/** Parsed `Retry-After`, in seconds — set on rate limits that carry it. */\n\tretryAfterSeconds?: number;\n}\n\n/**\n * Root of the SDK error family. Implements the same protocol as `BaseError`\n * in `@secondlayer/stacks` (`shortMessage`, `cause`, `toJSON`) so a failed\n * chain read and a failed platform read serialize and introspect identically.\n * It intentionally does NOT extend that class: cross-package `instanceof` is\n * unreliable under per-package bundling anyway (match on `code`/`name` across\n * packages).\n *\n * `retryable` is the signal the consume loops act on: 429/5xx/network are\n * retryable, 4xx and body-serialization failures are not.\n */\nexport class SecondLayerError extends Error {\n\toverride name = \"SecondLayerError\";\n\t/** The one-line failure, without the appended context blocks. */\n\tshortMessage: string;\n\tcode?: string;\n\tdocsUrl?: string;\n\tmetaMessages?: string[];\n\tretryable: boolean;\n\tretryAfterSeconds?: number;\n\n\tconstructor(shortMessage: string, options: SecondLayerErrorOptions = {}) {\n\t\tconst detailBlocks = [\n\t\t\t...(options.metaMessages ?? []),\n\t\t\t...(options.details ? [options.details] : []),\n\t\t\t...(options.docsUrl ? [`Docs: ${options.docsUrl}`] : []),\n\t\t];\n\t\tconst message = [\n\t\t\tshortMessage,\n\t\t\tdetailBlocks.length > 0 ? `\\n${detailBlocks.join(\"\\n\")}` : \"\",\n\t\t].join(\"\");\n\t\tsuper(message, options.cause ? { cause: options.cause } : undefined);\n\t\tthis.shortMessage = shortMessage;\n\t\tthis.code = options.code;\n\t\tthis.docsUrl = options.docsUrl;\n\t\tthis.metaMessages = options.metaMessages;\n\t\tthis.retryable = options.retryable ?? false;\n\t\tthis.retryAfterSeconds = options.retryAfterSeconds;\n\t}\n\n\t/**\n\t * Walk the cause chain. With a predicate, returns the first error matching\n\t * it (or `null`); without one, returns the deepest cause. Mirrors viem's\n\t * `error.walk()` so cross-library error handling reads the same.\n\t */\n\twalk(fn?: (err: unknown) => boolean): unknown {\n\t\t// biome-ignore lint/suspicious/noExplicitAny: cause chains are untyped by nature\n\t\tlet err: any = this;\n\t\tlet last: unknown = this;\n\t\twhile (err != null) {\n\t\t\tif (fn?.(err)) return err;\n\t\t\tlast = err;\n\t\t\terr = err.cause;\n\t\t}\n\t\treturn fn ? null : last;\n\t}\n\n\ttoJSON(): {\n\t\tname: string;\n\t\tmessage: string;\n\t\tshortMessage: string;\n\t\tcause: string | undefined;\n\t\tcode: string | undefined;\n\t\tdocsUrl: string | undefined;\n\t\tretryable: boolean;\n\t\tretryAfterSeconds: number | undefined;\n\t} {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tmessage: this.message,\n\t\t\tshortMessage: this.shortMessage,\n\t\t\tcause: this.cause instanceof Error ? this.cause.message : undefined,\n\t\t\tcode: this.code,\n\t\t\tdocsUrl: this.docsUrl,\n\t\t\tretryable: this.retryable,\n\t\t\tretryAfterSeconds: this.retryAfterSeconds,\n\t\t};\n\t}\n}\n\n/** Retryability of an HTTP status: 429 and 5xx are transient. */\nfunction statusRetryable(status: number): boolean {\n\treturn status === 429 || status >= 500;\n}\n\n/** Docs page for a status/code pair, when one exists. */\nfunction docsFor(status: number, code?: string): string | undefined {\n\tif (code === \"UPGRADE_REQUIRED\" || status === 402)\n\t\treturn `${DOCS_BASE}/docs/authentication#pay-as-you-go-credits`;\n\tif (status === 429 || status === 401)\n\t\treturn `${DOCS_BASE}/docs/authentication`;\n\treturn undefined;\n}\n\n/**\n * Error thrown by {@link SecondLayer} when an API request fails.\n * Includes the HTTP status code for programmatic error handling.\n *\n * @example\n * ```ts\n * try {\n * await client.subgraphs.status(\"my-subgraph\");\n * } catch (err) {\n * if (err instanceof ApiError && err.status === 404) {\n * console.log(\"Subgraph not found\");\n * }\n * }\n * ```\n */\nexport class ApiError extends SecondLayerError {\n\tconstructor(\n\t\t/** HTTP status code (0 for network errors). */\n\t\tpublic status: number,\n\t\tmessage: string,\n\t\t/** Raw response body (parsed JSON if possible) — preserved for callers that need error details. */\n\t\tpublic body?: unknown,\n\t\t/** Stable machine-readable code from the API's `{error, code}` error envelope. */\n\t\tcode?: string,\n\t\toptions: SecondLayerErrorOptions = {},\n\t) {\n\t\tsuper(message, {\n\t\t\tcode,\n\t\t\tretryable: options.retryable ?? statusRetryable(status),\n\t\t\tdocsUrl: options.docsUrl ?? docsFor(status, code),\n\t\t\t...(options.cause ? { cause: options.cause } : {}),\n\t\t\t...(options.details ? { details: options.details } : {}),\n\t\t\t...(options.metaMessages ? { metaMessages: options.metaMessages } : {}),\n\t\t\t...(options.retryAfterSeconds !== undefined\n\t\t\t\t? { retryAfterSeconds: options.retryAfterSeconds }\n\t\t\t\t: {}),\n\t\t});\n\t\tthis.name = \"ApiError\";\n\t}\n}\n\n/** Thrown on a 401 by both the instance clients and Streams. Carries the\n * server's `{error, code}` envelope when it sent one, so a revoked token reads\n * differently from a missing one. */\nexport class AuthError extends ApiError {\n\toverride readonly status = 401 as const;\n\n\tconstructor(\n\t\tmessage = \"API key invalid or expired.\",\n\t\tbody?: unknown,\n\t\tcode?: string,\n\t) {\n\t\tsuper(401, message, body, code);\n\t\tthis.name = \"AuthError\";\n\t}\n}\n\n/** Thrown on a 429 by both the instance clients and Streams. `retryable`,\n * with `retryAfterSeconds` parsed from the `Retry-After` header when sent. */\nexport class RateLimitError extends ApiError {\n\toverride readonly status = 429 as const;\n\n\tconstructor(\n\t\tmessage = \"Rate limited. Try again later.\",\n\t\t/** Raw `Retry-After` header value (seconds or HTTP-date). */\n\t\treadonly retryAfter?: string,\n\t\tbody?: unknown,\n\t\tcode?: string,\n\t) {\n\t\tsuper(429, message, body, code, {\n\t\t\tretryable: true,\n\t\t\tretryAfterSeconds: parseRetryAfter(retryAfter),\n\t\t});\n\t\tthis.name = \"RateLimitError\";\n\t}\n}\n\n/** Thrown on a 4xx the caller can fix (bad cursor, bad params). Never retried.\n * `code` is the server's machine-readable code when the envelope carried one. */\nexport class ValidationError extends ApiError {\n\tconstructor(message: string, status: number, body?: unknown, code?: string) {\n\t\tsuper(status, message, body, code, { retryable: false });\n\t\tthis.name = \"ValidationError\";\n\t}\n}\n\n/** Parse a `Retry-After` header: delta-seconds or an HTTP-date. */\nexport function parseRetryAfter(value?: string | null): number | undefined {\n\tif (!value) return undefined;\n\tconst seconds = Number(value);\n\tif (Number.isFinite(seconds) && seconds >= 0) return seconds;\n\tconst date = Date.parse(value);\n\tif (!Number.isNaN(date)) return Math.max(0, (date - Date.now()) / 1000);\n\treturn undefined;\n}\n",
6
- "import { ValidationError } from \"../errors.ts\";\nimport type { ConsumerSink } from \"./types.ts\";\n\n/** Default checkpoint table name, shared by every SQL-backed sink so two\n * sinks on the same database land in one table keyed by `id`. */\nexport const DEFAULT_CHECKPOINT_TABLE = \"sl_consumer_checkpoints\";\n\n/**\n * The driver surface a database adapter implements — the ~7 methods that\n * actually differ between SQL stores. Everything above them (the\n * commit/rollback call sequences, the guards, identifier validation, the\n * checkpoint schema) is policy owned by {@link createSink}, so a driver\n * cannot get the ordering wrong: it never sees a cursor write outside the\n * transaction that carries the rows, and never sees a delete without the\n * rewound cursor riding along.\n *\n * Identifier args (`table`, `column`) arrive pre-validated against\n * `[A-Za-z_][A-Za-z0-9_]*` — safe to interpolate after quoting (see\n * {@link quoteIdent}). Values (cursor, height, id) must still be bound as\n * parameters.\n */\nexport interface SinkDriver<Tx> {\n\t/** Run `fn` inside ONE transaction: begin, run, commit — a throw from\n\t * `fn` must roll the whole transaction back and re-throw. */\n\ttransact<T>(fn: (tx: Tx) => Promise<T>): Promise<T>;\n\t/** Create the checkpoint store if missing: `(id primary key, cursor)`.\n\t * Must be safe under concurrent first start (two consumers racing the\n\t * same CREATE). */\n\tensureCheckpointStore(): Promise<void>;\n\t/** The committed cursor for this sink's `id`, or `null` if none. */\n\treadCursor(): Promise<string | null>;\n\t/** Upsert this sink's cursor row inside `tx`. */\n\twriteCursor(tx: Tx, cursor: string): Promise<void>;\n\t/** Delete this sink's cursor row inside `tx`: a rewind to pre-genesis\n\t * (fork at block 0). Optional for drivers written before it existed;\n\t * without it a genesis rewind throws instead of writing a bad cursor. */\n\tclearCursor?(tx: Tx): Promise<void>;\n\t/** Delete rows with `height column >= height` from `table`, inside `tx`. */\n\tdeleteAtOrAbove(tx: Tx, table: string, height: number): Promise<void>;\n\t/** Whether `table` exists AND carries `column` — the first-use check that\n\t * keeps reorg rollback from being a silent no-op. */\n\thasColumn(table: string, column: string): Promise<boolean>;\n\t/** Optional: assert this consumer is the only live writer for its `id`,\n\t * inside `tx`. Must FAIL LOUDLY (throw) when another writer holds it —\n\t * never block or interleave (contract invariant #13). */\n\tacquireLock?(tx: Tx): Promise<void>;\n}\n\n/** Options for {@link createSink} — the policy inputs, driver-agnostic.\n * Concrete sinks re-expose these with schema-typed `tables`/`height`. */\nexport interface CreateSinkOptions {\n\t/** Error-message prefix naming the concrete sink (e.g. `\"kyselySink\"`),\n\t * so a thrown guard points at the thing the user actually constructed. */\n\tlabel: string;\n\t/** Checkpoint identity AND concurrency key. */\n\tid: string;\n\t/** Rollback scope: on a reorg, rows at/above the fork point are deleted\n\t * from exactly these tables. */\n\ttables: readonly string[];\n\t/** The block-height stamp column, present on every declared table. */\n\theight: string;\n\t/** Checkpoint table name. Default {@link DEFAULT_CHECKPOINT_TABLE}. */\n\tcheckpointTable?: string;\n\t/** Forwarded to {@link ConsumerSink.capabilities}. */\n\tcapabilities?: ConsumerSink[\"capabilities\"];\n}\n\n/** Throw unless `name` is a bare SQL identifier (letters, digits,\n * underscores; no leading digit) — the guard that makes interpolating\n * table/column names into DDL and DELETE statements safe. */\nexport function assertSqlIdentifier(name: string, label: string): void {\n\tif (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {\n\t\tthrow new ValidationError(\n\t\t\t`${label}: invalid identifier \"${name}\" (letters, digits, underscores only).`,\n\t\t\t400,\n\t\t);\n\t}\n}\n\n/** Double-quote a (pre-validated) identifier for interpolation. */\nexport function quoteIdent(name: string): string {\n\treturn `\"${name}\"`;\n}\n\n/**\n * Build a {@link ConsumerSink} from a {@link SinkDriver}: the portable ~90\n * lines every SQL sink otherwise re-implements — and re-risks. Owns the two\n * transaction sequences (begin → lock → write rows → write cursor;\n * begin → lock → delete `>=` fork → write rewound cursor), the empty-`tables`\n * guard, identifier validation, and the first-use height-column check.\n *\n * A driver implemented against this base cannot violate contract invariants\n * #4, #5, #8, #9, or #11 (see {@link ConsumerSink}) without breaking\n * `transact` itself — which is exactly what the conformance kit probes.\n */\nexport function createSink<Tx>(\n\tdriver: SinkDriver<Tx>,\n\toptions: CreateSinkOptions,\n): ConsumerSink<Tx> {\n\tconst { label } = options;\n\tconst checkpointTable = options.checkpointTable ?? DEFAULT_CHECKPOINT_TABLE;\n\tif (options.tables.length === 0) {\n\t\tthrow new ValidationError(\n\t\t\t`${label}: \\`tables\\` is empty — declare every table the handler writes, or reorg rollback is a no-op and orphaned rows persist forever.`,\n\t\t\t400,\n\t\t);\n\t}\n\tassertSqlIdentifier(checkpointTable, label);\n\tassertSqlIdentifier(options.height, label);\n\tfor (const table of options.tables) assertSqlIdentifier(table, label);\n\n\treturn {\n\t\tcapabilities: options.capabilities,\n\n\t\tasync loadCursor() {\n\t\t\tawait driver.ensureCheckpointStore();\n\t\t\t// First-use validation of the rollback precondition: every declared\n\t\t\t// table must exist and carry the height column. Failing here beats a\n\t\t\t// rollback that silently deletes nothing during a reorg.\n\t\t\tfor (const table of options.tables) {\n\t\t\t\tif (!(await driver.hasColumn(table, options.height))) {\n\t\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t\t`${label}: table \"${table}\" has no \"${options.height}\" column — the height stamp is what makes reorg rollback possible. Add the column (or fix \\`height\\`).`,\n\t\t\t\t\t\t400,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn driver.readCursor();\n\t\t},\n\n\t\tasync commitBatch(cursor, write) {\n\t\t\tawait driver.transact(async (tx) => {\n\t\t\t\tawait driver.acquireLock?.(tx);\n\t\t\t\tawait write(tx);\n\t\t\t\tawait driver.writeCursor(tx, cursor);\n\t\t\t});\n\t\t},\n\n\t\tasync rollback(forkPointHeight, rewindCursor) {\n\t\t\tawait driver.transact(async (tx) => {\n\t\t\t\tawait driver.acquireLock?.(tx);\n\t\t\t\t// INCLUSIVE of the fork block: the new canonical chain re-supplies\n\t\t\t\t// it, and the consumer rewinds to re-read from `fork:0`.\n\t\t\t\tfor (const table of options.tables) {\n\t\t\t\t\tawait driver.deleteAtOrAbove(tx, table, forkPointHeight);\n\t\t\t\t}\n\t\t\t\tif (rewindCursor === null) {\n\t\t\t\t\tif (!driver.clearCursor) {\n\t\t\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t\t\t`${label}: this driver has no clearCursor, so a rewind to pre-genesis cannot be committed. Add clearCursor to the driver, or resume with an explicit fromCursor.`,\n\t\t\t\t\t\t\t400,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tawait driver.clearCursor(tx);\n\t\t\t\t} else {\n\t\t\t\t\tawait driver.writeCursor(tx, rewindCursor);\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t};\n}\n",
7
- "import { type Kysely, type Transaction, sql } from \"kysely\";\nimport { ValidationError } from \"../errors.ts\";\nimport {\n\tDEFAULT_CHECKPOINT_TABLE,\n\ttype SinkDriver,\n\tcreateSink,\n\tquoteIdent,\n} from \"./core.ts\";\nimport type { ConsumerSink } from \"./types.ts\";\n\n/**\n * Column present on EVERY declared table — `keyof` a union of row types is\n * the intersection of their keys, so a column missing from any one table is\n * a compile error at the `height:` option.\n */\ntype CommonColumn<DB, T extends keyof DB> = keyof DB[T] & string;\n\nexport interface KyselySinkOptions<DB, T extends keyof DB & string> {\n\t/** Checkpoint identity AND concurrency key: the cursor row's primary key,\n\t * and the input to `pg_try_advisory_xact_lock(hashtextextended(id, 0))`.\n\t * The lock is transaction-scoped: it stops two replicas from\n\t * INTERLEAVING inside a commit, but is released at each commit boundary\n\t * — it is NOT a fence, so two replicas alternating batches both pass.\n\t * Run exactly one consumer per id; the lock turns the racy overlap loud,\n\t * it does not make a second replica safe. */\n\tid: string;\n\t/** Rollback scope. On a reorg, rows AT OR ABOVE the fork point are deleted\n\t * from exactly these tables (inclusive `>=` — the new chain re-supplies\n\t * the fork block). A table you write but don't declare keeps orphaned\n\t * rows forever, so declare everything the handler touches. */\n\ttables: readonly T[];\n\t/** The block-height stamp column, present on every declared table (compile\n\t * and first-use checked). Height-stamp rollback is correct for\n\t * APPEND-ONLY projections (one row per event/call); aggregates that\n\t * mutate rows (balances, counters) can't be rolled back this way — use a\n\t * subgraph for those. */\n\theight: CommonColumn<DB, T>;\n\t/** Checkpoint table name. Default `sl_consumer_checkpoints` (created on\n\t * first use). */\n\tcheckpointTable?: string;\n}\n\n/**\n * A {@link ConsumerSink} over a Kysely Postgres database — keyed on the\n * QUERY BUILDER (not the driver) so the `DB` schema generic flows through:\n * `tables` is `(keyof DB)[]`, `height` must exist on every declared table,\n * and `ctx.tx` inside `onBatch` is a fully typed `Transaction<DB>`.\n *\n * What it owns (so your indexer doesn't):\n * - the checkpoint table + cursor load on start;\n * - rows AND cursor committed in ONE transaction per batch — a handler\n * throw aborts both, so a crashed batch is re-read on restart with no\n * gaps and no double-writes;\n * - reorg rollback: delete `>= fork_point_height` from every declared table\n * and commit the rewound cursor atomically (the crash-between-the-two-\n * writes gap is unrepresentable);\n * - a per-id advisory lock, so two replicas of the same consumer can't\n * interleave commits.\n *\n * Structurally it is a 7-method {@link SinkDriver} on the shared\n * `createSink` base (`@secondlayer/sdk/sinks/core`), which owns the\n * transaction sequences and guards — this file only knows how to speak\n * Postgres-flavored Kysely.\n *\n * ```ts\n * const sink = kyselySink(db, { id: \"sales\", tables: [\"sales\"], height: \"block_height\" });\n * await index.contractCalls.consume({\n * contractId: MARKETPLACE, functionName: \"purchase-asset\", fromHeight: 0,\n * sink,\n * onBatch: (calls, _env, ctx) =>\n * ctx.tx.insertInto(\"sales\").values(calls.map(toSale)).execute(),\n * });\n * ```\n */\nexport function kyselySink<DB, T extends keyof DB & string>(\n\tdb: Kysely<DB>,\n\toptions: KyselySinkOptions<DB, T>,\n): ConsumerSink<Transaction<DB>> {\n\tconst checkpointTable = options.checkpointTable ?? DEFAULT_CHECKPOINT_TABLE;\n\tconst cp = quoteIdent(checkpointTable);\n\n\tconst driver: SinkDriver<Transaction<DB>> = {\n\t\ttransact: (fn) => db.transaction().execute(fn),\n\n\t\tasync ensureCheckpointStore() {\n\t\t\ttry {\n\t\t\t\tawait sql\n\t\t\t\t\t.raw(\n\t\t\t\t\t\t`CREATE TABLE IF NOT EXISTS ${cp} (id text PRIMARY KEY, cursor text NOT NULL)`,\n\t\t\t\t\t)\n\t\t\t\t\t.execute(db);\n\t\t\t} catch (err) {\n\t\t\t\t// Two consumers racing the same first start: IF NOT EXISTS still\n\t\t\t\t// throws under concurrency (42P07 duplicate_table, or 23505 on the\n\t\t\t\t// pg_type catalog). Either way the table exists — the outcome we\n\t\t\t\t// were creating.\n\t\t\t\tconst code = (err as { code?: string } | null)?.code;\n\t\t\t\tif (code !== \"42P07\" && code !== \"23505\") throw err;\n\t\t\t}\n\t\t},\n\n\t\tasync readCursor() {\n\t\t\tconst row = await sql<{ cursor: string }>`\n\t\t\t\tSELECT cursor FROM ${sql.raw(cp)} WHERE id = ${options.id}\n\t\t\t`.execute(db);\n\t\t\treturn row.rows[0]?.cursor ?? null;\n\t\t},\n\n\t\tasync writeCursor(tx, cursor) {\n\t\t\t// Identifiers via validated sql.raw; VALUES via bound parameters.\n\t\t\tawait sql`\n\t\t\t\tINSERT INTO ${sql.raw(cp)} (id, cursor) VALUES (${options.id}, ${cursor})\n\t\t\t\tON CONFLICT (id) DO UPDATE SET cursor = EXCLUDED.cursor\n\t\t\t`.execute(tx);\n\t\t},\n\n\t\tasync clearCursor(tx) {\n\t\t\tawait sql`DELETE FROM ${sql.raw(cp)} WHERE id = ${options.id}`.execute(\n\t\t\t\ttx,\n\t\t\t);\n\t\t},\n\n\t\tasync deleteAtOrAbove(tx, table, height) {\n\t\t\t// Identifiers via validated sql.raw; the height bound as a parameter.\n\t\t\tawait sql`\n\t\t\t\tDELETE FROM ${sql.raw(quoteIdent(table))}\n\t\t\t\tWHERE ${sql.raw(quoteIdent(options.height as string))} >= ${height}\n\t\t\t`.execute(tx);\n\t\t},\n\n\t\tasync hasColumn(table, column) {\n\t\t\tconst col = await sql<{ ok: boolean }>`\n\t\t\t\tSELECT EXISTS (\n\t\t\t\t\tSELECT 1 FROM information_schema.columns\n\t\t\t\t\tWHERE table_schema = current_schema()\n\t\t\t\t\t\tAND table_name = ${table} AND column_name = ${column}\n\t\t\t\t) AS \"ok\"\n\t\t\t`.execute(db);\n\t\t\treturn col.rows[0]?.ok ?? false;\n\t\t},\n\n\t\tasync acquireLock(tx) {\n\t\t\t// hashtextextended (int8), not hashtext (int4): the 32-bit space\n\t\t\t// collides across distinct ids at real scale, and a collision reads\n\t\t\t// as a false \"another consumer\" 409 between unrelated sinks.\n\t\t\tconst locked = await sql<{ ok: boolean }>`\n\t\t\t\tSELECT pg_try_advisory_xact_lock(hashtextextended(${options.id}, 0)) AS \"ok\"\n\t\t\t`.execute(tx);\n\t\t\tif (!locked.rows[0]?.ok) {\n\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t`kyselySink: another consumer holds the \"${options.id}\" lock — two replicas of the same consumer would interleave commits. Stop the other instance or use a distinct id.`,\n\t\t\t\t\t409,\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\t};\n\n\treturn createSink(driver, {\n\t\tlabel: \"kyselySink\",\n\t\tid: options.id,\n\t\ttables: options.tables,\n\t\theight: options.height as string,\n\t\tcheckpointTable,\n\t});\n}\n"
6
+ "import { ValidationError } from \"../errors.ts\";\nimport type { ConsumerSink } from \"./types.ts\";\n\n/** Default checkpoint table name, shared by every SQL-backed sink so two\n * sinks on the same database land in one table keyed by `id`. */\nexport const DEFAULT_CHECKPOINT_TABLE = \"sl_consumer_checkpoints\";\n\n/**\n * The driver surface a database adapter implements — the ~7 methods that\n * actually differ between SQL stores. Everything above them (the\n * commit/rollback call sequences, the guards, identifier validation, the\n * checkpoint schema) is policy owned by {@link createSink}, so a driver\n * cannot get the ordering wrong: it never sees a cursor write outside the\n * transaction that carries the rows, and never sees a delete without the\n * rewound cursor riding along.\n *\n * Identifier args (`table`, `column`) arrive pre-validated against\n * `[A-Za-z_][A-Za-z0-9_]*` — safe to interpolate after quoting (see\n * {@link quoteIdent}). Values (cursor, height, id) must still be bound as\n * parameters.\n */\nexport interface SinkDriver<Tx> {\n\t/** Run `fn` inside ONE transaction: begin, run, commit — a throw from\n\t * `fn` must roll the whole transaction back and re-throw. */\n\ttransact<T>(fn: (tx: Tx) => Promise<T>): Promise<T>;\n\t/** Create the checkpoint store if missing: `(id primary key, cursor)`.\n\t * Must be safe under concurrent first start (two consumers racing the\n\t * same CREATE). */\n\tensureCheckpointStore(): Promise<void>;\n\t/** The committed cursor for this sink's `id`, or `null` if none. */\n\treadCursor(): Promise<string | null>;\n\t/** Upsert this sink's cursor row inside `tx`. */\n\twriteCursor(tx: Tx, cursor: string): Promise<void>;\n\t/** Delete this sink's cursor row inside `tx`: a rewind to pre-genesis\n\t * (fork at block 0). Optional for drivers written before it existed;\n\t * without it a genesis rewind throws instead of writing a bad cursor. */\n\tclearCursor?(tx: Tx): Promise<void>;\n\t/** Delete rows with `height column >= height` from `table`, inside `tx`. */\n\tdeleteAtOrAbove(tx: Tx, table: string, height: number): Promise<void>;\n\t/** Whether `table` exists AND carries `column` — the first-use check that\n\t * keeps reorg rollback from being a silent no-op. */\n\thasColumn(table: string, column: string): Promise<boolean>;\n\t/** Optional: assert this consumer is the only live writer for its `id`,\n\t * inside `tx`. Must FAIL LOUDLY (throw) when another writer holds it —\n\t * never block or interleave (contract invariant #13). */\n\tacquireLock?(tx: Tx): Promise<void>;\n}\n\n/** Context handed to {@link CreateSinkOptions.onRollback}. `forkPointHeight`\n * is the undo range (inclusive `>=`); `rewindCursor` is what the checkpoint\n * will become after this transaction — `null` only for a fork at genesis. */\nexport type SinkRollbackContext = {\n\tforkPointHeight: number;\n\trewindCursor: string | null;\n};\n\n/** Options for {@link createSink} — the policy inputs, driver-agnostic.\n * Concrete sinks re-expose these with schema-typed `tables`/`height`. */\nexport interface CreateSinkOptions<Tx = unknown> {\n\t/** Error-message prefix naming the concrete sink (e.g. `\"kyselySink\"`),\n\t * so a thrown guard points at the thing the user actually constructed. */\n\tlabel: string;\n\t/** Checkpoint identity AND concurrency key. */\n\tid: string;\n\t/** Rollback scope: on a reorg, rows at/above the fork point are deleted\n\t * from exactly these tables. Fact tables only — a fold (balances,\n\t * counters) does not belong here; invert it in `onRollback`. */\n\ttables: readonly string[];\n\t/** The block-height stamp column, present on every declared table. */\n\theight: string;\n\t/** Checkpoint table name. Default {@link DEFAULT_CHECKPOINT_TABLE}. */\n\tcheckpointTable?: string;\n\t/** Forwarded to {@link ConsumerSink.capabilities}. */\n\tcapabilities?: ConsumerSink[\"capabilities\"];\n\t/** Runs inside the rollback transaction after the lock, before any\n\t * `DELETE … height >= fork`. Doomed fact rows are still visible.\n\t * Remaining facts are `height < forkPointHeight`. A throw aborts the\n\t * whole rewind (no delete, no cursor write). Called on every\n\t * `rollback`, including re-application after a crash — derive undo\n\t * from the doomed rows so a second pass is a no-op. */\n\tonRollback?: (tx: Tx, ctx: SinkRollbackContext) => Promise<void> | void;\n}\n\n/** Throw unless `name` is a bare SQL identifier (letters, digits,\n * underscores; no leading digit) — the guard that makes interpolating\n * table/column names into DDL and DELETE statements safe. */\nexport function assertSqlIdentifier(name: string, label: string): void {\n\tif (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {\n\t\tthrow new ValidationError(\n\t\t\t`${label}: invalid identifier \"${name}\" (letters, digits, underscores only).`,\n\t\t\t400,\n\t\t);\n\t}\n}\n\n/** Double-quote a (pre-validated) identifier for interpolation. */\nexport function quoteIdent(name: string): string {\n\treturn `\"${name}\"`;\n}\n\n/**\n * Build a {@link ConsumerSink} from a {@link SinkDriver}: the portable ~90\n * lines every SQL sink otherwise re-implements — and re-risks. Owns the two\n * transaction sequences (begin → lock → write rows → write cursor;\n * begin → lock → onRollback? → delete `>=` fork → write rewound cursor), the\n * empty-`tables` guard, identifier validation, and the first-use height-column\n * check.\n *\n * A driver implemented against this base cannot violate contract invariants\n * #4, #5, #8, #9, or #11 (see {@link ConsumerSink}) without breaking\n * `transact` itself — which is exactly what the conformance kit probes.\n */\nexport function createSink<Tx>(\n\tdriver: SinkDriver<Tx>,\n\toptions: CreateSinkOptions<Tx>,\n): ConsumerSink<Tx> {\n\tconst { label } = options;\n\tconst checkpointTable = options.checkpointTable ?? DEFAULT_CHECKPOINT_TABLE;\n\tif (options.tables.length === 0) {\n\t\tthrow new ValidationError(\n\t\t\t`${label}: \\`tables\\` is empty — declare every table the handler writes, or reorg rollback is a no-op and orphaned rows persist forever.`,\n\t\t\t400,\n\t\t);\n\t}\n\tassertSqlIdentifier(checkpointTable, label);\n\tassertSqlIdentifier(options.height, label);\n\tfor (const table of options.tables) assertSqlIdentifier(table, label);\n\n\treturn {\n\t\tcapabilities: options.capabilities,\n\n\t\tasync loadCursor() {\n\t\t\tawait driver.ensureCheckpointStore();\n\t\t\t// First-use validation of the rollback precondition: every declared\n\t\t\t// table must exist and carry the height column. Failing here beats a\n\t\t\t// rollback that silently deletes nothing during a reorg.\n\t\t\tfor (const table of options.tables) {\n\t\t\t\tif (!(await driver.hasColumn(table, options.height))) {\n\t\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t\t`${label}: table \"${table}\" has no \"${options.height}\" column — the height stamp is what makes reorg rollback possible. Add the column (or fix \\`height\\`).`,\n\t\t\t\t\t\t400,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn driver.readCursor();\n\t\t},\n\n\t\tasync commitBatch(cursor, write) {\n\t\t\tawait driver.transact(async (tx) => {\n\t\t\t\tawait driver.acquireLock?.(tx);\n\t\t\t\tawait write(tx);\n\t\t\t\tawait driver.writeCursor(tx, cursor);\n\t\t\t});\n\t\t},\n\n\t\tasync rollback(forkPointHeight, rewindCursor) {\n\t\t\tawait driver.transact(async (tx) => {\n\t\t\t\tawait driver.acquireLock?.(tx);\n\t\t\t\t// Folds (balances, last-wins) invert/recompute here, while doomed\n\t\t\t\t// fact rows are still visible. A throw aborts the rewind.\n\t\t\t\tawait options.onRollback?.(tx, { forkPointHeight, rewindCursor });\n\t\t\t\t// INCLUSIVE of the fork block: the new canonical chain re-supplies\n\t\t\t\t// it, and the consumer rewinds to re-read from `fork:0`.\n\t\t\t\tfor (const table of options.tables) {\n\t\t\t\t\tawait driver.deleteAtOrAbove(tx, table, forkPointHeight);\n\t\t\t\t}\n\t\t\t\tif (rewindCursor === null) {\n\t\t\t\t\tif (!driver.clearCursor) {\n\t\t\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t\t\t`${label}: this driver has no clearCursor, so a rewind to pre-genesis cannot be committed. Add clearCursor to the driver, or resume with an explicit fromCursor.`,\n\t\t\t\t\t\t\t400,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tawait driver.clearCursor(tx);\n\t\t\t\t} else {\n\t\t\t\t\tawait driver.writeCursor(tx, rewindCursor);\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t};\n}\n",
7
+ "import { type Kysely, type Transaction, sql } from \"kysely\";\nimport { ValidationError } from \"../errors.ts\";\nimport {\n\tDEFAULT_CHECKPOINT_TABLE,\n\ttype SinkDriver,\n\ttype SinkRollbackContext,\n\tcreateSink,\n\tquoteIdent,\n} from \"./core.ts\";\nimport type { ConsumerSink } from \"./types.ts\";\n\nexport type { SinkRollbackContext };\n\n/**\n * Column present on EVERY declared table — `keyof` a union of row types is\n * the intersection of their keys, so a column missing from any one table is\n * a compile error at the `height:` option.\n */\ntype CommonColumn<DB, T extends keyof DB> = keyof DB[T] & string;\n\nexport interface KyselySinkOptions<DB, T extends keyof DB & string> {\n\t/** Checkpoint identity AND concurrency key: the cursor row's primary key,\n\t * and the input to `pg_try_advisory_xact_lock(hashtextextended(id, 0))`.\n\t * The lock is transaction-scoped: it stops two replicas from\n\t * INTERLEAVING inside a commit, but is released at each commit boundary\n\t * — it is NOT a fence, so two replicas alternating batches both pass.\n\t * Run exactly one consumer per id; the lock turns the racy overlap loud,\n\t * it does not make a second replica safe. */\n\tid: string;\n\t/** Rollback scope. On a reorg, rows AT OR ABOVE the fork point are deleted\n\t * from exactly these tables (inclusive `>=` — the new chain re-supplies\n\t * the fork block). Fact tables only: a fold (balances, counters) does\n\t * not belong here — invert it in `onRollback`. A table you write but\n\t * don't declare keeps orphaned rows forever. */\n\ttables: readonly T[];\n\t/** The block-height stamp column, present on every declared table (compile\n\t * and first-use checked). Height-stamp rollback is correct for\n\t * append-only projections (one row per event/call). */\n\theight: CommonColumn<DB, T>;\n\t/** Checkpoint table name. Default `sl_consumer_checkpoints` (created on\n\t * first use). */\n\tcheckpointTable?: string;\n\t/** Same transaction as the fact-table delete, before it. Doomed rows are\n\t * still visible; remaining facts are `height < forkPointHeight`. A throw\n\t * aborts the rewind. Derive undo from the doomed rows so a re-applied\n\t * rollback is a no-op. */\n\tonRollback?: (\n\t\ttx: Transaction<DB>,\n\t\tctx: SinkRollbackContext,\n\t) => Promise<void> | void;\n}\n\n/**\n * A {@link ConsumerSink} over a Kysely Postgres database — keyed on the\n * QUERY BUILDER (not the driver) so the `DB` schema generic flows through:\n * `tables` is `(keyof DB)[]`, `height` must exist on every declared table,\n * and `ctx.tx` inside `onBatch` is a fully typed `Transaction<DB>`.\n *\n * What it owns (so your indexer doesn't):\n * - the checkpoint table + cursor load on start;\n * - rows AND cursor committed in ONE transaction per batch — a handler\n * throw aborts both, so a crashed batch is re-read on restart with no\n * gaps and no double-writes;\n * - reorg rollback: `onRollback` (doomed facts still visible), then delete\n * `>= fork_point_height` from every declared table, then the rewound\n * cursor — one transaction (the crash-between-the-two-writes gap is\n * unrepresentable);\n * - a per-id advisory lock, so two replicas of the same consumer can't\n * interleave commits.\n *\n * Structurally it is a 7-method {@link SinkDriver} on the shared\n * `createSink` base (`@secondlayer/sdk/sinks/core`), which owns the\n * transaction sequences and guards — this file only knows how to speak\n * Postgres-flavored Kysely.\n *\n * ```ts\n * const sink = kyselySink(db, { id: \"sales\", tables: [\"sales\"], height: \"block_height\" });\n * await index.contractCalls.consume({\n * contractId: MARKETPLACE, functionName: \"purchase-asset\", fromHeight: 0,\n * sink,\n * onBatch: (calls, _env, ctx) =>\n * ctx.tx.insertInto(\"sales\").values(calls.map(toSale)).execute(),\n * });\n * ```\n */\nexport function kyselySink<DB, T extends keyof DB & string>(\n\tdb: Kysely<DB>,\n\toptions: KyselySinkOptions<DB, T>,\n): ConsumerSink<Transaction<DB>> {\n\tconst checkpointTable = options.checkpointTable ?? DEFAULT_CHECKPOINT_TABLE;\n\tconst cp = quoteIdent(checkpointTable);\n\n\tconst driver: SinkDriver<Transaction<DB>> = {\n\t\ttransact: (fn) => db.transaction().execute(fn),\n\n\t\tasync ensureCheckpointStore() {\n\t\t\ttry {\n\t\t\t\tawait sql\n\t\t\t\t\t.raw(\n\t\t\t\t\t\t`CREATE TABLE IF NOT EXISTS ${cp} (id text PRIMARY KEY, cursor text NOT NULL)`,\n\t\t\t\t\t)\n\t\t\t\t\t.execute(db);\n\t\t\t} catch (err) {\n\t\t\t\t// Two consumers racing the same first start: IF NOT EXISTS still\n\t\t\t\t// throws under concurrency (42P07 duplicate_table, or 23505 on the\n\t\t\t\t// pg_type catalog). Either way the table exists — the outcome we\n\t\t\t\t// were creating.\n\t\t\t\tconst code = (err as { code?: string } | null)?.code;\n\t\t\t\tif (code !== \"42P07\" && code !== \"23505\") throw err;\n\t\t\t}\n\t\t},\n\n\t\tasync readCursor() {\n\t\t\tconst row = await sql<{ cursor: string }>`\n\t\t\t\tSELECT cursor FROM ${sql.raw(cp)} WHERE id = ${options.id}\n\t\t\t`.execute(db);\n\t\t\treturn row.rows[0]?.cursor ?? null;\n\t\t},\n\n\t\tasync writeCursor(tx, cursor) {\n\t\t\t// Identifiers via validated sql.raw; VALUES via bound parameters.\n\t\t\tawait sql`\n\t\t\t\tINSERT INTO ${sql.raw(cp)} (id, cursor) VALUES (${options.id}, ${cursor})\n\t\t\t\tON CONFLICT (id) DO UPDATE SET cursor = EXCLUDED.cursor\n\t\t\t`.execute(tx);\n\t\t},\n\n\t\tasync clearCursor(tx) {\n\t\t\tawait sql`DELETE FROM ${sql.raw(cp)} WHERE id = ${options.id}`.execute(\n\t\t\t\ttx,\n\t\t\t);\n\t\t},\n\n\t\tasync deleteAtOrAbove(tx, table, height) {\n\t\t\t// Identifiers via validated sql.raw; the height bound as a parameter.\n\t\t\tawait sql`\n\t\t\t\tDELETE FROM ${sql.raw(quoteIdent(table))}\n\t\t\t\tWHERE ${sql.raw(quoteIdent(options.height as string))} >= ${height}\n\t\t\t`.execute(tx);\n\t\t},\n\n\t\tasync hasColumn(table, column) {\n\t\t\tconst col = await sql<{ ok: boolean }>`\n\t\t\t\tSELECT EXISTS (\n\t\t\t\t\tSELECT 1 FROM information_schema.columns\n\t\t\t\t\tWHERE table_schema = current_schema()\n\t\t\t\t\t\tAND table_name = ${table} AND column_name = ${column}\n\t\t\t\t) AS \"ok\"\n\t\t\t`.execute(db);\n\t\t\treturn col.rows[0]?.ok ?? false;\n\t\t},\n\n\t\tasync acquireLock(tx) {\n\t\t\t// hashtextextended (int8), not hashtext (int4): the 32-bit space\n\t\t\t// collides across distinct ids at real scale, and a collision reads\n\t\t\t// as a false \"another consumer\" 409 between unrelated sinks.\n\t\t\tconst locked = await sql<{ ok: boolean }>`\n\t\t\t\tSELECT pg_try_advisory_xact_lock(hashtextextended(${options.id}, 0)) AS \"ok\"\n\t\t\t`.execute(tx);\n\t\t\tif (!locked.rows[0]?.ok) {\n\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t`kyselySink: another consumer holds the \"${options.id}\" lock — two replicas of the same consumer would interleave commits. Stop the other instance or use a distinct id.`,\n\t\t\t\t\t409,\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\t};\n\n\treturn createSink(driver, {\n\t\tlabel: \"kyselySink\",\n\t\tid: options.id,\n\t\ttables: options.tables,\n\t\theight: options.height as string,\n\t\tcheckpointTable,\n\t\tonRollback: options.onRollback,\n\t});\n}\n"
8
8
  ],
9
- "mappings": ";AAAA,IAAM,YAAY;AAAA;AA6BX,MAAM,yBAAyB,MAAM;AAAA,EAClC,OAAO;AAAA,EAEhB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA,WAAW,CAAC,cAAsB,UAAmC,CAAC,GAAG;AAAA,IACxE,MAAM,eAAe;AAAA,MACpB,GAAI,QAAQ,gBAAgB,CAAC;AAAA,MAC7B,GAAI,QAAQ,UAAU,CAAC,QAAQ,OAAO,IAAI,CAAC;AAAA,MAC3C,GAAI,QAAQ,UAAU,CAAC,SAAS,QAAQ,SAAS,IAAI,CAAC;AAAA,IACvD;AAAA,IACA,MAAM,UAAU;AAAA,MACf;AAAA,MACA,aAAa,SAAS,IAAI;AAAA,EAAK,aAAa,KAAK;AAAA,CAAI,MAAM;AAAA,IAC5D,EAAE,KAAK,EAAE;AAAA,IACT,MAAM,SAAS,QAAQ,QAAQ,EAAE,OAAO,QAAQ,MAAM,IAAI,SAAS;AAAA,IACnE,KAAK,eAAe;AAAA,IACpB,KAAK,OAAO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ACP,IAAI,QAAQ;AAAA,IACZ,QAAQ,QAAQ;AAAA,IAChB,QAAQ,QAAQ;AAAA,IAChB;AAAA,IACA,YAAY,QAAQ;AAAA,EACrB,CAAC;AAAA;",
10
+ "debugId": "4C5BB7B77B93BD5664756E2164756E21",
11
11
  "names": []
12
12
  }
@@ -482,7 +482,8 @@ type StreamsEventsConsumeParams<
482
482
  * the loop resumes from the sink's committed cursor, `onBatch` receives
483
483
  * `ctx.tx` and must write ONLY through it (rows and cursor commit in one
484
484
  * transaction), reorg rollback is automatic, and `onBatch`'s return value
485
- * is ignored.
485
+ * is ignored. Folds (balances) invert in the sink's `onRollback`, not in
486
+ * `onReorg`.
486
487
  */
487
488
  sink?: ConsumerSink<TTx>;
488
489
  /** Fires once per page, before `onBatch` and before any early return. */
@@ -12,7 +12,7 @@
12
12
  "import { createHash } from \"node:crypto\";\nimport { verifyStreamsBulkManifestSignature } from \"@secondlayer/shared/streams-bulk-manifest\";\nimport { defaultSleep, fetchPageWithRetry } from \"./consumer.ts\";\nimport { StreamsServerError, StreamsSignatureError } from \"./errors.ts\";\nimport type {\n\tFetchLike,\n\tStreamsDumpFile,\n\tStreamsDumps,\n\tStreamsDumpsManifest,\n} from \"./types.ts\";\n\n/**\n * Bulk parquet dumps: the cold backfill path for \"download all the raw data\".\n *\n * The manifest lives at `<dumpsBaseUrl>/manifest/latest.json` and each file's\n * `path` is the object key under the same base. Downloads are verified against\n * the manifest sha256 so a truncated or tampered file is rejected.\n *\n * When `verifyManifest` is set (the default), the manifest's own ed25519\n * signature is checked (against the published Streams key) BEFORE any file sha256\n * is trusted — a sha256 is only as trustworthy as the manifest it came from.\n */\nexport function createStreamsDumps(opts: {\n\tbaseUrl?: string;\n\tfetchImpl: FetchLike;\n\tverifyManifest?: boolean;\n\tloadPublicKeyPem?: () => Promise<string>;\n}): StreamsDumps {\n\tconst baseUrl = opts.baseUrl?.replace(/\\/+$/, \"\");\n\n\tfunction requireBaseUrl(): string {\n\t\tif (!baseUrl) {\n\t\t\tthrow new StreamsServerError(\n\t\t\t\t\"Streams dumps require `dumpsBaseUrl` on createStreamsClient.\",\n\t\t\t\t0,\n\t\t\t);\n\t\t}\n\t\treturn baseUrl;\n\t}\n\n\tfunction fileUrl(file: StreamsDumpFile): string {\n\t\tconst base = requireBaseUrl();\n\t\tconst path = file.path.replace(/^\\/+/, \"\");\n\t\t// Manifest file paths are bucket-root-absolute (they embed the dataset\n\t\t// prefix), while `baseUrl` already ends with that prefix — strip the\n\t\t// overlap so both the manifest and its files resolve from one base URL.\n\t\ttry {\n\t\t\tconst basePath = new URL(base).pathname.replace(/^\\/+|\\/+$/g, \"\");\n\t\t\tif (basePath && path.startsWith(`${basePath}/`)) {\n\t\t\t\treturn `${base}/${path.slice(basePath.length + 1)}`;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Non-URL base (tests, relative proxies): fall through to plain join.\n\t\t}\n\t\treturn `${base}/${path}`;\n\t}\n\n\tasync function list(): Promise<StreamsDumpsManifest> {\n\t\tconst url = `${requireBaseUrl()}/manifest/latest.json`;\n\t\tconst res = await opts.fetchImpl(url);\n\t\tif (!res.ok) {\n\t\t\tthrow new StreamsServerError(\n\t\t\t\t`Could not fetch dumps manifest (${res.status}).`,\n\t\t\t\tres.status,\n\t\t\t);\n\t\t}\n\t\tconst manifest = (await res.json()) as StreamsDumpsManifest;\n\t\tif (opts.verifyManifest) {\n\t\t\tif (!opts.loadPublicKeyPem) {\n\t\t\t\tthrow new StreamsSignatureError(\n\t\t\t\t\t\"Manifest verification is on but no signing key source is configured.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst publicKeyPem = await opts.loadPublicKeyPem();\n\t\t\tif (!verifyStreamsBulkManifestSignature(manifest, publicKeyPem)) {\n\t\t\t\tthrow new StreamsSignatureError(\n\t\t\t\t\t\"Dumps manifest signature is missing or invalid.\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn manifest;\n\t}\n\n\t/** Fetch one file and hash it as it arrives. Each chunk goes through the\n\t * digest once and is kept once, so a multi-hundred-MB parquet costs its\n\t * own size in memory rather than double. A dropped socket or 5xx retries\n\t * the whole file under the same policy `consume()` uses for pages. */\n\tasync function download(file: StreamsDumpFile): Promise<Uint8Array> {\n\t\treturn fetchPageWithRetry(() => downloadOnce(file), {\n\t\t\tsleep: defaultSleep,\n\t\t});\n\t}\n\n\tasync function downloadOnce(file: StreamsDumpFile): Promise<Uint8Array> {\n\t\tconst res = await opts.fetchImpl(fileUrl(file));\n\t\tif (!res.ok) {\n\t\t\tthrow new StreamsServerError(\n\t\t\t\t`Could not download dump ${file.path} (${res.status}).`,\n\t\t\t\tres.status,\n\t\t\t);\n\t\t}\n\t\tif (!res.body) {\n\t\t\tthrow new StreamsServerError(\n\t\t\t\t`Dump ${file.path} response has no body.`,\n\t\t\t\t0,\n\t\t\t);\n\t\t}\n\t\tconst hash = createHash(\"sha256\");\n\t\tconst chunks: Uint8Array[] = [];\n\t\tlet total = 0;\n\t\tconst reader = res.body.getReader();\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst { value, done } = await reader.read();\n\t\t\t\tif (done) break;\n\t\t\t\thash.update(value);\n\t\t\t\tchunks.push(value);\n\t\t\t\ttotal += value.byteLength;\n\t\t\t}\n\t\t} catch {\n\t\t\t// A body that dies mid-transfer is the same transient as a socket\n\t\t\t// that never answered: let the retry policy take it.\n\t\t\tthrow new StreamsServerError(\n\t\t\t\t`Download of dump ${file.path} was interrupted after ${total} bytes.`,\n\t\t\t\t0,\n\t\t\t);\n\t\t}\n\t\tconst digest = hash.digest(\"hex\");\n\t\tif (digest !== file.sha256) {\n\t\t\tthrow new StreamsSignatureError(\n\t\t\t\t`Dump ${file.path} sha256 mismatch (expected ${file.sha256}, got ${digest}).`,\n\t\t\t);\n\t\t}\n\t\tif (chunks.length === 1 && chunks[0]) return chunks[0];\n\t\tconst bytes = new Uint8Array(total);\n\t\tlet offset = 0;\n\t\tfor (const chunk of chunks) {\n\t\t\tbytes.set(chunk, offset);\n\t\t\toffset += chunk.byteLength;\n\t\t}\n\t\treturn bytes;\n\t}\n\n\treturn { list, fileUrl, download };\n}\n",
13
13
  "import { ed25519 } from \"@secondlayer/shared\";\nimport { buildQuery } from \"../base.ts\";\nimport {\n\tStreamsServerError,\n\tStreamsSignatureError,\n\tmapStreamsError,\n} from \"./errors.ts\";\nimport type {\n\tFetchLike,\n\tStreamsEvent,\n\tStreamsEventsSubscribeParams,\n\tStreamsSubscription,\n} from \"./types.ts\";\n\ntype VerificationKey = {\n\tkeyId: string;\n\tpublicKey: ReturnType<typeof ed25519.loadEd25519PublicKey>;\n};\n\n/** Backoff ceiling: a subscriber that keeps failing asks once per half\n * minute, which a restarting instance can absorb from every worker at once. */\nexport const SUBSCRIBE_MAX_RECONNECT_DELAY_MS = 30_000;\n/** Three server heartbeats (20 s each) with no frame means the socket is\n * half-open, not idle. */\nexport const SUBSCRIBE_DEFAULT_STALE_AFTER_MS = 60_000;\n\n/**\n * Pause before reconnect attempt `attempt` (0 = first retry): `base * 2^attempt`\n * capped at 30 s, scaled by a jitter in [0.5, 1] so a fleet that dropped\n * together does not reconnect together. Never shorter than a `Retry-After`\n * the server sent, since that is the one number it is sure about.\n */\nexport function reconnectDelay(\n\tattempt: number,\n\tbaseMs: number,\n\tretryAfterSeconds?: number,\n\trandom: () => number = Math.random,\n): number {\n\tconst capped = Math.min(\n\t\tbaseMs * 2 ** Math.max(0, attempt),\n\t\tSUBSCRIBE_MAX_RECONNECT_DELAY_MS,\n\t);\n\tconst jittered = capped * (0.5 + random() * 0.5);\n\tconst floor = (retryAfterSeconds ?? 0) * 1000;\n\treturn Math.max(jittered, floor);\n}\n\n/** An error the loop stops on: a retry cannot change the answer. */\nfunction isTerminal(err: unknown): boolean {\n\tif (err instanceof StreamsSignatureError) return true;\n\treturn (err as { retryable?: boolean } | null)?.retryable === false;\n}\n\n/**\n * Subscribe to the Streams SSE push surface (`GET /v1/streams/events/stream`).\n *\n * A fetch-based reader (not `EventSource`) so it can send `Authorization` when\n * a key is present, which `EventSource` cannot. Works in browsers and Node 18+.\n * Reconnects from the last handled cursor after a dropped connection, a clean\n * server close, or a stale socket, with exponential backoff; stops on an error\n * a retry cannot fix and rejects the handle's `done`.\n */\nexport function subscribeStreamsEvents(opts: {\n\tbaseUrl: string;\n\t/** Request headers for every connection (bearer token, `x-sl-origin`). */\n\theaders?: Record<string, string>;\n\tfetchImpl: FetchLike;\n\t/**\n\t * `off` skips verification; `lenient` (default) verifies a frame when it\n\t * carries a `sig` and delivers it unverified when it doesn't (unsigned\n\t * self-host); `strict` requires every frame to be signed. An invalid `sig`\n\t * always throws regardless of mode.\n\t */\n\tverify: \"off\" | \"lenient\" | \"strict\";\n\t/** Resolve the key a frame names by `key_id` (a fetched key refreshes once\n\t * on an unknown id; a pinned key fails closed), or the cached key when\n\t * the frame carries none. */\n\tloadKey: (keyId?: string | null) => Promise<VerificationKey>;\n\t/** First reconnect pause; see {@link StreamsEventsSubscribeParams.reconnectDelayMs}. */\n\treconnectDelayMs?: number;\n\t/** Idle limit before the socket is treated as dead; see\n\t * {@link StreamsEventsSubscribeParams.staleAfterMs}. */\n\tstaleAfterMs?: number;\n\t/** Jitter source, injectable for tests. */\n\trandom?: () => number;\n\tparams: StreamsEventsSubscribeParams;\n}): StreamsSubscription {\n\tconst { params } = opts;\n\tconst controller = new AbortController();\n\tconst external = params.signal;\n\tif (external) {\n\t\tif (external.aborted) controller.abort();\n\t\telse\n\t\t\texternal.addEventListener(\"abort\", () => controller.abort(), {\n\t\t\t\tonce: true,\n\t\t\t});\n\t}\n\tlet cursor = params.fromCursor ?? null;\n\tconst baseDelayMs = opts.reconnectDelayMs ?? params.reconnectDelayMs ?? 1000;\n\tconst staleAfterMs =\n\t\topts.staleAfterMs ??\n\t\tparams.staleAfterMs ??\n\t\tSUBSCRIBE_DEFAULT_STALE_AFTER_MS;\n\t// Consecutive failures since the last frame; drives the backoff exponent.\n\tlet attempt = 0;\n\n\tconst run = async (): Promise<void> => {\n\t\twhile (!controller.signal.aborted) {\n\t\t\ttry {\n\t\t\t\tconst url = `${opts.baseUrl}/v1/streams/events/stream${buildQuery({\n\t\t\t\t\tfrom_cursor: cursor ?? undefined,\n\t\t\t\t\ttypes: params.types,\n\t\t\t\t\tnot_types: params.notTypes,\n\t\t\t\t\tcontract_id: params.contractId,\n\t\t\t\t\tsender: params.sender,\n\t\t\t\t\trecipient: params.recipient,\n\t\t\t\t\tasset_identifier: params.assetIdentifier,\n\t\t\t\t\t// JSON in a query param, so SSE keeps plain GET semantics:\n\t\t\t\t\t// no POST-and-stream variant of this route.\n\t\t\t\t\tfilters: params.filters ? JSON.stringify(params.filters) : undefined,\n\t\t\t\t})}`;\n\t\t\t\tawait readSse({\n\t\t\t\t\turl,\n\t\t\t\t\theaders: opts.headers ?? {},\n\t\t\t\t\tsignal: controller.signal,\n\t\t\t\t\tfetchImpl: opts.fetchImpl,\n\t\t\t\t\tstaleAfterMs,\n\t\t\t\t\tmapError: mapStreamsError,\n\t\t\t\t\tonFrame: async (frame) => {\n\t\t\t\t\t\t// Any frame, ping included, proves the socket is live.\n\t\t\t\t\t\tattempt = 0;\n\t\t\t\t\t\tif (frame.event === \"ping\" || !frame.data) return;\n\t\t\t\t\t\tlet parsed: { event?: StreamsEvent; sig?: string; key_id?: string };\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tparsed = JSON.parse(frame.data);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\treturn; // ignore non-JSON frames\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!parsed.event) return;\n\t\t\t\t\t\tif (opts.verify !== \"off\") {\n\t\t\t\t\t\t\tif (!parsed.sig) {\n\t\t\t\t\t\t\t\t// Strict requires a signed frame; lenient (default) delivers an\n\t\t\t\t\t\t\t\t// unsigned frame (e.g. self-host with no signing key).\n\t\t\t\t\t\t\t\tif (opts.verify === \"strict\") {\n\t\t\t\t\t\t\t\t\tthrow new StreamsSignatureError(\n\t\t\t\t\t\t\t\t\t\t\"Streams SSE frame signature is missing.\",\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// The frame names its key, so a rotation mid-stream is a\n\t\t\t\t\t\t\t\t// one-time refresh instead of a reconnect loop that fails\n\t\t\t\t\t\t\t\t// every frame forever.\n\t\t\t\t\t\t\t\tconst key = await opts.loadKey(parsed.key_id);\n\t\t\t\t\t\t\t\t// A signature is present, so verify it in either mode; an\n\t\t\t\t\t\t\t\t// invalid signature always fails closed.\n\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t!ed25519.verifyEd25519(\n\t\t\t\t\t\t\t\t\t\tJSON.stringify(parsed.event),\n\t\t\t\t\t\t\t\t\t\tparsed.sig,\n\t\t\t\t\t\t\t\t\t\tkey.publicKey,\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\tthrow new StreamsSignatureError(\n\t\t\t\t\t\t\t\t\t\t\"Streams SSE frame signature is invalid.\",\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// The cursor moves only once the handler has taken the event.\n\t\t\t\t\t\t// A throw here reconnects from the previous cursor, so this\n\t\t\t\t\t\t// event is delivered again rather than skipped.\n\t\t\t\t\t\tawait params.onEvent(parsed.event);\n\t\t\t\t\t\tcursor = (parsed.event as { cursor?: string }).cursor ?? cursor;\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\t// Clean end (server closed the stream): reconnect from `cursor`\n\t\t\t\t// after the same pause as an error, so a proxy that answers 200 and\n\t\t\t\t// closes at once cannot spin a hot loop.\n\t\t\t\tawait sleep(\n\t\t\t\t\treconnectDelay(attempt, baseDelayMs, undefined, opts.random),\n\t\t\t\t\tcontroller.signal,\n\t\t\t\t);\n\t\t\t\tattempt += 1;\n\t\t\t} catch (err) {\n\t\t\t\tif (controller.signal.aborted) return;\n\t\t\t\tparams.onError?.(err);\n\t\t\t\tif (isTerminal(err)) throw err;\n\t\t\t\tconst retryAfterSeconds = (err as { retryAfterSeconds?: number })\n\t\t\t\t\t.retryAfterSeconds;\n\t\t\t\tawait sleep(\n\t\t\t\t\treconnectDelay(attempt, baseDelayMs, retryAfterSeconds, opts.random),\n\t\t\t\t\tcontroller.signal,\n\t\t\t\t);\n\t\t\t\tattempt += 1;\n\t\t\t}\n\t\t}\n\t};\n\tconst done = run();\n\t// The caller may never look at `done`; a terminal error already reached\n\t// `onError`, so an unobserved rejection must not crash the process.\n\tdone.catch(() => {});\n\tconst unsubscribe = () => controller.abort();\n\treturn Object.assign(unsubscribe, { done });\n}\n\n/** One parsed `text/event-stream` frame. */\nexport type SseFrame = { event?: string; data?: string };\n\n/**\n * Open one SSE connection and hand every frame to `onFrame` until the server\n * closes the stream or `signal` aborts. Fetch-based rather than `EventSource`\n * so the request can carry `Authorization`. A non-OK response throws through\n * `mapError` (default: a retryable `StreamsServerError`); a thrown `onFrame`\n * propagates and cancels the body. With `staleAfterMs`, a read that sees no\n * frame for that long cancels the body and throws a retryable\n * `StreamsServerError` (`STREAM_STALE`). Reconnecting is the caller's job, so\n * each surface keeps its own cursor rule.\n */\nexport async function readSse(opts: {\n\turl: string;\n\theaders?: Record<string, string>;\n\tsignal: AbortSignal;\n\tfetchImpl: FetchLike;\n\tonFrame: (frame: SseFrame) => void | Promise<void>;\n\tstaleAfterMs?: number;\n\tmapError?: (res: Response) => Promise<never>;\n}): Promise<void> {\n\tconst res = await opts.fetchImpl(opts.url, {\n\t\theaders: { ...(opts.headers ?? {}), Accept: \"text/event-stream\" },\n\t\tsignal: opts.signal,\n\t});\n\tif (!res.ok) {\n\t\tif (opts.mapError) await opts.mapError(res);\n\t\tthrow new StreamsServerError(\n\t\t\t`Streams SSE returned ${res.status}.`,\n\t\t\tres.status,\n\t\t);\n\t}\n\tif (!res.body) {\n\t\tthrow new StreamsServerError(\"Streams SSE response has no body.\", 0);\n\t}\n\tfor await (const frame of parseSseFrames(\n\t\tres.body,\n\t\topts.signal,\n\t\topts.staleAfterMs,\n\t)) {\n\t\tawait opts.onFrame(frame);\n\t}\n}\n\nfunction sleep(ms: number, signal: AbortSignal): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tif (signal.aborted) return resolve();\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(timer);\n\t\t\tresolve();\n\t\t};\n\t\tconst timer = setTimeout(() => {\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n}\n\n/** `reader.read()` raced against an idle timer; a timeout throws a retryable\n * error so the caller's reconnect path takes over. */\nasync function readWithStaleTimer<R extends { read(): Promise<unknown> }>(\n\treader: R,\n\tstaleAfterMs: number | undefined,\n): Promise<Awaited<ReturnType<R[\"read\"]>>> {\n\tif (staleAfterMs === undefined || !Number.isFinite(staleAfterMs)) {\n\t\treturn reader.read() as Promise<Awaited<ReturnType<R[\"read\"]>>>;\n\t}\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tconst stale = new Promise<never>((_, reject) => {\n\t\ttimer = setTimeout(\n\t\t\t() =>\n\t\t\t\treject(\n\t\t\t\t\tnew StreamsServerError(\n\t\t\t\t\t\t`Streams SSE went quiet for ${staleAfterMs} ms; reconnecting.`,\n\t\t\t\t\t\t0,\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\"STREAM_STALE\",\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\tstaleAfterMs,\n\t\t);\n\t});\n\ttry {\n\t\treturn (await Promise.race([reader.read(), stale])) as Awaited<\n\t\t\tReturnType<R[\"read\"]>\n\t\t>;\n\t} finally {\n\t\tclearTimeout(timer);\n\t}\n}\n\nasync function* parseSseFrames(\n\tbody: ReadableStream<Uint8Array>,\n\tsignal: AbortSignal,\n\tstaleAfterMs?: number,\n): AsyncGenerator<SseFrame> {\n\tconst reader = body.getReader();\n\tconst decoder = new TextDecoder();\n\tlet buffer = \"\";\n\ttry {\n\t\twhile (!signal.aborted) {\n\t\t\tconst { value, done } = await readWithStaleTimer(reader, staleAfterMs);\n\t\t\tif (done) break;\n\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\tlet sep = buffer.indexOf(\"\\n\\n\");\n\t\t\twhile (sep !== -1) {\n\t\t\t\tyield parseFrame(buffer.slice(0, sep));\n\t\t\t\tbuffer = buffer.slice(sep + 2);\n\t\t\t\tsep = buffer.indexOf(\"\\n\\n\");\n\t\t\t}\n\t\t}\n\t} finally {\n\t\ttry {\n\t\t\tawait reader.cancel();\n\t\t} catch {\n\t\t\t// best-effort\n\t\t}\n\t}\n}\n\nfunction parseFrame(raw: string): SseFrame {\n\tlet event: string | undefined;\n\tconst data: string[] = [];\n\tfor (const line of raw.split(\"\\n\")) {\n\t\tif (line.startsWith(\"data:\")) {\n\t\t\tdata.push(line.slice(line.startsWith(\"data: \") ? 6 : 5));\n\t\t} else if (line.startsWith(\"event:\")) {\n\t\t\tevent = line.slice(line.startsWith(\"event: \") ? 7 : 6).trim();\n\t\t}\n\t}\n\treturn { event, data: data.length > 0 ? data.join(\"\\n\") : undefined };\n}\n",
14
14
  "export { createStreamsClient } from \"./client.ts\";\nexport { decode } from \"./decode.ts\";\nexport {\n\tAuthError,\n\tRateLimitError,\n\tStreamsServerError,\n\tStreamsSignatureError,\n\tValidationError,\n} from \"./errors.ts\";\n// ── Per-type guard+decode pairs ─────────────────────────────────────────\n// @deprecated (whole block): these 22 helpers return DB-row shapes\n// (`decoded_payload` nested, `source_cursor`) and force an 11-branch\n// guard+decode dispatch, which is the wrong default for a consumer. Use\n// `decode(event)` — one call, the same flat `event_type`-discriminated row\n// Index serves — or `decoded: true` on `streams.events.consume`.\n//\n// They are NOT going away: building a `decoded_events`-shaped projection is a\n// real use, and it is what our own decoder does. They move to the explicit\n// `@secondlayer/sdk/streams/rows` subpath at the next major, so reaching for\n// the storage shape is a deliberate act rather than the first thing autocomplete\n// offers. Import from there today.\nexport {\n\tdecodeFtTransfer,\n\tisFtTransfer,\n\tdecodeNftTransfer,\n\tisNftTransfer,\n\tdecodeStxBurn,\n\tdecodeStxLock,\n\tdecodeStxMint,\n\tdecodeStxTransfer,\n\tisStxBurn,\n\tisStxLock,\n\tisStxMint,\n\tisStxTransfer,\n\tdecodeFtBurn,\n\tdecodeFtMint,\n\tdecodeNftBurn,\n\tdecodeNftMint,\n\tisFtBurn,\n\tisFtMint,\n\tisNftBurn,\n\tisNftMint,\n\tdecodePrint,\n\tisPrint,\n} from \"@secondlayer/shared/streams-rows\";\nexport type {\n\tDecodedEventColumns,\n\tDecodedEventRow,\n\tDecodedFtBurn,\n\tDecodedFtBurnPayload,\n\tDecodedFtMint,\n\tDecodedFtMintPayload,\n\tDecodedFtTransfer,\n\tDecodedFtTransferPayload,\n\tDecodedNftBurn,\n\tDecodedNftBurnPayload,\n\tDecodedNftMint,\n\tDecodedNftMintPayload,\n\tDecodedNftTransfer,\n\tDecodedNftTransferPayload,\n\tDecodedPrint,\n\tDecodedPrintPayload,\n\tDecodedPrintValue,\n\tDecodedStxBurn,\n\tDecodedStxBurnPayload,\n\tDecodedStxLock,\n\tDecodedStxLockPayload,\n\tDecodedStxMint,\n\tDecodedStxMintPayload,\n\tDecodedStxTransfer,\n\tDecodedStxTransferPayload,\n\tFtTransferEvent,\n\tFtTransferPayload,\n\tNftTransferEvent,\n\tNftTransferPayload,\n} from \"@secondlayer/shared/streams-rows\";\nexport { STREAMS_EVENT_TYPES } from \"./types.ts\";\nexport { Cursor } from \"./cursor.ts\";\nexport type {\n\tConsumerBatchContext,\n\tFetchLike,\n\tStreamsBatch,\n\tStreamsBatchContext,\n\tStreamsClient,\n\tStreamsConsumeParams,\n\tStreamsCanonicalBlock,\n\tStreamsDumpFile,\n\tStreamsDumps,\n\tStreamsDumpsManifest,\n\tStreamsEvent,\n\tStreamsEventPayload,\n\tStreamsEventsConsumeParams,\n\tStreamsEventsConsumeResult,\n\tStreamsEventsEnvelope,\n\tStreamsEventsListEnvelope,\n\tStreamsEventsListParams,\n\tStreamsEventsStreamParams,\n\tStreamsEventsSubscribeParams,\n\tStreamsSubscription,\n\tStreamsEventType,\n\tStreamsReorg,\n\tStreamsReorgContext,\n\tStreamsReorgsListEnvelope,\n\tStreamsReorgsListParams,\n\tStreamsTip,\n} from \"./types.ts\";\n",
15
- "// Canonical event primitives (StreamsEvent, payload types, event-type vocab)\n// live in @secondlayer/shared/streams-rows; re-exported here so the public\n// Streams surface is unchanged.\nimport {\n\tSTREAMS_EVENT_TYPES,\n\ttype StreamsEvent,\n\ttype StreamsEventType,\n} from \"@secondlayer/shared/streams-rows\";\nimport type { IndexEvent } from \"../index-api/client.ts\";\nimport type { ConsumerSink, WithSinkTx } from \"../sinks/types.ts\";\n\nexport { STREAMS_EVENT_TYPES, type StreamsEvent, type StreamsEventType };\nexport type {\n\tFtBurnPayload,\n\tFtMintPayload,\n\tFtTransferPayload,\n\tNftBurnPayload,\n\tNftMintPayload,\n\tNftTransferPayload,\n\tPrintPayload,\n\tStreamsClarityValue,\n\tStreamsEventBase,\n\tStreamsEventPayload,\n\tStxBurnPayload,\n\tStxLockPayload,\n\tStxMintPayload,\n\tStxTransferPayload,\n} from \"@secondlayer/shared/streams-rows\";\n\nexport type StreamsTip = {\n\tblock_height: number;\n\tblock_hash: string;\n\tburn_block_height: number;\n\t/**\n\t * Highest Stacks block past the burn-confirmation finality boundary.\n\t * Optional for back-compat; the API always sets it.\n\t */\n\tfinalized_height?: number;\n\tlag_seconds: number;\n\t/**\n\t * Oldest height still seekable on the live API for the caller's tier\n\t * (`tip - retention`). `null` = unlimited retention. Older reads must use the\n\t * cold dumps lane. Optional for back-compat.\n\t */\n\toldest_seekable_height?: number | null;\n\t/** Oldest seekable cursor (`<oldest_seekable_height>:0`); `null` = unlimited. */\n\toldest_cursor?: string | null;\n};\n\nexport type StreamsCanonicalBlock = {\n\tblock_height: number;\n\tblock_hash: string;\n\tburn_block_height: number;\n\tburn_block_hash: string | null;\n\tis_canonical: true;\n};\n\nexport type StreamsReorg = {\n\tdetected_at: string;\n\tfork_point_height: number;\n\torphaned_range: { from: string; to: string };\n\t/**\n\t * First position of the new canonical chain at the fork, `fork:0`\n\t * (INCLUSIVE). Not an exclusive resume token — resuming directly from it\n\t * skips `fork:0`. The consumer rewinds to the foot of `fork_point_height`\n\t * (`Cursor.atHeight`) to re-read the new run from `fork:0` inclusive.\n\t */\n\tnew_canonical_tip: string;\n};\n\nexport type StreamsEventsEnvelope<TEvent = StreamsEvent> = {\n\tevents: TEvent[];\n\tnext_cursor: string | null;\n\ttip: StreamsTip;\n\treorgs: StreamsReorg[];\n};\n\nexport type StreamsEventsListEnvelope = Omit<\n\tStreamsEventsEnvelope,\n\t\"next_cursor\"\n>;\n\n/** The StreamsEvent union narrowed to a `types` selection — what a\n * const-generic `types: [\"ft_transfer\"]` buys at the type level. */\nexport type StreamsEventOfTypes<T extends readonly StreamsEventType[]> =\n\tExtract<StreamsEvent, { event_type: T[number] }>;\n\nexport type StreamsReorgsListParams = {\n\tsince: string;\n\tlimit?: number;\n};\n\nexport type StreamsReorgsListEnvelope = {\n\treorgs: StreamsReorg[];\n\tnext_since: string | null;\n};\n\n/** A filter that matches a single value or any value in a list. */\nexport type StreamsFilterValue = string | readonly string[];\n\n/**\n * One labelled filter group. Fields inside a group AND together; groups in a\n * map OR together server-side.\n */\nexport type StreamsLabelledFilter = {\n\ttypes?: readonly StreamsEventType[];\n\tcontractId?: StreamsFilterValue;\n\tsender?: StreamsFilterValue;\n\trecipient?: StreamsFilterValue;\n\tassetIdentifier?: string;\n};\n\n/** A map of label → filter group. Labels are yours; the server echoes them. */\nexport type StreamsFilterMap = Record<string, StreamsLabelledFilter>;\n\n/**\n * The events one label can yield. A group that declares `types` narrows to\n * exactly those variants, so a per-label handler needs no `event_type` guard;\n * a group without `types` keeps the full union.\n */\nexport type StreamsEventForFilter<F, D extends boolean = false> = F extends {\n\ttypes: readonly (infer T extends StreamsEventType)[];\n}\n\t? D extends true\n\t\t? Extract<IndexEvent, { event_type: T }>\n\t\t: Extract<StreamsEvent, { event_type: T }>\n\t: D extends true\n\t\t? IndexEvent\n\t\t: StreamsEvent;\n\nexport type StreamsEventsListParams = {\n\tcursor?: string | null;\n\tfromHeight?: number;\n\ttoHeight?: number;\n\ttypes?: readonly StreamsEventType[];\n\t/** Event types to exclude (applied after `types`). */\n\tnotTypes?: readonly StreamsEventType[];\n\tcontractId?: StreamsFilterValue;\n\tsender?: StreamsFilterValue;\n\trecipient?: StreamsFilterValue;\n\tassetIdentifier?: string;\n\t/**\n\t * Labelled filter groups. The groups OR together in one scan and each\n\t * returned event carries the labels it matched (`event.matched`) — two\n\t * unrelated concerns share one page, one cursor, one checkpoint.\n\t */\n\tfilters?: StreamsFilterMap;\n\tlimit?: number;\n};\n\nexport type StreamsEventsStreamParams = {\n\tfromCursor?: string | null;\n\ttypes?: readonly StreamsEventType[];\n\tnotTypes?: readonly StreamsEventType[];\n\tcontractId?: StreamsFilterValue;\n\tsender?: StreamsFilterValue;\n\trecipient?: StreamsFilterValue;\n\tassetIdentifier?: string;\n\t/** Labelled filter groups; see {@link StreamsEventsListParams.filters}. */\n\tfilters?: StreamsFilterMap;\n\tbatchSize?: number;\n\temptyBackoffMs?: number;\n\tmaxPages?: number;\n\tmaxEmptyPolls?: number;\n\tsignal?: AbortSignal;\n};\n\nexport type StreamsEventsSubscribeParams = {\n\t/** Resume strictly after this cursor; omit to live-tail from the tip. */\n\tfromCursor?: string | null;\n\ttypes?: readonly StreamsEventType[];\n\tnotTypes?: readonly StreamsEventType[];\n\tcontractId?: StreamsFilterValue;\n\tsender?: StreamsFilterValue;\n\trecipient?: StreamsFilterValue;\n\tassetIdentifier?: string;\n\t/** Labelled filter groups; see {@link StreamsEventsListParams.filters}. */\n\tfilters?: StreamsFilterMap;\n\t/** Abort to unsubscribe (the returned function does the same). */\n\tsignal?: AbortSignal;\n\t/**\n\t * Called for each pushed event, in order. The resume cursor advances only\n\t * after this resolves, so a handler that throws sees the same event again\n\t * on reconnect (at-least-once). Key durable writes by `cursor`.\n\t */\n\tonEvent: (event: StreamsEvent) => void | Promise<void>;\n\t/**\n\t * Called on every failure. Transport errors (dropped socket, 5xx, 429, a\n\t * stale connection, a throwing handler) reconnect from the last handled\n\t * cursor with exponential backoff. Errors that a retry cannot fix (401,\n\t * 4xx, a bad signature) end the subscription and reject its `done`.\n\t */\n\tonError?: (err: unknown) => void;\n\t/**\n\t * First reconnect pause in ms (default 1000). Doubles per consecutive\n\t * failure up to 30 s with jitter, resets once a frame arrives, and never\n\t * undercuts a `Retry-After`.\n\t */\n\treconnectDelayMs?: number;\n\t/**\n\t * Reconnect when no frame (pings included) arrives for this long (default\n\t * 60000, three server heartbeats). Catches a half-open socket that never\n\t * errors; set it above your instance's heartbeat interval.\n\t */\n\tstaleAfterMs?: number;\n};\n\n/**\n * Handle for a live subscription: call it to unsubscribe. `done` resolves\n * after unsubscribe (or the signal aborting) and rejects with the error that\n * ended the loop when a retry could not fix it, so a worker can `await`\n * it instead of polling for silence.\n */\nexport type StreamsSubscription = {\n\t(): void;\n\tdone: Promise<void>;\n};\n\n/**\n * The checkpoint the SDK computes for a batch. Persist `cursor` inside the same\n * transaction as your projection writes, then resume from it via `fromCursor`.\n * It is the position to advance to: `next_cursor` normally, or the last\n * finalized event when `finalizedOnly` is set.\n */\n/**\n * What the loop knows at the end of a page, handed to `onBatch`.\n *\n * `cursor` is the position to commit. The rest answers \"how far along am I,\n * and am I still moving\" — the question every deployed consumer has to expose\n * for a health check.\n *\n * Progress is reported here rather than left to callers because only the loop\n * can get it right: `height` has to survive empty pages (normal at the tip)\n * and has to roll back to `fork_point_height - 1` after a reorg rewind.\n * Deriving it from `cursor` is wrong — `Cursor.atHeight` encodes the foot of a\n * block as `${height - 1}:<sentinel>`, so a rewound cursor parses to a\n * position that was never reached.\n */\nexport type ConsumerBatchContext<TTip = unknown, TReorg = unknown> = {\n\t/** Checkpoint to commit alongside your rows. */\n\tcursor: string | null;\n\t/** Highest canonical block a row was DELIVERED from. `null` before the\n\t * first row of a fresh consume. With a sparse filter this parks at the\n\t * last matching event — it measures event recency, not progress. */\n\theight: number | null;\n\t/** Highest canonical block the sweep has VERIFIED through: an empty page\n\t * is the server confirming nothing matches between the cursor and the\n\t * tip, so a caught-up tail scans to the tip even when `height` is far\n\t * below it. Rolls back with reorg rewinds. */\n\tscannedHeight: number | null;\n\t/** Chain tip as of this page's read. */\n\ttipHeight: number;\n\t/** `tipHeight - scannedHeight`, floored at 0 — the consumer's actual\n\t * backlog. `null` until a position is known. A caught-up consumer on a\n\t * quiet contract reads ~0 here while `tipHeight - height` grows — that\n\t * difference is event age, not lag. */\n\tblocksBehind: number | null;\n\t/**\n\t * The full tip for this page — `StreamsTip` or `IndexTip` depending on the\n\t * surface. Exposed here so a handler never needs the `envelope` parameter,\n\t * which is the only way to reach it today and is also how the worst\n\t * `finalizedOnly` mistake becomes reachable (`return envelope.next_cursor`\n\t * jumps the cursor past events that were filtered out and never delivered).\n\t */\n\ttip: TTip;\n\t/**\n\t * Reorgs reported alongside this page; empty when none. Rollback still\n\t * belongs in `onReorg` — this is for observability inside a batch.\n\t */\n\treorgs: readonly TReorg[];\n};\n\n/** @deprecated Use {@link ConsumerBatchContext} — the Index and Streams loops\n * share one shape now. Kept as an alias so existing annotations compile. */\nexport type StreamsBatchContext = ConsumerBatchContext;\n\n/**\n * The checkpoint for a reorg rollback. Persist `cursor` (the rewind position)\n * inside the same transaction as your rollback so the two commit atomically.\n */\n/** `cursor` is the rewind position the loop resumes from after `onReorg`:\n * the foot of the fork point, or `null` for a fork at genesis. Persist it\n * in the same transaction as the rollback. */\nexport type StreamsReorgContext = { cursor: string | null };\n\nexport type StreamsEventsConsumeParams<\n\tTTx = never,\n\tD extends boolean = false,\n\tF extends StreamsFilterMap = Record<never, never>,\n> = {\n\tfromCursor?: string | null;\n\t/**\n\t * Deliver events pre-decoded as the flat, `event_type`-discriminated rows\n\t * Index serves (`IndexEvent`), so Streams consumption reads identically\n\t * to Index consumption — no guard+decode pairs in your handler.\n\t */\n\tdecoded?: D;\n\t/**\n\t * Destination adapter that owns the checkpoint + rollback transaction\n\t * (e.g. `kyselySink` from `@secondlayer/sdk/sinks/kysely`). With a sink:\n\t * the loop resumes from the sink's committed cursor, `onBatch` receives\n\t * `ctx.tx` and must write ONLY through it (rows and cursor commit in one\n\t * transaction), reorg rollback is automatic, and `onBatch`'s return value\n\t * is ignored.\n\t */\n\tsink?: ConsumerSink<TTx>;\n\t/** Fires once per page, before `onBatch` and before any early return. */\n\tonProgress?: (ctx: ConsumerBatchContext) => void;\n\tmode?: \"tail\" | \"bounded\";\n\t/**\n\t * Emit only finalized (immutable) events and never surface reorgs. The SDK\n\t * checkpoints at the last finalized event and re-reads the unfinalized tail\n\t * until it settles. Trades finality lag for zero reorg handling; `onReorg` is\n\t * ignored.\n\t */\n\tfinalizedOnly?: boolean;\n\ttypes?: readonly StreamsEventType[];\n\tnotTypes?: readonly StreamsEventType[];\n\tcontractId?: StreamsFilterValue;\n\tsender?: StreamsFilterValue;\n\trecipient?: StreamsFilterValue;\n\tassetIdentifier?: string;\n\t/**\n\t * Labelled filter groups. The groups OR together in ONE server-side scan,\n\t * so two unrelated concerns share one page, one cursor, and one checkpoint\n\t * instead of two consume loops. Pair with `on` to handle each label.\n\t */\n\tfilters?: F;\n\t/**\n\t * One handler per label in `filters`. Every label must be handled, so\n\t * adding a label is a compile error until its handler exists.\n\t *\n\t * A label's declared `types` narrows its handler's events, so `payload` is\n\t * typed without an `event_type` guard. Labels are dispatched in declaration\n\t * order: a label's own events stay in cursor order, but events of different\n\t * labels do not interleave within a page — add `onBatch` when you need\n\t * strict global order across labels.\n\t */\n\ton?: {\n\t\t[K in keyof F]: (\n\t\t\tevents: StreamsEventForFilter<F[K], D>[],\n\t\t\tctx: StreamsBatchContext & WithSinkTx<TTx>,\n\t\t) => void | Promise<void>;\n\t};\n\tbatchSize?: number;\n\t/**\n\t * Apply a page of canonical events. Persist `ctx.cursor` in the same\n\t * transaction as your writes. Returning a cursor overrides `ctx.cursor` as\n\t * the resume point (advanced manual control); returning nothing uses it.\n\t *\n\t * Optional only when `on` handles the page instead; a consume call with\n\t * neither throws.\n\t */\n\tonBatch?: (\n\t\tevents: D extends true ? IndexEvent[] : StreamsEvent[],\n\t\t/**\n\t\t * @deprecated Read `ctx.tip` / `ctx.reorgs` instead. The envelope is\n\t\t * also how the worst `finalizedOnly` mistake stays reachable —\n\t\t * returning `envelope.next_cursor` jumps the cursor past unfinalized\n\t\t * events that were filtered out and never delivered. Removed in the\n\t\t * next major.\n\t\t */\n\t\tenvelope: StreamsEventsEnvelope,\n\t\tctx: StreamsBatchContext & WithSinkTx<TTx>,\n\t) =>\n\t\t| void\n\t\t| string\n\t\t| null\n\t\t| undefined\n\t\t| Promise<void>\n\t\t| Promise<string | null | undefined>;\n\t/**\n\t * Roll your projection back to `reorg.fork_point_height`, persisting\n\t * `ctx.cursor` in the same transaction. Called once per *new* reorg at or\n\t * below the checkpoint (deduped in-memory, fork-ascending) before the SDK\n\t * rewinds and re-reads the now-canonical events. A reorg whose fork sits\n\t * above the checkpoint is not a rollback (nothing past it was written) and\n\t * is skipped. Omit it to ignore reorgs (events stay canonical, but stale\n\t * rows from an orphaned fork are left in place).\n\t *\n\t * With `onReorg` or a `sink` attached, every empty page also polls\n\t * `reorgs.list` (one extra request per idle poll) so a fork that lands\n\t * while the consumer idles at the tip is rolled back too.\n\t */\n\tonReorg?: (\n\t\treorg: StreamsReorg,\n\t\tctx: StreamsReorgContext,\n\t) => Promise<void> | void;\n\t/** Deepest rewind one reorg may make below the checkpoint before the loop\n\t * refuses with `ValidationError`. Default 1000 blocks. The fork point is\n\t * server supplied and drives a delete on every declared table, so raise\n\t * this only for a source you trust. */\n\tmaxRollbackDepth?: number;\n\t/** Page-fetch retries after the first failure (429/5xx/network only —\n\t * 4xx and handler throws always propagate). Default 3; `0` disables. */\n\tretryCount?: number;\n\t/** Base retry delay in ms; the n-th retry waits `retryDelay * n`. A server\n\t * `Retry-After` overrides it. Default 1000. */\n\tretryDelay?: number;\n\t/** Void observer, called before each retry sleep (metrics/logging). */\n\tonError?: (\n\t\terr: unknown,\n\t\tctx: { attempt: number; retriesLeft: number; delayMs: number },\n\t) => void;\n\temptyBackoffMs?: number;\n\tmaxPages?: number;\n\tmaxEmptyPolls?: number;\n\tsignal?: AbortSignal;\n};\n\n/**\n * One yielded page from {@link StreamsClient.consume} — the\n * `GET /v1/streams/events` envelope verbatim, with `next_cursor` renamed to\n * `cursor` (the checkpoint to persist and resume from).\n */\nexport type StreamsBatch<TEvent = StreamsEvent> = {\n\t/** Canonical events of this page, in cursor order. */\n\tevents: TEvent[];\n\t/** Checkpoint after this page — pass back as `consume({ cursor })` to resume. */\n\tcursor: string | null;\n\ttip: StreamsTip;\n\t/** Chain reorgs reported alongside this page; empty when none. */\n\treorgs: StreamsReorg[];\n};\n\nexport type StreamsConsumeParams = {\n\t/** Resume strictly after this cursor; omit to start from the oldest seekable page. */\n\tcursor?: string | null;\n\ttypes?: readonly StreamsEventType[];\n\tnotTypes?: readonly StreamsEventType[];\n\tcontractId?: StreamsFilterValue;\n\tsender?: StreamsFilterValue;\n\trecipient?: StreamsFilterValue;\n\tassetIdentifier?: string;\n\t/** Labelled OR-groups — same semantics as `events.consume`; each returned\n\t * event echoes the labels it matched. */\n\tfilters?: StreamsFilterMap;\n\t/** Events per page (the `limit` query param). Default 100. */\n\tbatchSize?: number;\n\t/** Poll interval while caught up at the tip, in ms. Default 2000. */\n\tintervalMs?: number;\n\t/** Abort to end the iteration. */\n\tsignal?: AbortSignal;\n};\n\nexport type StreamsEventsConsumeResult = {\n\tcursor: string | null;\n\tpages: number;\n\temptyPolls: number;\n};\n\nexport type StreamsEventsReplayParams = {\n\t/** Start point: `\"genesis\"` (default) or a `<block>:<index>` cursor. */\n\tfrom?: \"genesis\" | string;\n\t/**\n\t * Called once per finalized dump file, in block order, before live tailing.\n\t * Process the parquet with your own tooling (e.g. DuckDB) — the SDK does not\n\t * decode parquet. Use `client.dumps.download(file)` to fetch + verify bytes.\n\t *\n\t * Delivery is file-granular and at-least-once: a file whose range straddles\n\t * `from` is handed over whole. `ctx.from` is that cursor (`null` from\n\t * genesis); skip rows at or below it, or key rows by `cursor` so a re-run\n\t * is an idempotent no-op. Files ending at or below `from` are not handed\n\t * over at all.\n\t */\n\tonDumpFile: (\n\t\tfile: StreamsDumpFile,\n\t\tctx: { from: string | null },\n\t) => Promise<void> | void;\n\t/** Called per live page after the dump phase, like `consume`. */\n\tonBatch: (\n\t\tevents: StreamsEvent[],\n\t\tenvelope: StreamsEventsEnvelope,\n\t) => Promise<string | null | undefined> | string | null | undefined;\n\t/**\n\t * Called when the live-tail phase (after the dump backfill) crosses a reorg,\n\t * before the cursor rewinds and re-reads the now-canonical events — same\n\t * contract as `consume`. The dump-backfill phase is finalized and never\n\t * reorgs; omit this to leave stale rows from an orphaned fork in place.\n\t */\n\tonReorg?: (\n\t\treorg: StreamsReorg,\n\t\tctx: StreamsReorgContext,\n\t) => Promise<void> | void;\n\tmode?: \"tail\" | \"bounded\";\n\tbatchSize?: number;\n\temptyBackoffMs?: number;\n\tmaxPages?: number;\n\tmaxEmptyPolls?: number;\n\tsignal?: AbortSignal;\n\t/** Narrow the LIVE TAIL after the dump phase. The dump files themselves are\n\t * always all-type (block-partitioned parquet) — filter those in your own\n\t * tooling while processing each file. */\n\ttypes?: readonly StreamsEventType[];\n\tnotTypes?: readonly StreamsEventType[];\n\t/** Labelled OR-groups for the live tail, like `consume`. */\n\tfilters?: StreamsFilterMap;\n};\n\nexport type FetchLike = (\n\tinput: string | URL | Request,\n\tinit?: RequestInit,\n) => Promise<Response>;\n\n/** One bulk parquet file in the dumps manifest. `path` is the object key under\n * the dumps base URL. */\nexport type StreamsDumpFile = {\n\tpath: string;\n\tfrom_block: number;\n\tto_block: number;\n\tmin_cursor: string | null;\n\tmax_cursor: string | null;\n\trow_count: number;\n\tbyte_size: number;\n\tsha256: string;\n\tschema_version: number;\n\tcreated_at: string;\n};\n\nexport type StreamsDumpsManifest = {\n\tdataset: string;\n\tnetwork: string;\n\tversion: string;\n\tschema_version: number;\n\tgenerated_at: string;\n\tproducer_version: string;\n\tfinality_lag_blocks: number;\n\t/** Cursor at the end of the finalized bulk coverage — hand to live tailing. */\n\tlatest_finalized_cursor: string | null;\n\tcoverage: { from_block: number; to_block: number };\n\tfiles: StreamsDumpFile[];\n\t/** ed25519 signature over the manifest's canonical bytes. Absent on legacy\n\t * unsigned manifests. Verified by `list()` when `verifyDumpsManifest` is on. */\n\tsignature?: string;\n\t/** Short id of the signing public key. */\n\tkey_id?: string;\n};\n\nexport type StreamsDumps = {\n\t/** Fetch and parse the latest dumps manifest. */\n\tlist(): Promise<StreamsDumpsManifest>;\n\t/** Absolute URL for a manifest file. */\n\tfileUrl(file: StreamsDumpFile): string;\n\t/** Download a parquet file and verify its sha256 against the manifest. */\n\tdownload(file: StreamsDumpFile): Promise<Uint8Array>;\n};\n\nexport type StreamsClient = {\n\t/**\n\t * Follow Streams as an async iterator of page batches.\n\t *\n\t * Yields one {@link StreamsBatch} per `GET /v1/streams/events` page — the\n\t * existing envelope (`events`, `next_cursor` → `cursor`, `tip`, `reorgs`)\n\t * with zero extra API calls. Batches are chosen over per-block groupings\n\t * because the envelope is page-keyed, so every yield is exactly one fetch.\n\t * Empty pages are skipped; at the tip the iterator re-polls every\n\t * `intervalMs` (default 2000) until aborted via `signal`.\n\t *\n\t * Reorgs are surfaced on the batch (`batch.reorgs`) but the cursor is not\n\t * rewound automatically — use `events.consume` with `onReorg` for managed\n\t * rollback semantics.\n\t */\n\t/** Narrowing overload: a literal `types` array narrows every batch's\n\t * event union to exactly those members. */\n\tconsume<const T extends readonly StreamsEventType[]>(\n\t\tparams: StreamsConsumeParams & { types: T },\n\t): AsyncIterableIterator<StreamsBatch<StreamsEventOfTypes<T>>>;\n\tconsume(params?: StreamsConsumeParams): AsyncIterableIterator<StreamsBatch>;\n\tevents: {\n\t\t/** Narrowing overload, matching `consume`. */\n\t\tlist<const T extends readonly StreamsEventType[]>(\n\t\t\tparams: StreamsEventsListParams & { types: T },\n\t\t): Promise<StreamsEventsEnvelope<StreamsEventOfTypes<T>>>;\n\t\tlist(params?: StreamsEventsListParams): Promise<StreamsEventsEnvelope>;\n\t\tbyTxId(txId: string): Promise<StreamsEventsListEnvelope>;\n\t\t/**\n\t\t * Pull pages from Streams and call `onBatch` after each page.\n\t\t *\n\t\t * Use `consume` for indexers and ETL jobs that own checkpointing. Return\n\t\t * the checkpoint cursor from `onBatch`. Default `mode: \"tail\"` keeps\n\t\t * polling when caught up; `mode: \"bounded\"` exits on the first empty page.\n\t\t * The consumer also exits when `maxPages`, `maxEmptyPolls`, or `signal`\n\t\t * stops it.\n\t\t */\n\t\tconsume<\n\t\t\tconst F extends StreamsFilterMap = Record<never, never>,\n\t\t\tTTx = never,\n\t\t\tD extends boolean = false,\n\t\t>(\n\t\t\t// The redundant `sink` member gives TS a DIRECT inference site for\n\t\t\t// TTx — inference does not reliably traverse the params alias.\n\t\t\tparams: StreamsEventsConsumeParams<TTx, D, F> & {\n\t\t\t\tsink?: ConsumerSink<TTx>;\n\t\t\t},\n\t\t): Promise<StreamsEventsConsumeResult>;\n\t\t/**\n\t\t * Backfill from bulk dumps, then continue live from the dump→live seam in\n\t\t * one call. Iterates finalized dump files (via `onDumpFile`) in block\n\t\t * order, then tails live from the manifest's `latest_finalized_cursor`\n\t\t * (exclusive input → no gap or duplicate at the seam). Requires\n\t\t * `dumpsBaseUrl`.\n\t\t */\n\t\treplay(\n\t\t\tparams: StreamsEventsReplayParams,\n\t\t): Promise<StreamsEventsConsumeResult>;\n\t\t/**\n\t\t * Follow Streams as an async iterator.\n\t\t *\n\t\t * Use `stream` for live processors and watch-style apps. It tails\n\t\t * indefinitely by default and stops when its `AbortSignal`, `maxPages`, or\n\t\t * `maxEmptyPolls` stops it.\n\t\t */\n\t\t/** Narrowing overload, matching `consume`. */\n\t\tstream<const T extends readonly StreamsEventType[]>(\n\t\t\tparams: StreamsEventsStreamParams & { types: T },\n\t\t): AsyncIterable<StreamsEventOfTypes<T>>;\n\t\tstream(params?: StreamsEventsStreamParams): AsyncIterable<StreamsEvent>;\n\t\t/**\n\t\t * Subscribe to the real-time SSE push surface. Calls `onEvent` for each new\n\t\t * canonical event as the server pushes it (chain cadence, not poll-bounded),\n\t\t * and verifies each frame's inline ed25519 signature when the client was\n\t\t * created with `verify`. Returns an unsubscribe function whose `done`\n\t\t * settles when the loop ends. Not reorg-aware: an event delivered then\n\t\t * orphaned is never retracted. Durable writers use `consume()`.\n\t\t */\n\t\tsubscribe(params: StreamsEventsSubscribeParams): StreamsSubscription;\n\t};\n\tblocks: {\n\t\tevents(heightOrHash: number | string): Promise<StreamsEventsListEnvelope>;\n\t};\n\treorgs: {\n\t\tlist(params: StreamsReorgsListParams): Promise<StreamsReorgsListEnvelope>;\n\t};\n\t/** Bulk parquet dumps. Requires `dumpsBaseUrl` on the client. */\n\tdumps: StreamsDumps;\n\tcanonical(height: number): Promise<StreamsCanonicalBlock>;\n\ttip(): Promise<StreamsTip>;\n};\n"
15
+ "// Canonical event primitives (StreamsEvent, payload types, event-type vocab)\n// live in @secondlayer/shared/streams-rows; re-exported here so the public\n// Streams surface is unchanged.\nimport {\n\tSTREAMS_EVENT_TYPES,\n\ttype StreamsEvent,\n\ttype StreamsEventType,\n} from \"@secondlayer/shared/streams-rows\";\nimport type { IndexEvent } from \"../index-api/client.ts\";\nimport type { ConsumerSink, WithSinkTx } from \"../sinks/types.ts\";\n\nexport { STREAMS_EVENT_TYPES, type StreamsEvent, type StreamsEventType };\nexport type {\n\tFtBurnPayload,\n\tFtMintPayload,\n\tFtTransferPayload,\n\tNftBurnPayload,\n\tNftMintPayload,\n\tNftTransferPayload,\n\tPrintPayload,\n\tStreamsClarityValue,\n\tStreamsEventBase,\n\tStreamsEventPayload,\n\tStxBurnPayload,\n\tStxLockPayload,\n\tStxMintPayload,\n\tStxTransferPayload,\n} from \"@secondlayer/shared/streams-rows\";\n\nexport type StreamsTip = {\n\tblock_height: number;\n\tblock_hash: string;\n\tburn_block_height: number;\n\t/**\n\t * Highest Stacks block past the burn-confirmation finality boundary.\n\t * Optional for back-compat; the API always sets it.\n\t */\n\tfinalized_height?: number;\n\tlag_seconds: number;\n\t/**\n\t * Oldest height still seekable on the live API for the caller's tier\n\t * (`tip - retention`). `null` = unlimited retention. Older reads must use the\n\t * cold dumps lane. Optional for back-compat.\n\t */\n\toldest_seekable_height?: number | null;\n\t/** Oldest seekable cursor (`<oldest_seekable_height>:0`); `null` = unlimited. */\n\toldest_cursor?: string | null;\n};\n\nexport type StreamsCanonicalBlock = {\n\tblock_height: number;\n\tblock_hash: string;\n\tburn_block_height: number;\n\tburn_block_hash: string | null;\n\tis_canonical: true;\n};\n\nexport type StreamsReorg = {\n\tdetected_at: string;\n\tfork_point_height: number;\n\torphaned_range: { from: string; to: string };\n\t/**\n\t * First position of the new canonical chain at the fork, `fork:0`\n\t * (INCLUSIVE). Not an exclusive resume token — resuming directly from it\n\t * skips `fork:0`. The consumer rewinds to the foot of `fork_point_height`\n\t * (`Cursor.atHeight`) to re-read the new run from `fork:0` inclusive.\n\t */\n\tnew_canonical_tip: string;\n};\n\nexport type StreamsEventsEnvelope<TEvent = StreamsEvent> = {\n\tevents: TEvent[];\n\tnext_cursor: string | null;\n\ttip: StreamsTip;\n\treorgs: StreamsReorg[];\n};\n\nexport type StreamsEventsListEnvelope = Omit<\n\tStreamsEventsEnvelope,\n\t\"next_cursor\"\n>;\n\n/** The StreamsEvent union narrowed to a `types` selection — what a\n * const-generic `types: [\"ft_transfer\"]` buys at the type level. */\nexport type StreamsEventOfTypes<T extends readonly StreamsEventType[]> =\n\tExtract<StreamsEvent, { event_type: T[number] }>;\n\nexport type StreamsReorgsListParams = {\n\tsince: string;\n\tlimit?: number;\n};\n\nexport type StreamsReorgsListEnvelope = {\n\treorgs: StreamsReorg[];\n\tnext_since: string | null;\n};\n\n/** A filter that matches a single value or any value in a list. */\nexport type StreamsFilterValue = string | readonly string[];\n\n/**\n * One labelled filter group. Fields inside a group AND together; groups in a\n * map OR together server-side.\n */\nexport type StreamsLabelledFilter = {\n\ttypes?: readonly StreamsEventType[];\n\tcontractId?: StreamsFilterValue;\n\tsender?: StreamsFilterValue;\n\trecipient?: StreamsFilterValue;\n\tassetIdentifier?: string;\n};\n\n/** A map of label → filter group. Labels are yours; the server echoes them. */\nexport type StreamsFilterMap = Record<string, StreamsLabelledFilter>;\n\n/**\n * The events one label can yield. A group that declares `types` narrows to\n * exactly those variants, so a per-label handler needs no `event_type` guard;\n * a group without `types` keeps the full union.\n */\nexport type StreamsEventForFilter<F, D extends boolean = false> = F extends {\n\ttypes: readonly (infer T extends StreamsEventType)[];\n}\n\t? D extends true\n\t\t? Extract<IndexEvent, { event_type: T }>\n\t\t: Extract<StreamsEvent, { event_type: T }>\n\t: D extends true\n\t\t? IndexEvent\n\t\t: StreamsEvent;\n\nexport type StreamsEventsListParams = {\n\tcursor?: string | null;\n\tfromHeight?: number;\n\ttoHeight?: number;\n\ttypes?: readonly StreamsEventType[];\n\t/** Event types to exclude (applied after `types`). */\n\tnotTypes?: readonly StreamsEventType[];\n\tcontractId?: StreamsFilterValue;\n\tsender?: StreamsFilterValue;\n\trecipient?: StreamsFilterValue;\n\tassetIdentifier?: string;\n\t/**\n\t * Labelled filter groups. The groups OR together in one scan and each\n\t * returned event carries the labels it matched (`event.matched`) — two\n\t * unrelated concerns share one page, one cursor, one checkpoint.\n\t */\n\tfilters?: StreamsFilterMap;\n\tlimit?: number;\n};\n\nexport type StreamsEventsStreamParams = {\n\tfromCursor?: string | null;\n\ttypes?: readonly StreamsEventType[];\n\tnotTypes?: readonly StreamsEventType[];\n\tcontractId?: StreamsFilterValue;\n\tsender?: StreamsFilterValue;\n\trecipient?: StreamsFilterValue;\n\tassetIdentifier?: string;\n\t/** Labelled filter groups; see {@link StreamsEventsListParams.filters}. */\n\tfilters?: StreamsFilterMap;\n\tbatchSize?: number;\n\temptyBackoffMs?: number;\n\tmaxPages?: number;\n\tmaxEmptyPolls?: number;\n\tsignal?: AbortSignal;\n};\n\nexport type StreamsEventsSubscribeParams = {\n\t/** Resume strictly after this cursor; omit to live-tail from the tip. */\n\tfromCursor?: string | null;\n\ttypes?: readonly StreamsEventType[];\n\tnotTypes?: readonly StreamsEventType[];\n\tcontractId?: StreamsFilterValue;\n\tsender?: StreamsFilterValue;\n\trecipient?: StreamsFilterValue;\n\tassetIdentifier?: string;\n\t/** Labelled filter groups; see {@link StreamsEventsListParams.filters}. */\n\tfilters?: StreamsFilterMap;\n\t/** Abort to unsubscribe (the returned function does the same). */\n\tsignal?: AbortSignal;\n\t/**\n\t * Called for each pushed event, in order. The resume cursor advances only\n\t * after this resolves, so a handler that throws sees the same event again\n\t * on reconnect (at-least-once). Key durable writes by `cursor`.\n\t */\n\tonEvent: (event: StreamsEvent) => void | Promise<void>;\n\t/**\n\t * Called on every failure. Transport errors (dropped socket, 5xx, 429, a\n\t * stale connection, a throwing handler) reconnect from the last handled\n\t * cursor with exponential backoff. Errors that a retry cannot fix (401,\n\t * 4xx, a bad signature) end the subscription and reject its `done`.\n\t */\n\tonError?: (err: unknown) => void;\n\t/**\n\t * First reconnect pause in ms (default 1000). Doubles per consecutive\n\t * failure up to 30 s with jitter, resets once a frame arrives, and never\n\t * undercuts a `Retry-After`.\n\t */\n\treconnectDelayMs?: number;\n\t/**\n\t * Reconnect when no frame (pings included) arrives for this long (default\n\t * 60000, three server heartbeats). Catches a half-open socket that never\n\t * errors; set it above your instance's heartbeat interval.\n\t */\n\tstaleAfterMs?: number;\n};\n\n/**\n * Handle for a live subscription: call it to unsubscribe. `done` resolves\n * after unsubscribe (or the signal aborting) and rejects with the error that\n * ended the loop when a retry could not fix it, so a worker can `await`\n * it instead of polling for silence.\n */\nexport type StreamsSubscription = {\n\t(): void;\n\tdone: Promise<void>;\n};\n\n/**\n * The checkpoint the SDK computes for a batch. Persist `cursor` inside the same\n * transaction as your projection writes, then resume from it via `fromCursor`.\n * It is the position to advance to: `next_cursor` normally, or the last\n * finalized event when `finalizedOnly` is set.\n */\n/**\n * What the loop knows at the end of a page, handed to `onBatch`.\n *\n * `cursor` is the position to commit. The rest answers \"how far along am I,\n * and am I still moving\" — the question every deployed consumer has to expose\n * for a health check.\n *\n * Progress is reported here rather than left to callers because only the loop\n * can get it right: `height` has to survive empty pages (normal at the tip)\n * and has to roll back to `fork_point_height - 1` after a reorg rewind.\n * Deriving it from `cursor` is wrong — `Cursor.atHeight` encodes the foot of a\n * block as `${height - 1}:<sentinel>`, so a rewound cursor parses to a\n * position that was never reached.\n */\nexport type ConsumerBatchContext<TTip = unknown, TReorg = unknown> = {\n\t/** Checkpoint to commit alongside your rows. */\n\tcursor: string | null;\n\t/** Highest canonical block a row was DELIVERED from. `null` before the\n\t * first row of a fresh consume. With a sparse filter this parks at the\n\t * last matching event — it measures event recency, not progress. */\n\theight: number | null;\n\t/** Highest canonical block the sweep has VERIFIED through: an empty page\n\t * is the server confirming nothing matches between the cursor and the\n\t * tip, so a caught-up tail scans to the tip even when `height` is far\n\t * below it. Rolls back with reorg rewinds. */\n\tscannedHeight: number | null;\n\t/** Chain tip as of this page's read. */\n\ttipHeight: number;\n\t/** `tipHeight - scannedHeight`, floored at 0 — the consumer's actual\n\t * backlog. `null` until a position is known. A caught-up consumer on a\n\t * quiet contract reads ~0 here while `tipHeight - height` grows — that\n\t * difference is event age, not lag. */\n\tblocksBehind: number | null;\n\t/**\n\t * The full tip for this page — `StreamsTip` or `IndexTip` depending on the\n\t * surface. Exposed here so a handler never needs the `envelope` parameter,\n\t * which is the only way to reach it today and is also how the worst\n\t * `finalizedOnly` mistake becomes reachable (`return envelope.next_cursor`\n\t * jumps the cursor past events that were filtered out and never delivered).\n\t */\n\ttip: TTip;\n\t/**\n\t * Reorgs reported alongside this page; empty when none. Rollback still\n\t * belongs in `onReorg` — this is for observability inside a batch.\n\t */\n\treorgs: readonly TReorg[];\n};\n\n/** @deprecated Use {@link ConsumerBatchContext} — the Index and Streams loops\n * share one shape now. Kept as an alias so existing annotations compile. */\nexport type StreamsBatchContext = ConsumerBatchContext;\n\n/**\n * The checkpoint for a reorg rollback. Persist `cursor` (the rewind position)\n * inside the same transaction as your rollback so the two commit atomically.\n */\n/** `cursor` is the rewind position the loop resumes from after `onReorg`:\n * the foot of the fork point, or `null` for a fork at genesis. Persist it\n * in the same transaction as the rollback. */\nexport type StreamsReorgContext = { cursor: string | null };\n\nexport type StreamsEventsConsumeParams<\n\tTTx = never,\n\tD extends boolean = false,\n\tF extends StreamsFilterMap = Record<never, never>,\n> = {\n\tfromCursor?: string | null;\n\t/**\n\t * Deliver events pre-decoded as the flat, `event_type`-discriminated rows\n\t * Index serves (`IndexEvent`), so Streams consumption reads identically\n\t * to Index consumption — no guard+decode pairs in your handler.\n\t */\n\tdecoded?: D;\n\t/**\n\t * Destination adapter that owns the checkpoint + rollback transaction\n\t * (e.g. `kyselySink` from `@secondlayer/sdk/sinks/kysely`). With a sink:\n\t * the loop resumes from the sink's committed cursor, `onBatch` receives\n\t * `ctx.tx` and must write ONLY through it (rows and cursor commit in one\n\t * transaction), reorg rollback is automatic, and `onBatch`'s return value\n\t * is ignored. Folds (balances) invert in the sink's `onRollback`, not in\n\t * `onReorg`.\n\t */\n\tsink?: ConsumerSink<TTx>;\n\t/** Fires once per page, before `onBatch` and before any early return. */\n\tonProgress?: (ctx: ConsumerBatchContext) => void;\n\tmode?: \"tail\" | \"bounded\";\n\t/**\n\t * Emit only finalized (immutable) events and never surface reorgs. The SDK\n\t * checkpoints at the last finalized event and re-reads the unfinalized tail\n\t * until it settles. Trades finality lag for zero reorg handling; `onReorg` is\n\t * ignored.\n\t */\n\tfinalizedOnly?: boolean;\n\ttypes?: readonly StreamsEventType[];\n\tnotTypes?: readonly StreamsEventType[];\n\tcontractId?: StreamsFilterValue;\n\tsender?: StreamsFilterValue;\n\trecipient?: StreamsFilterValue;\n\tassetIdentifier?: string;\n\t/**\n\t * Labelled filter groups. The groups OR together in ONE server-side scan,\n\t * so two unrelated concerns share one page, one cursor, and one checkpoint\n\t * instead of two consume loops. Pair with `on` to handle each label.\n\t */\n\tfilters?: F;\n\t/**\n\t * One handler per label in `filters`. Every label must be handled, so\n\t * adding a label is a compile error until its handler exists.\n\t *\n\t * A label's declared `types` narrows its handler's events, so `payload` is\n\t * typed without an `event_type` guard. Labels are dispatched in declaration\n\t * order: a label's own events stay in cursor order, but events of different\n\t * labels do not interleave within a page — add `onBatch` when you need\n\t * strict global order across labels.\n\t */\n\ton?: {\n\t\t[K in keyof F]: (\n\t\t\tevents: StreamsEventForFilter<F[K], D>[],\n\t\t\tctx: StreamsBatchContext & WithSinkTx<TTx>,\n\t\t) => void | Promise<void>;\n\t};\n\tbatchSize?: number;\n\t/**\n\t * Apply a page of canonical events. Persist `ctx.cursor` in the same\n\t * transaction as your writes. Returning a cursor overrides `ctx.cursor` as\n\t * the resume point (advanced manual control); returning nothing uses it.\n\t *\n\t * Optional only when `on` handles the page instead; a consume call with\n\t * neither throws.\n\t */\n\tonBatch?: (\n\t\tevents: D extends true ? IndexEvent[] : StreamsEvent[],\n\t\t/**\n\t\t * @deprecated Read `ctx.tip` / `ctx.reorgs` instead. The envelope is\n\t\t * also how the worst `finalizedOnly` mistake stays reachable —\n\t\t * returning `envelope.next_cursor` jumps the cursor past unfinalized\n\t\t * events that were filtered out and never delivered. Removed in the\n\t\t * next major.\n\t\t */\n\t\tenvelope: StreamsEventsEnvelope,\n\t\tctx: StreamsBatchContext & WithSinkTx<TTx>,\n\t) =>\n\t\t| void\n\t\t| string\n\t\t| null\n\t\t| undefined\n\t\t| Promise<void>\n\t\t| Promise<string | null | undefined>;\n\t/**\n\t * Roll your projection back to `reorg.fork_point_height`, persisting\n\t * `ctx.cursor` in the same transaction. Called once per *new* reorg at or\n\t * below the checkpoint (deduped in-memory, fork-ascending) before the SDK\n\t * rewinds and re-reads the now-canonical events. A reorg whose fork sits\n\t * above the checkpoint is not a rollback (nothing past it was written) and\n\t * is skipped. Omit it to ignore reorgs (events stay canonical, but stale\n\t * rows from an orphaned fork are left in place).\n\t *\n\t * With `onReorg` or a `sink` attached, every empty page also polls\n\t * `reorgs.list` (one extra request per idle poll) so a fork that lands\n\t * while the consumer idles at the tip is rolled back too.\n\t */\n\tonReorg?: (\n\t\treorg: StreamsReorg,\n\t\tctx: StreamsReorgContext,\n\t) => Promise<void> | void;\n\t/** Deepest rewind one reorg may make below the checkpoint before the loop\n\t * refuses with `ValidationError`. Default 1000 blocks. The fork point is\n\t * server supplied and drives a delete on every declared table, so raise\n\t * this only for a source you trust. */\n\tmaxRollbackDepth?: number;\n\t/** Page-fetch retries after the first failure (429/5xx/network only —\n\t * 4xx and handler throws always propagate). Default 3; `0` disables. */\n\tretryCount?: number;\n\t/** Base retry delay in ms; the n-th retry waits `retryDelay * n`. A server\n\t * `Retry-After` overrides it. Default 1000. */\n\tretryDelay?: number;\n\t/** Void observer, called before each retry sleep (metrics/logging). */\n\tonError?: (\n\t\terr: unknown,\n\t\tctx: { attempt: number; retriesLeft: number; delayMs: number },\n\t) => void;\n\temptyBackoffMs?: number;\n\tmaxPages?: number;\n\tmaxEmptyPolls?: number;\n\tsignal?: AbortSignal;\n};\n\n/**\n * One yielded page from {@link StreamsClient.consume} — the\n * `GET /v1/streams/events` envelope verbatim, with `next_cursor` renamed to\n * `cursor` (the checkpoint to persist and resume from).\n */\nexport type StreamsBatch<TEvent = StreamsEvent> = {\n\t/** Canonical events of this page, in cursor order. */\n\tevents: TEvent[];\n\t/** Checkpoint after this page — pass back as `consume({ cursor })` to resume. */\n\tcursor: string | null;\n\ttip: StreamsTip;\n\t/** Chain reorgs reported alongside this page; empty when none. */\n\treorgs: StreamsReorg[];\n};\n\nexport type StreamsConsumeParams = {\n\t/** Resume strictly after this cursor; omit to start from the oldest seekable page. */\n\tcursor?: string | null;\n\ttypes?: readonly StreamsEventType[];\n\tnotTypes?: readonly StreamsEventType[];\n\tcontractId?: StreamsFilterValue;\n\tsender?: StreamsFilterValue;\n\trecipient?: StreamsFilterValue;\n\tassetIdentifier?: string;\n\t/** Labelled OR-groups — same semantics as `events.consume`; each returned\n\t * event echoes the labels it matched. */\n\tfilters?: StreamsFilterMap;\n\t/** Events per page (the `limit` query param). Default 100. */\n\tbatchSize?: number;\n\t/** Poll interval while caught up at the tip, in ms. Default 2000. */\n\tintervalMs?: number;\n\t/** Abort to end the iteration. */\n\tsignal?: AbortSignal;\n};\n\nexport type StreamsEventsConsumeResult = {\n\tcursor: string | null;\n\tpages: number;\n\temptyPolls: number;\n};\n\nexport type StreamsEventsReplayParams = {\n\t/** Start point: `\"genesis\"` (default) or a `<block>:<index>` cursor. */\n\tfrom?: \"genesis\" | string;\n\t/**\n\t * Called once per finalized dump file, in block order, before live tailing.\n\t * Process the parquet with your own tooling (e.g. DuckDB) — the SDK does not\n\t * decode parquet. Use `client.dumps.download(file)` to fetch + verify bytes.\n\t *\n\t * Delivery is file-granular and at-least-once: a file whose range straddles\n\t * `from` is handed over whole. `ctx.from` is that cursor (`null` from\n\t * genesis); skip rows at or below it, or key rows by `cursor` so a re-run\n\t * is an idempotent no-op. Files ending at or below `from` are not handed\n\t * over at all.\n\t */\n\tonDumpFile: (\n\t\tfile: StreamsDumpFile,\n\t\tctx: { from: string | null },\n\t) => Promise<void> | void;\n\t/** Called per live page after the dump phase, like `consume`. */\n\tonBatch: (\n\t\tevents: StreamsEvent[],\n\t\tenvelope: StreamsEventsEnvelope,\n\t) => Promise<string | null | undefined> | string | null | undefined;\n\t/**\n\t * Called when the live-tail phase (after the dump backfill) crosses a reorg,\n\t * before the cursor rewinds and re-reads the now-canonical events — same\n\t * contract as `consume`. The dump-backfill phase is finalized and never\n\t * reorgs; omit this to leave stale rows from an orphaned fork in place.\n\t */\n\tonReorg?: (\n\t\treorg: StreamsReorg,\n\t\tctx: StreamsReorgContext,\n\t) => Promise<void> | void;\n\tmode?: \"tail\" | \"bounded\";\n\tbatchSize?: number;\n\temptyBackoffMs?: number;\n\tmaxPages?: number;\n\tmaxEmptyPolls?: number;\n\tsignal?: AbortSignal;\n\t/** Narrow the LIVE TAIL after the dump phase. The dump files themselves are\n\t * always all-type (block-partitioned parquet) — filter those in your own\n\t * tooling while processing each file. */\n\ttypes?: readonly StreamsEventType[];\n\tnotTypes?: readonly StreamsEventType[];\n\t/** Labelled OR-groups for the live tail, like `consume`. */\n\tfilters?: StreamsFilterMap;\n};\n\nexport type FetchLike = (\n\tinput: string | URL | Request,\n\tinit?: RequestInit,\n) => Promise<Response>;\n\n/** One bulk parquet file in the dumps manifest. `path` is the object key under\n * the dumps base URL. */\nexport type StreamsDumpFile = {\n\tpath: string;\n\tfrom_block: number;\n\tto_block: number;\n\tmin_cursor: string | null;\n\tmax_cursor: string | null;\n\trow_count: number;\n\tbyte_size: number;\n\tsha256: string;\n\tschema_version: number;\n\tcreated_at: string;\n};\n\nexport type StreamsDumpsManifest = {\n\tdataset: string;\n\tnetwork: string;\n\tversion: string;\n\tschema_version: number;\n\tgenerated_at: string;\n\tproducer_version: string;\n\tfinality_lag_blocks: number;\n\t/** Cursor at the end of the finalized bulk coverage — hand to live tailing. */\n\tlatest_finalized_cursor: string | null;\n\tcoverage: { from_block: number; to_block: number };\n\tfiles: StreamsDumpFile[];\n\t/** ed25519 signature over the manifest's canonical bytes. Absent on legacy\n\t * unsigned manifests. Verified by `list()` when `verifyDumpsManifest` is on. */\n\tsignature?: string;\n\t/** Short id of the signing public key. */\n\tkey_id?: string;\n};\n\nexport type StreamsDumps = {\n\t/** Fetch and parse the latest dumps manifest. */\n\tlist(): Promise<StreamsDumpsManifest>;\n\t/** Absolute URL for a manifest file. */\n\tfileUrl(file: StreamsDumpFile): string;\n\t/** Download a parquet file and verify its sha256 against the manifest. */\n\tdownload(file: StreamsDumpFile): Promise<Uint8Array>;\n};\n\nexport type StreamsClient = {\n\t/**\n\t * Follow Streams as an async iterator of page batches.\n\t *\n\t * Yields one {@link StreamsBatch} per `GET /v1/streams/events` page — the\n\t * existing envelope (`events`, `next_cursor` → `cursor`, `tip`, `reorgs`)\n\t * with zero extra API calls. Batches are chosen over per-block groupings\n\t * because the envelope is page-keyed, so every yield is exactly one fetch.\n\t * Empty pages are skipped; at the tip the iterator re-polls every\n\t * `intervalMs` (default 2000) until aborted via `signal`.\n\t *\n\t * Reorgs are surfaced on the batch (`batch.reorgs`) but the cursor is not\n\t * rewound automatically — use `events.consume` with `onReorg` for managed\n\t * rollback semantics.\n\t */\n\t/** Narrowing overload: a literal `types` array narrows every batch's\n\t * event union to exactly those members. */\n\tconsume<const T extends readonly StreamsEventType[]>(\n\t\tparams: StreamsConsumeParams & { types: T },\n\t): AsyncIterableIterator<StreamsBatch<StreamsEventOfTypes<T>>>;\n\tconsume(params?: StreamsConsumeParams): AsyncIterableIterator<StreamsBatch>;\n\tevents: {\n\t\t/** Narrowing overload, matching `consume`. */\n\t\tlist<const T extends readonly StreamsEventType[]>(\n\t\t\tparams: StreamsEventsListParams & { types: T },\n\t\t): Promise<StreamsEventsEnvelope<StreamsEventOfTypes<T>>>;\n\t\tlist(params?: StreamsEventsListParams): Promise<StreamsEventsEnvelope>;\n\t\tbyTxId(txId: string): Promise<StreamsEventsListEnvelope>;\n\t\t/**\n\t\t * Pull pages from Streams and call `onBatch` after each page.\n\t\t *\n\t\t * Use `consume` for indexers and ETL jobs that own checkpointing. Return\n\t\t * the checkpoint cursor from `onBatch`. Default `mode: \"tail\"` keeps\n\t\t * polling when caught up; `mode: \"bounded\"` exits on the first empty page.\n\t\t * The consumer also exits when `maxPages`, `maxEmptyPolls`, or `signal`\n\t\t * stops it.\n\t\t */\n\t\tconsume<\n\t\t\tconst F extends StreamsFilterMap = Record<never, never>,\n\t\t\tTTx = never,\n\t\t\tD extends boolean = false,\n\t\t>(\n\t\t\t// The redundant `sink` member gives TS a DIRECT inference site for\n\t\t\t// TTx — inference does not reliably traverse the params alias.\n\t\t\tparams: StreamsEventsConsumeParams<TTx, D, F> & {\n\t\t\t\tsink?: ConsumerSink<TTx>;\n\t\t\t},\n\t\t): Promise<StreamsEventsConsumeResult>;\n\t\t/**\n\t\t * Backfill from bulk dumps, then continue live from the dump→live seam in\n\t\t * one call. Iterates finalized dump files (via `onDumpFile`) in block\n\t\t * order, then tails live from the manifest's `latest_finalized_cursor`\n\t\t * (exclusive input → no gap or duplicate at the seam). Requires\n\t\t * `dumpsBaseUrl`.\n\t\t */\n\t\treplay(\n\t\t\tparams: StreamsEventsReplayParams,\n\t\t): Promise<StreamsEventsConsumeResult>;\n\t\t/**\n\t\t * Follow Streams as an async iterator.\n\t\t *\n\t\t * Use `stream` for live processors and watch-style apps. It tails\n\t\t * indefinitely by default and stops when its `AbortSignal`, `maxPages`, or\n\t\t * `maxEmptyPolls` stops it.\n\t\t */\n\t\t/** Narrowing overload, matching `consume`. */\n\t\tstream<const T extends readonly StreamsEventType[]>(\n\t\t\tparams: StreamsEventsStreamParams & { types: T },\n\t\t): AsyncIterable<StreamsEventOfTypes<T>>;\n\t\tstream(params?: StreamsEventsStreamParams): AsyncIterable<StreamsEvent>;\n\t\t/**\n\t\t * Subscribe to the real-time SSE push surface. Calls `onEvent` for each new\n\t\t * canonical event as the server pushes it (chain cadence, not poll-bounded),\n\t\t * and verifies each frame's inline ed25519 signature when the client was\n\t\t * created with `verify`. Returns an unsubscribe function whose `done`\n\t\t * settles when the loop ends. Not reorg-aware: an event delivered then\n\t\t * orphaned is never retracted. Durable writers use `consume()`.\n\t\t */\n\t\tsubscribe(params: StreamsEventsSubscribeParams): StreamsSubscription;\n\t};\n\tblocks: {\n\t\tevents(heightOrHash: number | string): Promise<StreamsEventsListEnvelope>;\n\t};\n\treorgs: {\n\t\tlist(params: StreamsReorgsListParams): Promise<StreamsReorgsListEnvelope>;\n\t};\n\t/** Bulk parquet dumps. Requires `dumpsBaseUrl` on the client. */\n\tdumps: StreamsD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+B;AAAA,QACrC,OAAO,QACN,sBAAsB,mBAAmB,OAAO,YAAY,CAAC,UAC9D;AAAA;AAAA,IAEF;AAAA,IACA,QAAQ,EAAE,MAAM,WAAW;AAAA,IAC3B;AAAA,IACA,SAAS,CAAC,QAAgB;AAAA,MACzB,OAAO,QAA+B,yBAAyB,QAAQ;AAAA;AAAA,IAExE,GAAG,GAAG;AAAA,MACL,OAAO,QAAoB,iBAAiB;AAAA;AAAA,EAE9C;AAAA;;;ASnhBD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AClBA;AAAA;AAAA;",
18
18
  "debugId": "6013F1D9BD2F6AD764756E2164756E21",
@@ -686,7 +686,8 @@ type StreamsEventsConsumeParams<
686
686
  * the loop resumes from the sink's committed cursor, `onBatch` receives
687
687
  * `ctx.tx` and must write ONLY through it (rows and cursor commit in one
688
688
  * transaction), reorg rollback is automatic, and `onBatch`'s return value
689
- * is ignored.
689
+ * is ignored. Folds (balances) invert in the sink's `onRollback`, not in
690
+ * `onReorg`.
690
691
  */
691
692
  sink?: ConsumerSink<TTx>;
692
693
  /** Fires once per page, before `onBatch` and before any early return. */
@@ -1032,7 +1033,8 @@ type IndexConsumeOptions<
1032
1033
  * the loop resumes from the sink's committed cursor, `onBatch` receives
1033
1034
  * `ctx.tx` and must write ONLY through it (rows and cursor commit in one
1034
1035
  * transaction — a throw aborts both), reorg rollback is automatic (no
1035
- * `onReorg` needed), and `onBatch`'s return value is ignored.
1036
+ * `onReorg` needed), and `onBatch`'s return value is ignored. Folds
1037
+ * (balances) invert in the sink's `onRollback`, not in `onReorg`.
1036
1038
  */
1037
1039
  sink?: ConsumerSink<TTx>;
1038
1040
  /** Fires once per page, before `onBatch` and before any early return —