@secondlayer/sdk 9.0.2 → 10.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +85 -17
- package/README.md +98 -31
- package/dist/index.d.ts +234 -113
- package/dist/index.js +768 -436
- package/dist/index.js.map +19 -19
- package/dist/sinks/bun-sqlite.d.ts +18 -4
- package/dist/sinks/bun-sqlite.js +21 -20
- package/dist/sinks/bun-sqlite.js.map +5 -5
- package/dist/sinks/core.d.ts +30 -7
- package/dist/sinks/core.js +16 -19
- package/dist/sinks/core.js.map +4 -4
- package/dist/sinks/drizzle.d.ts +23 -6
- package/dist/sinks/drizzle.js +22 -21
- package/dist/sinks/drizzle.js.map +5 -5
- package/dist/sinks/kysely.d.ts +26 -11
- package/dist/sinks/kysely.js +23 -21
- package/dist/sinks/kysely.js.map +5 -5
- package/dist/sinks/testing.d.ts +4 -1
- package/dist/sinks/testing.js +14 -1
- package/dist/sinks/testing.js.map +3 -3
- package/dist/streams/index.d.ts +92 -23
- package/dist/streams/index.js +395 -183
- package/dist/streams/index.js.map +12 -12
- package/dist/subgraphs/index.d.ts +202 -94
- package/dist/subgraphs/index.js +764 -434
- package/dist/subgraphs/index.js.map +17 -17
- package/package.json +4 -4
|
@@ -2,19 +2,19 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["src/streams/client.ts", "src/errors.ts", "src/base.ts", "src/streams/cursor.ts", "src/streams/errors.ts", "src/streams/consumer.ts", "src/streams/decode.ts", "src/streams/dumps.ts", "src/streams/subscribe.ts", "src/streams/index.ts", "src/streams/types.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"import { ed25519 } from \"@secondlayer/shared\";\nimport { buildQuery, resolveBaseUrl } from \"../base.ts\";\nimport type { IndexEvent } from \"../index-api/client.ts\";\nimport type { ConsumerSink } from \"../sinks/types.ts\";\nimport {\n\ttype StreamsEventsFetcher,\n\tconsumeStreamsEvents,\n\titerateStreamsBatches,\n\tstreamStreamsEvents,\n} from \"./consumer.ts\";\nimport { Cursor } from \"./cursor.ts\";\nimport { decode } from \"./decode.ts\";\nimport { createStreamsDumps } from \"./dumps.ts\";\nimport {\n\tAuthError,\n\tRateLimitError,\n\tStreamsServerError,\n\tStreamsSignatureError,\n\tValidationError,\n} from \"./errors.ts\";\nimport { subscribeStreamsEvents } from \"./subscribe.ts\";\nimport type {\n\tFetchLike,\n\tStreamsCanonicalBlock,\n\tStreamsClient,\n\tStreamsConsumeParams,\n\tStreamsEvent,\n\tStreamsEventType,\n\tStreamsEventsConsumeParams,\n\tStreamsEventsConsumeResult,\n\tStreamsEventsEnvelope,\n\tStreamsEventsListEnvelope,\n\tStreamsEventsListParams,\n\tStreamsEventsReplayParams,\n\tStreamsEventsStreamParams,\n\tStreamsEventsSubscribeParams,\n\tStreamsFilterMap,\n\tStreamsFilterValue,\n\tStreamsReorgsListEnvelope,\n\tStreamsReorgsListParams,\n\tStreamsTip,\n} from \"./types.ts\";\n\n/** Parse a `<block>:<index>` cursor; null sorts before genesis. */\nfunction cursorTuple(cursor: string | null): [number, number] {\n\tif (!cursor) return [-1, -1];\n\tconst { blockHeight, eventIndex } = Cursor.parse(cursor);\n\treturn [blockHeight, eventIndex];\n}\n\n/** The greater of two cursors (later in the stream). */\nfunction maxCursor(a: string | null, b: string | null): string | null {\n\tconst [ah, ai] = cursorTuple(a);\n\tconst [bh, bi] = cursorTuple(b);\n\treturn ah > bh || (ah === bh && ai >= bi) ? a : b;\n}\n\n/**\n * The narrowing set every Streams read forwards verbatim to the consumer\n * loops. Kept in one place because each field is optional: a forgotten one is\n * a type-checkable object that silently widens the stream toward the full\n * firehose — which is billed per row, and has happened. `events.replay()`\n * deliberately forwards a subset and stays explicit.\n */\nfunction streamsFilters(params: {\n\ttypes?: readonly StreamsEventType[];\n\tnotTypes?: readonly StreamsEventType[];\n\tcontractId?: StreamsFilterValue;\n\tsender?: StreamsFilterValue;\n\trecipient?: StreamsFilterValue;\n\tassetIdentifier?: string;\n\tfilters?: StreamsFilterMap;\n}) {\n\treturn {\n\t\ttypes: params.types,\n\t\tnotTypes: params.notTypes,\n\t\tcontractId: params.contractId,\n\t\tsender: params.sender,\n\t\trecipient: params.recipient,\n\t\tassetIdentifier: params.assetIdentifier,\n\t\tfilters: params.filters,\n\t};\n}\n\nexport type CreateStreamsClientOptions = {\n\tapiKey?: string;\n\tbaseUrl?: string;\n\tfetchImpl?: FetchLike;\n\t/**\n\t * Public base URL for bulk parquet dumps (the R2/CDN bucket root). Required\n\t * to use `client.dumps`. See `GET /public/streams/dumps/manifest`.\n\t */\n\tdumpsBaseUrl?: string;\n\t/**\n\t * Verify the ed25519 `X-Signature` on every REST response and per-frame SSE\n\t * signature. Three states:\n\t * - **default (omitted)** — *lenient*: verify when the server signs (the\n\t * hosted API signs every response), and pass through when no signature is\n\t * present (e.g. a self-hosted instance with no `STREAMS_SIGNING_PRIVATE_KEY`).\n\t * So verification is on by default against the hosted API without breaking\n\t * unsigned self-host deployments. An *invalid* signature always throws.\n\t * - **`true`** (or `{ publicKey }` to pin a known PEM) — *strict*: a missing\n\t * OR invalid signature throws `StreamsSignatureError`. Use this when you\n\t * require a portable, non-repudiable attestation and won't accept unsigned\n\t * data (it also closes the lenient mode's strip-the-header downgrade).\n\t * - **`false`** — off.\n\t *\n\t * The key is fetched once from `/public/streams/signing-key` (cached; a\n\t * rotated `X-Signature-KeyId` triggers one refresh) unless a PEM is pinned.\n\t */\n\tverify?: boolean | { publicKey: string };\n\t/**\n\t * Verify the bulk dumps manifest's ed25519 signature in `client.dumps.list()`\n\t * before trusting any file sha256 (default ON). Uses the same key source as\n\t * `verify` (fetches `/public/streams/signing-key`, or a pinned PEM). Pass\n\t * `false` to opt out. A missing or invalid signature throws\n\t * `StreamsSignatureError`.\n\t */\n\tverifyDumpsManifest?: boolean;\n};\n\nfunction normalizeBaseUrl(baseUrl: string): string {\n\treturn baseUrl.replace(/\\/+$/, \"\");\n}\n\nasync function responseBody(response: Response): Promise<unknown> {\n\tconst text = await response.text();\n\tif (text.length === 0) return undefined;\n\ttry {\n\t\treturn JSON.parse(text);\n\t} catch {\n\t\treturn text;\n\t}\n}\n\nfunction errorMessage(body: unknown, fallback: string): string {\n\tif (body && typeof body === \"object\") {\n\t\tconst record = body as Record<string, unknown>;\n\t\tconst message = record.error ?? record.message;\n\t\tif (typeof message === \"string\" && message.length > 0) return message;\n\t}\n\tif (typeof body === \"string\" && body.length > 0) return body;\n\treturn fallback;\n}\n\nasync function mapStreamsError(response: Response): Promise<never> {\n\tconst body = await responseBody(response);\n\n\tif (response.status === 401) {\n\t\tthrow new AuthError(errorMessage(body, \"API key invalid or expired.\"));\n\t}\n\n\tif (response.status === 429) {\n\t\tconst retryAfter = response.headers.get(\"Retry-After\") ?? undefined;\n\t\tthrow new RateLimitError(\n\t\t\terrorMessage(body, \"Rate limited. Try again later.\"),\n\t\t\tretryAfter,\n\t\t);\n\t}\n\n\tif (response.status >= 500) {\n\t\tthrow new StreamsServerError(\n\t\t\terrorMessage(body, `Streams server returned ${response.status}.`),\n\t\t\tresponse.status,\n\t\t\tbody,\n\t\t);\n\t}\n\n\tthrow new ValidationError(\n\t\terrorMessage(body, `Streams request returned ${response.status}.`),\n\t\tresponse.status,\n\t\tbody,\n\t);\n}\n\nexport function createStreamsClient(\n\toptions: CreateStreamsClientOptions,\n): StreamsClient {\n\tconst baseUrl = normalizeBaseUrl(resolveBaseUrl(options.baseUrl));\n\tconst fetchImpl = options.fetchImpl ?? ((input, init) => fetch(input, init));\n\tconst verify = options.verify;\n\t// On by default, but lenient: the hosted API signs every response, while a\n\t// self-hosted instance without STREAMS_SIGNING_PRIVATE_KEY serves none.\n\t// Lenient verifies when a signature is present and passes through when it is\n\t// absent — so the default neither skips hosted verification nor breaks OSS.\n\t// `verify: true` / `{ publicKey }` is strict (missing signature throws);\n\t// `verify: false` is off. An invalid signature always throws.\n\tconst verifyMode: \"off\" | \"lenient\" | \"strict\" =\n\t\tverify === false ? \"off\" : verify === undefined ? \"lenient\" : \"strict\";\n\n\t// Lazily resolve and cache the verification key alongside its id, so a\n\t// rotation (signalled by a changed `X-Signature-KeyId`) can be detected.\n\ttype VerificationKey = {\n\t\tkeyId: string;\n\t\tpublicKeyPem: string;\n\t\tpublicKey: ReturnType<typeof ed25519.loadEd25519PublicKey>;\n\t};\n\tlet keyPromise: Promise<VerificationKey> | null = null;\n\tfunction loadKey(): Promise<VerificationKey> {\n\t\tif (keyPromise) return keyPromise;\n\t\tkeyPromise = (async () => {\n\t\t\tif (typeof verify === \"object\") {\n\t\t\t\treturn {\n\t\t\t\t\tkeyId: ed25519.ed25519KeyId(verify.publicKey),\n\t\t\t\t\tpublicKeyPem: verify.publicKey,\n\t\t\t\t\tpublicKey: ed25519.loadEd25519PublicKey(verify.publicKey),\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst res = await fetchImpl(`${baseUrl}/public/streams/signing-key`);\n\t\t\tif (!res.ok) {\n\t\t\t\tthrow new StreamsSignatureError(\n\t\t\t\t\t`Could not fetch signing key (${res.status}).`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst body = (await res.json()) as {\n\t\t\t\tpublic_key_pem?: string;\n\t\t\t\tkey_id?: string;\n\t\t\t};\n\t\t\tif (!body.public_key_pem) {\n\t\t\t\tthrow new StreamsSignatureError(\"Signing key response missing key.\");\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tkeyId: body.key_id ?? ed25519.ed25519KeyId(body.public_key_pem),\n\t\t\t\tpublicKeyPem: body.public_key_pem,\n\t\t\t\tpublicKey: ed25519.loadEd25519PublicKey(body.public_key_pem),\n\t\t\t};\n\t\t})();\n\t\treturn keyPromise;\n\t}\n\n\tconst dumps = createStreamsDumps({\n\t\tbaseUrl: options.dumpsBaseUrl,\n\t\tfetchImpl,\n\t\tverifyManifest: options.verifyDumpsManifest ?? true,\n\t\tloadPublicKeyPem: async () => (await loadKey()).publicKeyPem,\n\t});\n\n\tasync function request<T>(path: string): Promise<T> {\n\t\tconst response = await fetchImpl(`${baseUrl}${path}`, {\n\t\t\theaders: options.apiKey\n\t\t\t\t? { Authorization: `Bearer ${options.apiKey}` }\n\t\t\t\t: {},\n\t\t});\n\t\tif (!response.ok) await mapStreamsError(response);\n\t\tconst text = await response.text();\n\t\tif (verifyMode !== \"off\") {\n\t\t\tconst signature = response.headers.get(\"X-Signature\");\n\t\t\tif (!signature) {\n\t\t\t\t// Strict requires a signature; lenient (default) lets an unsigned\n\t\t\t\t// response through — e.g. self-host with no signing key configured.\n\t\t\t\tif (verifyMode === \"strict\") {\n\t\t\t\t\tthrow new StreamsSignatureError(\"Response is missing X-Signature.\");\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst responseKeyId = response.headers.get(\"X-Signature-KeyId\");\n\t\t\t\tlet key = await loadKey();\n\t\t\t\t// The server rotated to a key we haven't seen.\n\t\t\t\tif (responseKeyId && responseKeyId !== key.keyId) {\n\t\t\t\t\tif (typeof verify === \"object\") {\n\t\t\t\t\t\t// Pinned key: a different id is never the pinned key — fail closed.\n\t\t\t\t\t\tthrow new StreamsSignatureError(\n\t\t\t\t\t\t\t`Response signed with key '${responseKeyId}', expected pinned key '${key.keyId}'.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\t// Fetched key: refresh once. A still-mismatched id (no re-loop)\n\t\t\t\t\t// means the endpoint doesn't serve the signing key — fail closed.\n\t\t\t\t\tkeyPromise = null;\n\t\t\t\t\tkey = await loadKey();\n\t\t\t\t\tif (responseKeyId !== key.keyId) {\n\t\t\t\t\t\tthrow new StreamsSignatureError(\n\t\t\t\t\t\t\t`Response signed with key '${responseKeyId}' not served by the signing-key endpoint.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// A signature is present, so verify it regardless of strict/lenient —\n\t\t\t\t// an invalid signature always fails closed.\n\t\t\t\tif (!ed25519.verifyEd25519(text, signature, key.publicKey)) {\n\t\t\t\t\tthrow new StreamsSignatureError();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn JSON.parse(text) as T;\n\t}\n\n\t// StreamsEventsFetchParams is a strict subset of StreamsEventsListParams, so\n\t// this is checked by the compiler rather than by a hand-copied destructure.\n\tconst fetchEvents: StreamsEventsFetcher = listEvents;\n\n\tfunction encodeFilters(filters: StreamsFilterMap | undefined) {\n\t\treturn filters ? JSON.stringify(filters) : undefined;\n\t}\n\n\tasync function listEvents(\n\t\tparams: StreamsEventsListParams = {},\n\t): Promise<StreamsEventsEnvelope> {\n\t\treturn request<StreamsEventsEnvelope>(\n\t\t\t`/v1/streams/events${buildQuery({\n\t\t\t\tcursor: params.cursor,\n\t\t\t\tfrom_height: params.fromHeight,\n\t\t\t\tto_height: params.toHeight,\n\t\t\t\tlimit: params.limit,\n\t\t\t\tcontract_id: params.contractId,\n\t\t\t\tsender: params.sender,\n\t\t\t\trecipient: params.recipient,\n\t\t\t\tasset_identifier: params.assetIdentifier,\n\t\t\t\ttypes: params.types,\n\t\t\t\tnot_types: params.notTypes,\n\t\t\t\tfilters: encodeFilters(params.filters),\n\t\t\t})}`,\n\t\t);\n\t}\n\n\t/**\n\t * One signature, two shapes: a flat filter with `onBatch`, or a labelled\n\t * `filters` map with a handler per label (or both). Deliberately NOT\n\t * overloaded — an overloaded interface member strips contextual typing from\n\t * every stub and alternate implementation of `StreamsClient`.\n\t */\n\tfunction consumeEvents<\n\t\tconst F extends StreamsFilterMap = Record<never, never>,\n\t\tTTx = never,\n\t\tD extends boolean = false,\n\t>(\n\t\t// Redundant `sink` member: direct TTx inference site (inference\n\t\t// does not traverse the params alias).\n\t\tparams: StreamsEventsConsumeParams<TTx, D, F> & {\n\t\t\tsink?: ConsumerSink<TTx>;\n\t\t},\n\t): Promise<StreamsEventsConsumeResult> {\n\t\tconst labels = params.filters ? Object.keys(params.filters) : [];\n\t\t// The \"at least one handler\" rule is conditional on `filters`, so it\n\t\t// can't live in the type without making `F` uninferrable. Fail loudly\n\t\t// instead of consuming pages into nothing.\n\t\tif (labels.length === 0 && !params.onBatch) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t\"consume requires onBatch, or filters + on handlers.\",\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\tif (labels.length > 0 && !params.on && !params.onBatch) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t\"consume with filters requires on handlers (or onBatch).\",\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\tconst dispatch = params.on as\n\t\t\t| Record<\n\t\t\t\t\tstring,\n\t\t\t\t\t(\n\t\t\t\t\t\tevents: StreamsEvent[] | IndexEvent[],\n\t\t\t\t\t\tctx: Parameters<\n\t\t\t\t\t\t\tNonNullable<StreamsEventsConsumeParams<TTx>[\"onBatch\"]>\n\t\t\t\t\t\t>[2],\n\t\t\t\t\t) => void | Promise<void>\n\t\t\t >\n\t\t\t| undefined;\n\n\t\t// With `decoded: true`, events arrive as the flat Index-shaped rows —\n\t\t// decoding never appears in the handler.\n\t\tconst project = (events: StreamsEvent[]): StreamsEvent[] | IndexEvent[] =>\n\t\t\tparams.decoded ? events.map(decode) : events;\n\n\t\tconst onBatch: StreamsEventsConsumeParams<TTx>[\"onBatch\"] = async (\n\t\t\tevents,\n\t\t\tenvelope,\n\t\t\tctx,\n\t\t) => {\n\t\t\t// Label dispatch reads the wire `matched` array, so it has to run\n\t\t\t// BEFORE decode — the decoded row shape does not carry it.\n\t\t\tfor (const label of labels) {\n\t\t\t\tconst forLabel = events.filter((event) =>\n\t\t\t\t\tevent.matched?.includes(label),\n\t\t\t\t);\n\t\t\t\tif (forLabel.length === 0) continue;\n\t\t\t\tawait dispatch?.[label]?.(project(forLabel), ctx);\n\t\t\t}\n\t\t\t// The `decoded` flag is a runtime value here, so `project`'s return\n\t\t\t// can't be narrowed to the D-conditional the declared handler wants.\n\t\t\tconst userOnBatch = params.onBatch as StreamsEventsConsumeParams<\n\t\t\t\tTTx,\n\t\t\t\tboolean\n\t\t\t>[\"onBatch\"];\n\t\t\t// `onBatch`'s several legal return shapes collapse to one here: the\n\t\t\t// consume loop only ever reads a cursor string or nothing.\n\t\t\treturn (await userOnBatch?.(project(events), envelope, ctx)) as\n\t\t\t\t| string\n\t\t\t\t| null\n\t\t\t\t| undefined;\n\t\t};\n\n\t\treturn consumeStreamsEvents<TTx>({\n\t\t\tfromCursor: params.fromCursor,\n\t\t\tsink: params.sink,\n\t\t\tonProgress: params.onProgress,\n\t\t\tmode: params.mode,\n\t\t\tfinalizedOnly: params.finalizedOnly,\n\t\t\t...streamsFilters(params),\n\t\t\tbatchSize: params.batchSize ?? 100,\n\t\t\tfetchEvents,\n\t\t\tonBatch,\n\t\t\tonReorg: params.onReorg,\n\t\t\temptyBackoffMs: params.emptyBackoffMs,\n\t\t\tmaxPages: params.maxPages,\n\t\t\tmaxEmptyPolls: params.maxEmptyPolls,\n\t\t\tsignal: params.signal,\n\t\t\tretryCount: params.retryCount,\n\t\t\tretryDelay: params.retryDelay,\n\t\t\tonError: params.onError,\n\t\t});\n\t}\n\n\treturn {\n\t\tconsume(params: StreamsConsumeParams = {}) {\n\t\t\treturn iterateStreamsBatches({\n\t\t\t\tfromCursor: params.cursor,\n\t\t\t\tbatchSize: params.batchSize ?? 100,\n\t\t\t\tintervalMs: params.intervalMs ?? 2000,\n\t\t\t\t...streamsFilters(params),\n\t\t\t\tsignal: params.signal,\n\t\t\t\tfetchEvents,\n\t\t\t});\n\t\t},\n\t\tevents: {\n\t\t\tlist: listEvents,\n\t\t\tbyTxId(txId: string) {\n\t\t\t\treturn request<StreamsEventsListEnvelope>(\n\t\t\t\t\t`/v1/streams/events/${encodeURIComponent(txId)}`,\n\t\t\t\t);\n\t\t\t},\n\t\t\tconsume: consumeEvents,\n\t\t\tstream(params: StreamsEventsStreamParams = {}) {\n\t\t\t\treturn streamStreamsEvents({\n\t\t\t\t\tfromCursor: params.fromCursor,\n\t\t\t\t\t// Includes the labelled OR-groups: dropping them here silently\n\t\t\t\t\t// widened the stream to the FULL firehose (billed per row).\n\t\t\t\t\t...streamsFilters(params),\n\t\t\t\t\tbatchSize: params.batchSize ?? 100,\n\t\t\t\t\temptyBackoffMs: params.emptyBackoffMs,\n\t\t\t\t\tmaxPages: params.maxPages,\n\t\t\t\t\tmaxEmptyPolls: params.maxEmptyPolls,\n\t\t\t\t\tsignal: params.signal,\n\t\t\t\t\tfetchEvents,\n\t\t\t\t});\n\t\t\t},\n\t\t\tsubscribe(params: StreamsEventsSubscribeParams) {\n\t\t\t\treturn subscribeStreamsEvents({\n\t\t\t\t\tbaseUrl,\n\t\t\t\t\tapiKey: options.apiKey,\n\t\t\t\t\tfetchImpl,\n\t\t\t\t\tverify: verifyMode,\n\t\t\t\t\tloadKey,\n\t\t\t\t\tparams,\n\t\t\t\t});\n\t\t\t},\n\t\t\tasync replay(params: StreamsEventsReplayParams) {\n\t\t\t\tconst fromCursor =\n\t\t\t\t\tparams.from === \"genesis\" ? null : (params.from ?? null);\n\t\t\t\tconst fromBlock = fromCursor ? cursorTuple(fromCursor)[0] : 0;\n\t\t\t\tconst manifest = await dumps.list();\n\n\t\t\t\t// Hydrate finalized history from dumps, in block order.\n\t\t\t\tconst files = manifest.files\n\t\t\t\t\t.filter((file) => file.to_block >= fromBlock)\n\t\t\t\t\t.sort(\n\t\t\t\t\t\t(a, b) => a.from_block - b.from_block || a.to_block - b.to_block,\n\t\t\t\t\t);\n\t\t\t\tfor (const file of files) {\n\t\t\t\t\tif (params.signal?.aborted) break;\n\t\t\t\t\tawait params.onDumpFile(file);\n\t\t\t\t}\n\n\t\t\t\t// Seam: tail live from just past the dumped coverage. Cursor input is\n\t\t\t\t// exclusive, so the first live event is strictly after the last dump.\n\t\t\t\tconst seam = maxCursor(fromCursor, manifest.latest_finalized_cursor);\n\t\t\t\treturn consumeStreamsEvents({\n\t\t\t\t\tfromCursor: seam,\n\t\t\t\t\tmode: params.mode ?? \"tail\",\n\t\t\t\t\tbatchSize: params.batchSize ?? 100,\n\t\t\t\t\t// Live-tail narrowing only — the dump phase above hands over\n\t\t\t\t\t// whole all-type files by design.\n\t\t\t\t\ttypes: params.types,\n\t\t\t\t\tnotTypes: params.notTypes,\n\t\t\t\t\tfilters: params.filters,\n\t\t\t\t\tfetchEvents,\n\t\t\t\t\tonBatch: params.onBatch,\n\t\t\t\t\tonReorg: params.onReorg,\n\t\t\t\t\temptyBackoffMs: params.emptyBackoffMs,\n\t\t\t\t\tmaxPages: params.maxPages,\n\t\t\t\t\tmaxEmptyPolls: params.maxEmptyPolls,\n\t\t\t\t\tsignal: params.signal,\n\t\t\t\t});\n\t\t\t},\n\t\t},\n\t\tblocks: {\n\t\t\tevents(heightOrHash: number | string) {\n\t\t\t\treturn request<StreamsEventsListEnvelope>(\n\t\t\t\t\t`/v1/streams/blocks/${encodeURIComponent(String(heightOrHash))}/events`,\n\t\t\t\t);\n\t\t\t},\n\t\t},\n\t\treorgs: {\n\t\t\tlist(params: StreamsReorgsListParams) {\n\t\t\t\treturn request<StreamsReorgsListEnvelope>(\n\t\t\t\t\t`/v1/streams/reorgs${buildQuery({\n\t\t\t\t\t\tsince: params.since,\n\t\t\t\t\t\tlimit: params.limit,\n\t\t\t\t\t})}`,\n\t\t\t\t);\n\t\t\t},\n\t\t},\n\t\tdumps,\n\t\tcanonical(height: number) {\n\t\t\treturn request<StreamsCanonicalBlock>(`/v1/streams/canonical/${height}`);\n\t\t},\n\t\ttip() {\n\t\t\treturn request<StreamsTip>(\"/v1/streams/tip\");\n\t\t},\n\t};\n}\n",
|
|
6
|
-
"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
|
|
7
|
-
"import { ApiError, AuthError, RateLimitError } from \"./errors.ts\";\n\nexport type FetchLike = (\n\tinput: string | URL | Request,\n\tinit?: RequestInit,\n) => Promise<Response>;\n\nexport interface SecondLayerOptions {\n\t/** Base URL of the instance API (trailing slashes are stripped). */\n\tbaseUrl: string;\n\t/** Bearer token for authenticated requests. */\n\tapiKey?: string;\n\t/** Fetch implementation. Tests and edge runtimes can provide their own. */\n\tfetchImpl?: FetchLike;\n\t/** Public base URL for Streams bulk parquet dumps (the cold backfill plane).\n\t * Required for `streams.dumps.*`; without it the dumps client falls back to\n\t * its built-in default. */\n\tdumpsBaseUrl?: string;\n\t/** Deploy origin label sent as `x-sl-origin` (telemetry). Defaults to `cli`. */\n\torigin?: \"cli\" | \"mcp\" | \"session\";\n}\n\n/** Product default: the local one-box API. Override with `baseUrl` or `SL_API_URL`. */\nexport const LOCAL_API_URL = \"http://127.0.0.1:3800\";\n\nexport function resolveBaseUrl(explicit?: string): string {\n\tif (explicit && explicit.length > 0) return explicit.replace(/\\/+$/, \"\");\n\tif (typeof process !== \"undefined\") {\n\t\tconst fromEnv = process.env?.SL_API_URL || process.env?.SECONDLAYER_API_URL;\n\t\tif (fromEnv) return fromEnv.replace(/\\/+$/, \"\");\n\t}\n\treturn LOCAL_API_URL;\n}\n\n/** Credential env vars, highest precedence first. `INSTANCE_TOKEN` is the\n * canonical name — it is what `secondlayer init` writes into `.env.local` and\n * what the instance API validates bearer tokens against. `SL_API_KEY` is a\n * legacy alias, kept working so existing exports and CI secrets don't break. */\nexport const CREDENTIAL_ENV_VARS = [\"INSTANCE_TOKEN\", \"SL_API_KEY\"] as const;\n\n/** Conflicting pairs already warned about, so a process with a genuine\n * misconfiguration says so once rather than on every client construction. */\nconst warnedConflicts = new Set<string>();\n\n/** Resolve the credential a client should use. Precedence, highest first:\n *\n * 1. an explicit `apiKey` option — including an explicit `\"\"`, which is how\n * you opt a client back into keyless reads on a machine that has a key\n * exported;\n * 2. `INSTANCE_TOKEN` — the canonical credential var, shared with the CLI\n * and MCP server;\n * 3. `SL_API_KEY` — legacy alias for the same value.\n *\n * Env values that are empty strings count as unset. Falling back to the env at\n * all is what stops `new Index()` from silently running keyless and 402-ing on\n * the first deep-history read.\n *\n * When both env vars are set to *different* non-empty values there is no\n * correct silent answer, so `INSTANCE_TOKEN` wins and we warn once on stderr —\n * the whole point of this precedence is that a misconfigured credential should\n * never authenticate as nobody without saying so.\n *\n * Guarded for browsers and edge runtimes, where `process` is undefined. */\nexport function resolveApiKey(apiKey?: string): string | undefined {\n\tif (apiKey !== undefined) return apiKey;\n\tif (typeof process === \"undefined\") return undefined;\n\tconst instanceToken = process.env?.INSTANCE_TOKEN || undefined;\n\tconst legacyKey = process.env?.SL_API_KEY || undefined;\n\tif (instanceToken && legacyKey && instanceToken !== legacyKey) {\n\t\tconst pair = `${instanceToken}\u0000${legacyKey}`;\n\t\tif (!warnedConflicts.has(pair)) {\n\t\t\twarnedConflicts.add(pair);\n\t\t\tconsole.warn(\n\t\t\t\t\"[secondlayer] INSTANCE_TOKEN and SL_API_KEY are set to different values — using INSTANCE_TOKEN (SL_API_KEY is a legacy alias for it).\",\n\t\t\t);\n\t\t}\n\t}\n\treturn instanceToken ?? legacyKey;\n}\n\n/** Build a query-string suffix from name→value pairs. Skips null/undefined and\n * empty values; arrays are comma-joined. Returns \"\" (never a dangling \"?\") or\n * \"?a=1&b=2\" — the one canonical builder every list endpoint shares, so the\n * empty-query guard can't be forgotten per call site. */\nexport function buildQuery(\n\tparams: Record<\n\t\tstring,\n\t\tnumber | string | boolean | readonly string[] | null | undefined\n\t>,\n): string {\n\tconst search = new URLSearchParams();\n\tfor (const [name, value] of Object.entries(params)) {\n\t\tif (value === undefined || value === null) continue;\n\t\tconst serialized = Array.isArray(value) ? value.join(\",\") : String(value);\n\t\tif (serialized.length === 0) continue;\n\t\tsearch.set(name, serialized);\n\t}\n\tconst query = search.toString();\n\treturn query ? `?${query}` : \"\";\n}\n\nexport abstract class BaseClient {\n\tprotected baseUrl: string;\n\tprotected apiKey?: string;\n\tprotected origin: \"cli\" | \"mcp\" | \"session\";\n\tprotected fetchImpl: FetchLike;\n\n\tconstructor(options: Partial<SecondLayerOptions> = {}) {\n\t\tthis.baseUrl = resolveBaseUrl(options.baseUrl);\n\t\tthis.apiKey = resolveApiKey(options.apiKey);\n\t\tthis.origin = options.origin ?? \"cli\";\n\t\t// Bind the global so a bare `fetch` reference doesn't lose its Request\n\t\t// context on runtimes where fetch is a method (workerd, older Node).\n\t\tthis.fetchImpl = options.fetchImpl ?? ((...args) => fetch(...args));\n\t}\n\n\tstatic authHeaders(apiKey?: string): Record<string, string> {\n\t\tconst headers: Record<string, string> = {\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t};\n\t\tif (apiKey) {\n\t\t\theaders.Authorization = `Bearer ${apiKey}`;\n\t\t}\n\t\treturn headers;\n\t}\n\n\tprotected async request<T>(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t): Promise<T> {\n\t\tconst response = await this.fetchResponse(method, path, body);\n\t\tif (response.status === 204) {\n\t\t\treturn undefined as T;\n\t\t}\n\t\treturn response.json() as Promise<T>;\n\t}\n\n\t/** Like `request`, but maps a 404 to `null` instead of throwing — the one\n\t * place that owns the \"absent resource\" rule for `get*` accessors. */\n\tprotected async requestOrNull<T>(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t): Promise<T | null> {\n\t\ttry {\n\t\t\treturn await this.request<T>(method, path, body);\n\t\t} catch (err) {\n\t\t\tif (err instanceof ApiError && err.status === 404) return null;\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tprotected async requestText(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t): Promise<string> {\n\t\tconst response = await this.fetchResponse(method, path, body);\n\t\treturn response.text();\n\t}\n\n\tprivate async fetchResponse(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t): Promise<Response> {\n\t\tconst url = `${this.baseUrl}${path}`;\n\t\tconst headers = BaseClient.authHeaders(this.apiKey);\n\t\theaders[\"x-sl-origin\"] = this.origin;\n\n\t\t// Serialize the body BEFORE the network try so a body-encoding error\n\t\t// (e.g. unsupported BigInt) isn't misreported as \"Cannot reach API\".\n\t\t// BigInts are stringified — server schemas accept jsonb so the value\n\t\t// reaches the server intact, and any field that needs an actual bigint\n\t\t// at runtime is rehydrated by the consuming module (subgraph handler\n\t\t// code preserves the literal). See packages/subgraphs source-matcher\n\t\t// for the post-load shape.\n\t\tlet serializedBody: string | undefined;\n\t\tif (body !== undefined && body !== null) {\n\t\t\ttry {\n\t\t\t\tserializedBody = JSON.stringify(body, (_key, value) =>\n\t\t\t\t\ttypeof value === \"bigint\" ? value.toString() : value,\n\t\t\t\t);\n\t\t\t} catch (err) {\n\t\t\t\tconst detail = err instanceof Error ? err.message : String(err);\n\t\t\t\t// Not retryable: the same body will fail to serialize again.\n\t\t\t\tthrow new ApiError(\n\t\t\t\t\t0,\n\t\t\t\t\t`Failed to serialize request body: ${detail}`,\n\t\t\t\t\tundefined,\n\t\t\t\t\tundefined,\n\t\t\t\t\t{ retryable: false },\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tlet response: Response;\n\t\ttry {\n\t\t\tresponse = await this.fetchImpl(url, {\n\t\t\t\tmethod,\n\t\t\t\theaders,\n\t\t\t\tbody: serializedBody,\n\t\t\t});\n\t\t} catch (err) {\n\t\t\tthrow new ApiError(\n\t\t\t\t0,\n\t\t\t\t`Cannot reach API at ${this.baseUrl}. Check your connection or try again.`,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\t{ retryable: true, cause: err instanceof Error ? err : undefined },\n\t\t\t);\n\t\t}\n\n\t\tif (!response.ok) {\n\t\t\tif (response.status === 401) {\n\t\t\t\tthrow new AuthError();\n\t\t\t}\n\n\t\t\tif (response.status === 429) {\n\t\t\t\t// The header is preserved as `retryAfterSeconds` (not just prose) so\n\t\t\t\t// the consume loops can honor it.\n\t\t\t\tconst retryAfter = response.headers.get(\"Retry-After\");\n\t\t\t\tconst msg = retryAfter\n\t\t\t\t\t? `Rate limited. Wait ${retryAfter} seconds.`\n\t\t\t\t\t: \"Rate limited. Try again later.\";\n\t\t\t\tthrow new RateLimitError(msg, retryAfter ?? undefined);\n\t\t\t}\n\n\t\t\tif (response.status >= 500) {\n\t\t\t\tthrow new ApiError(\n\t\t\t\t\tresponse.status,\n\t\t\t\t\t`Server error. Try again or check status at ${this.baseUrl}/health`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst errorBody = await response.text();\n\t\t\tlet message = `HTTP ${response.status}`;\n\t\t\tlet parsedBody: unknown = errorBody;\n\t\t\tlet code: string | undefined;\n\t\t\ttry {\n\t\t\t\tconst json = JSON.parse(errorBody);\n\t\t\t\tparsedBody = json;\n\t\t\t\tconst err = json.error ?? json.message;\n\t\t\t\tif (typeof err === \"string\") {\n\t\t\t\t\tmessage = err;\n\t\t\t\t} else if (err && typeof err === \"object\") {\n\t\t\t\t\tmessage = JSON.stringify(err);\n\t\t\t\t}\n\t\t\t\tif (typeof json.code === \"string\") {\n\t\t\t\t\tcode = json.code;\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\tif (errorBody) message = errorBody;\n\t\t\t}\n\t\t\tthrow new ApiError(response.status, message, parsedBody, code);\n\t\t}\n\n\t\treturn response;\n\t}\n}\n",
|
|
8
|
-
"import {\n\tblockEndCursor,\n\tdecodeStreamsCursor,\n\tencodeStreamsCursor,\n} from \"@secondlayer/shared\";\nimport { ValidationError } from \"./errors.ts\";\n\n/**\n * Helpers for Streams cursors. A cursor is the opaque `<block>:<index>` string\n * that marks a position in the event stream; treat the format as an\n * implementation detail and go through these helpers instead of string-building\n * it at call sites. Encode/decode and the rewind sentinel come from the\n * canonical codec in `@secondlayer/shared` so the SDK cannot accept a spelling\n * the server would 400, or rewind to a different foot than Index/Streams.\n */\nexport const Cursor = {\n\t/**\n\t * Cursor at the foot of `height` — a position that sorts strictly below the\n\t * first event of block `height` (`height:0`) and strictly above every event\n\t * of block `height - 1`. Cursors are exclusive (`(bh,ei) > after`), so\n\t * resuming from it re-reads the entire canonical run starting at `height:0`\n\t * inclusive. This is the position to rewind to after a reorg whose fork point\n\t * is `height`: the new canonical block at `height` carries a fresh first\n\t * event at `(height, 0)` that the consumer MUST re-read.\n\t *\n\t * Encoded as `blockEndCursor(height - 1)` rather than the seemingly-natural\n\t * `${height}:0` — that earlier form was an off-by-one: being exclusive, it\n\t * skipped `(height, 0)`, silently dropping the fork block's first row on\n\t * every reorg. The sentinel is int4 max (the `event_index`/`tx_index` column\n\t * type), larger than any real index, so nothing at `height - 1` survives the\n\t * keyset and the next returned row is exactly `(height, 0)`.\n\t
|
|
9
|
-
"// AuthError / RateLimitError / ValidationError are shared across the whole SDK\n// (Index and the platform clients throw them too) and live in ../errors.ts —\n// re-exported here so `@secondlayer/sdk/streams` imports keep working.\nimport {
|
|
10
|
-
"import type { ConsumerSink, WithSinkTx } from \"../sinks/types.ts\";\nimport { Cursor } from \"./cursor.ts\";\nimport { ValidationError } from \"./errors.ts\";\nimport type {\n\tConsumerBatchContext,\n\tStreamsBatch,\n\tStreamsEvent,\n\tStreamsEventType,\n\tStreamsEventsEnvelope,\n\tStreamsFilterMap,\n\tStreamsFilterValue,\n\tStreamsReorg,\n} from \"./types.ts\";\n\n/** Stable identity of a reorg, for in-memory dedup across re-reported pages. */\nfunction reorgKey(reorg: StreamsReorg): string {\n\treturn `${reorg.detected_at}|${reorg.fork_point_height}|${reorg.new_canonical_tip}`;\n}\n\ntype StreamsEventsFetchParams = {\n\tcursor?: string | null;\n\tlimit: number;\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, forwarded to the server verbatim. */\n\tfilters?: StreamsFilterMap;\n};\n\nexport type StreamsEventsFetcher = (\n\tparams: StreamsEventsFetchParams,\n) => Promise<StreamsEventsEnvelope>;\n\nexport type Sleep = (ms: number, signal?: AbortSignal) => Promise<void>;\n\n/**\n * Guard the `finalizedOnly` checkpoint contract. Shared by both loops.\n *\n * In `finalizedOnly` mode the unfinalized tail is filtered OUT of the batch\n * and re-read next poll — and `onReorg` is skipped entirely, so nothing ever\n * re-reads a range the cursor has passed. Returning a cursor above the last\n * delivered finalized event (e.g. `envelope.next_cursor`, which points past\n * the filtered tail) therefore drops those events permanently and silently.\n * Throw instead: this is the one wrong return the loop can detect.\n */\nexport function assertFinalizedCheckpoint(\n\t// biome-ignore lint/suspicious/noConfusingVoidType: mirrors the onBatch return union it validates\n\treturned: string | null | undefined | void,\n\tcheckpoint: string | null,\n): void {\n\tif (returned === null || returned === undefined) return;\n\tif (returned === checkpoint) return;\n\tconst r = Cursor.parse(returned);\n\tconst c = checkpoint === null ? null : Cursor.parse(checkpoint);\n\tconst above =\n\t\tc === null ||\n\t\tr.blockHeight > c.blockHeight ||\n\t\t(r.blockHeight === c.blockHeight && r.eventIndex > c.eventIndex);\n\tif (above) {\n\t\tconst boundary = c ? ` (\"${checkpoint}\")` : \" (none delivered yet)\";\n\t\tthrow new ValidationError(\n\t\t\t`onBatch returned cursor \"${returned}\", above the last delivered finalized event${boundary}. With finalizedOnly, events past that point were filtered out and will be re-read once finalized — committing beyond it skips them permanently. Return ctx.cursor (or nothing); never envelope.next_cursor.`,\n\t\t\t400,\n\t\t);\n\t}\n}\n\n/**\n * Fail fast on an impossible sink/mode pairing. Shared by both loops, checked\n * BEFORE the first fetch and before `loadCursor`: a `finalizedOnly` sink\n * (append-only store — cannot undo committed rows) following the unfinalized\n * tip would corrupt on the first fork, and the corruption is silent until the\n * fork happens. Throwing at startup is the only loud moment available.\n */\nexport function assertSinkModeCompatible(\n\tsink: Pick<ConsumerSink, \"capabilities\"> | undefined,\n\tfinalizedOnly: boolean,\n): void {\n\tif (sink?.capabilities?.finalizedOnly && !finalizedOnly) {\n\t\tthrow new ValidationError(\n\t\t\t\"This sink declares capabilities.finalizedOnly — it cannot roll back reorged rows, and following the unfinalized tip would corrupt it at the first fork. Pass finalizedOnly: true to consume(), or use a sink that implements rollback.\",\n\t\t\t400,\n\t\t);\n\t}\n}\n\n/**\n * The height a resume cursor implies — seeds the loop's \"highest block\n * reached\" so a consumer restarted into a quiet tail reports its true\n * position (`checkpoint`, `height`, `blocksBehind`) instead of `null`s\n * until the first delivered row. Lenient: an unparseable cursor seeds\n * nothing and is left for the server to reject.\n */\nexport function resumeHeight(cursor: string | null): number | null {\n\tif (cursor === null) return null;\n\ttry {\n\t\treturn Cursor.parse(cursor).blockHeight;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Build the ctx handed to `onBatch`. Shared by the Streams and Index loops so\n * the two can't drift on what \"progress\" means. `blocksBehind` measures the\n * consumer's BACKLOG (`tip - scannedHeight`), not the age of the last\n * delivered event — a caught-up tail on a quiet contract is 0 behind. */\nexport function batchContext<TTip extends { block_height: number }, TReorg>(\n\tcursor: string | null,\n\theight: number | null,\n\ttip: TTip,\n\treorgs: readonly TReorg[] = [],\n\tscannedHeight: number | null = null,\n): ConsumerBatchContext<TTip, TReorg> {\n\tconst tipHeight = tip.block_height;\n\tconst position = scannedHeight ?? height;\n\treturn {\n\t\tcursor,\n\t\theight,\n\t\tscannedHeight: position,\n\t\ttipHeight,\n\t\tblocksBehind: position === null ? null : Math.max(0, tipHeight - position),\n\t\ttip,\n\t\treorgs,\n\t};\n}\n\n/** Options shared by both consume loops' page-fetch retry. Vocabulary matches\n * `@secondlayer/stacks` transports (`retryCount`/`retryDelay`) — one retry\n * language across the family, not a third. */\nexport type PageRetryOptions = {\n\t/** Retries after the first failure. Default 3; `0` disables. */\n\tretryCount?: number;\n\t/** Base delay in ms; the n-th retry waits `retryDelay * n` (matches the\n\t * stacks transport). A server `Retry-After` overrides it. Default 1000. */\n\tretryDelay?: number;\n\t/** Void observer, called before each retry sleep (metrics/logging). The\n\t * retry policy owns the decision; this cannot change it. */\n\tonError?: (\n\t\terr: unknown,\n\t\tctx: { attempt: number; retriesLeft: number; delayMs: number },\n\t) => void;\n};\n\n/** Retry-After above this is treated as \"give up now, resume later\". */\nconst MAX_RETRY_AFTER_MS = 300_000;\n\nfunction errRetryable(err: unknown): boolean {\n\t// SecondLayerError family carries an explicit signal; a bare TypeError is\n\t// the raw fetch network failure (Streams' fetchImpl isn't wrapped).\n\tif (err && typeof err === \"object\" && \"retryable\" in err) {\n\t\treturn (err as { retryable: unknown }).retryable === true;\n\t}\n\treturn err instanceof TypeError;\n}\n\nfunction errRetryAfterMs(err: unknown): number | undefined {\n\tif (err && typeof err === \"object\" && \"retryAfterSeconds\" in err) {\n\t\tconst seconds = (err as { retryAfterSeconds: unknown }).retryAfterSeconds;\n\t\tif (typeof seconds === \"number\" && Number.isFinite(seconds)) {\n\t\t\treturn Math.min(seconds * 1000, MAX_RETRY_AFTER_MS);\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/**\n * Run one page fetch with retries. Scoped to the FETCH only — never the loop\n * body: retrying after an `onReorg`/`onBatch` throw would re-enter with\n * `handledReorgs` partially mutated and skip a rollback silently. `onBatch`\n * and `onReorg` throws always propagate to the caller.\n */\nexport async function fetchPageWithRetry<T>(\n\tfetchPage: () => Promise<T>,\n\topts: PageRetryOptions & { sleep: Sleep; signal?: AbortSignal },\n): Promise<T> {\n\tconst retryCount = opts.retryCount ?? 3;\n\tconst retryDelay = opts.retryDelay ?? 1000;\n\tfor (let attempt = 0; ; attempt++) {\n\t\ttry {\n\t\t\treturn await fetchPage();\n\t\t} catch (err) {\n\t\t\tconst retriesLeft = retryCount - attempt;\n\t\t\tif (retriesLeft <= 0 || !errRetryable(err) || opts.signal?.aborted) {\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t\tconst delayMs = errRetryAfterMs(err) ?? retryDelay * (attempt + 1);\n\t\t\topts.onError?.(err, { attempt, retriesLeft, delayMs });\n\t\t\tawait opts.sleep(delayMs, opts.signal);\n\t\t\t// Aborted mid-sleep: surface the original failure, not a fresh fetch.\n\t\t\tif (opts.signal?.aborted) throw err;\n\t\t}\n\t}\n}\n\nexport async function defaultSleep(\n\tms: number,\n\tsignal?: AbortSignal,\n): Promise<void> {\n\tif (signal?.aborted) return;\n\n\tawait new Promise<void>((resolve) => {\n\t\tconst timeout = setTimeout(resolve, ms);\n\t\tif (!signal) return;\n\t\tsignal.addEventListener(\n\t\t\t\"abort\",\n\t\t\t() => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\tresolve();\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t});\n}\n\nexport async function consumeStreamsEvents<TTx = never>(opts: {\n\tfromCursor?: string | null;\n\tmode?: \"tail\" | \"bounded\";\n\tfinalizedOnly?: boolean;\n\tbatchSize: number;\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, forwarded to the server verbatim. */\n\tfilters?: StreamsFilterMap;\n\tfetchEvents: StreamsEventsFetcher;\n\t/** Destination adapter owning checkpoint + rollback (see IndexConsumeOptions.sink). */\n\tsink?: ConsumerSink<TTx>;\n\t/** Fires once per page, before `onBatch` and any early return. */\n\tonProgress?: (ctx: ConsumerBatchContext) => void;\n\tonBatch: (\n\t\tevents: StreamsEvent[],\n\t\tenvelope: StreamsEventsEnvelope,\n\t\tctx: ConsumerBatchContext & 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\tonReorg?: (\n\t\treorg: StreamsReorg,\n\t\tctx: { cursor: string },\n\t) => Promise<void> | void;\n\tsleep?: Sleep;\n\temptyBackoffMs?: number;\n\tmaxPages?: number;\n\tmaxEmptyPolls?: number;\n\tretryCount?: number;\n\tretryDelay?: number;\n\tonError?: PageRetryOptions[\"onError\"];\n\tsignal?: AbortSignal;\n}): Promise<{ cursor: string | null; pages: number; emptyPolls: number }> {\n\tconst sleep = opts.sleep ?? defaultSleep;\n\tconst mode = opts.mode ?? \"tail\";\n\tconst finalizedOnly = opts.finalizedOnly ?? false;\n\tconst emptyBackoffMs = opts.emptyBackoffMs ?? 500;\n\tconst maxPages = opts.maxPages ?? Number.POSITIVE_INFINITY;\n\tconst maxEmptyPolls = opts.maxEmptyPolls ?? Number.POSITIVE_INFINITY;\n\tassertSinkModeCompatible(opts.sink, finalizedOnly);\n\t// Resume order: explicit fromCursor, then the sink's committed checkpoint.\n\t// `loadCursor` is also the sink's INIT — it creates the checkpoint table and\n\t// validates the rollback precondition. Short-circuiting it on an explicit\n\t// `fromCursor` meant a replay-from-cursor run crashed on its first commit,\n\t// and skipped the height-column check that keeps reorg rollback from being\n\t// a silent no-op. Always initialize; `fromCursor` still wins as the resume\n\t// position.\n\tconst committedCursor = (await opts.sink?.loadCursor()) ?? null;\n\tlet cursor = opts.fromCursor ?? committedCursor;\n\t// In-memory only: rollback is idempotent, so a crash before the rewind is\n\t// re-detected and re-applied harmlessly on restart — no need to persist.\n\tconst handledReorgs = new Set<string>();\n\tlet pages = 0;\n\tlet emptyPolls = 0;\n\t// Highest block reached, carried across empty pages so a caught-up tail\n\t// keeps reporting its position instead of dropping to null. Seeded from\n\t// the resume cursor: a restart into a quiet tail knows where it stands\n\t// before the first row lands.\n\tlet height: number | null = resumeHeight(cursor);\n\t// Highest block VERIFIED — how far the sweep is actually caught up, as\n\t// opposed to `height` (last delivered row). Starts at the resume position;\n\t// each page moves it (see below).\n\tlet scanned: number | null = height;\n\n\twhile (\n\t\tpages < maxPages &&\n\t\temptyPolls < maxEmptyPolls &&\n\t\t!opts.signal?.aborted\n\t) {\n\t\t// Retry wraps ONLY the page fetch: one transient 429/5xx must not kill\n\t\t// an hours-long backfill, and handler throws must never be re-entered.\n\t\tconst envelope = await fetchPageWithRetry(\n\t\t\t() =>\n\t\t\t\topts.fetchEvents({\n\t\t\t\t\tcursor,\n\t\t\t\t\tlimit: opts.batchSize,\n\t\t\t\t\ttypes: opts.types,\n\t\t\t\t\tnotTypes: opts.notTypes,\n\t\t\t\t\tcontractId: opts.contractId,\n\t\t\t\t\tsender: opts.sender,\n\t\t\t\t\trecipient: opts.recipient,\n\t\t\t\t\tassetIdentifier: opts.assetIdentifier,\n\t\t\t\t\tfilters: opts.filters,\n\t\t\t\t}),\n\t\t\t{\n\t\t\t\tretryCount: opts.retryCount,\n\t\t\t\tretryDelay: opts.retryDelay,\n\t\t\t\tonError: opts.onError,\n\t\t\t\tsleep,\n\t\t\t\tsignal: opts.signal,\n\t\t\t},\n\t\t);\n\t\tpages++;\n\n\t\t// Reorgs: roll back each new fork, then rewind to the lowest fork point\n\t\t// and re-read the now-canonical run. Finalized data never reorgs, so\n\t\t// `finalizedOnly` skips this entirely. A sink makes rollback\n\t\t// UNCONDITIONAL — omitting `onReorg` used to skip reorgs silently.\n\t\tif (!finalizedOnly && (opts.onReorg || opts.sink)) {\n\t\t\tconst fresh = envelope.reorgs\n\t\t\t\t.filter((reorg) => !handledReorgs.has(reorgKey(reorg)))\n\t\t\t\t.sort((a, b) => a.fork_point_height - b.fork_point_height);\n\t\t\tif (fresh.length > 0) {\n\t\t\t\tconst forkPoint = Math.min(\n\t\t\t\t\t...fresh.map((reorg) => reorg.fork_point_height),\n\t\t\t\t);\n\t\t\t\tconst rewind = Cursor.atHeight(forkPoint);\n\t\t\t\tfor (const reorg of fresh) {\n\t\t\t\t\tawait opts.sink?.rollback(reorg.fork_point_height, rewind);\n\t\t\t\t\tawait opts.onReorg?.(reorg, { cursor: rewind });\n\t\t\t\t\thandledReorgs.add(reorgKey(reorg));\n\t\t\t\t}\n\t\t\t\tcursor = rewind;\n\t\t\t\t// Everything at and above the fork is no longer canonical, so the\n\t\t\t\t// reached height rolls back with it — including the verified\n\t\t\t\t// position: the new chain above the fork is unread.\n\t\t\t\theight = forkPoint > 0 ? forkPoint - 1 : null;\n\t\t\t\tscanned = height;\n\t\t\t\temptyPolls = 0;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tconst emitted = finalizedOnly\n\t\t\t? envelope.events.filter((event) => event.finalized)\n\t\t\t: envelope.events;\n\t\t// Only advance to the last finalized event in finalizedOnly mode; the\n\t\t// unfinalized tail is re-read next poll until it settles.\n\t\tconst checkpoint = finalizedOnly\n\t\t\t? (emitted.at(-1)?.cursor ?? cursor)\n\t\t\t: envelope.next_cursor;\n\t\t// Ascending cursor order, so the last row is the highest block this page\n\t\t// reached; an empty page keeps the previous value.\n\t\theight = emitted.at(-1)?.block_height ?? height;\n\t\t// Verified position. Rows delivered → through the last row (the page\n\t\t// limit hides what's above it). Empty page with an ADVANCED cursor →\n\t\t// through that cursor only (a server may cap an expensive filtered\n\t\t// scan; claiming the tip would overstate). Truly empty page → the\n\t\t// server confirmed nothing matches up to the tip. Non-empty raw page\n\t\t// fully filtered (unfinalized tail) → position unchanged.\n\t\tif (emitted.length > 0) {\n\t\t\tscanned = height;\n\t\t} else if (checkpoint !== null && checkpoint !== cursor) {\n\t\t\tscanned = resumeHeight(checkpoint) ?? scanned;\n\t\t} else if (envelope.events.length === 0) {\n\t\t\tscanned = envelope.tip.block_height;\n\t\t}\n\n\t\t// An empty page reports the STANDING cursor, not null: the committed\n\t\t// checkpoint is still this consumer's position while it idles.\n\t\tconst ctx = batchContext(\n\t\t\tcheckpoint ?? cursor,\n\t\t\theight,\n\t\t\tenvelope.tip,\n\t\t\tenvelope.reorgs,\n\t\t\tscanned,\n\t\t);\n\t\t// Before any early return: an empty page still proves the loop is alive.\n\t\topts.onProgress?.(ctx);\n\n\t\tlet nextCursor: string | null;\n\t\tif (opts.sink) {\n\t\t\tconst sink = opts.sink;\n\t\t\t// Rows and cursor commit in ONE transaction; a handler throw aborts\n\t\t\t// both. Nothing moved → nothing to commit, handler not invoked.\n\t\t\tif (\n\t\t\t\tcheckpoint !== null &&\n\t\t\t\t(checkpoint !== cursor || emitted.length > 0)\n\t\t\t) {\n\t\t\t\tawait sink.commitBatch(checkpoint, async (tx) => {\n\t\t\t\t\t// The cast is sound exactly as far as the sink's own typing:\n\t\t\t\t\t// `sink: ConsumerSink<TTx>` binds TTx, and `tx` here is what its\n\t\t\t\t\t// commitBatch lends. Nothing verifies it at runtime — a sink whose\n\t\t\t\t\t// declared Tx lies about what it lends fails inside the handler.\n\t\t\t\t\tawait opts.onBatch(emitted, envelope, {\n\t\t\t\t\t\t...ctx,\n\t\t\t\t\t\ttx,\n\t\t\t\t\t} as ConsumerBatchContext & WithSinkTx<TTx>);\n\t\t\t\t});\n\t\t\t}\n\t\t\tnextCursor = checkpoint;\n\t\t} else {\n\t\t\tconst returnedCursor = await opts.onBatch(\n\t\t\t\temitted,\n\t\t\t\tenvelope,\n\t\t\t\tctx as ConsumerBatchContext & WithSinkTx<TTx>,\n\t\t\t);\n\t\t\tif (finalizedOnly) assertFinalizedCheckpoint(returnedCursor, checkpoint);\n\t\t\tnextCursor = returnedCursor ?? checkpoint;\n\t\t}\n\n\t\tif (nextCursor && nextCursor !== cursor) {\n\t\t\tcursor = nextCursor;\n\t\t\temptyPolls = 0;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (emitted.length === 0) {\n\t\t\temptyPolls++;\n\t\t\tif (mode === \"bounded\") {\n\t\t\t\treturn { cursor, pages, emptyPolls };\n\t\t\t}\n\t\t\tawait sleep(emptyBackoffMs, opts.signal);\n\t\t\tcontinue;\n\t\t}\n\n\t\treturn { cursor, pages, emptyPolls };\n\t}\n\n\treturn { cursor, pages, emptyPolls };\n}\n\n/**\n * Async-iterator form of the Streams pull loop, yielding one {@link StreamsBatch}\n * per fetched page. Each yield maps 1:1 onto a `GET /v1/streams/events` envelope\n * (`{ events, next_cursor, tip, reorgs }` → `{ events, cursor, tip, reorgs }`) —\n * no extra API calls, no regrouping. Pages with no events and no reorgs are not\n * yielded; the iterator sleeps `intervalMs` and re-polls the tip instead.\n */\nexport async function* iterateStreamsBatches(opts: {\n\tfromCursor?: string | null;\n\tbatchSize: number;\n\tintervalMs: number;\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, forwarded to the server verbatim. */\n\tfilters?: StreamsFilterMap;\n\tfetchEvents: StreamsEventsFetcher;\n\tsleep?: Sleep;\n\tsignal?: AbortSignal;\n}): AsyncGenerator<StreamsBatch> {\n\tconst sleep = opts.sleep ?? defaultSleep;\n\tlet cursor = opts.fromCursor ?? null;\n\n\twhile (!opts.signal?.aborted) {\n\t\tconst envelope = await opts.fetchEvents({\n\t\t\tcursor,\n\t\t\tlimit: opts.batchSize,\n\t\t\ttypes: opts.types,\n\t\t\tnotTypes: opts.notTypes,\n\t\t\tcontractId: opts.contractId,\n\t\t\tsender: opts.sender,\n\t\t\trecipient: opts.recipient,\n\t\t\tassetIdentifier: opts.assetIdentifier,\n\t\t\tfilters: opts.filters,\n\t\t});\n\n\t\tconst checkpoint = envelope.next_cursor ?? cursor;\n\t\tif (envelope.events.length > 0 || envelope.reorgs.length > 0) {\n\t\t\tyield {\n\t\t\t\tevents: envelope.events,\n\t\t\t\tcursor: checkpoint,\n\t\t\t\ttip: envelope.tip,\n\t\t\t\treorgs: envelope.reorgs,\n\t\t\t};\n\t\t}\n\n\t\tconst advanced = checkpoint !== null && checkpoint !== cursor;\n\t\tcursor = checkpoint;\n\t\t// Caught up at the tip: wait one poll interval before re-reading.\n\t\tif (!advanced && envelope.events.length === 0) {\n\t\t\tif (opts.signal?.aborted) return;\n\t\t\tawait sleep(opts.intervalMs, opts.signal);\n\t\t}\n\t}\n}\n\nexport async function* streamStreamsEvents(opts: {\n\tfromCursor?: string | null;\n\tbatchSize: number;\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, forwarded to the server verbatim. */\n\tfilters?: StreamsFilterMap;\n\tfetchEvents: StreamsEventsFetcher;\n\tsleep?: Sleep;\n\temptyBackoffMs?: number;\n\tmaxPages?: number;\n\tmaxEmptyPolls?: number;\n\tsignal?: AbortSignal;\n}): AsyncGenerator<StreamsEvent> {\n\tconst sleep = opts.sleep ?? defaultSleep;\n\tconst emptyBackoffMs = opts.emptyBackoffMs ?? 500;\n\tconst maxPages = opts.maxPages ?? Number.POSITIVE_INFINITY;\n\tconst maxEmptyPolls = opts.maxEmptyPolls ?? Number.POSITIVE_INFINITY;\n\tlet cursor = opts.fromCursor ?? null;\n\tlet pages = 0;\n\tlet emptyPolls = 0;\n\n\twhile (\n\t\tpages < maxPages &&\n\t\temptyPolls < maxEmptyPolls &&\n\t\t!opts.signal?.aborted\n\t) {\n\t\tconst envelope = await opts.fetchEvents({\n\t\t\tcursor,\n\t\t\tlimit: opts.batchSize,\n\t\t\ttypes: opts.types,\n\t\t\tnotTypes: opts.notTypes,\n\t\t\tcontractId: opts.contractId,\n\t\t\tsender: opts.sender,\n\t\t\trecipient: opts.recipient,\n\t\t\tassetIdentifier: opts.assetIdentifier,\n\t\t\tfilters: opts.filters,\n\t\t});\n\t\tpages++;\n\n\t\tfor (const event of envelope.events) {\n\t\t\tif (opts.signal?.aborted) return;\n\t\t\tyield event;\n\t\t}\n\n\t\tconst nextCursor = envelope.next_cursor;\n\t\tif (nextCursor && nextCursor !== cursor) {\n\t\t\tcursor = nextCursor;\n\t\t\temptyPolls = 0;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (envelope.events.length === 0) {\n\t\t\temptyPolls++;\n\t\t\tif (emptyPolls >= maxEmptyPolls || pages >= maxPages) return;\n\t\t\tawait sleep(emptyBackoffMs, opts.signal);\n\t\t\tcontinue;\n\t\t}\n\n\t\treturn;\n\t}\n}\n",
|
|
5
|
+
"import { ed25519 } from \"@secondlayer/shared\";\nimport { buildQuery, resolveApiKey, resolveBaseUrl } from \"../base.ts\";\nimport type { IndexEvent } from \"../index-api/client.ts\";\nimport type { ConsumerSink } from \"../sinks/types.ts\";\nimport {\n\ttype StreamsEventsFetcher,\n\tconsumeStreamsEvents,\n\titerateStreamsBatches,\n\tstreamStreamsEvents,\n} from \"./consumer.ts\";\nimport { Cursor } from \"./cursor.ts\";\nimport { decode } from \"./decode.ts\";\nimport { createStreamsDumps } from \"./dumps.ts\";\nimport {\n\tStreamsServerError,\n\tStreamsSignatureError,\n\tValidationError,\n\tmapStreamsError,\n} from \"./errors.ts\";\nimport { subscribeStreamsEvents } from \"./subscribe.ts\";\nimport type {\n\tFetchLike,\n\tStreamsCanonicalBlock,\n\tStreamsClient,\n\tStreamsConsumeParams,\n\tStreamsEvent,\n\tStreamsEventType,\n\tStreamsEventsConsumeParams,\n\tStreamsEventsConsumeResult,\n\tStreamsEventsEnvelope,\n\tStreamsEventsListEnvelope,\n\tStreamsEventsListParams,\n\tStreamsEventsReplayParams,\n\tStreamsEventsStreamParams,\n\tStreamsEventsSubscribeParams,\n\tStreamsFilterMap,\n\tStreamsFilterValue,\n\tStreamsReorgsListEnvelope,\n\tStreamsReorgsListParams,\n\tStreamsTip,\n} from \"./types.ts\";\n\n/** Parse a `<block>:<index>` cursor; null sorts before genesis. */\nfunction cursorTuple(cursor: string | null): [number, number] {\n\tif (!cursor) return [-1, -1];\n\tconst { blockHeight, eventIndex } = Cursor.parse(cursor);\n\treturn [blockHeight, eventIndex];\n}\n\n/** The greater of two cursors (later in the stream). */\nfunction maxCursor(a: string | null, b: string | null): string | null {\n\tconst [ah, ai] = cursorTuple(a);\n\tconst [bh, bi] = cursorTuple(b);\n\treturn ah > bh || (ah === bh && ai >= bi) ? a : b;\n}\n\n/**\n * The narrowing set every Streams read forwards verbatim to the consumer\n * loops. Kept in one place because each field is optional: a forgotten one is\n * a type-checkable object that silently widens the stream toward the full\n * firehose — which is billed per row, and has happened. `events.replay()`\n * deliberately forwards a subset and stays explicit.\n */\nfunction streamsFilters(params: {\n\ttypes?: readonly StreamsEventType[];\n\tnotTypes?: readonly StreamsEventType[];\n\tcontractId?: StreamsFilterValue;\n\tsender?: StreamsFilterValue;\n\trecipient?: StreamsFilterValue;\n\tassetIdentifier?: string;\n\tfilters?: StreamsFilterMap;\n}) {\n\treturn {\n\t\ttypes: params.types,\n\t\tnotTypes: params.notTypes,\n\t\tcontractId: params.contractId,\n\t\tsender: params.sender,\n\t\trecipient: params.recipient,\n\t\tassetIdentifier: params.assetIdentifier,\n\t\tfilters: params.filters,\n\t};\n}\n\nexport type CreateStreamsClientOptions = {\n\tapiKey?: string;\n\tbaseUrl?: string;\n\t/** Deploy origin label sent as `x-sl-origin` (telemetry). Defaults to `cli`. */\n\torigin?: \"cli\" | \"mcp\" | \"session\";\n\tfetchImpl?: FetchLike;\n\t/**\n\t * Public base URL for bulk parquet dumps (the R2/CDN bucket root). Required\n\t * to use `client.dumps`. See `GET /public/streams/dumps/manifest`.\n\t */\n\tdumpsBaseUrl?: string;\n\t/**\n\t * Verify the ed25519 `X-Signature` on every REST response and per-frame SSE\n\t * signature. Three states:\n\t * - **default (omitted)** — *lenient*: verify when the server signs (the\n\t * hosted API signs every response), and pass through when no signature is\n\t * present (e.g. a self-hosted instance with no `STREAMS_SIGNING_PRIVATE_KEY`).\n\t * So verification is on by default against the hosted API without breaking\n\t * unsigned self-host deployments. An *invalid* signature always throws.\n\t * - **`true`** (or `{ publicKey }` to pin a known PEM) — *strict*: a missing\n\t * OR invalid signature throws `StreamsSignatureError`. Use this when you\n\t * require a portable, non-repudiable attestation and won't accept unsigned\n\t * data (it also closes the lenient mode's strip-the-header downgrade).\n\t * - **`false`** — off.\n\t *\n\t * The key is fetched once from `/public/streams/signing-key` (cached; a\n\t * rotated `X-Signature-KeyId` triggers one refresh) unless a PEM is pinned.\n\t */\n\tverify?: boolean | { publicKey: string };\n\t/**\n\t * Verify the bulk dumps manifest's ed25519 signature in `client.dumps.list()`\n\t * before trusting any file sha256 (default ON). Uses the same key source as\n\t * `verify` (fetches `/public/streams/signing-key`, or a pinned PEM). Pass\n\t * `false` to opt out. A missing or invalid signature throws\n\t * `StreamsSignatureError`.\n\t */\n\tverifyDumpsManifest?: boolean;\n};\n\nfunction normalizeBaseUrl(baseUrl: string): string {\n\treturn baseUrl.replace(/\\/+$/, \"\");\n}\n\n/** Loopback hosts, where plain http carries no more exposure than the box\n * itself. Anywhere else, http means a network hop anyone on the path can\n * rewrite, key endpoint included. */\nfunction isLoopbackUrl(baseUrl: string): boolean {\n\ttry {\n\t\tconst { hostname } = new URL(baseUrl);\n\t\treturn (\n\t\t\thostname === \"localhost\" ||\n\t\t\thostname === \"127.0.0.1\" ||\n\t\t\thostname === \"::1\" ||\n\t\t\thostname === \"[::1]\" ||\n\t\t\thostname.startsWith(\"127.\")\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport function createStreamsClient(\n\toptions: CreateStreamsClientOptions,\n): StreamsClient {\n\tconst baseUrl = normalizeBaseUrl(resolveBaseUrl(options.baseUrl));\n\t// Same credential precedence as every other client (explicit option, then\n\t// INSTANCE_TOKEN, then SL_API_KEY), so the same code authenticates the same\n\t// way whether it enters through `new SecondLayer()` or here.\n\tconst apiKey = resolveApiKey(options.apiKey);\n\tconst origin = options.origin ?? \"cli\";\n\tconst authHeaders = (): Record<string, string> => ({\n\t\t\"x-sl-origin\": origin,\n\t\t...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),\n\t});\n\tconst fetchImpl = options.fetchImpl ?? ((input, init) => fetch(input, init));\n\tconst verify = options.verify;\n\t// On by default, but lenient: the hosted API signs every response, while a\n\t// self-hosted instance without STREAMS_SIGNING_PRIVATE_KEY serves none.\n\t// Lenient verifies when a signature is present and passes through when it is\n\t// absent — so the default neither skips hosted verification nor breaks OSS.\n\t// `verify: true` / `{ publicKey }` is strict (missing signature throws);\n\t// `verify: false` is off. An invalid signature always throws.\n\tconst verifyMode: \"off\" | \"lenient\" | \"strict\" =\n\t\tverify === false ? \"off\" : verify === undefined ? \"lenient\" : \"strict\";\n\t// Strict mode promises the response came from the holder of a known key.\n\t// A key fetched over plain http from a host off the box is whatever the\n\t// path served, so the promise only holds with a pinned PEM there.\n\tif (\n\t\tverify === true &&\n\t\tbaseUrl.startsWith(\"http:\") &&\n\t\t!isLoopbackUrl(baseUrl)\n\t) {\n\t\tthrow new ValidationError(\n\t\t\t`verify: true over plain http to ${baseUrl} fetches the signing key from the same unprotected path it verifies. Pin the key with verify: { publicKey } (see GET /public/streams/signing-key), or use https.`,\n\t\t\t400,\n\t\t);\n\t}\n\n\t// Lazily resolve and cache the verification key alongside its id, so a\n\t// rotation (signalled by a changed `X-Signature-KeyId`) can be detected.\n\ttype VerificationKey = {\n\t\tkeyId: string;\n\t\tpublicKeyPem: string;\n\t\tpublicKey: ReturnType<typeof ed25519.loadEd25519PublicKey>;\n\t};\n\t// Only a successful fetch stays cached. A 5xx or a dropped socket on the\n\t// key endpoint used to park a rejected promise here for the life of the\n\t// client; now it surfaces as a retryable error and the next call refetches.\n\tlet keyPromise: Promise<VerificationKey> | null = null;\n\tfunction loadKey(): Promise<VerificationKey> {\n\t\tif (keyPromise) return keyPromise;\n\t\tconst pending = (async () => {\n\t\t\tif (typeof verify === \"object\") {\n\t\t\t\treturn {\n\t\t\t\t\tkeyId: ed25519.ed25519KeyId(verify.publicKey),\n\t\t\t\t\tpublicKeyPem: verify.publicKey,\n\t\t\t\t\tpublicKey: ed25519.loadEd25519PublicKey(verify.publicKey),\n\t\t\t\t};\n\t\t\t}\n\t\t\tlet res: Response;\n\t\t\ttry {\n\t\t\t\tres = await fetchImpl(`${baseUrl}/public/streams/signing-key`);\n\t\t\t} catch {\n\t\t\t\tthrow new StreamsServerError(\n\t\t\t\t\t`Could not reach the signing key at ${baseUrl}/public/streams/signing-key. Retryable.`,\n\t\t\t\t\t0,\n\t\t\t\t\tundefined,\n\t\t\t\t\t\"SIGNING_KEY_UNAVAILABLE\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!res.ok) {\n\t\t\t\tif (res.status >= 500 || res.status === 429) {\n\t\t\t\t\tthrow new StreamsServerError(\n\t\t\t\t\t\t`Could not fetch signing key (${res.status}). Retryable.`,\n\t\t\t\t\t\tres.status,\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\"SIGNING_KEY_UNAVAILABLE\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthrow new StreamsSignatureError(\n\t\t\t\t\t`Could not fetch signing key (${res.status}).`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst body = (await res.json()) as {\n\t\t\t\tpublic_key_pem?: string;\n\t\t\t\tkey_id?: string;\n\t\t\t};\n\t\t\tif (!body.public_key_pem) {\n\t\t\t\tthrow new StreamsSignatureError(\"Signing key response missing key.\");\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tkeyId: body.key_id ?? ed25519.ed25519KeyId(body.public_key_pem),\n\t\t\t\tpublicKeyPem: body.public_key_pem,\n\t\t\t\tpublicKey: ed25519.loadEd25519PublicKey(body.public_key_pem),\n\t\t\t};\n\t\t})();\n\t\tkeyPromise = pending;\n\t\tpending.catch(() => {\n\t\t\tif (keyPromise === pending) keyPromise = null;\n\t\t});\n\t\treturn pending;\n\t}\n\t/** Resolve the key a response claims to be signed with. A fetched key\n\t * refreshes once on an unknown id; a pinned key never changes, so an\n\t * unknown id is a failure either way. Shared by REST reads and SSE frames. */\n\tasync function loadKeyFor(\n\t\tresponseKeyId: string | null | undefined,\n\t): Promise<VerificationKey> {\n\t\tlet key = await loadKey();\n\t\tif (!responseKeyId || responseKeyId === key.keyId) return key;\n\t\tif (typeof verify === \"object\") {\n\t\t\tthrow new StreamsSignatureError(\n\t\t\t\t`Response signed with key '${responseKeyId}', expected pinned key '${key.keyId}'.`,\n\t\t\t);\n\t\t}\n\t\t// Refresh once. A still-mismatched id (no re-loop) means the endpoint\n\t\t// does not serve the signing key: fail closed.\n\t\tkeyPromise = null;\n\t\tkey = await loadKey();\n\t\tif (responseKeyId !== key.keyId) {\n\t\t\tthrow new StreamsSignatureError(\n\t\t\t\t`Response signed with key '${responseKeyId}' not served by the signing-key endpoint.`,\n\t\t\t);\n\t\t}\n\t\treturn key;\n\t}\n\n\tconst dumps = createStreamsDumps({\n\t\tbaseUrl: options.dumpsBaseUrl,\n\t\tfetchImpl,\n\t\tverifyManifest: options.verifyDumpsManifest ?? true,\n\t\tloadPublicKeyPem: async () => (await loadKey()).publicKeyPem,\n\t});\n\n\tasync function request<T>(path: string): Promise<T> {\n\t\tconst response = await fetchImpl(`${baseUrl}${path}`, {\n\t\t\theaders: authHeaders(),\n\t\t});\n\t\tif (!response.ok) await mapStreamsError(response);\n\t\tconst text = await response.text();\n\t\tif (verifyMode !== \"off\") {\n\t\t\tconst signature = response.headers.get(\"X-Signature\");\n\t\t\tif (!signature) {\n\t\t\t\t// Strict requires a signature; lenient (default) lets an unsigned\n\t\t\t\t// response through — e.g. self-host with no signing key configured.\n\t\t\t\tif (verifyMode === \"strict\") {\n\t\t\t\t\tthrow new StreamsSignatureError(\"Response is missing X-Signature.\");\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst key = await loadKeyFor(response.headers.get(\"X-Signature-KeyId\"));\n\t\t\t\t// A signature is present, so verify it regardless of strict/lenient —\n\t\t\t\t// an invalid signature always fails closed.\n\t\t\t\tif (!ed25519.verifyEd25519(text, signature, key.publicKey)) {\n\t\t\t\t\tthrow new StreamsSignatureError();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn JSON.parse(text) as T;\n\t}\n\n\t// StreamsEventsFetchParams is a strict subset of StreamsEventsListParams, so\n\t// this is checked by the compiler rather than by a hand-copied destructure.\n\tconst fetchEvents: StreamsEventsFetcher = listEvents;\n\n\tfunction listReorgs(params: StreamsReorgsListParams) {\n\t\treturn request<StreamsReorgsListEnvelope>(\n\t\t\t`/v1/streams/reorgs${buildQuery({\n\t\t\t\tsince: params.since,\n\t\t\t\tlimit: params.limit,\n\t\t\t})}`,\n\t\t);\n\t}\n\t// Idle-tip reorg detection for the consume loop (one request per empty\n\t// page); the public `reorgs.list` is the same call.\n\tconst fetchReorgs = (params: { since: string }) => listReorgs(params);\n\n\tfunction encodeFilters(filters: StreamsFilterMap | undefined) {\n\t\treturn filters ? JSON.stringify(filters) : undefined;\n\t}\n\n\tasync function listEvents(\n\t\tparams: StreamsEventsListParams = {},\n\t): Promise<StreamsEventsEnvelope> {\n\t\treturn request<StreamsEventsEnvelope>(\n\t\t\t`/v1/streams/events${buildQuery({\n\t\t\t\tcursor: params.cursor,\n\t\t\t\tfrom_height: params.fromHeight,\n\t\t\t\tto_height: params.toHeight,\n\t\t\t\tlimit: params.limit,\n\t\t\t\tcontract_id: params.contractId,\n\t\t\t\tsender: params.sender,\n\t\t\t\trecipient: params.recipient,\n\t\t\t\tasset_identifier: params.assetIdentifier,\n\t\t\t\ttypes: params.types,\n\t\t\t\tnot_types: params.notTypes,\n\t\t\t\tfilters: encodeFilters(params.filters),\n\t\t\t})}`,\n\t\t);\n\t}\n\n\t/**\n\t * One signature, two shapes: a flat filter with `onBatch`, or a labelled\n\t * `filters` map with a handler per label (or both). Deliberately NOT\n\t * overloaded — an overloaded interface member strips contextual typing from\n\t * every stub and alternate implementation of `StreamsClient`.\n\t */\n\tfunction consumeEvents<\n\t\tconst F extends StreamsFilterMap = Record<never, never>,\n\t\tTTx = never,\n\t\tD extends boolean = false,\n\t>(\n\t\t// Redundant `sink` member: direct TTx inference site (inference\n\t\t// does not traverse the params alias).\n\t\tparams: StreamsEventsConsumeParams<TTx, D, F> & {\n\t\t\tsink?: ConsumerSink<TTx>;\n\t\t},\n\t): Promise<StreamsEventsConsumeResult> {\n\t\tconst labels = params.filters ? Object.keys(params.filters) : [];\n\t\t// The \"at least one handler\" rule is conditional on `filters`, so it\n\t\t// can't live in the type without making `F` uninferrable. Fail loudly\n\t\t// instead of consuming pages into nothing.\n\t\tif (labels.length === 0 && !params.onBatch) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t\"consume requires onBatch, or filters + on handlers.\",\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\tif (labels.length > 0 && !params.on && !params.onBatch) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t\"consume with filters requires on handlers (or onBatch).\",\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\tconst dispatch = params.on as\n\t\t\t| Record<\n\t\t\t\t\tstring,\n\t\t\t\t\t(\n\t\t\t\t\t\tevents: StreamsEvent[] | IndexEvent[],\n\t\t\t\t\t\tctx: Parameters<\n\t\t\t\t\t\t\tNonNullable<StreamsEventsConsumeParams<TTx>[\"onBatch\"]>\n\t\t\t\t\t\t>[2],\n\t\t\t\t\t) => void | Promise<void>\n\t\t\t >\n\t\t\t| undefined;\n\n\t\t// With `decoded: true`, events arrive as the flat Index-shaped rows —\n\t\t// decoding never appears in the handler.\n\t\tconst project = (events: StreamsEvent[]): StreamsEvent[] | IndexEvent[] =>\n\t\t\tparams.decoded ? events.map(decode) : events;\n\n\t\tconst onBatch: StreamsEventsConsumeParams<TTx>[\"onBatch\"] = async (\n\t\t\tevents,\n\t\t\tenvelope,\n\t\t\tctx,\n\t\t) => {\n\t\t\t// Label dispatch reads the wire `matched` array, so it has to run\n\t\t\t// BEFORE decode — the decoded row shape does not carry it.\n\t\t\tfor (const label of labels) {\n\t\t\t\tconst forLabel = events.filter((event) =>\n\t\t\t\t\tevent.matched?.includes(label),\n\t\t\t\t);\n\t\t\t\tif (forLabel.length === 0) continue;\n\t\t\t\tawait dispatch?.[label]?.(project(forLabel), ctx);\n\t\t\t}\n\t\t\t// The `decoded` flag is a runtime value here, so `project`'s return\n\t\t\t// can't be narrowed to the D-conditional the declared handler wants.\n\t\t\tconst userOnBatch = params.onBatch as StreamsEventsConsumeParams<\n\t\t\t\tTTx,\n\t\t\t\tboolean\n\t\t\t>[\"onBatch\"];\n\t\t\t// `onBatch`'s several legal return shapes collapse to one here: the\n\t\t\t// consume loop only ever reads a cursor string or nothing.\n\t\t\treturn (await userOnBatch?.(project(events), envelope, ctx)) as\n\t\t\t\t| string\n\t\t\t\t| null\n\t\t\t\t| undefined;\n\t\t};\n\n\t\treturn consumeStreamsEvents<TTx>({\n\t\t\tfromCursor: params.fromCursor,\n\t\t\tsink: params.sink,\n\t\t\tonProgress: params.onProgress,\n\t\t\tmode: params.mode,\n\t\t\tfinalizedOnly: params.finalizedOnly,\n\t\t\t...streamsFilters(params),\n\t\t\tbatchSize: params.batchSize ?? 100,\n\t\t\tfetchEvents,\n\t\t\tfetchReorgs,\n\t\t\tonBatch,\n\t\t\tonReorg: params.onReorg,\n\t\t\tmaxRollbackDepth: params.maxRollbackDepth,\n\t\t\temptyBackoffMs: params.emptyBackoffMs,\n\t\t\tmaxPages: params.maxPages,\n\t\t\tmaxEmptyPolls: params.maxEmptyPolls,\n\t\t\tsignal: params.signal,\n\t\t\tretryCount: params.retryCount,\n\t\t\tretryDelay: params.retryDelay,\n\t\t\tonError: params.onError,\n\t\t});\n\t}\n\n\treturn {\n\t\tconsume(params: StreamsConsumeParams = {}) {\n\t\t\treturn iterateStreamsBatches({\n\t\t\t\tfromCursor: params.cursor,\n\t\t\t\tbatchSize: params.batchSize ?? 100,\n\t\t\t\tintervalMs: params.intervalMs ?? 2000,\n\t\t\t\t...streamsFilters(params),\n\t\t\t\tsignal: params.signal,\n\t\t\t\tfetchEvents,\n\t\t\t});\n\t\t},\n\t\tevents: {\n\t\t\tlist: listEvents,\n\t\t\tbyTxId(txId: string) {\n\t\t\t\treturn request<StreamsEventsListEnvelope>(\n\t\t\t\t\t`/v1/streams/events/${encodeURIComponent(txId)}`,\n\t\t\t\t);\n\t\t\t},\n\t\t\tconsume: consumeEvents,\n\t\t\tstream(params: StreamsEventsStreamParams = {}) {\n\t\t\t\treturn streamStreamsEvents({\n\t\t\t\t\tfromCursor: params.fromCursor,\n\t\t\t\t\t// Includes the labelled OR-groups: dropping them here silently\n\t\t\t\t\t// widened the stream to the FULL firehose (billed per row).\n\t\t\t\t\t...streamsFilters(params),\n\t\t\t\t\tbatchSize: params.batchSize ?? 100,\n\t\t\t\t\temptyBackoffMs: params.emptyBackoffMs,\n\t\t\t\t\tmaxPages: params.maxPages,\n\t\t\t\t\tmaxEmptyPolls: params.maxEmptyPolls,\n\t\t\t\t\tsignal: params.signal,\n\t\t\t\t\tfetchEvents,\n\t\t\t\t});\n\t\t\t},\n\t\t\tsubscribe(params: StreamsEventsSubscribeParams) {\n\t\t\t\treturn subscribeStreamsEvents({\n\t\t\t\t\tbaseUrl,\n\t\t\t\t\theaders: authHeaders(),\n\t\t\t\t\tfetchImpl,\n\t\t\t\t\tverify: verifyMode,\n\t\t\t\t\tloadKey: loadKeyFor,\n\t\t\t\t\treconnectDelayMs: params.reconnectDelayMs,\n\t\t\t\t\tstaleAfterMs: params.staleAfterMs,\n\t\t\t\t\tparams,\n\t\t\t\t});\n\t\t\t},\n\t\t\tasync replay(params: StreamsEventsReplayParams) {\n\t\t\t\tconst fromCursor =\n\t\t\t\t\tparams.from === \"genesis\" ? null : (params.from ?? null);\n\t\t\t\tconst fromBlock = fromCursor ? cursorTuple(fromCursor)[0] : 0;\n\t\t\t\tconst manifest = await dumps.list();\n\n\t\t\t\t// Hydrate finalized history from dumps, in block order. Files\n\t\t\t\t// ending at or below `from` carry nothing new; a file straddling\n\t\t\t\t// it is handed over whole, with `from` so the handler can skip\n\t\t\t\t// the rows at or below the checkpoint (file-granular delivery).\n\t\t\t\tconst files = manifest.files\n\t\t\t\t\t.filter((file) => file.to_block >= fromBlock)\n\t\t\t\t\t.filter(\n\t\t\t\t\t\t(file) =>\n\t\t\t\t\t\t\tfromCursor === null ||\n\t\t\t\t\t\t\tfile.max_cursor === null ||\n\t\t\t\t\t\t\tmaxCursor(fromCursor, file.max_cursor) !== fromCursor,\n\t\t\t\t\t)\n\t\t\t\t\t.sort(\n\t\t\t\t\t\t(a, b) => a.from_block - b.from_block || a.to_block - b.to_block,\n\t\t\t\t\t);\n\t\t\t\tfor (const file of files) {\n\t\t\t\t\tif (params.signal?.aborted) break;\n\t\t\t\t\tawait params.onDumpFile(file, { from: fromCursor });\n\t\t\t\t}\n\n\t\t\t\t// Seam: tail live from just past the dumped coverage. Cursor input is\n\t\t\t\t// exclusive, so the first live event is strictly after the last dump.\n\t\t\t\tconst seam = maxCursor(fromCursor, manifest.latest_finalized_cursor);\n\t\t\t\treturn consumeStreamsEvents({\n\t\t\t\t\tfromCursor: seam,\n\t\t\t\t\tmode: params.mode ?? \"tail\",\n\t\t\t\t\tbatchSize: params.batchSize ?? 100,\n\t\t\t\t\t// Live-tail narrowing only — the dump phase above hands over\n\t\t\t\t\t// whole all-type files by design.\n\t\t\t\t\ttypes: params.types,\n\t\t\t\t\tnotTypes: params.notTypes,\n\t\t\t\t\tfilters: params.filters,\n\t\t\t\t\tfetchEvents,\n\t\t\t\t\tonBatch: params.onBatch,\n\t\t\t\t\tonReorg: params.onReorg,\n\t\t\t\t\temptyBackoffMs: params.emptyBackoffMs,\n\t\t\t\t\tmaxPages: params.maxPages,\n\t\t\t\t\tmaxEmptyPolls: params.maxEmptyPolls,\n\t\t\t\t\tsignal: params.signal,\n\t\t\t\t});\n\t\t\t},\n\t\t},\n\t\tblocks: {\n\t\t\tevents(heightOrHash: number | string) {\n\t\t\t\treturn request<StreamsEventsListEnvelope>(\n\t\t\t\t\t`/v1/streams/blocks/${encodeURIComponent(String(heightOrHash))}/events`,\n\t\t\t\t);\n\t\t\t},\n\t\t},\n\t\treorgs: { list: listReorgs },\n\t\tdumps,\n\t\tcanonical(height: number) {\n\t\t\treturn request<StreamsCanonicalBlock>(`/v1/streams/canonical/${height}`);\n\t\t},\n\t\ttip() {\n\t\t\treturn request<StreamsTip>(\"/v1/streams/tip\");\n\t\t},\n\t};\n}\n",
|
|
6
|
+
"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",
|
|
7
|
+
"import {\n\tApiError,\n\tAuthError,\n\tRateLimitError,\n\tparseRetryAfter,\n} from \"./errors.ts\";\n\nexport type FetchLike = (\n\tinput: string | URL | Request,\n\tinit?: RequestInit,\n) => Promise<Response>;\n\nexport interface SecondLayerOptions {\n\t/** Base URL of the instance API (trailing slashes are stripped). */\n\tbaseUrl: string;\n\t/** Bearer token for authenticated requests. */\n\tapiKey?: string;\n\t/** Fetch implementation. Tests and edge runtimes can provide their own. */\n\tfetchImpl?: FetchLike;\n\t/** Public base URL for Streams bulk parquet dumps (the cold backfill plane).\n\t * Required for `streams.dumps.*`; without it the dumps client falls back to\n\t * its built-in default. */\n\tdumpsBaseUrl?: string;\n\t/** Deploy origin label sent as `x-sl-origin` (telemetry). Defaults to `cli`. */\n\torigin?: \"cli\" | \"mcp\" | \"session\";\n\t/** Check the ed25519 signature on every Streams read. Omit for lenient\n\t * (verify when signed, pass through unsigned self-host responses), `true`\n\t * or `{ publicKey }` for strict, `false` for off. Reaches `sl.streams`. */\n\tverify?: boolean | { publicKey: string };\n\t/** Check the dumps manifest signature before trusting any file hash\n\t * (default on). Reaches `sl.streams.dumps`. */\n\tverifyDumpsManifest?: boolean;\n\t/** How long one request may take, headers and body, before it fails with a\n\t * retryable `ApiError` (default 30 000 ms). A hung socket then trips the\n\t * retry policy instead of stalling a walk or consume loop forever. `0`\n\t * disables the timeout. */\n\trequestTimeoutMs?: number;\n}\n\n/** Default per-request budget. Long enough for a 1000-row filtered page on a\n * cold cache, short enough that a half-open connection surfaces as a retry. */\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n\n/** Per-call options every `request*` method accepts. */\nexport type RequestOptions = {\n\t/** Cancels the in-flight request (and its body read). The rejection is the\n\t * signal's reason, an `AbortError` by default, never an `ApiError`. */\n\tsignal?: AbortSignal;\n};\n\n/** The rejection a caller abort produces when the signal carries no reason. */\nexport function abortError(): Error {\n\treturn new DOMException(\"This operation was aborted\", \"AbortError\");\n}\n\n/** Reject as soon as `signal` aborts, even when `promise` is a fetch\n * implementation that ignores its `signal` argument. */\nfunction raceAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n\tif (signal.aborted) return Promise.reject(signal.reason ?? abortError());\n\treturn new Promise<T>((resolve, reject) => {\n\t\tconst onAbort = () => reject(signal.reason ?? abortError());\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tpromise.then(resolve, reject).finally(() => {\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t});\n\t});\n}\n\n/** Product default: the local one-box API. Override with `baseUrl` or `SL_API_URL`. */\nexport const LOCAL_API_URL = \"http://127.0.0.1:3800\";\n\nexport function resolveBaseUrl(explicit?: string): string {\n\tif (explicit && explicit.length > 0) return explicit.replace(/\\/+$/, \"\");\n\tif (typeof process !== \"undefined\") {\n\t\tconst fromEnv = process.env?.SL_API_URL || process.env?.SECONDLAYER_API_URL;\n\t\tif (fromEnv) return fromEnv.replace(/\\/+$/, \"\");\n\t}\n\treturn LOCAL_API_URL;\n}\n\n/** Credential env vars, highest precedence first. `INSTANCE_TOKEN` is the\n * canonical name — it is what `secondlayer init` writes into `.env.local` and\n * what the instance API validates bearer tokens against. `SL_API_KEY` is a\n * legacy alias, kept working so existing exports and CI secrets don't break. */\nexport const CREDENTIAL_ENV_VARS = [\"INSTANCE_TOKEN\", \"SL_API_KEY\"] as const;\n\n/** Conflicting pairs already warned about, so a process with a genuine\n * misconfiguration says so once rather than on every client construction. */\nconst warnedConflicts = new Set<string>();\n\n/** Resolve the credential a client should use. Precedence, highest first:\n *\n * 1. an explicit `apiKey` option — including an explicit `\"\"`, which is how\n * you opt a client back into keyless reads on a machine that has a key\n * exported;\n * 2. `INSTANCE_TOKEN` — the canonical credential var, shared with the CLI\n * and MCP server;\n * 3. `SL_API_KEY` — legacy alias for the same value.\n *\n * Env values that are empty strings count as unset. Falling back to the env at\n * all is what stops `new Index()` from silently running keyless and 402-ing on\n * the first deep-history read.\n *\n * When both env vars are set to *different* non-empty values there is no\n * correct silent answer, so `INSTANCE_TOKEN` wins and we warn once on stderr —\n * the whole point of this precedence is that a misconfigured credential should\n * never authenticate as nobody without saying so.\n *\n * Guarded for browsers and edge runtimes, where `process` is undefined. */\nexport function resolveApiKey(apiKey?: string): string | undefined {\n\tif (apiKey !== undefined) return apiKey;\n\tif (typeof process === \"undefined\") return undefined;\n\tconst instanceToken = process.env?.INSTANCE_TOKEN || undefined;\n\tconst legacyKey = process.env?.SL_API_KEY || undefined;\n\tif (instanceToken && legacyKey && instanceToken !== legacyKey) {\n\t\tconst pair = `${instanceToken}\\u0000${legacyKey}`;\n\t\tif (!warnedConflicts.has(pair)) {\n\t\t\twarnedConflicts.add(pair);\n\t\t\tconsole.warn(\n\t\t\t\t\"[secondlayer] INSTANCE_TOKEN and SL_API_KEY are set to different values — using INSTANCE_TOKEN (SL_API_KEY is a legacy alias for it).\",\n\t\t\t);\n\t\t}\n\t}\n\treturn instanceToken ?? legacyKey;\n}\n\n/** Percent-encode one URL path segment. Every caller-supplied identifier\n * (subgraph name, table, subscription id) goes through this before it is\n * interpolated into a path, so `..`, `/`, `?` and `#` in an id cannot\n * retarget the authenticated request at a different route. */\nexport function seg(value: string | number): string {\n\treturn encodeURIComponent(String(value));\n}\n\n/** Build a query-string suffix from name→value pairs. Skips null/undefined and\n * empty values; arrays are comma-joined. Returns \"\" (never a dangling \"?\") or\n * \"?a=1&b=2\" — the one canonical builder every list endpoint shares, so the\n * empty-query guard can't be forgotten per call site. */\nexport function buildQuery(\n\tparams: Record<\n\t\tstring,\n\t\tnumber | string | boolean | readonly string[] | null | undefined\n\t>,\n): string {\n\tconst search = new URLSearchParams();\n\tfor (const [name, value] of Object.entries(params)) {\n\t\tif (value === undefined || value === null) continue;\n\t\tconst serialized = Array.isArray(value) ? value.join(\",\") : String(value);\n\t\tif (serialized.length === 0) continue;\n\t\tsearch.set(name, serialized);\n\t}\n\tconst query = search.toString();\n\treturn query ? `?${query}` : \"\";\n}\n\n/** Pull the message and code out of an API error body. The API answers every\n * failure with `{error, code}`; a proxy in front of it may answer with plain\n * text or nothing, so the body is kept whichever shape it took and the\n * message is left undefined when there is none worth surfacing. */\nexport function parseErrorEnvelope(text: string): {\n\tmessage?: string;\n\tcode?: string;\n\tbody: unknown;\n} {\n\tif (text.length === 0) return { body: undefined };\n\ttry {\n\t\tconst json = JSON.parse(text);\n\t\tlet message: string | undefined;\n\t\tlet code: string | undefined;\n\t\tif (json && typeof json === \"object\") {\n\t\t\tconst err = json.error ?? json.message;\n\t\t\tif (typeof err === \"string\" && err.length > 0) message = err;\n\t\t\telse if (err && typeof err === \"object\") message = JSON.stringify(err);\n\t\t\tif (typeof json.code === \"string\") code = json.code;\n\t\t}\n\t\treturn { message, code, body: json };\n\t} catch {\n\t\treturn { message: text, body: text };\n\t}\n}\n\nexport abstract class BaseClient {\n\tprotected baseUrl: string;\n\tprotected apiKey?: string;\n\tprotected origin: \"cli\" | \"mcp\" | \"session\";\n\tprotected fetchImpl: FetchLike;\n\tprotected requestTimeoutMs: number;\n\n\tconstructor(options: Partial<SecondLayerOptions> = {}) {\n\t\tthis.baseUrl = resolveBaseUrl(options.baseUrl);\n\t\tthis.apiKey = resolveApiKey(options.apiKey);\n\t\tthis.origin = options.origin ?? \"cli\";\n\t\tthis.requestTimeoutMs =\n\t\t\toptions.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n\t\t// Bind the global so a bare `fetch` reference doesn't lose its Request\n\t\t// context on runtimes where fetch is a method (workerd, older Node).\n\t\tthis.fetchImpl = options.fetchImpl ?? ((...args) => fetch(...args));\n\t}\n\n\tstatic authHeaders(apiKey?: string): Record<string, string> {\n\t\tconst headers: Record<string, string> = {\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t};\n\t\tif (apiKey) {\n\t\t\theaders.Authorization = `Bearer ${apiKey}`;\n\t\t}\n\t\treturn headers;\n\t}\n\n\tprotected async request<T>(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t\topts: RequestOptions = {},\n\t): Promise<T> {\n\t\treturn this.withRequestBudget(opts.signal, async (signal) => {\n\t\t\tconst response = await this.fetchResponse(method, path, body, signal);\n\t\t\tif (response.status === 204) {\n\t\t\t\treturn undefined as T;\n\t\t\t}\n\t\t\treturn (await raceAbort(response.json(), signal)) as T;\n\t\t});\n\t}\n\n\t/** Like `request`, but maps a 404 to `null` instead of throwing — the one\n\t * place that owns the \"absent resource\" rule for `get*` accessors. */\n\tprotected async requestOrNull<T>(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t\topts: RequestOptions = {},\n\t): Promise<T | null> {\n\t\ttry {\n\t\t\treturn await this.request<T>(method, path, body, opts);\n\t\t} catch (err) {\n\t\t\tif (err instanceof ApiError && err.status === 404) return null;\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tprotected async requestText(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t\topts: RequestOptions = {},\n\t): Promise<string> {\n\t\treturn this.withRequestBudget(opts.signal, async (signal) => {\n\t\t\tconst response = await this.fetchResponse(method, path, body, signal);\n\t\t\treturn raceAbort(response.text(), signal);\n\t\t});\n\t}\n\n\t/** Run one request under the caller's signal plus the per-request timeout.\n\t * One combined signal covers the fetch and the body read, so a socket that\n\t * stalls mid-body times out the same way one that never answers does. A\n\t * timeout rejects with a retryable `ApiError`; a caller abort rejects with\n\t * the signal's reason so loops can tell \"stop\" from \"try again\". */\n\tprivate async withRequestBudget<T>(\n\t\tcallerSignal: AbortSignal | undefined,\n\t\trun: (signal: AbortSignal) => Promise<T>,\n\t): Promise<T> {\n\t\tconst controller = new AbortController();\n\t\tlet timedOut = false;\n\t\tconst forward = () =>\n\t\t\tcontroller.abort(callerSignal?.reason ?? abortError());\n\t\tif (callerSignal?.aborted) forward();\n\t\telse callerSignal?.addEventListener(\"abort\", forward, { once: true });\n\t\tconst timer =\n\t\t\tthis.requestTimeoutMs > 0\n\t\t\t\t? setTimeout(() => {\n\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\tcontroller.abort(abortError());\n\t\t\t\t\t}, this.requestTimeoutMs)\n\t\t\t\t: undefined;\n\t\ttry {\n\t\t\treturn await run(controller.signal);\n\t\t} catch (err) {\n\t\t\tif (timedOut && !callerSignal?.aborted) {\n\t\t\t\tthrow new ApiError(\n\t\t\t\t\t0,\n\t\t\t\t\t`No response from ${this.baseUrl} within ${this.requestTimeoutMs}ms. Retryable. Raise requestTimeoutMs for slow filtered reads.`,\n\t\t\t\t\tundefined,\n\t\t\t\t\t\"REQUEST_TIMEOUT\",\n\t\t\t\t\t{ retryable: true, cause: err instanceof Error ? err : undefined },\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow err;\n\t\t} finally {\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\tcallerSignal?.removeEventListener(\"abort\", forward);\n\t\t}\n\t}\n\n\t/** Issue the HTTP request and map non-2xx statuses onto the error family.\n\t * `signal` is the combined caller-plus-timeout signal from `request*`;\n\t * subclasses that stream a body call this directly and read it themselves. */\n\tprotected async fetchResponse(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t\tsignal?: AbortSignal,\n\t): Promise<Response> {\n\t\tconst url = `${this.baseUrl}${path}`;\n\t\tconst headers = BaseClient.authHeaders(this.apiKey);\n\t\theaders[\"x-sl-origin\"] = this.origin;\n\n\t\t// Serialize the body BEFORE the network try so a body-encoding error\n\t\t// (e.g. unsupported BigInt) isn't misreported as \"Cannot reach API\".\n\t\t// BigInts are stringified — server schemas accept jsonb so the value\n\t\t// reaches the server intact, and any field that needs an actual bigint\n\t\t// at runtime is rehydrated by the consuming module (subgraph handler\n\t\t// code preserves the literal). See packages/subgraphs source-matcher\n\t\t// for the post-load shape.\n\t\tlet serializedBody: string | undefined;\n\t\tif (body !== undefined && body !== null) {\n\t\t\ttry {\n\t\t\t\tserializedBody = JSON.stringify(body, (_key, value) =>\n\t\t\t\t\ttypeof value === \"bigint\" ? value.toString() : value,\n\t\t\t\t);\n\t\t\t} catch (err) {\n\t\t\t\tconst detail = err instanceof Error ? err.message : String(err);\n\t\t\t\t// Not retryable: the same body will fail to serialize again.\n\t\t\t\tthrow new ApiError(\n\t\t\t\t\t0,\n\t\t\t\t\t`Failed to serialize request body: ${detail}`,\n\t\t\t\t\tundefined,\n\t\t\t\t\tundefined,\n\t\t\t\t\t{ retryable: false },\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tlet response: Response;\n\t\ttry {\n\t\t\tconst pending = this.fetchImpl(url, {\n\t\t\t\tmethod,\n\t\t\t\theaders,\n\t\t\t\tbody: serializedBody,\n\t\t\t\tsignal,\n\t\t\t});\n\t\t\tresponse = signal ? await raceAbort(pending, signal) : await pending;\n\t\t} catch (err) {\n\t\t\t// An abort (caller or timeout) is not a network failure; let the\n\t\t\t// budget wrapper decide what it means.\n\t\t\tif (signal?.aborted) throw err;\n\t\t\tthrow new ApiError(\n\t\t\t\t0,\n\t\t\t\t`Cannot reach API at ${this.baseUrl}. Check your connection or try again.`,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\t{ retryable: true, cause: err instanceof Error ? err : undefined },\n\t\t\t);\n\t\t}\n\n\t\tif (!response.ok) {\n\t\t\t// Read the envelope once for every failure status. The API answers\n\t\t\t// 401 and 503 with `{error, code}` too (a revoked token, an index\n\t\t\t// still catching up), and that code is what a caller branches on.\n\t\t\tconst errorBody = signal\n\t\t\t\t? await raceAbort(response.text(), signal)\n\t\t\t\t: await response.text();\n\t\t\tconst envelope = parseErrorEnvelope(errorBody);\n\t\t\tconst retryAfter = response.headers.get(\"Retry-After\") ?? undefined;\n\n\t\t\tif (response.status === 401) {\n\t\t\t\tthrow new AuthError(\n\t\t\t\t\tenvelope.message ?? \"API key invalid or expired.\",\n\t\t\t\t\tenvelope.body,\n\t\t\t\t\tenvelope.code,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (response.status === 429) {\n\t\t\t\t// The header is preserved as `retryAfterSeconds` (not just prose) so\n\t\t\t\t// the consume loops can honor it.\n\t\t\t\tconst fallback = retryAfter\n\t\t\t\t\t? `Rate limited. Wait ${retryAfter} seconds.`\n\t\t\t\t\t: \"Rate limited. Try again later.\";\n\t\t\t\tthrow new RateLimitError(\n\t\t\t\t\tenvelope.message ?? fallback,\n\t\t\t\t\tretryAfter,\n\t\t\t\t\tenvelope.body,\n\t\t\t\t\tenvelope.code,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (response.status >= 500) {\n\t\t\t\tconst retryAfterSeconds = parseRetryAfter(retryAfter);\n\t\t\t\tthrow new ApiError(\n\t\t\t\t\tresponse.status,\n\t\t\t\t\tenvelope.message ??\n\t\t\t\t\t\t`Server error. Try again or check status at ${this.baseUrl}/health`,\n\t\t\t\t\tenvelope.body,\n\t\t\t\t\tenvelope.code,\n\t\t\t\t\tretryAfterSeconds !== undefined ? { retryAfterSeconds } : {},\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tthrow new ApiError(\n\t\t\t\tresponse.status,\n\t\t\t\tenvelope.message ?? `HTTP ${response.status}`,\n\t\t\t\tenvelope.body,\n\t\t\t\tenvelope.code,\n\t\t\t);\n\t\t}\n\n\t\treturn response;\n\t}\n}\n",
|
|
8
|
+
"import {\n\tblockEndCursor,\n\tdecodeStreamsCursor,\n\tencodeStreamsCursor,\n} from \"@secondlayer/shared\";\nimport { ValidationError } from \"./errors.ts\";\n\n/**\n * Helpers for Streams cursors. A cursor is the opaque `<block>:<index>` string\n * that marks a position in the event stream; treat the format as an\n * implementation detail and go through these helpers instead of string-building\n * it at call sites. Encode/decode and the rewind sentinel come from the\n * canonical codec in `@secondlayer/shared` so the SDK cannot accept a spelling\n * the server would 400, or rewind to a different foot than Index/Streams.\n */\nexport const Cursor = {\n\t/**\n\t * Cursor at the foot of `height` — a position that sorts strictly below the\n\t * first event of block `height` (`height:0`) and strictly above every event\n\t * of block `height - 1`. Cursors are exclusive (`(bh,ei) > after`), so\n\t * resuming from it re-reads the entire canonical run starting at `height:0`\n\t * inclusive. This is the position to rewind to after a reorg whose fork point\n\t * is `height`: the new canonical block at `height` carries a fresh first\n\t * event at `(height, 0)` that the consumer MUST re-read.\n\t *\n\t * Encoded as `blockEndCursor(height - 1)` rather than the seemingly-natural\n\t * `${height}:0` — that earlier form was an off-by-one: being exclusive, it\n\t * skipped `(height, 0)`, silently dropping the fork block's first row on\n\t * every reorg. The sentinel is int4 max (the `event_index`/`tx_index` column\n\t * type), larger than any real index, so nothing at `height - 1` survives the\n\t * keyset and the next returned row is exactly `(height, 0)`.\n\t *\n\t * `atHeight(0)` is `null`: the pre-genesis position both consume loops\n\t * accept as \"read everything from the first event\". There is no string\n\t * cursor below `0:0`, and `0:0` itself is exclusive, so returning it here\n\t * skipped the genesis event.\n\t */\n\tatHeight(height: number): string | null {\n\t\tif (height <= 0) return null;\n\t\treturn encodeStreamsCursor(blockEndCursor(height - 1));\n\t},\n\n\t/** Parse a `<block>:<index>` cursor. Throws `ValidationError` if malformed. */\n\tparse(cursor: string): { blockHeight: number; eventIndex: number } {\n\t\ttry {\n\t\t\tconst decoded = decodeStreamsCursor(cursor);\n\t\t\treturn {\n\t\t\t\tblockHeight: decoded.block_height,\n\t\t\t\teventIndex: decoded.event_index,\n\t\t\t};\n\t\t} catch {\n\t\t\tthrow new ValidationError(\n\t\t\t\t`Invalid stream cursor \"${cursor}\"; expected \"<block>:<index>\" (e.g. \"951475:3\").`,\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t},\n};\n",
|
|
9
|
+
"// AuthError / RateLimitError / ValidationError are shared across the whole SDK\n// (Index and the platform clients throw them too) and live in ../errors.ts —\n// re-exported here so `@secondlayer/sdk/streams` imports keep working.\nimport { parseErrorEnvelope } from \"../base.ts\";\nimport {\n\tApiError,\n\tAuthError,\n\tRateLimitError,\n\tSecondLayerError,\n\tValidationError,\n} from \"../errors.ts\";\n\nexport { AuthError, RateLimitError, ValidationError } from \"../errors.ts\";\n\n/** Thrown on a 5xx from the Streams API, and on a failed signing-key fetch.\n * `retryable`: the page retry policy tries again. */\nexport class StreamsServerError extends ApiError {\n\tconstructor(message: string, status: number, body?: unknown, code?: string) {\n\t\tsuper(status, message, body, code, { retryable: true });\n\t\tthis.name = \"StreamsServerError\";\n\t}\n}\n\n/** Thrown when response signature verification is enabled and fails. */\nexport class StreamsSignatureError extends SecondLayerError {\n\tconstructor(message = \"Streams response signature verification failed.\") {\n\t\tsuper(message);\n\t\tthis.name = \"StreamsSignatureError\";\n\t}\n}\n\n/** Map a non-OK Streams response onto the SDK error family. The server's\n * `{error, code}` envelope survives on `message`/`code`/`body`, the same way\n * it does on Index reads, so `err.code === \"CURSOR_INVALID\"` branches the\n * same whichever client raised it. */\nexport async function mapStreamsError(response: Response): Promise<never> {\n\tconst { message, code, body } = parseErrorEnvelope(await response.text());\n\n\tif (response.status === 401) {\n\t\tthrow new AuthError(message ?? \"API key invalid or expired.\", body, code);\n\t}\n\n\tif (response.status === 429) {\n\t\tconst retryAfter = response.headers.get(\"Retry-After\") ?? undefined;\n\t\tthrow new RateLimitError(\n\t\t\tmessage ?? \"Rate limited. Try again later.\",\n\t\t\tretryAfter,\n\t\t\tbody,\n\t\t\tcode,\n\t\t);\n\t}\n\n\tif (response.status >= 500) {\n\t\tthrow new StreamsServerError(\n\t\t\tmessage ?? `Streams server returned ${response.status}.`,\n\t\t\tresponse.status,\n\t\t\tbody,\n\t\t\tcode,\n\t\t);\n\t}\n\n\tthrow new ValidationError(\n\t\tmessage ?? `Streams request returned ${response.status}.`,\n\t\tresponse.status,\n\t\tbody,\n\t\tcode,\n\t);\n}\n",
|
|
10
|
+
"import type { ConsumerSink, WithSinkTx } from \"../sinks/types.ts\";\nimport { Cursor } from \"./cursor.ts\";\nimport { ValidationError } from \"./errors.ts\";\nimport type {\n\tConsumerBatchContext,\n\tStreamsBatch,\n\tStreamsEvent,\n\tStreamsEventType,\n\tStreamsEventsEnvelope,\n\tStreamsFilterMap,\n\tStreamsFilterValue,\n\tStreamsReorg,\n\tStreamsReorgsListEnvelope,\n} from \"./types.ts\";\n\n/** Stable identity of a reorg, for in-memory dedup across re-reported pages. */\nfunction reorgKey(reorg: StreamsReorg): string {\n\treturn `${reorg.detected_at}|${reorg.fork_point_height}|${reorg.new_canonical_tip}`;\n}\n\n/** Default ceiling on how far below the checkpoint one reorg may rewind. */\nexport const DEFAULT_MAX_ROLLBACK_DEPTH = 1000;\n\n/** What one call to {@link applyReorgs} did. `null` when nothing rewound. */\nexport type ReorgRewind = {\n\t/** Lowest fork point rolled back. */\n\tforkPoint: number;\n\t/** Cursor to resume from: the foot of `forkPoint`, or `null` (pre-genesis). */\n\tcursor: string | null;\n};\n\n/**\n * Apply a page's (or the reorg list's) reorgs against the consumer's position.\n * Shared by the Streams and Index loops so the two cannot drift on the one\n * rule that decides data loss: NEVER rewind forward.\n *\n * A reorg is only actionable when its fork point is at or below the height\n * the cursor has reached (`fork_point_height <= resumeHeight(cursor)`).\n * Servers attach every reorg whose orphaned span intersects the page span, so\n * a page read from below the fork carries a reorg the consumer has not\n * written past yet. Rewinding to it would move the cursor FORWARD and skip\n * every row between the checkpoint and the fork, durably once a sink commits\n * the rewound cursor. Those reorgs are marked handled and left alone: the\n * page itself is already the canonical chain.\n *\n * Every fresh reorg is validated BEFORE the sink sees any of them: the fork\n * point must be a non-negative safe integer, and the rewind may not reach\n * more than `maxRollbackDepth` blocks below the checkpoint unless the caller\n * raised the ceiling. `fork_point_height` drives a `DELETE ... >= fork` on\n * every declared table, so a malformed or hostile value is refused loudly\n * rather than executed.\n */\nexport async function applyReorgs<\n\tTReorg extends { fork_point_height: number },\n>(opts: {\n\treorgs: readonly TReorg[];\n\tcursor: string | null;\n\t/** In-memory dedup across re-reported pages; mutated. */\n\thandled: Set<string>;\n\tkeyOf: (reorg: TReorg) => string;\n\tsink?: Pick<ConsumerSink<unknown>, \"rollback\">;\n\tonReorg?: (\n\t\treorg: TReorg,\n\t\tctx: { cursor: string | null },\n\t) => Promise<void> | void;\n\tmaxRollbackDepth?: number;\n}): Promise<ReorgRewind | null> {\n\tconst fresh = opts.reorgs.filter(\n\t\t(reorg) => !opts.handled.has(opts.keyOf(reorg)),\n\t);\n\tif (fresh.length === 0) return null;\n\n\tfor (const reorg of fresh) {\n\t\tconst fork = reorg.fork_point_height;\n\t\tif (!Number.isSafeInteger(fork) || fork < 0) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t`Reorg fork_point_height ${String(fork)} is not a non-negative integer. Rollback deletes every row at or above the fork from every declared table, so a malformed fork point is refused before the sink runs.`,\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst position = resumeHeight(opts.cursor);\n\tconst applicable = fresh\n\t\t.filter((reorg) => position !== null && reorg.fork_point_height <= position)\n\t\t.sort((a, b) => a.fork_point_height - b.fork_point_height);\n\t// Fork above the checkpoint: nothing at or past it has been written, and\n\t// the page being read is already the new chain. Remember it, do not move.\n\tfor (const reorg of fresh) {\n\t\tif (!applicable.includes(reorg)) opts.handled.add(opts.keyOf(reorg));\n\t}\n\tif (applicable.length === 0 || position === null) return null;\n\n\tconst forkPoint = applicable[0]?.fork_point_height ?? position;\n\tconst depth = position - forkPoint;\n\tconst maxDepth = opts.maxRollbackDepth ?? DEFAULT_MAX_ROLLBACK_DEPTH;\n\tif (depth > maxDepth) {\n\t\tthrow new ValidationError(\n\t\t\t`Reorg at fork ${forkPoint} rewinds ${depth} blocks below the checkpoint at height ${position}, past maxRollbackDepth (${maxDepth}). A rollback this deep deletes every row at or above the fork from every declared table. Confirm the source is trusted, then pass maxRollbackDepth: ${depth} or higher to allow it.`,\n\t\t\t400,\n\t\t);\n\t}\n\n\tconst rewind = Cursor.atHeight(forkPoint);\n\tfor (const reorg of applicable) {\n\t\t// Sink first: rollback + rewound cursor commit atomically. A user\n\t\t// onReorg (if any) runs after, for observability.\n\t\tawait opts.sink?.rollback(reorg.fork_point_height, rewind);\n\t\tawait opts.onReorg?.(reorg, { cursor: rewind });\n\t\topts.handled.add(opts.keyOf(reorg));\n\t}\n\treturn { forkPoint, cursor: rewind };\n}\n\ntype StreamsEventsFetchParams = {\n\tcursor?: string | null;\n\tlimit: number;\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, forwarded to the server verbatim. */\n\tfilters?: StreamsFilterMap;\n};\n\nexport type StreamsEventsFetcher = (\n\tparams: StreamsEventsFetchParams,\n) => Promise<StreamsEventsEnvelope>;\n\nexport type Sleep = (ms: number, signal?: AbortSignal) => Promise<void>;\n\n/**\n * Guard the `finalizedOnly` checkpoint contract. Shared by both loops.\n *\n * In `finalizedOnly` mode the unfinalized tail is filtered OUT of the batch\n * and re-read next poll — and `onReorg` is skipped entirely, so nothing ever\n * re-reads a range the cursor has passed. Returning a cursor above the last\n * delivered finalized event (e.g. `envelope.next_cursor`, which points past\n * the filtered tail) therefore drops those events permanently and silently.\n * Throw instead: this is the one wrong return the loop can detect.\n */\nexport function assertFinalizedCheckpoint(\n\t// biome-ignore lint/suspicious/noConfusingVoidType: mirrors the onBatch return union it validates\n\treturned: string | null | undefined | void,\n\tcheckpoint: string | null,\n): void {\n\tif (returned === null || returned === undefined) return;\n\tif (returned === checkpoint) return;\n\tconst r = Cursor.parse(returned);\n\tconst c = checkpoint === null ? null : Cursor.parse(checkpoint);\n\tconst above =\n\t\tc === null ||\n\t\tr.blockHeight > c.blockHeight ||\n\t\t(r.blockHeight === c.blockHeight && r.eventIndex > c.eventIndex);\n\tif (above) {\n\t\tconst boundary = c ? ` (\"${checkpoint}\")` : \" (none delivered yet)\";\n\t\tthrow new ValidationError(\n\t\t\t`onBatch returned cursor \"${returned}\", above the last delivered finalized event${boundary}. With finalizedOnly, events past that point were filtered out and will be re-read once finalized — committing beyond it skips them permanently. Return ctx.cursor (or nothing); never envelope.next_cursor.`,\n\t\t\t400,\n\t\t);\n\t}\n}\n\n/**\n * Fail fast on an impossible sink/mode pairing. Shared by both loops, checked\n * BEFORE the first fetch and before `loadCursor`: a `finalizedOnly` sink\n * (append-only store — cannot undo committed rows) following the unfinalized\n * tip would corrupt on the first fork, and the corruption is silent until the\n * fork happens. Throwing at startup is the only loud moment available.\n */\nexport function assertSinkModeCompatible(\n\tsink: Pick<ConsumerSink, \"capabilities\"> | undefined,\n\tfinalizedOnly: boolean,\n): void {\n\tif (sink?.capabilities?.finalizedOnly && !finalizedOnly) {\n\t\tthrow new ValidationError(\n\t\t\t\"This sink declares capabilities.finalizedOnly — it cannot roll back reorged rows, and following the unfinalized tip would corrupt it at the first fork. Pass finalizedOnly: true to consume(), or use a sink that implements rollback.\",\n\t\t\t400,\n\t\t);\n\t}\n}\n\n/**\n * The height a resume cursor implies — seeds the loop's \"highest block\n * reached\" so a consumer restarted into a quiet tail reports its true\n * position (`checkpoint`, `height`, `blocksBehind`) instead of `null`s\n * until the first delivered row. Lenient: an unparseable cursor seeds\n * nothing and is left for the server to reject.\n */\nexport function resumeHeight(cursor: string | null): number | null {\n\tif (cursor === null) return null;\n\ttry {\n\t\treturn Cursor.parse(cursor).blockHeight;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Build the ctx handed to `onBatch`. Shared by the Streams and Index loops so\n * the two can't drift on what \"progress\" means. `blocksBehind` measures the\n * consumer's BACKLOG (`tip - scannedHeight`), not the age of the last\n * delivered event — a caught-up tail on a quiet contract is 0 behind. */\nexport function batchContext<TTip extends { block_height: number }, TReorg>(\n\tcursor: string | null,\n\theight: number | null,\n\ttip: TTip,\n\treorgs: readonly TReorg[] = [],\n\tscannedHeight: number | null = null,\n): ConsumerBatchContext<TTip, TReorg> {\n\tconst tipHeight = tip.block_height;\n\tconst position = scannedHeight ?? height;\n\treturn {\n\t\tcursor,\n\t\theight,\n\t\tscannedHeight: position,\n\t\ttipHeight,\n\t\tblocksBehind: position === null ? null : Math.max(0, tipHeight - position),\n\t\ttip,\n\t\treorgs,\n\t};\n}\n\n/** Options shared by both consume loops' page-fetch retry. Vocabulary matches\n * `@secondlayer/stacks` transports (`retryCount`/`retryDelay`) — one retry\n * language across the family, not a third. */\nexport type PageRetryOptions = {\n\t/** Retries after the first failure. Default 3; `0` disables. */\n\tretryCount?: number;\n\t/** Base delay in ms; the n-th retry waits `retryDelay * n` (matches the\n\t * stacks transport). A server `Retry-After` overrides it. Default 1000. */\n\tretryDelay?: number;\n\t/** Void observer, called before each retry sleep (metrics/logging). The\n\t * retry policy owns the decision; this cannot change it. */\n\tonError?: (\n\t\terr: unknown,\n\t\tctx: { attempt: number; retriesLeft: number; delayMs: number },\n\t) => void;\n};\n\n/** Sleep clamp for a server `Retry-After`: the loop honors the header up to\n * five minutes per attempt and keeps retrying within `retryCount`. It never\n * gives up early on a long Retry-After; the tradeoff is a long wait, not a\n * dropped loop. Set `retryCount: 0` to surface the 429 immediately instead. */\nconst MAX_RETRY_AFTER_MS = 300_000;\n\nfunction errRetryable(err: unknown): boolean {\n\t// SecondLayerError family carries an explicit signal; a bare TypeError is\n\t// the raw fetch network failure (Streams' fetchImpl isn't wrapped).\n\tif (err && typeof err === \"object\" && \"retryable\" in err) {\n\t\treturn (err as { retryable: unknown }).retryable === true;\n\t}\n\treturn err instanceof TypeError;\n}\n\nfunction errRetryAfterMs(err: unknown): number | undefined {\n\tif (err && typeof err === \"object\" && \"retryAfterSeconds\" in err) {\n\t\tconst seconds = (err as { retryAfterSeconds: unknown }).retryAfterSeconds;\n\t\tif (typeof seconds === \"number\" && Number.isFinite(seconds)) {\n\t\t\treturn Math.min(seconds * 1000, MAX_RETRY_AFTER_MS);\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/**\n * Run one page fetch with retries. Scoped to the FETCH only — never the loop\n * body: retrying after an `onReorg`/`onBatch` throw would re-enter with\n * `handledReorgs` partially mutated and skip a rollback silently. `onBatch`\n * and `onReorg` throws always propagate to the caller.\n */\nexport async function fetchPageWithRetry<T>(\n\tfetchPage: () => Promise<T>,\n\topts: PageRetryOptions & { sleep: Sleep; signal?: AbortSignal },\n): Promise<T> {\n\tconst retryCount = opts.retryCount ?? 3;\n\tconst retryDelay = opts.retryDelay ?? 1000;\n\tfor (let attempt = 0; ; attempt++) {\n\t\ttry {\n\t\t\treturn await fetchPage();\n\t\t} catch (err) {\n\t\t\tconst retriesLeft = retryCount - attempt;\n\t\t\tif (retriesLeft <= 0 || !errRetryable(err) || opts.signal?.aborted) {\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t\tconst delayMs = errRetryAfterMs(err) ?? retryDelay * (attempt + 1);\n\t\t\topts.onError?.(err, { attempt, retriesLeft, delayMs });\n\t\t\tawait opts.sleep(delayMs, opts.signal);\n\t\t\t// Aborted mid-sleep: surface the original failure, not a fresh fetch.\n\t\t\tif (opts.signal?.aborted) throw err;\n\t\t}\n\t}\n}\n\nexport async function defaultSleep(\n\tms: number,\n\tsignal?: AbortSignal,\n): Promise<void> {\n\tif (signal?.aborted) return;\n\n\tawait new Promise<void>((resolve) => {\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(timeout);\n\t\t\tresolve();\n\t\t};\n\t\t// Detach on the timer path too: a tail at the tip sleeps once per\n\t\t// empty poll, and each sleep that left its listener behind pinned a\n\t\t// closure on the caller's long-lived signal until the process exited.\n\t\tconst timeout = 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\nexport async function consumeStreamsEvents<TTx = never>(opts: {\n\tfromCursor?: string | null;\n\tmode?: \"tail\" | \"bounded\";\n\tfinalizedOnly?: boolean;\n\tbatchSize: number;\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, forwarded to the server verbatim. */\n\tfilters?: StreamsFilterMap;\n\tfetchEvents: StreamsEventsFetcher;\n\t/** `GET /v1/streams/reorgs`, polled on idle (empty) pages so a reorg\n\t * that lands while the consumer sits at the tip is still rolled back.\n\t * Pages only carry reorgs overlapping their own span. */\n\tfetchReorgs?: (params: {\n\t\tsince: string;\n\t}) => Promise<StreamsReorgsListEnvelope>;\n\t/** Destination adapter owning checkpoint + rollback (see IndexConsumeOptions.sink). */\n\tsink?: ConsumerSink<TTx>;\n\t/** Fires once per page, before `onBatch` and any early return. */\n\tonProgress?: (ctx: ConsumerBatchContext) => void;\n\tonBatch: (\n\t\tevents: StreamsEvent[],\n\t\tenvelope: StreamsEventsEnvelope,\n\t\tctx: ConsumerBatchContext & 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\tonReorg?: (\n\t\treorg: StreamsReorg,\n\t\tctx: { cursor: string | null },\n\t) => Promise<void> | void;\n\t/** Deepest rewind one reorg may make below the checkpoint. Default 1000. */\n\tmaxRollbackDepth?: number;\n\tsleep?: Sleep;\n\temptyBackoffMs?: number;\n\tmaxPages?: number;\n\tmaxEmptyPolls?: number;\n\tretryCount?: number;\n\tretryDelay?: number;\n\tonError?: PageRetryOptions[\"onError\"];\n\tsignal?: AbortSignal;\n}): Promise<{ cursor: string | null; pages: number; emptyPolls: number }> {\n\tconst sleep = opts.sleep ?? defaultSleep;\n\tconst mode = opts.mode ?? \"tail\";\n\tconst finalizedOnly = opts.finalizedOnly ?? false;\n\tconst emptyBackoffMs = opts.emptyBackoffMs ?? 500;\n\tconst maxPages = opts.maxPages ?? Number.POSITIVE_INFINITY;\n\tconst maxEmptyPolls = opts.maxEmptyPolls ?? Number.POSITIVE_INFINITY;\n\tassertSinkModeCompatible(opts.sink, finalizedOnly);\n\t// Resume order: explicit fromCursor, then the sink's committed checkpoint.\n\t// `loadCursor` is also the sink's INIT — it creates the checkpoint table and\n\t// validates the rollback precondition. Short-circuiting it on an explicit\n\t// `fromCursor` meant a replay-from-cursor run crashed on its first commit,\n\t// and skipped the height-column check that keeps reorg rollback from being\n\t// a silent no-op. Always initialize; `fromCursor` still wins as the resume\n\t// position.\n\tconst committedCursor = (await opts.sink?.loadCursor()) ?? null;\n\tlet cursor = opts.fromCursor ?? committedCursor;\n\t// In-memory only: rollback is idempotent, so a crash before the rewind is\n\t// re-detected and re-applied harmlessly on restart — no need to persist.\n\tconst handledReorgs = new Set<string>();\n\t// Resume token for the idle-tip reorg list; `null` until the first idle\n\t// poll with a checkpoint to seed it from.\n\tlet reorgSince: string | null = null;\n\tlet pages = 0;\n\tlet emptyPolls = 0;\n\t// Highest block reached, carried across empty pages so a caught-up tail\n\t// keeps reporting its position instead of dropping to null. Seeded from\n\t// the resume cursor: a restart into a quiet tail knows where it stands\n\t// before the first row lands.\n\tlet height: number | null = resumeHeight(cursor);\n\t// Highest block VERIFIED — how far the sweep is actually caught up, as\n\t// opposed to `height` (last delivered row). Starts at the resume position;\n\t// each page moves it (see below).\n\tlet scanned: number | null = height;\n\n\twhile (\n\t\tpages < maxPages &&\n\t\temptyPolls < maxEmptyPolls &&\n\t\t!opts.signal?.aborted\n\t) {\n\t\t// Retry wraps ONLY the page fetch: one transient 429/5xx must not kill\n\t\t// an hours-long backfill, and handler throws must never be re-entered.\n\t\tconst envelope = await fetchPageWithRetry(\n\t\t\t() =>\n\t\t\t\topts.fetchEvents({\n\t\t\t\t\tcursor,\n\t\t\t\t\tlimit: opts.batchSize,\n\t\t\t\t\ttypes: opts.types,\n\t\t\t\t\tnotTypes: opts.notTypes,\n\t\t\t\t\tcontractId: opts.contractId,\n\t\t\t\t\tsender: opts.sender,\n\t\t\t\t\trecipient: opts.recipient,\n\t\t\t\t\tassetIdentifier: opts.assetIdentifier,\n\t\t\t\t\tfilters: opts.filters,\n\t\t\t\t}),\n\t\t\t{\n\t\t\t\tretryCount: opts.retryCount,\n\t\t\t\tretryDelay: opts.retryDelay,\n\t\t\t\tonError: opts.onError,\n\t\t\t\tsleep,\n\t\t\t\tsignal: opts.signal,\n\t\t\t},\n\t\t);\n\t\tpages++;\n\n\t\t// Reorgs: roll back each new fork at or below the checkpoint, then\n\t\t// rewind to the lowest fork point and re-read the now-canonical run.\n\t\t// Finalized data never reorgs, so `finalizedOnly` skips this entirely.\n\t\t// A sink makes rollback UNCONDITIONAL: omitting `onReorg` used to skip\n\t\t// reorgs silently.\n\t\tconst reorgsOn = !finalizedOnly && Boolean(opts.onReorg || opts.sink);\n\t\tif (reorgsOn) {\n\t\t\tconst rewound = await applyReorgs({\n\t\t\t\treorgs: envelope.reorgs,\n\t\t\t\tcursor,\n\t\t\t\thandled: handledReorgs,\n\t\t\t\tkeyOf: reorgKey,\n\t\t\t\tsink: opts.sink,\n\t\t\t\tonReorg: opts.onReorg,\n\t\t\t\tmaxRollbackDepth: opts.maxRollbackDepth,\n\t\t\t});\n\t\t\tif (rewound) {\n\t\t\t\tcursor = rewound.cursor;\n\t\t\t\t// Everything at and above the fork is no longer canonical, so the\n\t\t\t\t// reached height rolls back with it — including the verified\n\t\t\t\t// position: the new chain above the fork is unread.\n\t\t\t\theight = rewound.forkPoint > 0 ? rewound.forkPoint - 1 : null;\n\t\t\t\tscanned = height;\n\t\t\t\temptyPolls = 0;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\t// Idle tip: a page only reports reorgs overlapping its own span, so a\n\t\t// fork that lands while the consumer sits at the tip (orphaning rows\n\t\t// BELOW the next non-empty page) is never on a page. On an empty page\n\t\t// ask the reorg list instead: one extra request per idle poll. Seeded\n\t\t// from the checkpoint cursor (the API reads a cursor as \"reorgs that\n\t\t// orphaned anything at or above this position\"), then advanced by the\n\t\t// list's own `next_since` token.\n\t\tif (reorgsOn && opts.fetchReorgs && envelope.events.length === 0) {\n\t\t\treorgSince ??= cursor;\n\t\t\tif (reorgSince !== null) {\n\t\t\t\tconst since: string = reorgSince;\n\t\t\t\tconst fetchReorgs = opts.fetchReorgs;\n\t\t\t\tconst listed: StreamsReorgsListEnvelope = await fetchPageWithRetry(\n\t\t\t\t\t() => fetchReorgs({ since }),\n\t\t\t\t\t{\n\t\t\t\t\t\tretryCount: opts.retryCount,\n\t\t\t\t\t\tretryDelay: opts.retryDelay,\n\t\t\t\t\t\tonError: opts.onError,\n\t\t\t\t\t\tsleep,\n\t\t\t\t\t\tsignal: opts.signal,\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\tif (listed.next_since !== null) reorgSince = listed.next_since;\n\t\t\t\tconst rewound = await applyReorgs({\n\t\t\t\t\treorgs: listed.reorgs,\n\t\t\t\t\tcursor,\n\t\t\t\t\thandled: handledReorgs,\n\t\t\t\t\tkeyOf: reorgKey,\n\t\t\t\t\tsink: opts.sink,\n\t\t\t\t\tonReorg: opts.onReorg,\n\t\t\t\t\tmaxRollbackDepth: opts.maxRollbackDepth,\n\t\t\t\t});\n\t\t\t\tif (rewound) {\n\t\t\t\t\tcursor = rewound.cursor;\n\t\t\t\t\theight = rewound.forkPoint > 0 ? rewound.forkPoint - 1 : null;\n\t\t\t\t\tscanned = height;\n\t\t\t\t\temptyPolls = 0;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst emitted = finalizedOnly\n\t\t\t? envelope.events.filter((event) => event.finalized)\n\t\t\t: envelope.events;\n\t\t// Only advance to the last finalized event in finalizedOnly mode; the\n\t\t// unfinalized tail is re-read next poll until it settles.\n\t\tconst checkpoint = finalizedOnly\n\t\t\t? (emitted.at(-1)?.cursor ?? cursor)\n\t\t\t: envelope.next_cursor;\n\t\t// Ascending cursor order, so the last row is the highest block this page\n\t\t// reached; an empty page keeps the previous value.\n\t\theight = emitted.at(-1)?.block_height ?? height;\n\t\t// Verified position. Rows delivered → through the last row (the page\n\t\t// limit hides what's above it). Empty page with an ADVANCED cursor →\n\t\t// through that cursor only (a server may cap an expensive filtered\n\t\t// scan; claiming the tip would overstate). Truly empty page → the\n\t\t// server confirmed nothing matches up to the tip. Non-empty raw page\n\t\t// fully filtered (unfinalized tail) → position unchanged.\n\t\tif (emitted.length > 0) {\n\t\t\tscanned = height;\n\t\t} else if (checkpoint !== null && checkpoint !== cursor) {\n\t\t\tscanned = resumeHeight(checkpoint) ?? scanned;\n\t\t} else if (envelope.events.length === 0) {\n\t\t\tscanned = envelope.tip.block_height;\n\t\t}\n\n\t\t// An empty page reports the STANDING cursor, not null: the committed\n\t\t// checkpoint is still this consumer's position while it idles.\n\t\tconst ctx = batchContext(\n\t\t\tcheckpoint ?? cursor,\n\t\t\theight,\n\t\t\tenvelope.tip,\n\t\t\tenvelope.reorgs,\n\t\t\tscanned,\n\t\t);\n\t\t// Before any early return: an empty page still proves the loop is alive.\n\t\topts.onProgress?.(ctx);\n\n\t\tlet nextCursor: string | null;\n\t\tif (opts.sink) {\n\t\t\tconst sink = opts.sink;\n\t\t\t// Rows and cursor commit in ONE transaction; a handler throw aborts\n\t\t\t// both. Nothing moved → nothing to commit, handler not invoked.\n\t\t\tif (\n\t\t\t\tcheckpoint !== null &&\n\t\t\t\t(checkpoint !== cursor || emitted.length > 0)\n\t\t\t) {\n\t\t\t\tawait sink.commitBatch(checkpoint, async (tx) => {\n\t\t\t\t\t// The cast is sound exactly as far as the sink's own typing:\n\t\t\t\t\t// `sink: ConsumerSink<TTx>` binds TTx, and `tx` here is what its\n\t\t\t\t\t// commitBatch lends. Nothing verifies it at runtime — a sink whose\n\t\t\t\t\t// declared Tx lies about what it lends fails inside the handler.\n\t\t\t\t\tawait opts.onBatch(emitted, envelope, {\n\t\t\t\t\t\t...ctx,\n\t\t\t\t\t\ttx,\n\t\t\t\t\t} as ConsumerBatchContext & WithSinkTx<TTx>);\n\t\t\t\t});\n\t\t\t}\n\t\t\tnextCursor = checkpoint;\n\t\t} else {\n\t\t\tconst returnedCursor = await opts.onBatch(\n\t\t\t\temitted,\n\t\t\t\tenvelope,\n\t\t\t\tctx as ConsumerBatchContext & WithSinkTx<TTx>,\n\t\t\t);\n\t\t\tif (finalizedOnly) assertFinalizedCheckpoint(returnedCursor, checkpoint);\n\t\t\tnextCursor = returnedCursor ?? checkpoint;\n\t\t}\n\n\t\tif (nextCursor && nextCursor !== cursor) {\n\t\t\tcursor = nextCursor;\n\t\t\temptyPolls = 0;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (emitted.length === 0) {\n\t\t\temptyPolls++;\n\t\t\tif (mode === \"bounded\") {\n\t\t\t\treturn { cursor, pages, emptyPolls };\n\t\t\t}\n\t\t\tawait sleep(emptyBackoffMs, opts.signal);\n\t\t\tcontinue;\n\t\t}\n\n\t\treturn { cursor, pages, emptyPolls };\n\t}\n\n\treturn { cursor, pages, emptyPolls };\n}\n\n/**\n * Async-iterator form of the Streams pull loop, yielding one {@link StreamsBatch}\n * per fetched page. Each yield maps 1:1 onto a `GET /v1/streams/events` envelope\n * (`{ events, next_cursor, tip, reorgs }` → `{ events, cursor, tip, reorgs }`) —\n * no extra API calls, no regrouping. Pages with no events and no reorgs are not\n * yielded; the iterator sleeps `intervalMs` and re-polls the tip instead.\n */\nexport async function* iterateStreamsBatches(opts: {\n\tfromCursor?: string | null;\n\tbatchSize: number;\n\tintervalMs: number;\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, forwarded to the server verbatim. */\n\tfilters?: StreamsFilterMap;\n\tfetchEvents: StreamsEventsFetcher;\n\tsleep?: Sleep;\n\tsignal?: AbortSignal;\n}): AsyncGenerator<StreamsBatch> {\n\tconst sleep = opts.sleep ?? defaultSleep;\n\tlet cursor = opts.fromCursor ?? null;\n\n\twhile (!opts.signal?.aborted) {\n\t\tconst envelope = await opts.fetchEvents({\n\t\t\tcursor,\n\t\t\tlimit: opts.batchSize,\n\t\t\ttypes: opts.types,\n\t\t\tnotTypes: opts.notTypes,\n\t\t\tcontractId: opts.contractId,\n\t\t\tsender: opts.sender,\n\t\t\trecipient: opts.recipient,\n\t\t\tassetIdentifier: opts.assetIdentifier,\n\t\t\tfilters: opts.filters,\n\t\t});\n\n\t\tconst checkpoint = envelope.next_cursor ?? cursor;\n\t\tif (envelope.events.length > 0 || envelope.reorgs.length > 0) {\n\t\t\tyield {\n\t\t\t\tevents: envelope.events,\n\t\t\t\tcursor: checkpoint,\n\t\t\t\ttip: envelope.tip,\n\t\t\t\treorgs: envelope.reorgs,\n\t\t\t};\n\t\t}\n\n\t\tconst advanced = checkpoint !== null && checkpoint !== cursor;\n\t\tcursor = checkpoint;\n\t\t// Caught up at the tip: wait one poll interval before re-reading.\n\t\tif (!advanced && envelope.events.length === 0) {\n\t\t\tif (opts.signal?.aborted) return;\n\t\t\tawait sleep(opts.intervalMs, opts.signal);\n\t\t}\n\t}\n}\n\nexport async function* streamStreamsEvents(opts: {\n\tfromCursor?: string | null;\n\tbatchSize: number;\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, forwarded to the server verbatim. */\n\tfilters?: StreamsFilterMap;\n\tfetchEvents: StreamsEventsFetcher;\n\tsleep?: Sleep;\n\temptyBackoffMs?: number;\n\tmaxPages?: number;\n\tmaxEmptyPolls?: number;\n\tsignal?: AbortSignal;\n}): AsyncGenerator<StreamsEvent> {\n\tconst sleep = opts.sleep ?? defaultSleep;\n\tconst emptyBackoffMs = opts.emptyBackoffMs ?? 500;\n\tconst maxPages = opts.maxPages ?? Number.POSITIVE_INFINITY;\n\tconst maxEmptyPolls = opts.maxEmptyPolls ?? Number.POSITIVE_INFINITY;\n\tlet cursor = opts.fromCursor ?? null;\n\tlet pages = 0;\n\tlet emptyPolls = 0;\n\n\twhile (\n\t\tpages < maxPages &&\n\t\temptyPolls < maxEmptyPolls &&\n\t\t!opts.signal?.aborted\n\t) {\n\t\tconst envelope = await opts.fetchEvents({\n\t\t\tcursor,\n\t\t\tlimit: opts.batchSize,\n\t\t\ttypes: opts.types,\n\t\t\tnotTypes: opts.notTypes,\n\t\t\tcontractId: opts.contractId,\n\t\t\tsender: opts.sender,\n\t\t\trecipient: opts.recipient,\n\t\t\tassetIdentifier: opts.assetIdentifier,\n\t\t\tfilters: opts.filters,\n\t\t});\n\t\tpages++;\n\n\t\tfor (const event of envelope.events) {\n\t\t\tif (opts.signal?.aborted) return;\n\t\t\tyield event;\n\t\t}\n\n\t\tconst nextCursor = envelope.next_cursor;\n\t\tif (nextCursor && nextCursor !== cursor) {\n\t\t\tcursor = nextCursor;\n\t\t\temptyPolls = 0;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (envelope.events.length === 0) {\n\t\t\temptyPolls++;\n\t\t\tif (emptyPolls >= maxEmptyPolls || pages >= maxPages) return;\n\t\t\tawait sleep(emptyBackoffMs, opts.signal);\n\t\t\tcontinue;\n\t\t}\n\n\t\treturn;\n\t}\n}\n",
|
|
11
11
|
"import {\n\toptionalString,\n\trequireAmountField,\n\trequireHexValue,\n\trequireString,\n} from \"@secondlayer/shared/streams-rows\";\nimport type { IndexEvent } from \"../index-api/client.ts\";\nimport type { StreamsEvent } from \"./types.ts\";\n\n/**\n * Decode a raw Streams event into the SAME flat, `event_type`-discriminated\n * row shape Index serves — so Streams consumption reads identically to Index\n * consumption, with one call instead of eleven guard+decode pairs.\n *\n * ```ts\n * for (const event of envelope.events) {\n * const row = decode(event);\n * if (row.event_type === \"ft_transfer\") row.amount; // string, narrowed\n * }\n * ```\n *\n * Prefer `decoded: true` on `streams.events.consume` — then decoding never\n * appears in your code at all.\n */\nexport function decode(event: StreamsEvent): IndexEvent {\n\tconst base = {\n\t\tcursor: event.cursor,\n\t\tblock_height: event.block_height,\n\t\tblock_time: event.ts,\n\t\ttx_id: event.tx_id,\n\t\ttx_index: event.tx_index,\n\t\tevent_index: event.event_index,\n\t\tcontract_id: event.contract_id,\n\t};\n\t// Payloads are validated field-by-field (never trusted casts): a malformed\n\t// payload throws with the event type and field named.\n\tconst p = event.payload as Record<string, unknown>;\n\tswitch (event.event_type) {\n\t\tcase \"stx_transfer\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tevent_type: \"stx_transfer\",\n\t\t\t\tsender: requireString(p, \"sender\", event.event_type),\n\t\t\t\trecipient: requireString(p, \"recipient\", event.event_type),\n\t\t\t\tamount: requireAmountField(p, \"amount\", event.event_type),\n\t\t\t\tmemo: optionalString(p.memo),\n\t\t\t};\n\t\tcase \"stx_mint\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tevent_type: \"stx_mint\",\n\t\t\t\trecipient: requireString(p, \"recipient\", event.event_type),\n\t\t\t\tamount: requireAmountField(p, \"amount\", event.event_type),\n\t\t\t};\n\t\tcase \"stx_burn\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tevent_type: \"stx_burn\",\n\t\t\t\tsender: requireString(p, \"sender\", event.event_type),\n\t\t\t\tamount: requireAmountField(p, \"amount\", event.event_type),\n\t\t\t};\n\t\tcase \"stx_lock\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tevent_type: \"stx_lock\",\n\t\t\t\tsender: requireString(p, \"locked_address\", event.event_type),\n\t\t\t\tamount: requireAmountField(p, \"locked_amount\", event.event_type),\n\t\t\t\tpayload: { unlock_height: optionalString(p.unlock_height) },\n\t\t\t};\n\t\tcase \"ft_transfer\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tevent_type: \"ft_transfer\",\n\t\t\t\tasset_identifier: requireString(\n\t\t\t\t\tp,\n\t\t\t\t\t\"asset_identifier\",\n\t\t\t\t\tevent.event_type,\n\t\t\t\t),\n\t\t\t\tsender: requireString(p, \"sender\", event.event_type),\n\t\t\t\trecipient: requireString(p, \"recipient\", event.event_type),\n\t\t\t\tamount: requireAmountField(p, \"amount\", event.event_type),\n\t\t\t};\n\t\tcase \"ft_mint\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tevent_type: \"ft_mint\",\n\t\t\t\tasset_identifier: requireString(\n\t\t\t\t\tp,\n\t\t\t\t\t\"asset_identifier\",\n\t\t\t\t\tevent.event_type,\n\t\t\t\t),\n\t\t\t\trecipient: requireString(p, \"recipient\", event.event_type),\n\t\t\t\tamount: requireAmountField(p, \"amount\", event.event_type),\n\t\t\t};\n\t\tcase \"ft_burn\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tevent_type: \"ft_burn\",\n\t\t\t\tasset_identifier: requireString(\n\t\t\t\t\tp,\n\t\t\t\t\t\"asset_identifier\",\n\t\t\t\t\tevent.event_type,\n\t\t\t\t),\n\t\t\t\tsender: requireString(p, \"sender\", event.event_type),\n\t\t\t\tamount: requireAmountField(p, \"amount\", event.event_type),\n\t\t\t};\n\t\tcase \"nft_transfer\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tevent_type: \"nft_transfer\",\n\t\t\t\tasset_identifier: requireString(\n\t\t\t\t\tp,\n\t\t\t\t\t\"asset_identifier\",\n\t\t\t\t\tevent.event_type,\n\t\t\t\t),\n\t\t\t\tsender: requireString(p, \"sender\", event.event_type),\n\t\t\t\trecipient: requireString(p, \"recipient\", event.event_type),\n\t\t\t\tvalue: requireHexValue(p, event.event_type),\n\t\t\t};\n\t\tcase \"nft_mint\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tevent_type: \"nft_mint\",\n\t\t\t\tasset_identifier: requireString(\n\t\t\t\t\tp,\n\t\t\t\t\t\"asset_identifier\",\n\t\t\t\t\tevent.event_type,\n\t\t\t\t),\n\t\t\t\trecipient: requireString(p, \"recipient\", event.event_type),\n\t\t\t\tvalue: requireHexValue(p, event.event_type),\n\t\t\t};\n\t\tcase \"nft_burn\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tevent_type: \"nft_burn\",\n\t\t\t\tasset_identifier: requireString(\n\t\t\t\t\tp,\n\t\t\t\t\t\"asset_identifier\",\n\t\t\t\t\tevent.event_type,\n\t\t\t\t),\n\t\t\t\tsender: requireString(p, \"sender\", event.event_type),\n\t\t\t\tvalue: requireHexValue(p, event.event_type),\n\t\t\t};\n\t\tcase \"print\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tevent_type: \"print\",\n\t\t\t\tpayload: {\n\t\t\t\t\ttopic: optionalString(p.topic),\n\t\t\t\t\tvalue: p.value,\n\t\t\t\t\traw_value: optionalString(p.raw_value),\n\t\t\t\t},\n\t\t\t};\n\t}\n}\n",
|
|
12
|
-
"import { createHash } from \"node:crypto\";\nimport { verifyStreamsBulkManifestSignature } from \"@secondlayer/shared/streams-bulk-manifest\";\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\tasync function download(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\
|
|
13
|
-
"import { ed25519 } from \"@secondlayer/shared\";\nimport { buildQuery } from \"../base.ts\";\nimport { StreamsServerError, StreamsSignatureError } from \"./errors.ts\";\nimport type {\n\tFetchLike,\n\tStreamsEvent,\n\tStreamsEventsSubscribeParams,\n} from \"./types.ts\";\n\ntype VerificationKey = {\n\tpublicKey: ReturnType<typeof ed25519.loadEd25519PublicKey>;\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 — `EventSource` can't set headers. Works in browsers and\n * Node 18+. Reconnects from the last delivered cursor on a dropped connection\n * until the caller's signal aborts.\n */\nexport function subscribeStreamsEvents(opts: {\n\tbaseUrl: string;\n\tapiKey?: 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\tloadKey: () => Promise<VerificationKey>;\n\treconnectDelayMs?: number;\n\tparams: StreamsEventsSubscribeParams;\n}): () => void {\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 reconnectDelayMs = opts.reconnectDelayMs ?? 1000;\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\tconst res = await opts.fetchImpl(url, {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t...(opts.apiKey ? { Authorization: `Bearer ${opts.apiKey}` } : {}),\n\t\t\t\t\t\tAccept: \"text/event-stream\",\n\t\t\t\t\t},\n\t\t\t\t\tsignal: controller.signal,\n\t\t\t\t});\n\t\t\t\tif (!res.ok) {\n\t\t\t\t\tthrow new StreamsServerError(\n\t\t\t\t\t\t`Streams SSE returned ${res.status}.`,\n\t\t\t\t\t\tres.status,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (!res.body) {\n\t\t\t\t\tthrow new StreamsServerError(\"Streams SSE response has no body.\", 0);\n\t\t\t\t}\n\t\t\t\tfor await (const frame of parseSseFrames(res.body, controller.signal)) {\n\t\t\t\t\tif (frame.event === \"ping\" || !frame.data) continue;\n\t\t\t\t\tlet parsed: { event?: StreamsEvent; sig?: string };\n\t\t\t\t\ttry {\n\t\t\t\t\t\tparsed = JSON.parse(frame.data);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tcontinue; // ignore non-JSON frames\n\t\t\t\t\t}\n\t\t\t\t\tif (!parsed.event) continue;\n\t\t\t\t\tif (opts.verify !== \"off\") {\n\t\t\t\t\t\tif (!parsed.sig) {\n\t\t\t\t\t\t\t// Strict requires a signed frame; lenient (default) delivers an\n\t\t\t\t\t\t\t// unsigned frame (e.g. self-host with no signing key).\n\t\t\t\t\t\t\tif (opts.verify === \"strict\") {\n\t\t\t\t\t\t\t\tthrow new StreamsSignatureError(\n\t\t\t\t\t\t\t\t\t\"Streams SSE frame signature is missing.\",\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tconst key = await opts.loadKey();\n\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// invalid signature always fails closed.\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t!ed25519.verifyEd25519(\n\t\t\t\t\t\t\t\t\tJSON.stringify(parsed.event),\n\t\t\t\t\t\t\t\t\tparsed.sig,\n\t\t\t\t\t\t\t\t\tkey.publicKey,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tthrow new StreamsSignatureError(\n\t\t\t\t\t\t\t\t\t\"Streams SSE frame signature is invalid.\",\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}\n\t\t\t\t\tcursor = (parsed.event as { cursor?: string }).cursor ?? cursor;\n\t\t\t\t\tawait params.onEvent(parsed.event);\n\t\t\t\t}\n\t\t\t\t// Clean end (server closed the stream): reconnect from `cursor`.\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\tawait sleep(reconnectDelayMs, controller.signal);\n\t\t\t}\n\t\t}\n\t};\n\tvoid run();\n\treturn () => controller.abort();\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\nasync function* parseSseFrames(\n\tbody: ReadableStream<Uint8Array>,\n\tsignal: AbortSignal,\n): AsyncGenerator<{ event?: string; data?: string }> {\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 reader.read();\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): { event?: string; data?: string } {\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
|
-
"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\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/** Called for each pushed event, in order. */\n\tonEvent: (event: StreamsEvent) => void | Promise<void>;\n\t/** Called on a connection error; the subscription auto-reconnects from the\n\t * last delivered cursor unless the signal has aborted. */\n\tonError?: (err: unknown) => 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 */\nexport type StreamsReorgContext = { cursor: string };\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\n\t * (deduped in-memory, fork-ascending) before the SDK rewinds and re-reads the\n\t * now-canonical events. Omit it to ignore reorgs (events stay canonical, but\n\t * stale rows from an orphaned fork are left in place).\n\t */\n\tonReorg?: (\n\t\treorg: StreamsReorg,\n\t\tctx: StreamsReorgContext,\n\t) => Promise<void> | void;\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\tonDumpFile: (file: StreamsDumpFile) => 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.\n\t\t */\n\t\tsubscribe(params: StreamsEventsSubscribeParams): () => void;\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"
|
|
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
|
+
"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
|
+
"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. 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: StreamsDumps;\n\tcanonical(height: number): Promise<StreamsCanonicalBlock>;\n\ttip(): Promise<StreamsTip>;\n};\n"
|
|
16
16
|
],
|
|
17
|
-
"mappings": ";AAAA,oBAAS;;;ACAT,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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