@requence/service 0.8.2-edge.1151 → 0.8.2-edge.1155
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/README.md +258 -0
- package/build/{chunk-974rc2jy.js → chunk-gpyt51xn.js} +164 -3
- package/build/{chunk-974rc2jy.js.map → chunk-gpyt51xn.js.map} +7 -4
- package/build/cli.js +17 -30
- package/build/cli.js.map +3 -3
- package/build/index.js +538 -94
- package/build/index.js.map +18 -10
- package/build/types/helpers/src/index.d.ts +5 -0
- package/build/types/helpers/src/index.d.ts.map +1 -1
- package/build/types/helpers/src/protocol/NodeTree.d.ts +29 -0
- package/build/types/helpers/src/protocol/NodeTree.d.ts.map +1 -1
- package/build/types/helpers/src/protocol/command.d.ts +859 -7
- package/build/types/helpers/src/protocol/command.d.ts.map +1 -1
- package/build/types/helpers/src/protocol/index.d.ts +1 -0
- package/build/types/helpers/src/protocol/index.d.ts.map +1 -1
- package/build/types/helpers/src/protocol/sliceTreeList.d.ts +81 -0
- package/build/types/helpers/src/protocol/sliceTreeList.d.ts.map +1 -0
- package/build/types/helpers/src/protocol/treeNodes.d.ts +577 -2
- package/build/types/helpers/src/protocol/treeNodes.d.ts.map +1 -1
- package/build/types/helpers/src/protocol/update.d.ts +128 -10
- package/build/types/helpers/src/protocol/update.d.ts.map +1 -1
- package/build/types/helpers/src/utils/amqpPublishRetry.d.ts +113 -18
- package/build/types/helpers/src/utils/amqpPublishRetry.d.ts.map +1 -1
- package/build/types/helpers/src/utils/matchSchema.d.ts +14 -0
- package/build/types/helpers/src/utils/matchSchema.d.ts.map +1 -1
- package/build/types/helpers/src/utils/serviceRender.d.ts +73 -0
- package/build/types/helpers/src/utils/serviceRender.d.ts.map +1 -0
- package/build/types/helpers/src/utils/sliceClock.d.ts +61 -0
- package/build/types/helpers/src/utils/sliceClock.d.ts.map +1 -0
- package/build/types/helpers/src/utils/surfaceComponent.d.ts +116 -0
- package/build/types/helpers/src/utils/surfaceComponent.d.ts.map +1 -0
- package/build/types/helpers/src/utils/surfaceHandler.d.ts +171 -0
- package/build/types/helpers/src/utils/surfaceHandler.d.ts.map +1 -0
- package/build/types/helpers/src/utils/uiRebuild.d.ts +48 -0
- package/build/types/helpers/src/utils/uiRebuild.d.ts.map +1 -0
- package/build/types/service/src/boundary.d.ts +14 -1
- package/build/types/service/src/boundary.d.ts.map +1 -1
- package/build/types/service/src/createAmqpConnection.d.ts +55 -0
- package/build/types/service/src/createAmqpConnection.d.ts.map +1 -1
- package/build/types/service/src/errors.d.ts +11 -0
- package/build/types/service/src/errors.d.ts.map +1 -1
- package/build/types/service/src/helpers.d.ts +68 -0
- package/build/types/service/src/helpers.d.ts.map +1 -1
- package/build/types/service/src/index.d.ts +2 -0
- package/build/types/service/src/index.d.ts.map +1 -1
- package/build/types/service/src/surfaceHandler.d.ts +36 -0
- package/build/types/service/src/surfaceHandler.d.ts.map +1 -0
- package/build/types/service/src/surfaceUi.d.ts +141 -0
- package/build/types/service/src/surfaceUi.d.ts.map +1 -0
- package/build/types/service/src/transformer.d.ts +14 -0
- package/build/types/service/src/transformer.d.ts.map +1 -1
- package/build/types/service/src/ui.d.ts +247 -0
- package/build/types/service/src/ui.d.ts.map +1 -0
- package/build/types/service/src/uiWatch.d.ts +68 -0
- package/build/types/service/src/uiWatch.d.ts.map +1 -0
- package/package.json +10 -4
package/build/index.js.map
CHANGED
|
@@ -1,17 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/index.ts", "../../helpers/src/utils/guards.ts", "../../helpers/src/utils/mapData.ts", "../../helpers/src/utils/fileObject.ts", "../../helpers/src/utils/streamObject.ts", "../../helpers/src/utils/claimCheckObject.ts", "../../helpers/src/utils/requenceCallback.ts", "../../helpers/src/utils/
|
|
3
|
+
"sources": ["../../../node_modules/.bun/dlv@1.1.3/node_modules/dlv/dist/dlv.js", "../src/index.ts", "../../helpers/src/utils/guards.ts", "../../helpers/src/utils/mapData.ts", "../../helpers/src/utils/fileObject.ts", "../../helpers/src/utils/streamObject.ts", "../../helpers/src/utils/claimCheckObject.ts", "../../helpers/src/utils/requenceCallback.ts", "../../helpers/src/utils/serviceRender.ts", "../../helpers/src/utils/surfaceHandler.ts", "../../helpers/src/utils/uiRebuild.ts", "../../helpers/src/utils/obj.ts", "../../helpers/src/utils/amqpHeartbeat.ts", "../src/createAmqpConnection.ts", "../../helpers/src/msgpack/index.ts", "../../files/src/errors.ts", "../../files/src/streamFraming.ts", "../../files/src/remoteBody.ts", "../../files/src/RequenceFile.ts", "../../files/src/RequenceStream.ts", "../../files/src/handlers/transport.ts", "../../files/src/handlers/fileHandler.ts", "../../files/src/withRequenceStreams.ts", "../../files/src/handlers/streamHandler.ts", "../../files/src/handlers/claimCheckHandler.ts", "../../files/src/sanitizeLogData.ts", "../../callbacks/src/handler.ts", "../../transformer/src/errors.ts", "../../transformer/src/guards.ts", "../../transformer/src/walk.ts", "../../transformer/src/transform.ts", "../src/surfaceHandler.ts", "../src/transformer.ts", "../src/boundary.ts", "../src/helpers.ts", "../src/uiWatch.ts", "../src/ui.ts", "../src/utils.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"
|
|
5
|
+
"module.exports=function(t,e,l,n,o){for(e=e.split?e.split(\".\"):e,n=0;n<e.length;n++)t=t?t[e[n]]:o;return t===o?l:t};\n//# sourceMappingURL=dlv.js.map\n",
|
|
6
|
+
"import fs from 'node:fs'\nimport type { ConnectionOptions as TlsConnectionOptions } from 'node:tls'\n\nimport { deobfuscate } from '@requence/helpers'\nimport logger from '@requence/logger/simple'\nimport type { AmqpConnectionManagerOptions } from 'amqp-connection-manager'\n\nimport createAmqpConnection, {\n type ConnectionApi,\n type ConnectionStateListener,\n type MessageHandler,\n connectionOptionsSchema,\n} from './createAmqpConnection.ts'\n\nexport { RequenceFile, RequenceStream } from '@requence/files'\nexport {\n createCallback,\n type RequenceCallback,\n type WrappedRequenceCallback,\n} from '@requence/helpers'\nexport * from './errors.ts'\n// Types only: the facade's components are declarations of a runtime the *host*\n// provides, so re-exporting them as values here would emit a runtime re-export\n// of bindings that do not exist. A component author reaches them through the\n// `@requence/service/surface-ui` subpath instead — see `surfaceUi.ts`.\nexport type {\n ButtonProps,\n CheckboxProps,\n SelectOption,\n SelectProps,\n StackProps,\n SurfaceSpace,\n TextFieldProps,\n TextProps,\n} from './surfaceUi.ts'\nexport * from './ui.ts'\nexport * from './utils.ts'\n\nexport {\n type ConnectionState,\n type ConnectionStateListener,\n MessageHandler,\n} from './createAmqpConnection.ts'\n// Undocumented — privileged consumers (the reserved requence-logic runtime)\n// cast their handler context to this; see helpers.ts.\nexport type { PrivilegedContext, PrivilegedSends } from './helpers.ts'\nexport type ServiceApi<\n V extends keyof RequenceService.Version | (string & {}),\n> = ConnectionApi<V>\n\ninterface ServiceOptions<V extends string> {\n accessToken?: string\n devToken?: string\n version: V\n /**\n * Optional, author-chosen label announced in the AMQP client properties and\n * shown in the Requence UI next to the online count — \"which of my three\n * deployments is this?\".\n *\n * A DEBUGGING LABEL, not an identifier: it is not unique, nothing keys off\n * it, and no behaviour depends on it. Capped at 64 characters (longer labels\n * are truncated, never rejected).\n */\n name?: string\n prefetch?: number\n connectionTimeout?: number\n /** heartbeat interval in seconds — defaults to 30 */\n heartbeatInterval?: number\n silent?: boolean\n connectionOptions?: AmqpConnectionManagerOptions['connectionOptions']\n /** Max serialized body size in bytes before a PayloadTooLargeError is thrown. */\n maxMessageSize?: number\n // Undocumented (privileged consumers): skip file/stream/callback\n // rehydration on ingress; claim-checks still resolve. See helpers.ts.\n passthroughByteReferences?: boolean\n /**\n * Notified whenever the underlying AMQP connection is lost or (re)established.\n * amqp-connection-manager auto-reconnects, so this is the only observable\n * signal of a mid-life outage — use it to drive liveness/health reporting.\n */\n onConnectionStateChange?: ConnectionStateListener\n}\n\n// TLS connection options overridable via the environment. These are a\n// fallback only: a value supplied in code through `connectionOptions` always\n// wins (see resolveConnectionOptions). `CA` carries inline PEM, `CA_FILE` a\n// path to a PEM file (inline wins when both are set); `REJECT_UNAUTHORIZED`\n// disables certificate verification when falsy (\"false\"/\"0\"/\"no\").\nfunction resolveConnectionOptions(\n connectionOptions: AmqpConnectionManagerOptions['connectionOptions'],\n): AmqpConnectionManagerOptions['connectionOptions'] {\n const rejectEnv = process.env.REJECT_UNAUTHORIZED\n const caEnv = process.env.CA\n const caFileEnv = process.env.CA_FILE\n\n const tlsDefaults: TlsConnectionOptions = {}\n if (rejectEnv !== undefined) {\n tlsDefaults.rejectUnauthorized = !/^(false|0|no)$/i.test(rejectEnv.trim())\n }\n if (caEnv) {\n tlsDefaults.ca = caEnv\n } else if (caFileEnv) {\n tlsDefaults.ca = fs.readFileSync(caFileEnv)\n }\n\n if (Object.keys(tlsDefaults).length === 0) {\n return connectionOptions\n }\n\n // Env defaults first, code-supplied options last → code overrides env.\n return { ...tlsDefaults, ...connectionOptions }\n}\n\nlet pkgJson: any | null\nfunction loadPkgJson() {\n if (!pkgJson) {\n pkgJson = JSON.parse(fs.readFileSync('package.json', 'utf-8'))\n }\n return pkgJson\n}\n\n// The dev-token warning is about the process, not about one version: a worker\n// serving several versions would otherwise repeat it once per createService().\nlet didWarnDevToken = false\n\nexport function createService<\n V extends keyof RequenceService.Version | (string & {}),\n>(version: V, messageHandler: MessageHandler<V>): ServiceApi<V>\nexport function createService<\n V extends keyof RequenceService.Version | (string & {}),\n>(options: ServiceOptions<V>, messageHandler: MessageHandler<V>): ServiceApi<V>\nexport function createService<\n V extends keyof RequenceService.Version | (string & {}),\n>(\n optionsOrVersion: ServiceOptions<V> | string,\n optionalMessageHandler?: MessageHandler<V>,\n) {\n let options: ServiceOptions<V>\n let messageHandler: MessageHandler<V>\n if (typeof optionsOrVersion === 'string') {\n options = {\n version: optionsOrVersion as V,\n }\n messageHandler = optionalMessageHandler as MessageHandler<V>\n } else {\n options = optionsOrVersion\n messageHandler = optionalMessageHandler as MessageHandler<V>\n }\n\n let token =\n options.accessToken ??\n process.env.REQUENCE_SERVICE_ACCESS_TOKEN ??\n process.env.REQUENCE_ACCESS_TOKEN\n\n if (!token) {\n try {\n const pkgJson = loadPkgJson()\n token =\n pkgJson.requence?.service?.accessToken ?? pkgJson.requence?.accessToken\n } catch {\n //\n }\n }\n\n let devToken =\n options.devToken ??\n process.env.REQUENCE_SERVICE_DEV_TOKEN ??\n process.env.REQUENCE_DEV_TOKEN\n\n if (!devToken) {\n try {\n const pkgJson = loadPkgJson()\n devToken =\n pkgJson.requence?.service?.devToken ?? pkgJson.requence?.devToken\n } catch {\n //\n }\n }\n\n if (!token) {\n throw new Error('no access token provided')\n }\n\n const parts = deobfuscate(token)\n\n if (parts.length < 2 || parts[0] !== 'service') {\n throw new Error('invalid access token')\n }\n const url = parts[1]\n let devOverlay: string | undefined\n\n if (devToken) {\n const devParts = deobfuscate(devToken)\n if (devParts[0] !== 'api') {\n throw new Error(\n 'invalid dev token: please provide a personal access token',\n )\n }\n if (devParts[2] !== parts[2]) {\n throw new Error(\n 'invalid dev token: access token and dev token belong to different requence instances',\n )\n }\n devOverlay = devParts[1]\n\n // A dev token is not a mode this process announces anywhere else: it\n // quietly moves the worker off the deployed version's queue and onto a\n // personal overlay queue that the broker deletes once the process stops.\n // Deployed with one set, the service looks healthy and serves nothing.\n if (!didWarnDevToken) {\n didWarnDevToken = true\n logger.warn(\n 'Requence: started with a |dev token| — this worker consumes a personal dev-overlay queue instead of the deployed version, and that queue is deleted shortly after the process stops. Do not deploy with one: unset |REQUENCE_DEV_TOKEN| / |REQUENCE_SERVICE_DEV_TOKEN|, or remove |requence.devToken| from package.json.',\n )\n }\n }\n\n const envMaxMessageSize = process.env.REQUENCE_MAX_MESSAGE_SIZE\n ? Number(process.env.REQUENCE_MAX_MESSAGE_SIZE)\n : undefined\n\n return createAmqpConnection<V>(\n {\n // The schema strips unknown keys (and cannot carry a function), so the\n // listener is merged onto the parsed options rather than passed through it.\n ...connectionOptionsSchema.parse({\n ...options,\n connectionOptions: resolveConnectionOptions(options.connectionOptions),\n maxMessageSize: options.maxMessageSize ?? envMaxMessageSize,\n url,\n devOverlay,\n }),\n onConnectionStateChange: options.onConnectionStateChange,\n },\n messageHandler,\n )\n}\n",
|
|
6
7
|
"import { z } from 'zod/v4'\n\nconst recordSchema = z.record(z.string(), z.unknown())\nexport function isRecord(data: unknown): data is Record<string, unknown> {\n return recordSchema.safeParse(data).success\n}\n\nconst uuidSchema = z.uuid()\nexport function isUuid(data: unknown): data is string {\n return uuidSchema.safeParse(data).success\n}\n",
|
|
7
8
|
"import { isRecord } from './guards.ts'\n\ntype DataVistor<T> = (\n data: T,\n path: Array<string | number>,\n) => Promise<any> | any\n\ninterface DataVistors {\n Null?: DataVistor<null>\n String?: DataVistor<string>\n Number?: DataVistor<number>\n Object?: DataVistor<object>\n Array?: DataVistor<Array<any>>\n Buffer?: DataVistor<Uint8Array>\n Function?: DataVistor<(...args: any[]) => any>\n Symbol?: DataVistor<symbol>\n}\n\ntype HasPromiseVistor<T extends DataVistors, Then, Else> = T[keyof T] extends (\n ...args: any[]\n) => any\n ? Promise<any> extends ReturnType<T[keyof T]>\n ? Then\n : Else\n : Else\n\nfunction resolve<T>(value: T | Promise<T>, onResolve: (value: T) => void) {\n if (value instanceof Promise) {\n return Promise.resolve()\n .then(() => value)\n .then(onResolve)\n }\n return onResolve(value)\n}\n\nfunction notUndefined(value: unknown, fallback: unknown) {\n return resolve(value, (resolvedValue) =>\n typeof resolvedValue === 'undefined' ? fallback : resolvedValue,\n )\n}\n\nclass AbortMapData extends Error {}\n\nexport function mapData<\n Output,\n Input = unknown,\n V extends DataVistors = DataVistors,\n>(\n data: Input,\n visitors: V,\n): HasPromiseVistor<\n V,\n Promise<unknown extends Output ? Input : Output>,\n unknown extends Output ? Input : Output\n> {\n let aborted = false\n const traverseData = (data: any, path: Array<string | number>): any => {\n if (aborted) {\n return data\n }\n try {\n if (Array.isArray(data)) {\n return resolve(visitors.Array?.(data, path), (resolvedData) => {\n if (resolvedData) {\n return resolvedData\n }\n const items = data.map((item, index) =>\n traverseData(item, [...path, index]),\n )\n if (items.some((item) => item instanceof Promise)) {\n return Promise.all(items)\n }\n\n return items\n })\n }\n if (data === null) {\n return notUndefined(visitors.Null?.(data, path), data)\n }\n const runtimeBuffer = (\n globalThis as { Buffer?: { isBuffer(obj: unknown): boolean } }\n ).Buffer\n if (runtimeBuffer?.isBuffer(data)) {\n return notUndefined(visitors.Buffer?.(data as Uint8Array, path), data)\n }\n if (typeof data === 'string') {\n return notUndefined(visitors.String?.(data, path), data)\n }\n if (typeof data === 'number') {\n return notUndefined(visitors.Number?.(data, path), data)\n }\n if (typeof data === 'symbol') {\n return notUndefined(visitors.Symbol?.(data, path), data)\n }\n if (typeof data === 'function') {\n return notUndefined(visitors.Function?.(data, path), data)\n }\n if (isRecord(data)) {\n return resolve(visitors.Object?.({ ...data }, path), (resolvedData) => {\n const nextData = resolvedData ?? data\n if (!isRecord(nextData)) {\n return nextData\n }\n const entries = Object.entries(nextData).map(([key, value]) => [\n key,\n traverseData(value, [...path, key]),\n ])\n\n if (entries.some(([, value]) => value instanceof Promise)) {\n return Promise.all(\n entries.map(([key, value]) =>\n Promise.resolve()\n .then(() => value)\n .then((resolvedValue) => [key, resolvedValue]),\n ),\n ).then((entries) => Object.fromEntries(entries))\n }\n\n return Object.fromEntries(entries)\n })\n }\n if (typeof data === 'object' && data) {\n return notUndefined(visitors.Object?.(data, path), data)\n }\n return data\n } catch (error) {\n if (error instanceof AbortMapData) {\n aborted = true\n return data\n }\n throw error\n }\n }\n\n return traverseData(data, [])\n}\n\nmapData.abort = () => {\n throw new AbortMapData()\n}\n",
|
|
8
9
|
"import { z } from 'zod/v4'\n\nconst fileObjectSchema = z.object({\n size: z.int().positive(),\n mime: z.string(),\n url: z.url(),\n __REQUENCE_type: z.literal('RequenceFile'),\n})\n\nexport type FileObject = z.infer<typeof fileObjectSchema>\n\nexport function toFileObject(fileInfo: {\n size: number\n mime: string\n url: string\n}): FileObject {\n return {\n ...fileInfo,\n __REQUENCE_type: 'RequenceFile',\n }\n}\n\nexport function isFileObject(data: unknown): data is FileObject {\n return fileObjectSchema.safeParse(data).success\n}\n",
|
|
9
10
|
"import { z } from 'zod/v4'\n\nconst streamObjectSchema = z.object({\n mime: z.string(),\n url: z.string().url(),\n __REQUENCE_type: z.literal('RequenceStream'),\n})\n\nexport type StreamObject = z.infer<typeof streamObjectSchema>\n\nexport function isStreamObject(data: unknown): data is StreamObject {\n return streamObjectSchema.safeParse(data).success\n}\n\nexport function toStreamObject(streamInfo: {\n mime: string\n url: string\n}): StreamObject {\n return {\n ...streamInfo,\n __REQUENCE_type: 'RequenceStream',\n }\n}\n",
|
|
10
11
|
"import { z } from 'zod/v4'\n\nconst claimCheckObjectSchema = z.object({\n url: z.url(),\n size: z.int().positive(),\n __REQUENCE_type: z.literal('ClaimCheck'),\n})\n\n/**\n * Reference left behind by the oversized-message claim-check: the value was\n * offloaded to the files service and is fetched back (and re-walked) on\n * ingress by the `ClaimCheck` value handler.\n */\nexport type ClaimCheckObject = z.infer<typeof claimCheckObjectSchema>\n\nexport function toClaimCheckObject(info: {\n url: string\n size: number\n}): ClaimCheckObject {\n return {\n ...info,\n __REQUENCE_type: 'ClaimCheck',\n }\n}\n\nexport function isClaimCheckObject(data: unknown): data is ClaimCheckObject {\n return claimCheckObjectSchema.safeParse(data).success\n}\n\n/**\n * JSON-schema equivalent of the reference shape, for claim-check-aware\n * validation: a subschema position holding a `ClaimCheck` reference is\n * validated against this instead of the declared subschema (shape validation\n * of the offloaded value is deferred to the consumer after rehydration).\n */\nexport const claimCheckJsonSchema = {\n type: 'object',\n properties: {\n url: { type: 'string' },\n size: { type: 'integer' },\n __REQUENCE_type: { const: 'ClaimCheck' },\n },\n required: ['url', 'size', '__REQUENCE_type'],\n} as const\n",
|
|
11
12
|
"import { z } from 'zod/v4'\n\nconst callbackObjectSchema = z.object({\n sourceId: z.string(),\n outputName: z.string().nullable(),\n propertyPath: z.array(z.union([z.string(), z.int()])),\n callbackId: z.uuid(),\n __REQUENCE_type: z.literal('RequenceCallback'),\n})\n\nexport type CallbackObject = z.infer<typeof callbackObjectSchema>\n\nexport function isCallbackObject(data: unknown): data is CallbackObject {\n return callbackObjectSchema.safeParse(data).success\n}\n\nexport type RequenceCallback<T> = (arg: T) => void\nexport type WrappedRequenceCallback<T> = RequenceCallback<T> & {\n response(): Promise<T>\n}\n\nexport function createCallback<T>(\n callback?: (arg: T) => void,\n): WrappedRequenceCallback<T> {\n const { promise, resolve } = Promise.withResolvers<T>()\n\n const executor = (arg: T) => {\n resolve(arg)\n callback?.(arg)\n }\n\n return Object.assign(executor, {\n response() {\n return promise\n },\n })\n}\n",
|
|
13
|
+
"import { z } from 'zod/v4'\n\n/**\n * The render payload a service publishes when a handler calls\n * `context.render(ui, props)` — the wire shape shared by the service SDK\n * (which composes it) and the operator (which parses it before emitting the\n * render as a task update). See `knowledge/service-ui-surfaces.md`.\n *\n * `component.source` travels only on the **first** render of a given hash into a\n * given task; later renders carry the hash alone, because ui/backend stores the\n * bundle hash-addressed and that row outlives every render. A hash arriving\n * without a source that ui/backend has never seen is an error state on the\n * surface, not a silent fallback (D16).\n *\n * Per task rather than per connection because bundle retention is per task\n * (D19): the last-referent sweep removes a bundle once no task references it, and\n * a connection can outlive every task that referenced its component.\n *\n * Every field is deliberately a *top-level* key, because that is the granularity\n * the size-triggered claim-check works at: it offloads a record body's largest\n * top-level values first, and the publisher pins every one of these inline except\n * `props`. So an oversized render always offloads `props` — the one value whose\n * loss is a named error state rather than a broken surface. The source is capped\n * at {@link MAX_UI_SOURCE_BYTES} anyway, well under the offload threshold, so the\n * bundle always travels inline (D4).\n */\nexport const serviceRenderSchema = z.object({\n component: z.object({\n /**\n * The component's stable id (#103) — what a durable handler reference names,\n * and since #108 what a dev-loop bundle swap addresses.\n *\n * Recorded on the surface row, because the hash cannot serve as the\n * component's identity there either: a rebuild is precisely the event that\n * changes it, so a swap has to find the surfaces by the one field it leaves\n * alone.\n */\n id: z.string(),\n hash: z.string(),\n source: z.string().nullable().default(null),\n }),\n props: z.unknown(),\n /**\n * The UI's default props as `createUI(url, defaults)` recorded them — restated\n * on every render of that component, and folded UNDER the surface's stored\n * props at ingestion (#102).\n *\n * A separate field rather than merged into `props` by the SDK, which is what\n * the first cut did (#101), because the two are ranked differently and only\n * the receiver can rank them: a default is the weakest layer, overridden by\n * anything any render of this surface ever said, while `props` is the strongest\n * — the statement this render is making now. Merged before publishing, a\n * default would arrive indistinguishable from a fresh prop and would clobber an\n * override an earlier render made, on every render that stayed silent about it.\n *\n * Travels on EVERY render, not only the source-carrying one: the surface row\n * is last-write-wins and holds no memory of the UI itself, so a render that\n * omitted them would fold against nothing. They pass through the outbound\n * boundary like any other props, so a function among them becomes a callback of\n * whichever message published the render.\n *\n * Optional, unlike `props`: a component that declared none sends the key not\n * at all, so the fold reads \"no base layer\" rather than \"an empty one\".\n */\n defaults: z.unknown().optional(),\n surfaceId: z.string(),\n /**\n * The dev session that drew this surface (#108), or `null` for every render a\n * deployed service makes — which is all of them outside a dev overlay.\n *\n * Recorded on the surface row so a rebuild can repoint exactly the surfaces of\n * the session that produced it, and no others: a developer's edit must not\n * reach into a production surface of the same component. Opaque, and stable\n * across a restart of the dev process — see `uiRebuild.ts`.\n */\n devSession: z.string().nullable().default(null),\n})\n\nexport type ServiceRender = z.infer<typeof serviceRenderSchema>\n\n/**\n * Hard cap on a UI component bundle, enforced when the component is registered\n * (D4). Fits a self-contained React component, stays storable inline in\n * Postgres, and fails fast on an accidental whole-app bundle.\n */\nexport const MAX_UI_SOURCE_BYTES = 1024 * 1024\n\n/**\n * The surface a render targets when it names none (D3). A node's surfaces are\n * keyed by this id, so the default is a single surface per node/trace.\n */\nexport const DEFAULT_SURFACE_ID = 'default'\n\n/**\n * Hard cap on one value a browser sends into a surface — a callback\n * invocation's argument, or a deferred form's submitted response — enforced in\n * ui/backend before either is published (D7).\n *\n * One number for both because they are the same thing arriving by two routes:\n * viewer-authored bytes that reach service code, bounded before they enter the\n * fabric. A response additionally has to fit the node's own output, which the\n * operator enforces on the way in as it does for any service result.\n *\n * An interaction is exactly that — a click, a form submit, an approval — not\n * a data transfer, and unlike a service's own publishes it crosses no outbound\n * boundary: nothing offloads it, so its bytes reach the broker as they are. The\n * cap is what keeps that true, and it is deliberately far below any message\n * limit rather than tuned to one, so a task's `maxPayloadSize` can never make\n * the difference between a usable synchronous rejection and a dropped AMQP\n * connection.\n *\n * Lives here, next to {@link MAX_UI_SOURCE_BYTES}, rather than inside ui/backend:\n * the browser is the other party that has to respect it, and when the surface\n * host starts refusing an oversized argument before the round trip it should\n * read the number from where the server enforces it, not restate it.\n */\nexport const MAX_SURFACE_INTERACTION_BYTES = 64 * 1024\n",
|
|
14
|
+
"import { z } from 'zod/v4'\n\n/**\n * The reference tag of a **surface handler** — a function a service put in a\n * surface's props, which a viewer's interaction runs back in the service that\n * issued the render (#103).\n *\n * Deliberately not a `RequenceCallback`, even though the connection-bound arm\n * is routed the same way today. The two answer different questions and address\n * different things: a callback reference is a peer-to-peer control-flow handle\n * whose `outputName`/`propertyPath` address a position in the node's declared\n * *output schema*, while a handler reference addresses a **prop of a UI**, has\n * no output behind it, and — in its durable arm — names no connection at all.\n * Merging them would put a lifetime on every callback in the fabric and make a\n * durable reference look like something the operator should route by `sourceId`.\n */\nexport const SURFACE_HANDLER_TAG = 'RequenceHandler'\n\nconst handlerPathSchema = z.array(z.union([z.string(), z.int()]))\n\n/**\n * How long a handler can be reached, decided by **where the function was\n * written** — which is the only thing that actually bounds the closure's life:\n *\n * - `durable` — a function in the UI's default props. It closes over module\n * scope, so *any* instance of the service version can run it, now or after a\n * redeploy, and an invocation waits in the version's handler queue when none\n * is running. Addressed by `(uiId, path)`, because that pair is what survives\n * a rebuild and a restart; the component's content hash does not.\n * - `connection` — a function written inline at `context.render(...)`. It closes\n * over the running handler, so only that process can serve it and it dies when\n * the handler returns. Addressed by the registering connection plus an id in\n * its registry, exactly as a callback is.\n *\n * `uiId`/`path` ride on both arms: the connection-bound arm does not need them\n * to be *routed*, but they are what says which prop of which component this\n * handle belongs to, which is what the row-level `live` flag could never say\n * (#106).\n */\nexport const surfaceHandlerObjectSchema = z.discriminatedUnion('lifetime', [\n z.object({\n __REQUENCE_type: z.literal(SURFACE_HANDLER_TAG),\n lifetime: z.literal('durable'),\n uiId: z.string(),\n path: handlerPathSchema,\n }),\n z.object({\n __REQUENCE_type: z.literal(SURFACE_HANDLER_TAG),\n lifetime: z.literal('connection'),\n uiId: z.string(),\n path: handlerPathSchema,\n /** The connection that registered it; delivery routes by this. */\n connectionId: z.string(),\n /** Its id in that connection's registry. */\n handlerId: z.uuid(),\n }),\n])\n\nexport type SurfaceHandlerObject = z.infer<typeof surfaceHandlerObjectSchema>\nexport type SurfaceHandlerLifetime = SurfaceHandlerObject['lifetime']\n\nexport function isSurfaceHandlerObject(\n data: unknown,\n): data is SurfaceHandlerObject {\n return surfaceHandlerObjectSchema.safeParse(data).success\n}\n\n/**\n * The per-version **handler queue**: where a durable invocation waits until\n * some instance of that service version consumes it.\n *\n * Derived from the version's dispatch queue rather than composed from the\n * service and version names, so the two can never drift and a dev-overlay\n * connection — which consumes a rewritten dispatch queue — gets a handler queue\n * of its own for free.\n */\nexport function serviceHandlerQueueName(dispatchQueue: string): string {\n return `${dispatchQueue}-handlers`\n}\n\n/**\n * How long a durable invocation may wait in the handler queue before the broker\n * drops it (#116).\n *\n * The queue is **not a mailbox**. Reachability is checked before the click — a\n * version with no consumers reports `reachable: false` and the control is\n * withheld — so all this has to bridge is the seconds between that check and the\n * consume: a rolling redeploy, a scale-to-zero that started a moment ago, a\n * replica that took the invocation and died. Long enough that a normal restart\n * still serves the click, short enough that nobody is surprised by an effect\n * they pressed for hours ago.\n *\n * That is the half the flag cannot do on its own: the flag only makes the click\n * harder to fire, and a click that IS fired into an empty queue must expire and\n * be *reported* rather than sit there waiting for whoever deploys next.\n *\n * Expiry is not a drop: the queue dead-letters to `error`, so an expired\n * invocation comes back to the operator carrying its own `taskId` and surface\n * row, and is recorded as an `interactionError` (#107).\n */\nexport const SURFACE_HANDLER_INVOCATION_TTL_MS = 60_000\n\n/**\n * The handler queue's declaration arguments, as **one** object, because two\n * parties declare that queue — ui/backend's provisioner and the service SDK on\n * connect — and a broker answers a mismatch with a 406 that kills the declaring\n * channel. Anything short of a shared literal is a service that will not start.\n *\n * `deadLetterExchange` is what turns expiry into a *report*: `error` fans back\n * into the operator's own shard family, so an expired invocation arrives at the\n * error consumer still carrying its `taskId`, its surface row and its\n * `surfaceHandlerInvocation` marker. Without it the broker would simply drop the\n * message, which is the silent outcome #116 replaced.\n *\n * Note for whoever changes this: declaring a queue with a dead-letter exchange\n * needs WRITE permission on that exchange, so the service AMQP user is granted\n * it (`assertService`). It costs nothing — `error` is an internal exchange and\n * the broker refuses a client publish to one however the permissions read.\n */\nexport const SURFACE_HANDLER_QUEUE_ARGUMENTS = {\n messageTtl: SURFACE_HANDLER_INVOCATION_TTL_MS,\n deadLetterExchange: 'error',\n} as const\n\n/**\n * Whether a handler queue belongs to a **dev overlay** rather than to a deployed\n * service version — which decides what a failed interaction is allowed to say.\n *\n * A developer's overlay queue expires ~5s after the process disconnects\n * (`dev-overlay-auto-delete`), so an invocation into it is unroutable exactly as\n * one into a deleted version is, and the two are indistinguishable by outcome.\n * They are not the same event: telling an author their *service version is no\n * longer deployed* when they simply stopped `bun run dev` sends them looking at\n * the deployment (#116).\n *\n * Mirrors the `dev-overlay-auto-delete` policy's own pattern — the 32-character\n * key segment stays `.{32}`, because dev keys are access-token values and\n * contain non-word characters.\n */\nconst DEV_OVERLAY_HANDLER_QUEUE = /-dev-overlay-.{32}-handlers$/\n\nexport function isDevOverlayHandlerQueue(queueName: string): boolean {\n return DEV_OVERLAY_HANDLER_QUEUE.test(queueName)\n}\n\n/**\n * The header a durable invocation is stamped with, so the party that has to\n * answer an **unroutable** one can tell it from a dispatch (#104).\n *\n * A durable invocation is published `mandatory` into the `service` exchange, so\n * one whose queue is gone comes back to the operator looking like any other\n * undeliverable service message — and every other arm there fails the task's\n * node, which a viewer's click must never do.\n *\n * A header rather than the routing key's `-handlers` suffix, which is *nearly*\n * unambiguous and therefore worse: a version named `…-handlers` gives a dispatch\n * queue that ends the same way, and the failure that buys is a real service\n * dispatch silently swallowed instead of failing its node. This is exact, and it\n * is set by the only publisher there is.\n */\nexport const SURFACE_HANDLER_INVOCATION_HEADER = 'surfaceHandlerInvocation'\n\n/**\n * One durable handler invocation, as it travels on the queue above.\n *\n * The pair `(uiId, path)` is the whole address: the consuming instance looks the\n * UI up in its own registry and resolves the path against that UI's default\n * props. `taskId` is not part of the address — it is what makes the failure of\n * an invocation that names nothing say *which run* it belonged to.\n */\nexport const surfaceHandlerInvocationSchema = z.object({\n taskId: z.uuid(),\n /**\n * The **surface row** this interaction came from (#107) — `task_surface.id`,\n * not the author's `surfaceId`, which under-keys the (task, node, trace,\n * surface) state.\n *\n * Carried for one reason: it is the only way back. A failing invocation has no\n * request left to fail — the mutation returned *accepted* long before, possibly\n * to a viewer who has since closed the page — so the failure is recorded on the\n * surface itself, and the row is what names it. Nothing about the *delivery*\n * needs it, which is why it sits beside the address rather than in it.\n */\n surface: z.uuid(),\n uiId: z.string(),\n path: handlerPathSchema,\n /**\n * `.optional()` because an invocation with no argument is ordinary — a handler\n * may take none — and this rides a JSON queue, where `JSON.stringify` DELETES\n * an `undefined` value instead of encoding one. Under zod 4 an `unknown` field\n * is not optional by itself, so the key's absence would fail the parse and the\n * click would be dropped with only a line in the consuming instance's stderr.\n * The publisher normalises to `null`; this covers one that has not been rolled\n * forward.\n */\n arg: z.unknown().optional(),\n})\n\nexport type SurfaceHandlerInvocation = z.infer<\n typeof surfaceHandlerInvocationSchema\n>\n\n/**\n * How long a recorded interaction failure may be (#107).\n *\n * A thrown error's message is author-supplied text of no bounded length, and it\n * ends up on a row that is pushed to every viewer of the task on every render.\n * Truncated rather than rejected: a long message is still the most useful thing\n * anyone has about the failure, and its first characters are where the cause is.\n */\nexport const MAX_SURFACE_INTERACTION_ERROR_CHARS = 500\n\n/**\n * The header a **surface interaction failure report** is stamped with (#107), so\n * the operator can tell it from an ordinary service result.\n *\n * A report carries no message id and no index: the handler that failed was not\n * running for any message of the operator's — that is the whole of what makes a\n * durable handler durable — so it cannot ride the ordered dispatch buffer, and\n * every other arm of the result path would fail the node the surface is painted\n * on. It names a task, a surface row and what went wrong, and the operator\n * forwards it as a task update.\n */\nexport const SURFACE_INTERACTION_ERROR_HEADER = 'surfaceInteractionError'\n\n/**\n * One interaction failure, as a service reports it back to the operator (#107).\n *\n * The failing party writes the sentence: only it knows whether the component was\n * unregistered, the prop held nothing invokable, or the handler threw — and only\n * it can quote the error. The operator forwards the text verbatim; ui/backend\n * masks it and stores it on the row.\n */\nexport const surfaceInteractionErrorReportSchema = z.object({\n surface: z.uuid(),\n message: z.string(),\n})\n\nexport type SurfaceInteractionErrorReport = z.infer<\n typeof surfaceInteractionErrorReportSchema\n>\n",
|
|
15
|
+
"import { z } from 'zod/v4'\n\n/**\n * Marks a service message as a **dev-loop bundle swap** (#108) rather than a\n * result for one of the operator's dispatches.\n *\n * A rebuild changes which bytes the frame imports and nothing else — not the\n * props, not the handlers, not the node — so it is deliberately not a render. A\n * render would need the registering message to be unsettled and its registry\n * alive, which is what took the dev loop away from a deferred form: the handler\n * that drew it returned at the defer, so there is nothing left to re-render\n * through. A swap needs none of that, and so works identically for a live panel,\n * a deferred form, and a surface on a task that has already finished.\n *\n * Read on the same path as a result, and answered before it — like\n * `SURFACE_INTERACTION_ERROR_HEADER`, this message has no correlation id, no\n * index and no place in the ordered dispatch buffer, because it belongs to no\n * message of the operator's.\n */\nexport const UI_REBUILD_HEADER = 'uiRebuild'\n\n/**\n * What a rebuild says: *this component of this dev session is now these bytes*.\n *\n * `devSession` is opaque here and produced by the service SDK, which is the only\n * party that can: it is the one identity that survives the process being\n * restarted (a dev token plus the service version it is overlaying), so the\n * surfaces a session drew before a restart are still the same session's\n * afterwards. It deliberately carries no dev token in the clear — the token is\n * hashed into it — because it comes to rest in `task_surface`.\n *\n * `uiId` is the component's stable id (#103), which is what makes the swap\n * addressable at all: the hash is the thing that changed, so it cannot be the\n * thing looked up. A surface repoints when it belongs to this session AND shows\n * this component, whatever hash it is currently on — which is why a swap reaches\n * a surface that has sat through several rebuilds unseen.\n *\n * `source` always travels. The render payload's per-task dedup does not apply: a\n * swap is the first anyone has heard of this hash, and the surfaces it repoints\n * are precisely the ones that would otherwise be left naming a bundle nobody\n * stored.\n */\nexport const uiRebuildSchema = z.object({\n devSession: z.string(),\n uiId: z.string(),\n hash: z.string(),\n source: z.string(),\n})\n\nexport type UiRebuild = z.infer<typeof uiRebuildSchema>\n",
|
|
16
|
+
"import dlv from 'dlv'\nimport { dset } from 'dset'\n\nexport function setByPath<T extends Record<string, unknown>, U = T>(\n obj: T,\n keys: string | ArrayLike<string | number>,\n value: unknown,\n) {\n const clonedObj = structuredClone(obj)\n dset(clonedObj, keys, value)\n return clonedObj as unknown as U\n}\n\nexport const getByPath = dlv\n",
|
|
12
17
|
"// The negotiated AMQP heartbeat is the CLIENT's choice: the broker sets no\n// `heartbeat` in `deploy/swarm/rabbitmq/rabbitmq.conf`, so its own 60s default\n// is only a ceiling. `amqp-connection-manager` defaults to 5s, which makes any\n// event-loop stall longer than 10s (two missed intervals) fatal to every\n// connection in the deployment at once — that is what dropped eight connections\n// simultaneously in the 2026-07-30 incident.\n//\n// 30s tolerates ~60s of stall: longer than any GC/IO pause that does not already\n// mean the process is dead, short enough that a genuinely wedged client is still\n// reaped.\nexport const DEFAULT_AMQP_HEARTBEAT_SECONDS = 30\n\n// Sets the heartbeat as a URL query parameter, which is the one mechanism every\n// client understands: plain `amqplib` reads it during negotiation, and\n// `amqp-connection-manager` appends its own 5s default only when the param is\n// absent (`dist/cjs/AmqpConnectionManager.js`), so this wins there too.\n//\n// Non-destructive by design — an explicit `?heartbeat=` in the configured URL\n// always wins, and the input URL is never mutated.\nexport function withAmqpHeartbeat(url: URL): URL {\n const next = new URL(url.toString())\n if (!next.searchParams.has('heartbeat')) {\n next.searchParams.set('heartbeat', String(DEFAULT_AMQP_HEARTBEAT_SECONDS))\n }\n return next\n}\n",
|
|
13
|
-
"import { Buffer } from 'node:buffer'\n\nimport { Packr, addExtension } from 'msgpackr'\n\n/**\n * THE SHARED MSGPACK LAYER.\n *\n * Three things live here, and only these three:\n *\n * 1. `MSGPACK_EXTENSION_IDS` — the ONE allocation table for msgpack extension\n * type ids used anywhere in this repo.\n * 2. `packCommand` / `unpackCommand` — the AMQP task-command codec, shared by its\n * two parties: `@requence/task-builder` publishes, `@requence/operator`\n * consumes.\n * 3. `packWire` / `unpackWire` / `wireByteLength` — the high-volume AMQP wire\n * codec (service dispatch, service results, task updates). Its parties span\n * two languages, so unlike (2) it is a deliberately narrow, portable subset.\n *\n * It is its own subpath export (`@requence/helpers/msgpack`) so the msgpackr\n * dependency reaches only the packages that actually encode. Twelve packages\n * depend on `@requence/helpers`; most of them do not touch either codec and must\n * not carry a msgpack library into their bundle.\n *\n * Both codecs live in ONE module because `addExtension` is process-global (see\n * `MSGPACK_EXTENSION_IDS`). Splitting them would put the allocation table out of\n * sight of one of its two users, which is exactly the failure the table exists\n * to prevent.\n */\n\n/**\n * Extension type ids, allocated ONCE for the whole repo.\n *\n * **`addExtension` is process-global, not per-`Packr`.** Every instance in a\n * process shares one registry, so two codecs that pick the same id do not get two\n * namespaces — the second registration WINS and the first class silently decodes\n * as the second one. No error, no warning: a `NodeTree` comes back as a\n * `ReferenceCounter` and fails much later, somewhere unrelated. That is why the\n * numbers live in one table instead of next to each `addExtension` call.\n *\n * Ids 1 and 2 are also part of the stored Redis snapshot format, so renumbering\n * either one invalidates every live snapshot (a fleet-wide loud discard and\n * restart — there is no migration path, per the repo no-legacy-support policy).\n * Treat all of these as frozen; allocate a NEW number for anything new.\n */\nexport const MSGPACK_EXTENSION_IDS = {\n /** `@requence/operator`'s `ReferenceCounter` — snapshot path only. */\n referenceCounter: 1,\n /** `NodeTree` — snapshot path only; a command carries a `treeList`. */\n nodeTree: 2,\n /**\n * `URL` — registered below, because BOTH paths need it, and they need OPPOSITE\n * behaviour. See the registration for how one id serves both.\n */\n url: 3,\n} as const\n\n/**\n * Set for the duration of a `packWire` call, so the process-global `URL` extension\n * below can tell which codec is asking. `pack` is synchronous, so this cannot\n * interleave with another encode.\n *\n * Declared above the registration because `addExtension` reads `type` immediately.\n */\nlet packingForWire = false\n\n// THIS EXTENSION BELONGS TO THE SNAPSHOT AND COMMAND CODECS, NOT TO THE WIRE CODEC.\n// It exists because those two replaced superjson, which carried a `URL`;\n// structured-clone mode does not, so without this a `URL` in task input silently\n// becomes a string in transit — the same defect the `Date` handling prevents.\n//\n// The wire codec replaced `JSON.stringify`, which HAS no concept of a `URL` and\n// renders one as its href string. So it wants the opposite answer — and it cannot\n// simply decline this extension, because `addExtension` writes into module-level\n// arrays that every `Packr` in the process reads. There is no per-instance registry.\n//\n// Hence the getter, which is the wire codec's ONLY intrusion here. msgpackr's two\n// halves read `type` differently, and that is what lets one registration serve both:\n//\n// - `pack` reads it on EVERY call — `if (extension.type)` decides whether the ext\n// tag is written. `undefined` skips the tag, so `write`'s return value is encoded\n// as an ordinary string: exactly `JSON.stringify`'s output, with no pre-pack walk.\n// - `unpack` reads it ONCE, at registration (`currentExtensions[type] = …`), so the\n// decoder always knows id 3 and a command still round-trips to a real `URL`.\n//\n// Nothing about the snapshot or command format changes. `index.spec.ts` pins that:\n// a command still emits `d40300` and decodes to a `URL`, `packWire` never latches the\n// flag, and no ext tag reaches the wire — so a msgpackr release that started caching\n// `type` fails there rather than shipping undecodable bytes to a Python service.\naddExtension({\n Class: URL,\n get type() {\n return packingForWire ? undefined : MSGPACK_EXTENSION_IDS.url\n },\n write: (v: URL) => v.href,\n read: (href: string) => new URL(href),\n} as Parameters<typeof addExtension>[0])\n\n// `structuredClone: true` carries `Map`, `Set`, `Date`, `RegExp`, `Error`,\n// `BigInt`, typed arrays and `undefined` in the format itself, so there is no\n// annotation pass — which is the whole reason this beats superjson. `Map`\n// insertion order survives.\n//\n// Known and accepted difference from superjson: msgpack has no signed zero, so\n// `-0` arrives as `0`. No extension can fix it — the format has one zero.\nconst packr = new Packr({ structuredClone: true })\n\n/**\n * Encodes a task command (`CREATE` / `ABORT`) for the AMQP command queue.\n *\n * **Both parties must agree, and there is no negotiation on this queue.** A\n * command encoded by one codec and read by another does not degrade — it fails to\n * parse, and `consumers/tasks.ts` terminally fails that task. So a deploy that\n * changes this format has to move `task-builder` and the operator together;\n * anything in flight across the cutover is lost. That is the repo's\n * no-legacy-support policy applied deliberately: no dual-read, no format sniffing,\n * no version byte.\n */\nexport function packCommand(value: unknown) {\n return packr.pack(value)\n}\n\n/**\n * Decodes a task command off the AMQP command queue.\n *\n * Throws on anything that is not this codec's output — including a\n * superjson-shaped command from a pre-msgpack build, whose leading `{` decodes as\n * a positive fixint and whose trailing JSON text trips msgpack's end-of-buffer\n * check. The caller turns that into a terminal task failure; see `packCommand`\n * on why there is no fallback path.\n */\nexport function unpackCommand<T = unknown>(buffer: Buffer) {\n return packr.unpack(buffer) as T\n}\n\n/**\n * THE HIGH-VOLUME WIRE CODEC — a drop-in replacement for `JSON.stringify` /\n * `JSON.parse` on the three hot AMQP wires (service dispatch, service results,\n * task updates).\n *\n * **It is a codec swap, not a richer data model.** These wires are a\n * cross-language contract (TS service SDK, Python service SDK, `task-builder`),\n * so the format is a portable msgpack subset that any language's msgpack library\n * decodes — NOT the msgpackr dialect `packCommand` uses. Concretely:\n *\n * - `useRecords: false` — record structures are a msgpackr extension. They are\n * the single largest size win on the wide uniform arrays ETL moves (measured\n * -53% vs -17% without), and giving them up is the price of Python being able\n * to read the bytes at all.\n * - `structuredClone: false` — no reference/cycle extension, and no ext-type-0\n * `undefined`.\n * - `encodeUndefinedAsNil` — msgpackr's default `undefined` is ext type 0, which\n * is msgpackr-only. See `packWire` on why nil is still not free.\n * - `mapAsEmptyObject` / `setAsEmptyObject` — `JSON.stringify` renders a `Map` and\n * a `Set` as `{}`; without these msgpack would encode their contents and\n * silently start carrying data the JSON wire never did.\n * - `int64AsType: 'number'` — JSON has one number type, so a 64-bit integer from\n * the Python side must arrive as a `number`, not a `bigint`.\n *\n * A `URL` degrades to its href string, exactly as `JSON.stringify` does — see the\n * `URL` extension above for how it declines its own ext tag on this path.\n */\nconst wirePackr = new Packr({\n useRecords: false,\n structuredClone: false,\n encodeUndefinedAsNil: true,\n mapAsEmptyObject: true,\n setAsEmptyObject: true,\n int64AsType: 'number',\n})\n\n/**\n * **THE CONTRACT: this wire carries the JSON data model, and nothing else.**\n *\n * It replaced `JSON.stringify`, so by construction every value that reaches it is\n * already JSON-representable — task input arrives as JSON over HTTP, a node's output\n * arrives back over this same wire, and the envelope fields the operator adds are\n * strings and numbers. Nothing here has to carry a class.\n *\n * That is what makes the encoding usable from any language: it emits only msgpack's\n * CORE types, so a decoder needs no extension registered and no configuration.\n * `index.spec.ts` enforces this structurally — it walks the emitted bytes and fails\n * on any `ext` marker, over the JSON data model, real dispatch bodies, update\n * envelopes and `__REQUENCE_type` references.\n *\n * Two things to know about the encoding itself:\n *\n * 1. **`undefined` in a record becomes `null` instead of vanishing.** JSON drops the\n * key; msgpack has no way to express \"absent\" for a key it is already writing.\n * This is the one difference that can break a receiver: a Zod `.optional()`\n * accepts an absent key and rejects `null`. Envelope objects assembled on the\n * encode side must therefore omit undefined keys rather than assign them —\n * `omitUndefined` below is the shared way to do it. Values that came through JSON\n * cannot contain `undefined`, so only envelopes need the treatment.\n * 2. **`Uint8Array` becomes msgpack `bin`.** `bin` is a core type, not an extension,\n * so this costs nothing in portability — and it is the one place the wire is\n * denser than the JSON it replaced, which had to base64 (a 1.33x inflation).\n *\n * OUT OF CONTRACT, and deliberately not engineered around: `Date`, `RegExp`, `Error`\n * and any class registered via `addExtension` are not JSON, so they must not be put\n * on this wire. A `Date` in particular would emit msgpack's timestamp ext (-1) —\n * standard, but still an ext, which forfeits the \"decodes anywhere with no setup\"\n * guarantee above. The structural scan in the spec is what catches it if one ever\n * does slip in.\n */\nexport function packWire(value: unknown) {\n packingForWire = true\n try {\n return wirePackr.pack(value)\n } finally {\n packingForWire = false\n }\n}\n\n/** Decodes a body off one of the three high-volume wires. */\nexport function unpackWire<T = unknown>(buffer: Uint8Array) {\n return wirePackr.unpack(buffer) as T\n}\n\n/**\n * The encoded size of `value` under this codec, in bytes.\n *\n * The claim-check decides what to offload by measuring the serialized body, so\n * the codec and the size measurement are coupled: the invariant is **measured\n * size == published size**. A measurement taken with the wrong codec does not\n * fail loudly — it offloads too eagerly (a needless S3 round-trip on the hot\n * path) or too late (`PayloadTooLarge` at the broker). This is the only sanctioned\n * way to measure a body destined for this codec.\n */\nexport function wireByteLength(value: unknown) {\n return wirePackr.pack(value).length\n}\n\n/**\n * Drops keys whose value is `undefined`, so a record survives `packWire`\n * byte-equivalently to `JSON.stringify`.\n *\n * Needed only for envelope objects assembled right at an encode site (a dispatch\n * body's `options`, an update's optional fields): those are the only places an\n * `undefined` can still be present, per divergence (1) on `packWire`.\n */\nexport function omitUndefined<T extends Record<string, unknown>>(value: T): T {\n const out: Record<string, unknown> = {}\n for (const key of Object.keys(value)) {\n if (value[key] !== undefined) {\n out[key] = value[key]\n }\n }\n return out as T\n}\n\n/**\n * Which codec a body on one of the three high-volume wires is encoded with.\n *\n * `json` is the floor and never goes away: it is what an SDK that has not claimed\n * the `wire:msgpack1` capability speaks, and what every task keeps until it is\n * recreated. A rolling deploy therefore has both live at once, by design.\n */\nexport type WireCodec = 'json' | 'msgpack'\n\nexport const WIRE_CONTENT_TYPES = {\n json: 'application/json',\n msgpack: 'application/msgpack',\n} as const satisfies Record<WireCodec, string>\n\n/**\n * Maps an AMQP `content-type` to the codec that wrote the body.\n *\n * **Every decoder on these wires must go through here rather than assume.** An\n * absent or unrecognised content type is treated as `json`: that is the status\n * quo for anything published before this codec existed, and for any hop that\n * forwards a body without restating the header.\n */\nexport function wireCodecFromContentType(\n contentType: string | undefined,\n): WireCodec {\n return contentType === WIRE_CONTENT_TYPES.msgpack ? 'msgpack' : 'json'\n}\n\n/** Encodes a body for one of the three high-volume wires, with its content type. */\nexport function encodeWireBody(value: unknown, codec: WireCodec) {\n return {\n body:\n codec === 'msgpack'\n ? packWire(value)\n : Buffer.from(JSON.stringify(value ?? null)),\n contentType: WIRE_CONTENT_TYPES[codec],\n }\n}\n\n/**\n * Decodes a body off one of the three high-volume wires, switching on the codec\n * the publisher declared.\n *\n * This is what makes the migration rolling instead of a synchronised cutover: a\n * message already in flight when a deploy lands decodes under whichever codec\n * wrote it, so no queue has to be drained.\n */\nexport function decodeWireBody<T = unknown>(\n content: Uint8Array,\n contentType: string | undefined,\n): T {\n return wireCodecFromContentType(contentType) === 'msgpack'\n ? unpackWire<T>(content)\n : (JSON.parse(Buffer.from(content).toString()) as T)\n}\n\n/**\n * The encoded size of `value` under `codec`, in bytes — the claim-check's sizer.\n *\n * Both codecs are live at once (the choice is baked per service node), so the\n * threshold has to be measured with whichever codec this particular dispatch\n * uses. See `wireByteLength` on why a drifting measurement fails quietly.\n */\nexport function wireBodyByteLength(value: unknown, codec: WireCodec) {\n if (codec === 'msgpack') {\n return wireByteLength(value)\n }\n const json = JSON.stringify(value)\n return json === undefined ? 0 : Buffer.byteLength(json)\n}\n",
|
|
14
|
-
"import type { CallbackIngressContext } from '@requence/callbacks'\nimport {\n DEFAULT_AMQP_HEARTBEAT_SECONDS,\n type MaybePromise,\n deobfuscate,\n obfuscate,\n} from '@requence/helpers'\nimport type { WireCodec } from '@requence/helpers/msgpack'\nimport {\n decodeWireBody,\n encodeWireBody,\n wireCodecFromContentType,\n} from '@requence/helpers/msgpack'\nimport {\n CAPABILITY_HEADER_KEYS,\n buildServiceClientProperties,\n buildServiceIdentityHeaders,\n readRequiredCapabilities,\n unsupportedCapabilities,\n} from '@requence/helpers/protocol'\nimport { type Options, connect } from 'amqp-connection-manager'\nimport type { ConfirmChannel, ConsumeMessage } from 'amqplib'\nimport { z } from 'zod/v4'\n\nimport {\n type OutboundBoundary,\n createInboundBoundary,\n createOutboundBoundary,\n} from './boundary.ts'\nimport {\n PayloadTooLargeError,\n RequenceConnectionError,\n UnsupportedCapabilityError,\n} from './errors.ts'\nimport createContextHelper, {\n AbortError,\n type ContextHelper,\n type JSONValue,\n RetryError,\n SkipError,\n handlerStorage,\n unwrapOutputValue,\n} from './helpers.ts'\nimport { libVersion } from './macro.ts' with { type: 'macro' }\nimport { passthroughInboundTransformer } from './transformer.ts'\n\ntype InternalNamedOutput = '__internal_named_output__'\n\ntype Input<V extends keyof RequenceService.Version> =\n RequenceService.Version[V]['input']\ntype Configuration<V extends keyof RequenceService.Version> =\n RequenceService.Version[V]['configuration']\ntype OutputName<\n V extends keyof RequenceService.Version,\n K = keyof RequenceService.Version[V]['outputs'],\n> = K extends '__default__' ? null : K\n\ntype OutputValue<\n V extends keyof RequenceService.Version,\n O extends OutputName<V>,\n ON = O extends null ? '__default__' : O,\n> = ON extends keyof RequenceService.Version[V]['outputs']\n ? RequenceService.Version[V]['outputs'][ON]\n : never\n\ninterface ServiceContextHelper<\n V extends keyof RequenceService.Version,\n> extends Omit<\n ContextHelper,\n 'input' | 'configuration' | 'getData' | 'getConfiguration' | 'toOutput'\n> {\n input: Input<V>\n configuration: Configuration<V>\n\n toOutput<O extends OutputName<V>>(\n name: O,\n value: OutputValue<V, O>,\n ): InternalNamedOutput\n}\n\ntype ApiOutputName<V> = V extends keyof RequenceService.Version\n ? OutputName<V>\n : string | null\ntype ApiOutputValue<V, O> = V extends keyof RequenceService.Version\n ? O extends OutputName<V>\n ? OutputValue<V, O>\n : unknown\n : unknown\n\ninterface ActorApi<V> {\n sendToOutput<O extends ApiOutputName<V>>(\n outputName: O,\n data: ApiOutputValue<V, O>,\n options?: { overwrite?: boolean },\n ): void\n send(data: ApiOutputValue<V, null>, options?: { overwrite?: boolean }): void\n // Publishes a state writeback (`state: true` header). The operator honors\n // it only for privileged nodes; ordinary services' state messages are\n // ignored there.\n sendState(state: unknown): void\n abort(error: string | Error): void\n}\n\nexport interface ConnectionApi<V> {\n close(): Promise<void>\n open(): Promise<ConnectionApi<V>>\n act(\n messageKey: string,\n actor: (\n api: ActorApi<V>,\n ) =>\n | ApiOutputValue<V, null>\n | Promise<ApiOutputValue<V, null>>\n | void\n | Promise<void>\n | AsyncGenerator<ApiOutputValue<V, null>>\n | Generator<ApiOutputValue<V, null>>,\n ): Promise<void>\n}\n\nexport const messageKeySchema = z\n .string()\n .transform((str) => deobfuscate(str))\n .pipe(z.tuple([z.uuid(), z.uuid()]).rest(z.string()))\n .transform((arr) => ({\n taskId: arr[0],\n messageId: arr[1],\n uploadUrl: arr[2] || undefined,\n streamUrl: arr[3] || undefined,\n // Byte limits appended to the defer key alongside the transport URLs.\n // Old 4-part keys (pre-limits) parse with both absent → consumer defaults.\n maxPayloadSize:\n arr[4] && Number.isFinite(Number(arr[4])) ? Number(arr[4]) : undefined,\n maxFileSize:\n arr[5] && Number.isFinite(Number(arr[5])) ? Number(arr[5]) : undefined,\n }))\n\nconst headerSchema = z\n .object({\n properties: z.object({\n correlationId: z.uuid(),\n headers: z.object({\n taskId: z.uuid(),\n mode: z.enum(['LINEAR', 'CONTINUOUS']).default('LINEAR'),\n }),\n }),\n })\n .transform((msg) => ({\n messageId: msg.properties.correlationId,\n taskId: msg.properties.headers.taskId,\n mode: msg.properties.headers.mode,\n }))\n\nconst payloadSchema = z\n .object({\n content: z.instanceof(Buffer),\n properties: z.object({ contentType: z.string().optional() }),\n })\n // The dispatch codec is whatever the operator declared, never an assumption:\n // `ui/backend` bakes the choice per service node, so two nodes of one task can\n // legitimately arrive under different codecs, and a replica that has just been\n // rolled forward still receives JSON for tasks created before it attached.\n .transform((msg) => decodeWireBody(msg.content, msg.properties.contentType))\n .pipe(\n z.object({\n input: z.unknown(),\n configuration: z.unknown(),\n options: z.object({\n uploadUrl: z.url().optional(),\n streamUrl: z.url().optional(),\n maxPayloadSize: z.number().optional(),\n maxFileSize: z.number().optional(),\n }),\n }),\n )\n\nconst backchannelMessageSchema = z\n .object({\n content: z.instanceof(Buffer),\n properties: z.object({\n correlationId: z.string(),\n contentType: z.string().optional(),\n }),\n })\n // Header-driven like every other decoder on these wires. The backchannel itself\n // stays JSON — it is a low-volume control wire — but reading the header means it\n // is not the one consumer a later codec change has to remember to visit.\n .transform((message) => ({\n ...message,\n content: decodeWireBody(message.content, message.properties.contentType),\n }))\n .pipe(\n z.object({\n content: z.discriminatedUnion('type', [\n z.object({\n type: z.literal('stop'),\n }),\n z.object({\n type: z.literal('callback'),\n callbackId: z.uuid(),\n arg: z.any(),\n }),\n ]),\n properties: z.object({\n correlationId: z.string(),\n }),\n }),\n )\n .transform((message) => ({\n payload: message.content,\n messageId: message.properties.correlationId,\n }))\n\nconst abortSymbol = Symbol()\n\nexport const connectionOptionsSchema = z.object({\n url: z.union([\n z\n .string()\n .regex(/^amqps?:\\/\\/(.+):(.+)@(.+)$/)\n .transform((str) => new URL(str)),\n z\n .instanceof(URL)\n .refine((url) => url.protocol.match(/^amqps?:/), 'Wrong protocol'),\n ]),\n version: z.string(),\n // Author-chosen debugging label announced in the AMQP client properties.\n // Not length-validated on purpose — an over-long label is capped, never a\n // startup failure. Nothing keys off it.\n name: z.string().optional(),\n devOverlay: z.string().optional(),\n silent: z.boolean().optional(),\n prefetch: z.number().int().optional(),\n connectionTimeout: z.number().positive().default(3_000),\n heartbeatInterval: z.number().int().positive().optional(),\n connectionOptions: z.any().optional(),\n // Hard cap on the serialized message body. A body above this is rejected with a\n // clear PayloadTooLargeError *before* it reaches the broker — the broker itself\n // only signals oversize by tearing down the connection, which amqplib surfaces\n // as an opaque \"channel closed\". Set to match the broker's max_message_size.\n maxMessageSize: z\n .number()\n .int()\n .positive()\n .default(128 * 1024 * 1024), // RabbitMQ's historical default max_message_size\n // Undocumented (privileged consumers): skip file/stream/callback rehydration\n // on ingress — claim-checks still resolve; byte references reach the handler\n // as raw `__REQUENCE_type` wire objects. See helpers.ts.\n passthroughByteReferences: z.boolean().optional(),\n})\n\nexport type PrivilegedConnectionOptions = z.output<\n typeof connectionOptionsSchema\n>\nexport type ConnectionOptions = Omit<\n PrivilegedConnectionOptions,\n 'passthroughByteReferences'\n>\n\n// Live connection state, surfaced so a caller (e.g. the logic runtime's health\n// probe) can react to loss/recovery instead of trusting a one-shot startup\n// signal. `connected: false` carries the disconnect error when the broker\n// supplied one; `connected: true` fires on the initial connect and on every\n// subsequent auto-reconnect.\nexport interface ConnectionState {\n connected: boolean\n err?: Error\n}\nexport type ConnectionStateListener = (state: ConnectionState) => void\n\ntype MessageHandlerContext<V> = V extends keyof RequenceService.Version\n ? ServiceContextHelper<V>\n : ContextHelper\ntype MessageHandlerReturnValue<\n V,\n O = null,\n> = V extends keyof RequenceService.Version\n ? O extends OutputName<V>\n ? OutputValue<V, O> | InternalNamedOutput\n : void\n : JSONValue\n\ntype MessageHandlerFunction<V> = (\n context: MessageHandlerContext<V>,\n) => MaybePromise<MessageHandlerReturnValue<V> | void>\n\ntype MessageHandlerGenerator<V> = (\n context: MessageHandlerContext<V>,\n) => Generator<\n MessageHandlerReturnValue<V>,\n MessageHandlerReturnValue<V> | void,\n void\n>\ntype MessageHandlerAsyncGenerator<V> = (\n context: MessageHandlerContext<V>,\n) => AsyncGenerator<\n MessageHandlerReturnValue<V>,\n MessageHandlerReturnValue<V> | void,\n void\n>\n\nexport type MessageHandler<V> = V extends keyof RequenceService.Version\n ? RequenceService.Version[V]['mode'] extends 'LINEAR'\n ? MessageHandlerFunction<V>\n :\n | MessageHandlerAsyncGenerator<V>\n | MessageHandlerGenerator<V>\n | MessageHandlerFunction<V>\n :\n | MessageHandlerAsyncGenerator<V>\n | MessageHandlerGenerator<V>\n | MessageHandlerFunction<V>\n\nfunction isMessageHandlerGenerator<V extends keyof RequenceService.Version>(\n // oxlint-disable-next-line typescript/no-unsafe-function-type\n handler: Function,\n): handler is MessageHandlerGenerator<V> | MessageHandlerAsyncGenerator<V> {\n return (\n handler.constructor.name === 'GeneratorFunction' ||\n handler.constructor.name === 'AsyncGeneratorFunction'\n )\n}\n\nconst activeMessages = new Map<string, Promise<void>>()\n\n/**\n * The codec each in-flight dispatch arrived under, keyed by messageId.\n *\n * **A reply echoes the codec of its dispatch.** That is what keeps this direction\n * of the wire free of any capability logic: the service never chooses, never\n * configures and never negotiates a codec — it answers in the language it was\n * addressed in. The operator's result consumer then reads the content type back\n * off the reply, so the round trip needs no field anywhere in the protocol.\n *\n * A messageId absent from this map means JSON, which is both the pre-migration\n * status quo and the right answer for an operator loopback that never went\n * through a dispatch.\n */\nconst messageCodecs = new Map<string, WireCodec>()\n\n// A delivery tag belongs to the exact channel that delivered the message. When\n// that channel closes (e.g. the connection dropped mid-processing), amqplib\n// turns ack/nack into a synchronous `IllegalOperationError: Channel closed`.\n// The broker has already requeued the delivery for redelivery, so there is\n// nothing left to acknowledge — and we must NOT route this through the\n// reconnecting channelWrapper, which would send the stale tag on the new\n// channel and trip a 406 PRECONDITION_FAILED that kills the fresh channel.\nfunction isChannelClosedError(error: unknown): boolean {\n return error instanceof Error && error.name === 'IllegalOperationError'\n}\n\nfunction safeAck(channel: ConfirmChannel, message: ConsumeMessage) {\n try {\n channel.ack(message)\n } catch (error) {\n if (!isChannelClosedError(error)) {\n throw error\n }\n }\n}\n\nfunction safeNack(channel: ConfirmChannel, message: ConsumeMessage) {\n try {\n channel.nack(message)\n } catch (error) {\n if (!isChannelClosedError(error)) {\n throw error\n }\n }\n}\n\nexport default function createConnection<V>(\n {\n url,\n version,\n prefetch = 1,\n silent = false,\n connectionTimeout,\n // Without a default this is `undefined` and amqp-connection-manager falls\n // back to 5s, which makes any event-loop stall >10s fatal to the connection.\n // Defaulted here rather than per service so every deployed service converges\n // on the same interval on its next release.\n heartbeatInterval = DEFAULT_AMQP_HEARTBEAT_SECONDS,\n connectionOptions,\n name,\n devOverlay = '',\n maxMessageSize,\n onConnectionStateChange,\n ...rest\n }: ConnectionOptions & { onConnectionStateChange?: ConnectionStateListener },\n messageHandler: MessageHandler<V>,\n) {\n const passthroughByteReferences =\n (rest as PrivilegedConnectionOptions).passthroughByteReferences ?? false\n const baseQueue = `${url.username}@${version}`\n const queue = devOverlay\n ? `${baseQueue}-dev-overlay-${devOverlay}`\n : baseQueue\n const exchange = url.username\n const connection = connect(url.toString(), {\n connectionOptions: {\n ...connectionOptions,\n // Who we are, what we run, what we can decode — declared in the AMQP\n // connection frame so `ui/backend` knows it BEFORE the first dispatch.\n // amqp-connection-manager reuses these options on every reconnect, so\n // the announcement re-lands automatically. Merged LAST: the requence_*\n // keys are the contract and a caller may not shadow them.\n clientProperties: {\n ...connectionOptions?.clientProperties,\n ...buildServiceClientProperties({\n libVersion: libVersion(),\n serviceVersion: version,\n name,\n devOverlay: Boolean(devOverlay),\n }),\n },\n },\n heartbeatIntervalInSeconds: heartbeatInterval,\n })\n\n // amqp-connection-manager auto-reconnects, but without a listener a mid-\n // processing disconnect is completely silent: the raw amqplib channel that an\n // in-flight handler closed over is torn down, and the broker requeues every\n // unacked delivery. Surface it so the drop is at least observable.\n connection.on('disconnect', ({ err }: { err?: Error }) => {\n if (!silent && err) {\n console.error('Requence AMQP connection lost:', err.message)\n }\n onConnectionStateChange?.({ connected: false, err })\n })\n\n // A reconnect fires 'connect' again, but the connectedPromise's listener has\n // already unsubscribed, so recovery was previously invisible. Track whether\n // we have connected before to distinguish the initial connect from a\n // reconnect: log the recovery (mirroring the loss above) and surface it so\n // the caller can flip its state back. Fires for the initial connect too;\n // callers treat `connected: true` idempotently.\n let hasConnected = false\n connection.on('connect', () => {\n if (hasConnected && !silent) {\n console.info('Requence AMQP reconnected')\n }\n hasConnected = true\n onConnectionStateChange?.({ connected: true })\n })\n\n const connectedPromise = new Promise<void>((resolve, reject) => {\n const unsubscribe = () => {\n clearTimeout(timeout)\n connection.removeListener('connect', handleConnect)\n connection.removeListener('connectFailed', handleConnectFailed)\n }\n\n const timeout = setTimeout(() => {\n handleConnectFailed({\n err: new RequenceConnectionError('Requence connection timeout'),\n })\n }, connectionTimeout)\n\n const handleConnect = () => {\n unsubscribe()\n resolve()\n }\n\n const handleConnectFailed = ({ err }: { err: Error }) => {\n unsubscribe()\n if (\n err.message.startsWith(\n 'Handshake terminated by server: 403 (ACCESS-REFUSED)',\n )\n ) {\n reject(new RequenceConnectionError('Invalid service credentials'))\n } else {\n reject(err)\n }\n }\n\n connection.addListener('connect', handleConnect)\n connection.addListener('connectFailed', handleConnectFailed)\n })\n\n const connectionId = crypto.randomUUID()\n const backchannelQueue = `${baseQueue}-backchannel-${connectionId}`\n const generatorTerminators = new Map<string, (reason: string) => void>()\n // Each registry entry keeps the invocation dispatcher of the message that\n // registered the callback. Entries are deleted when that message settles,\n // so a stored dispatcher is live exactly as long as its callback is — this\n // is what lets a nested function in a callback argument reconstruct as\n // invokable (chaining): its invocations egress through the registering\n // message's context (results stream → operator → peer backchannel).\n const callbacks = new Map<\n string,\n {\n callback: (...args: any[]) => void\n onCallbackInvoke: CallbackIngressContext['onCallbackInvoke']\n }\n >()\n\n // Backchannel ingress (concept invariant 2): a callback argument was\n // egress-transformed by the invoking side (files/streams → references,\n // oversized values → claim-checks), so it must rehydrate here before\n // reaching user code. Connection-scoped: the callback owner is typically a\n // CONTINUOUS service whose lifetime differs from any single message, so no\n // per-message signal applies. `onCallbackInvoke` is supplied per call from\n // the registry entry, so nested functions reconstruct invokable.\n // Passthrough consumers (the logic runtime's guest channel) keep byte/callback\n // references raw here too — claim-checks still resolve, but files/streams/\n // callbacks reach the registered callback as their JSON-safe wire objects so\n // they can cross the guest's process boundary.\n const backchannelInbound = createInboundBoundary(\n passthroughByteReferences\n ? { transformer: passthroughInboundTransformer }\n : {},\n )\n\n const channelWrapper = connection.createChannel({\n async setup(channel: ConfirmChannel) {\n if (devOverlay) {\n await channel.assertQueue(queue)\n await channel.bindQueue(queue, 'service', queue)\n }\n await channel.checkExchange(exchange)\n await channel.checkExchange(`${exchange}-retry`)\n await channel.checkQueue(queue)\n await channel.prefetch(prefetch)\n\n await channel.assertQueue(backchannelQueue, {\n exclusive: true,\n })\n\n await channel.bindQueue(backchannelQueue, 'service', backchannelQueue)\n\n await channel.consume(\n backchannelQueue,\n async (message) => {\n const result = backchannelMessageSchema.safeParse(message)\n\n if (!result.success) {\n return\n }\n\n const backchannelMessage = result.data\n\n switch (backchannelMessage.payload.type) {\n case 'stop': {\n generatorTerminators.get(backchannelMessage.messageId)?.(\n 'task stopped',\n )\n break\n }\n case 'callback': {\n const entry = callbacks.get(backchannelMessage.payload.callbackId)\n if (!entry) {\n break\n }\n let arg: unknown\n try {\n arg = await backchannelInbound(backchannelMessage.payload.arg, {\n onCallbackInvoke: entry.onCallbackInvoke,\n })\n } catch (error) {\n // The backchannel consumes with noAck and outside any message\n // context, so a failed rehydration has no failure channel.\n // Never hand user code a raw reference — log and drop the\n // invocation instead.\n console.warn(\n `dropped callback invocation |${backchannelMessage.payload.callbackId}|: argument rehydration failed`,\n error instanceof Error ? error.message : error,\n )\n break\n }\n entry.callback(arg)\n break\n }\n }\n },\n {\n noAck: true,\n },\n )\n },\n })\n\n // ChannelWrapper is an EventEmitter; an unhandled 'error' would otherwise\n // propagate. Observe it rather than letting it surface as an uncaught error.\n channelWrapper.on('error', (err: Error) => {\n if (!silent) {\n console.error('Requence AMQP channel error:', err.message)\n }\n })\n\n const publish = ({\n data,\n outputName,\n messageId,\n priority,\n ...headers\n }: {\n index: number\n data?: unknown\n outputName?: string | null\n messageId: string\n taskId: string\n priority?: number\n version: string\n debugMethod?: 'log' | 'warn' | 'info' | 'error'\n debug?: boolean\n connectionId?: string\n callbackId?: string\n propertyPath?: (string | number)[]\n begin?: boolean\n deferred?: boolean\n done?: boolean\n // Privileged result protocol: `overwrite` marks a data message whose\n // value replaces (instead of merges into) downstream aggregation;\n // `state` marks a nodeStates writeback. The operator honors both only\n // for privileged nodes. Flow through via `...headers`.\n overwrite?: boolean\n state?: boolean\n // Per-attempt id: identifies this consume-handler invocation so the\n // operator can fence a superseded attempt's stragglers on the same\n // messageId. Flows through via `...headers`.\n epoch?: string\n // Who ran this node, stamped on the `begin` publish ONLY (see\n // `buildServiceIdentityHeaders`). The operator freezes these into the\n // NODE_START update; they are display-only and nothing branches on them.\n libVersion?: string\n serviceName?: string\n capabilities?: string\n }) => {\n const { body, contentType } = encodeWireBody(\n data ?? null,\n messageCodecs.get(messageId) ?? 'json',\n )\n\n // Guard the body size before it hits the broker. An oversized publish makes\n // RabbitMQ drop the whole connection, which amqplib reports as a generic\n // \"channel closed\" for every in-flight message — impossible to attribute to\n // size after the fact. Rejecting here yields a precise, catchable error and\n // leaves the connection intact for other messages.\n if (body.byteLength > maxMessageSize) {\n return Promise.reject(\n new PayloadTooLargeError(body.byteLength, maxMessageSize),\n )\n }\n\n return channelWrapper.publish(exchange, '', body, {\n correlationId: messageId,\n contentType,\n persistent: true,\n priority,\n headers: {\n outputName: outputName ?? null,\n connectionId,\n ...headers,\n },\n })\n }\n\n // The privileged send API (unit 05 headers), shared by the main-path handler\n // context and act()'s ActorApi: imperative data/state publishes through the\n // caller's outbound boundary, enrolled in its ledger so `settle()` gates the\n // done marker on them — a final state emission mechanically flushes before\n // `done`. `epoch`/`priority` are main-path-only and omitted from the\n // published headers when absent, keeping act()'s output byte-identical.\n const buildSendApi = (deps: {\n outbound: OutboundBoundary\n registerCallback: (callback: (...args: any[]) => void) => {\n sourceId: string\n callbackId: string\n }\n taskId: string\n messageId: string\n nextIndex: () => number\n epoch?: string\n priority?: number\n // act() only: wait for the deferring message's own processing to finish.\n gate?: () => Promise<void>\n }) => {\n const base = {\n ...(deps.epoch === undefined ? {} : { epoch: deps.epoch }),\n ...(deps.priority === undefined ? {} : { priority: deps.priority }),\n }\n return {\n async sendToOutput(\n outputName: string,\n data: unknown,\n options?: { overwrite?: boolean },\n ) {\n await deps.gate?.()\n deps.outbound.track(\n publish({\n index: deps.nextIndex(),\n version,\n messageId: deps.messageId,\n taskId: deps.taskId,\n data: await deps.outbound.send(data, {\n outputName: outputName as string | null,\n onCallback: deps.registerCallback,\n }),\n outputName: outputName as string | null,\n // only set when requested — omitted publishes stay identical\n ...(options?.overwrite ? { overwrite: true } : {}),\n ...base,\n }),\n )\n },\n async send(data: unknown, options?: { overwrite?: boolean }) {\n await deps.gate?.()\n deps.outbound.track(\n publish({\n index: deps.nextIndex(),\n version,\n messageId: deps.messageId,\n taskId: deps.taskId,\n data: await deps.outbound.send(data, {\n outputName: null,\n onCallback: deps.registerCallback,\n }),\n ...(options?.overwrite ? { overwrite: true } : {}),\n ...base,\n }),\n )\n },\n async sendState(state: unknown) {\n await deps.gate?.()\n deps.outbound.track(\n publish({\n // out-of-band like callback publishes: state bypasses the\n // operator's ordered dispatch buffer, so it must not consume a\n // publishIndex slot — `done` would otherwise wait on a gap.\n index: 0,\n version,\n messageId: deps.messageId,\n taskId: deps.taskId,\n // through the outbound boundary: a large state blob offloads\n // via claim-check like any large body, and the tracked publish\n // is settled before `done` goes out.\n data: await deps.outbound.send(state, { outputName: null }),\n state: true,\n ...base,\n }),\n )\n },\n }\n }\n\n channelWrapper.addSetup(async (channel: ConfirmChannel) => {\n channel.consume(queue, async (message) => {\n if (!message) {\n return\n }\n\n let publishIndex = 0\n let acked = false\n let terminated = false\n const registeredCallbackIds = new Set<string>()\n let resolveActiveMessage = () => {}\n // Captured for the finally block; header parsing now happens inside the\n // try so a malformed header goes through the error handling below instead\n // of throwing out of this async consumer as an unhandled rejection.\n let messageIdForCleanup: string | undefined\n // One epoch per consume-handler invocation (declared out here so the\n // catch-branch republishes can stamp it too). On redelivery/reconnect a\n // second invocation gets a fresh epoch, letting the operator tell the\n // attempts apart and fence the superseded one.\n const epoch = crypto.randomUUID()\n\n try {\n const { messageId, taskId, mode } = headerSchema.parse(message)\n messageIdForCleanup = messageId\n\n // The capability gate, ahead of everything the dispatch could ask of\n // this build — including its own decoding. A requirement stated in the\n // body would be unreadable exactly when it matters, so it rides in the\n // headers and is checked here, before `payloadSchema` touches the bytes.\n //\n // An empty requirement (every message published before this existed)\n // passes untouched.\n const unsupported = unsupportedCapabilities(\n readRequiredCapabilities(message.properties.headers),\n )\n if (unsupported.length > 0) {\n throw new UnsupportedCapabilityError(unsupported)\n }\n\n // Recorded before anything can publish, so every reply on this message —\n // including one from an error path — echoes the codec it arrived under.\n const dispatchCodec = wireCodecFromContentType(\n message.properties.contentType,\n )\n messageCodecs.set(messageId, dispatchCodec)\n\n let deferred = false\n let deferredReason: string | null = null\n\n const messageExecution = Promise.withResolvers<void>()\n activeMessages.set(messageId, messageExecution.promise)\n messageExecution.promise.then(() => {\n activeMessages.delete(messageId)\n })\n resolveActiveMessage = () => {\n messageExecution.resolve()\n }\n\n const payload = payloadSchema.parse(message)\n\n // The per-message abort controller is hoisted out of\n // createContextHelper so the outbound boundary can share its signal.\n const abortController = new AbortController()\n\n // One callback registrar for every egress sub-path (result, deferred\n // send, callback arg). Registered callbacks carry this message's\n // dispatcher so nested functions in their invocation arguments\n // reconstruct invokable (chaining).\n const registerCallback = (callback: (...args: any[]) => void) => {\n const callbackId = crypto.randomUUID()\n registeredCallbackIds.add(callbackId)\n callbacks.set(callbackId, {\n callback,\n onCallbackInvoke: dispatchInvocation,\n })\n return { sourceId: connectionId, callbackId }\n }\n\n // The component's single outbound boundary: owns ctx construction,\n // the background-upload ledger (done-gate) and the fail policy.\n // Fail-hard sends surface via outbound.settle() before the done\n // marker + ack; best-effort (log) sends degrade to warnings.\n const outbound = createOutboundBoundary({\n uploadUrl: payload.options.uploadUrl,\n streamUrl: payload.options.streamUrl,\n maxPayloadSize: payload.options.maxPayloadSize,\n maxFileSize: payload.options.maxFileSize,\n // Replies echo the dispatch codec, so the claim-check must measure\n // with it too — measured size == published size.\n wireCodec: dispatchCodec,\n signal: abortController.signal,\n warn: (msg, error) =>\n console.warn(\n `${msg} (task ${taskId})`,\n error instanceof Error ? error.message : (error ?? ''),\n ),\n })\n\n // This message's single invocation egress: callback arguments are\n // real node output (they carry an outputName), so they go through the\n // same boundary as results — nested files offload, nested functions\n // become callbacks. The send + publish are tracked in the boundary's\n // ledger, so a failure fails the task at the settle gate. Used both\n // for callbacks arriving in this message's input (via\n // createContextHelper) and for callbacks this message registers\n // (chained invocations dispatched from the backchannel).\n const dispatchInvocation = (params: {\n sourceId: string\n callbackId: string\n outputName: string | null\n propertyPath: (string | number)[]\n arg: unknown\n }) => {\n outbound.track(\n outbound\n .send(params.arg, {\n outputName: params.outputName,\n onCallback: registerCallback,\n })\n .then((data) =>\n publish({\n index: 0,\n version,\n taskId,\n messageId,\n data,\n outputName: params.outputName,\n connectionId: params.sourceId,\n callbackId: params.callbackId,\n propertyPath: params.propertyPath,\n epoch,\n }),\n ),\n )\n }\n\n const [extendedContext, terminatePromise] = (await createContextHelper({\n taskId,\n // Rehydration (FileObject/StreamObject -> RequenceFile/RequenceStream)\n // happens inside createContextHelper via its inbound boundary — the\n // signal-aware pass whose instances reach the handler.\n input: payload.input,\n configuration: payload.configuration,\n abortController,\n passthroughByteReferences,\n // Privileged send API on the handler ctx (runtime-only, hidden from\n // the ContextHelper type): shares this message's outbound boundary,\n // publishIndex counter, epoch and priority.\n sends: {\n ...buildSendApi({\n outbound,\n registerCallback,\n taskId,\n messageId,\n nextIndex: () => publishIndex++,\n epoch,\n priority: message.properties.priority,\n }),\n // Passthrough consumers hold raw callback wire refs — this is\n // their invocation egress, routed through the same\n // dispatchInvocation as a rehydrated callback call (fire-and-\n // forget; the outbound ledger settles the publish).\n invokeCallback: (ref, arg) =>\n dispatchInvocation({\n sourceId: ref.sourceId,\n callbackId: ref.callbackId,\n outputName: ref.outputName,\n propertyPath: ref.propertyPath,\n arg,\n }),\n options: payload.options,\n },\n onLog(debugMethod, data) {\n // Best-effort: a debug log must never fail the task. The boundary\n // sanitizes the payload (functions/opaque instances → labels),\n // degrades offload failures to warnings, and keeps the done-gate\n // waiting for the upload without letting it fail the task. On a\n // transform error it resolves `undefined` and nothing is published.\n void outbound.send(data, { bestEffort: true }).then((mapped) => {\n if (mapped === undefined) {\n return\n }\n publish({\n index: publishIndex++,\n version,\n messageId,\n taskId,\n data: mapped,\n debugMethod,\n priority: message.properties.priority,\n debug: true,\n epoch,\n })\n })\n },\n onDefer(reason) {\n deferred = true\n deferredReason = reason || null\n\n return obfuscate(\n taskId,\n messageId,\n payload.options.uploadUrl ?? '',\n payload.options.streamUrl ?? '',\n payload.options.maxPayloadSize?.toString() ?? '',\n payload.options.maxFileSize?.toString() ?? '',\n )\n },\n onCallback: dispatchInvocation,\n })) as unknown as [\n MessageHandlerContext<V>,\n PromiseWithResolvers<string>,\n ]\n\n await publish({\n index: publishIndex++,\n version,\n messageId,\n taskId,\n priority: message.properties.priority,\n begin: true,\n epoch,\n // The one stamp per node execution: this build, this box. It becomes\n // the NODE_START update's `service`, which is written once and never\n // re-derived — so anything absent here is lost for that run.\n ...buildServiceIdentityHeaders({\n libVersion: libVersion(),\n name,\n }),\n })\n\n if (isMessageHandlerGenerator(messageHandler)) {\n if (mode === 'CONTINUOUS') {\n // CONTINUOUS: ACK immediately, operator watchdog supervises. A\n // LINEAR message stays unacked until done — prefetch keeps\n // bounding concurrent work and the broker redelivers on a crash.\n safeAck(channel, message)\n acked = true\n }\n\n const generator = messageHandler(extendedContext)\n const terminationPromise = Promise.withResolvers<typeof abortSymbol>()\n generatorTerminators.set(messageId, (reason) => {\n terminated = true\n // Suppress native AbortError that may reject generator.return() when\n // context.terminated.signal fires and cancels a pending await inside\n // the generator (e.g. node:timers/promises setTimeout with { signal }).\n ;(generator.return() as Promise<unknown>).catch(\n (error: unknown) => {\n if (\n terminated &&\n error instanceof Error &&\n error.name === 'AbortError' &&\n !(error instanceof AbortError)\n ) {\n return\n }\n throw error\n },\n )\n terminationPromise.resolve(abortSymbol)\n terminatePromise.resolve(reason)\n })\n\n await handlerStorage.run(\n extendedContext as ContextHelper,\n async () => {\n while (true) {\n type IterResult = IteratorResult<\n MessageHandlerReturnValue<V, null>,\n void | MessageHandlerReturnValue<V, null>\n >\n // Catch native AbortError from context.terminated.signal so\n // generator implementations don't need their own try/catch.\n const nextPromise = Promise.resolve(generator.next()).then(\n (r) => r,\n (error: unknown) => {\n if (\n terminated &&\n error instanceof Error &&\n error.name === 'AbortError' &&\n !(error instanceof AbortError)\n ) {\n return { value: undefined, done: true } as IterResult\n }\n throw error\n },\n )\n const next = await Promise.race([\n terminationPromise.promise,\n nextPromise,\n ])\n if (next === abortSymbol) {\n break\n }\n\n const { value: result, done } = next\n\n if (deferred) {\n deferred = false\n console.warn(\n 'returning a value in a deferred message resets the deferred status',\n )\n }\n\n const { value: rawValue, outputName } =\n unwrapOutputValue(result)\n const value = await outbound.send(rawValue, {\n outputName,\n onCallback: registerCallback,\n })\n\n if (!done || typeof value !== 'undefined') {\n await publish({\n index: publishIndex++,\n version,\n messageId,\n taskId,\n data: value,\n priority: message.properties.priority,\n outputName,\n epoch,\n })\n }\n\n if (done) {\n break\n }\n }\n },\n )\n } else {\n const result = await handlerStorage.run(\n extendedContext as ContextHelper,\n () => messageHandler(extendedContext),\n )\n const { value: rawValue, outputName } = unwrapOutputValue(result)\n const value = await outbound.send(rawValue, {\n outputName,\n onCallback: () => {\n throw new Error(\n 'callbacks can only be used in generator functions',\n )\n },\n })\n if (deferred && value) {\n console.warn(\n 'returning a value in a deferred message resets the deferred status',\n )\n deferred = false\n }\n\n if (!deferred || value) {\n await publish({\n index: publishIndex++,\n version,\n messageId,\n taskId,\n data: value,\n priority: message.properties.priority,\n outputName,\n epoch,\n })\n }\n }\n\n await new Promise<void>((resolve, reject) => {\n setImmediate(async () => {\n try {\n // The boundary's settle gate: waits for every tracked background\n // upload/publish, then throws an AggregateError on any fail-hard\n // failure — which surfaces here and reaches the outer catch ->\n // exception republish -> throwServiceError -> failNode. The done\n // marker + ack only happen once every upload succeeded.\n if (!deferred) {\n await outbound.settle()\n }\n\n await publish({\n index: publishIndex++,\n version,\n messageId,\n taskId,\n data: deferredReason,\n priority: message.properties.priority,\n deferred,\n done: !deferred,\n epoch,\n })\n\n if (!acked) {\n safeAck(channel, message)\n }\n resolve()\n } catch (error) {\n reject(error)\n }\n })\n })\n } catch (error) {\n if (error instanceof SkipError) {\n if (!acked) {\n safeNack(channel, message)\n }\n return\n }\n if (error instanceof RetryError) {\n if (!acked) {\n safeAck(channel, message)\n }\n const properties: Options.Publish = {\n ...message.properties,\n expiration: error.delay || 1_000, // 1s\n }\n channelWrapper\n .publish(\n `${exchange}-retry`,\n version, // to other services\n message.content,\n properties,\n )\n .catch((publishError: unknown) => {\n if (!silent) {\n console.error(\n 'Failed to republish message for retry:',\n publishError,\n )\n }\n })\n\n return\n }\n\n // A refusal, not a failure: this box is the wrong one, the message is\n // fine. It goes back by REPUBLISHING to `<exchange>-retry`, never by\n // nacking, because a nack can carry no rejection count and a classic\n // queue offers none either — see `CAPABILITY_HEADER_KEYS.mismatch` in\n // `@requence/helpers/protocol` for the full argument, and this file's\n // spec, which pins it. The republish reaches the operator's error\n // consumer, which already counts attempts, delays and fails the node.\n if (error instanceof UnsupportedCapabilityError) {\n if (!silent) {\n console.error(error.message)\n }\n\n if (!acked) {\n safeAck(channel, message)\n }\n channelWrapper\n .publish(\n `${exchange}-retry`,\n 'operator', // back to operator\n // The dispatch verbatim: a reroute re-dispatches these bytes, and\n // this build never decoded them.\n message.content,\n {\n ...message.properties,\n headers: {\n ...message.properties.headers,\n version,\n [CAPABILITY_HEADER_KEYS.mismatch]: true,\n index: publishIndex++,\n 'error-message': error.message,\n },\n },\n )\n .catch((publishError: unknown) => {\n if (!silent) {\n console.error(\n 'Failed to publish capability mismatch message:',\n publishError,\n )\n }\n })\n\n return\n }\n\n if (error instanceof AbortError && error.message.length > 0) {\n if (!acked) {\n safeAck(channel, message)\n }\n channelWrapper\n .publish(\n `${exchange}-retry`,\n 'operator', //back to operator\n error.message,\n {\n ...message.properties,\n contentType: 'text/plain',\n headers: {\n ...message.properties.headers,\n index: publishIndex++,\n abort: true,\n },\n },\n )\n .catch((publishError: unknown) => {\n if (!silent) {\n console.error('Failed to publish abort message:', publishError)\n }\n })\n\n return\n }\n\n // Native AbortError thrown when context.terminated.signal fires\n // (e.g. node:timers/promises setTimeout with { signal: context.terminated.signal }).\n // Only suppress when actually in a terminated state — otherwise a\n // different AbortSignal caused the error and it should propagate.\n if (\n terminated &&\n error instanceof Error &&\n error.name === 'AbortError' &&\n !(error instanceof AbortError)\n ) {\n if (!acked) {\n safeAck(channel, message)\n }\n return\n }\n\n if (error instanceof Error) {\n if (!silent) {\n console.error('Encountered an error inside service handler:')\n console.error(error)\n }\n\n if (!acked) {\n safeAck(channel, message)\n }\n channelWrapper\n .publish(\n `${exchange}-retry`,\n 'operator', // back to operator\n message.content,\n {\n ...message.properties,\n headers: {\n ...message.properties.headers,\n version,\n exception: true,\n index: publishIndex++,\n 'error-message': error.message || 'error in service handler',\n },\n },\n )\n .catch((publishError: unknown) => {\n if (!silent) {\n console.error(\n 'Failed to publish exception message:',\n publishError,\n )\n }\n })\n\n return\n }\n } finally {\n if (messageIdForCleanup) {\n generatorTerminators.delete(messageIdForCleanup)\n // Bounded with the delivery rather than left to accumulate. A publish\n // that outlives the handler — a deferred message's later send — then\n // falls back to JSON, which the operator decodes correctly off the\n // header. It loses the size win for that one message and nothing else:\n // degrading to JSON is always safe, which is why the fallback is JSON\n // and not \"the last codec we saw\".\n messageCodecs.delete(messageIdForCleanup)\n }\n registeredCallbackIds.forEach((id) => callbacks.delete(id))\n resolveActiveMessage()\n }\n })\n })\n\n const activeMessageKeys = new Set<string>()\n const api: ConnectionApi<V> = {\n close: async () => {\n await channelWrapper.close()\n await connection.close()\n },\n open: () => connectedPromise.then(() => api),\n\n async act(messageKey, actor) {\n if (activeMessageKeys.has(messageKey)) {\n throw new Error('a defer key can only be used once')\n }\n\n activeMessageKeys.add(messageKey)\n\n let publishIndex = 0\n const { taskId, messageId, ...options } =\n messageKeySchema.parse(messageKey)\n\n const activeMessage = async () => {\n if (activeMessages.has(messageId)) {\n await activeMessages.get(messageId)\n }\n }\n\n const registeredCallbackIds = new Set<string>()\n // The deferred path's own outbound boundary: its ledger replaces the\n // old donePromises/uploadErrors pair — errors are caught at\n // registration time (nothing sits unhandled during long generator\n // iteration) and surfaced by settle() after the loop.\n const outbound = createOutboundBoundary(options)\n const registerCallback = (callback: (...args: any[]) => void) => {\n const callbackId = crypto.randomUUID()\n registeredCallbackIds.add(callbackId)\n callbacks.set(callbackId, {\n callback,\n onCallbackInvoke: dispatchInvocation,\n })\n return { sourceId: connectionId, callbackId }\n }\n\n // Deferred-path analogue of the main path's dispatchInvocation: chained\n // invocations of callbacks registered here egress through this deferred\n // message's context (no epoch, matching its other publishes).\n const dispatchInvocation = (params: {\n sourceId: string\n callbackId: string\n outputName: string | null\n propertyPath: (string | number)[]\n arg: unknown\n }) => {\n outbound.track(\n outbound\n .send(params.arg, {\n outputName: params.outputName,\n onCallback: registerCallback,\n })\n .then((data) =>\n publish({\n index: 0,\n version,\n taskId,\n messageId,\n data,\n outputName: params.outputName,\n connectionId: params.sourceId,\n callbackId: params.callbackId,\n propertyPath: params.propertyPath,\n }),\n ),\n )\n }\n\n const sendApi = {\n // The shared privileged send API, composed with act()'s own index\n // counter and its active-message gate; no epoch/priority — the\n // deferred path's publishes never carried them.\n ...buildSendApi({\n outbound,\n registerCallback,\n taskId,\n messageId,\n nextIndex: () => publishIndex++,\n gate: activeMessage,\n }),\n async abort(error: string | Error) {\n await activeMessage()\n channelWrapper.publish(\n `${exchange}-retry`,\n 'operator',\n error instanceof Error ? error.message : error,\n {\n persistent: true,\n correlationId: messageId,\n expiration: 0,\n priority: 0,\n contentType: 'text/plain',\n headers: {\n taskId,\n index: publishIndex++,\n abort: true,\n },\n },\n )\n },\n }\n\n const result = await actor(sendApi as ActorApi<V>)\n\n if (\n result != null &&\n typeof result === 'object' &&\n (Symbol.asyncIterator in result || Symbol.iterator in result)\n ) {\n // Generator: iterate and send each yielded value\n const iterable = result as AsyncIterable<unknown> | Iterable<unknown>\n for await (const value of iterable) {\n if (value !== undefined) {\n await sendApi.send(value)\n }\n }\n } else if (result !== undefined) {\n await sendApi.send(result)\n }\n\n await new Promise((resolve) => setImmediate(resolve))\n await activeMessage()\n\n try {\n // Settle gate: waits while sends enqueue more sends, then throws an\n // AggregateError on any failed background upload or publish.\n await outbound.settle()\n } catch (error) {\n // Do not mark the message done with a dangling reference. Signal\n // failure over the deferred-path error channel (abort -> operator\n // fails the node) and throw so act()'s caller sees it too.\n registeredCallbackIds.forEach((id) => callbacks.delete(id))\n const first =\n error instanceof AggregateError && error.errors[0] instanceof Error\n ? error.errors[0]\n : error instanceof Error\n ? error\n : new Error(String(error))\n await sendApi.abort(first)\n activeMessageKeys.delete(messageKey)\n throw error\n }\n\n registeredCallbackIds.forEach((id) => callbacks.delete(id))\n\n await publish({\n index: publishIndex++,\n version,\n messageId,\n taskId,\n done: true,\n })\n\n activeMessageKeys.delete(messageKey)\n },\n }\n\n return api\n}\n",
|
|
18
|
+
"import { createHash } from 'node:crypto'\n\nimport type { CallbackIngressContext } from '@requence/callbacks'\nimport {\n DEFAULT_AMQP_HEARTBEAT_SECONDS,\n DEFAULT_SURFACE_ID,\n MAX_SURFACE_INTERACTION_ERROR_CHARS,\n type MaybePromise,\n SURFACE_HANDLER_QUEUE_ARGUMENTS,\n SURFACE_HANDLER_TAG,\n SURFACE_INTERACTION_ERROR_HEADER,\n type SurfaceHandlerObject,\n UI_REBUILD_HEADER,\n type UiRebuild,\n deobfuscate,\n getByPath,\n obfuscate,\n serviceHandlerQueueName,\n surfaceHandlerInvocationSchema,\n} from '@requence/helpers'\nimport type { WireCodec } from '@requence/helpers/msgpack'\nimport {\n decodeWireBody,\n encodeWireBody,\n wireCodecFromContentType,\n} from '@requence/helpers/msgpack'\nimport {\n CAPABILITY_HEADER_KEYS,\n buildServiceClientProperties,\n buildServiceIdentityHeaders,\n readRequiredCapabilities,\n unsupportedCapabilities,\n} from '@requence/helpers/protocol'\nimport logger from '@requence/logger/simple'\nimport { type Options, connect } from 'amqp-connection-manager'\nimport type { ConfirmChannel, ConsumeMessage } from 'amqplib'\nimport { z } from 'zod/v4'\n\nimport {\n type OutboundBoundary,\n createInboundBoundary,\n createOutboundBoundary,\n} from './boundary.ts'\nimport {\n PayloadTooLargeError,\n RequenceConnectionError,\n UnsupportedCapabilityError,\n} from './errors.ts'\nimport createContextHelper, {\n AbortError,\n type ContextHelper,\n type JSONValue,\n RetryError,\n SkipError,\n handlerStorage,\n unwrapOutputValue,\n} from './helpers.ts'\nimport { libVersion } from './macro.ts' with { type: 'macro' }\nimport { passthroughInboundTransformer } from './transformer.ts'\nimport type { RenderProps, RequenceUI } from './ui.ts'\nimport {\n type MutableRequenceUI,\n findUIById,\n watchUIRebuilds,\n} from './uiWatch.ts'\n\ntype InternalNamedOutput = '__internal_named_output__'\n\n/**\n * A thrown value as a sentence a viewer can read — the text a recorded\n * interaction failure quotes (#107).\n *\n * The message and not the stack: the stack goes to this process's stderr, where\n * the author is, while the row is served to whoever is looking at the surface.\n */\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\ntype Input<V extends keyof RequenceService.Version> =\n RequenceService.Version[V]['input']\ntype Configuration<V extends keyof RequenceService.Version> =\n RequenceService.Version[V]['configuration']\ntype OutputName<\n V extends keyof RequenceService.Version,\n K = keyof RequenceService.Version[V]['outputs'],\n> = K extends '__default__' ? null : K\n\ntype OutputValue<\n V extends keyof RequenceService.Version,\n O extends OutputName<V>,\n ON = O extends null ? '__default__' : O,\n> = ON extends keyof RequenceService.Version[V]['outputs']\n ? RequenceService.Version[V]['outputs'][ON]\n : never\n\ninterface ServiceContextHelper<\n V extends keyof RequenceService.Version,\n> extends Omit<\n ContextHelper,\n 'input' | 'configuration' | 'getData' | 'getConfiguration' | 'toOutput'\n> {\n input: Input<V>\n configuration: Configuration<V>\n\n toOutput<O extends OutputName<V>>(\n name: O,\n value: OutputValue<V, O>,\n ): InternalNamedOutput\n}\n\ntype ApiOutputName<V> = V extends keyof RequenceService.Version\n ? OutputName<V>\n : string | null\ntype ApiOutputValue<V, O> = V extends keyof RequenceService.Version\n ? O extends OutputName<V>\n ? OutputValue<V, O>\n : unknown\n : unknown\n\ninterface ActorApi<V> {\n sendToOutput<O extends ApiOutputName<V>>(\n outputName: O,\n data: ApiOutputValue<V, O>,\n options?: { overwrite?: boolean },\n ): void\n send(data: ApiOutputValue<V, null>, options?: { overwrite?: boolean }): void\n // Publishes a state writeback (`state: true` header). The operator honors\n // it only for privileged nodes; ordinary services' state messages are\n // ignored there.\n sendState(state: unknown): void\n /**\n * Renders a UI component on the deferred node, for as long as this `act()`\n * call runs — the `act()` re-attach of\n * `knowledge/service-ui-surfaces.md`.\n *\n * Identical in contract to `context.render`: `props` is a plain object, and\n * functions inside it arrive in the component as invokable callbacks. The\n * difference is *whose* they are — they register in this `act()` call's own\n * registry, so they live exactly as long as the call. A deferring LINEAR\n * handler cannot hold one at all (its callbacks die when it returns), which is\n * why a live surface on a deferred node has to be rendered from here.\n *\n * That is also what makes it survive a restart: reload the pending keys,\n * `act()` again, and this render — fresh connection, fresh callbacks —\n * replaces the stale surface through the last-write-wins surface row. Nothing\n * about the component or the browser has to know it happened.\n *\n * **You own the double-attach lock.** See {@link ConnectionApi.act}: two\n * replicas that both load the same pending key will both render, and the\n * second one silently takes the surface over. Requence cannot hold that lock\n * for you — it warns loudly instead.\n *\n * A render is a patch here exactly as on the main path (#102), which is what\n * makes a re-attach cheap: restate what this process knows and let the fold\n * keep the rest.\n *\n * A function written *here* is connection-bound: it closes over this `act()`\n * call, so it dies with it. A function in the UI's own defaults is durable\n * whoever renders it (#103) — which is what an actor should reach for when it\n * wants a control to keep working after it has gone.\n */\n render<Props>(\n ui: RequenceUI<Props>,\n props: RenderProps<Props>,\n options?: { surfaceId?: string },\n ): void\n abort(error: string | Error): void\n}\n\nexport interface ConnectionApi<V> {\n close(): Promise<void>\n open(): Promise<ConnectionApi<V>>\n /**\n * Deliver the result of a deferred message, later and from anywhere: pass the\n * key `context.defer()` returned and the actor runs with a send API for that\n * message. It is also the only live window a deferred node has — see\n * {@link ActorApi.render}.\n *\n * **Double-attach is YOUR lock to hold.** You own the pending-key storage, so\n * you own the exclusivity. This connection refuses a key it is already acting\n * on, but that check is per-connection and in memory: two replicas that both\n * load the pending keys on boot will both `act()` the same key, both register\n * callbacks, and both render — and the second render replaces the first one's\n * surface, so clicks silently go to whichever instance rendered last. Requence\n * does not arbitrate this (that would need cross-replica holder state plus a\n * takeover path so a dead holder cannot block a key forever); it makes the\n * symptom loud instead, by warning when a render replaces a surface that is\n * still live on another connection.\n *\n * Take a lease on the key in your own store before acting, and only act on\n * keys you hold.\n */\n act(\n messageKey: string,\n actor: (\n api: ActorApi<V>,\n ) =>\n | ApiOutputValue<V, null>\n | Promise<ApiOutputValue<V, null>>\n | void\n | Promise<void>\n | AsyncGenerator<ApiOutputValue<V, null>>\n | Generator<ApiOutputValue<V, null>>,\n ): Promise<void>\n}\n\nexport const messageKeySchema = z\n .string()\n .transform((str) => deobfuscate(str))\n .pipe(z.tuple([z.uuid(), z.uuid()]).rest(z.string()))\n .transform((arr) => ({\n taskId: arr[0],\n messageId: arr[1],\n uploadUrl: arr[2] || undefined,\n streamUrl: arr[3] || undefined,\n // Byte limits appended to the defer key alongside the transport URLs.\n // Old 4-part keys (pre-limits) parse with both absent → consumer defaults.\n maxPayloadSize:\n arr[4] && Number.isFinite(Number(arr[4])) ? Number(arr[4]) : undefined,\n maxFileSize:\n arr[5] && Number.isFinite(Number(arr[5])) ? Number(arr[5]) : undefined,\n }))\n\nconst headerSchema = z\n .object({\n properties: z.object({\n correlationId: z.uuid(),\n headers: z.object({\n taskId: z.uuid(),\n mode: z.enum(['LINEAR', 'CONTINUOUS']).default('LINEAR'),\n }),\n }),\n })\n .transform((msg) => ({\n messageId: msg.properties.correlationId,\n taskId: msg.properties.headers.taskId,\n mode: msg.properties.headers.mode,\n }))\n\nconst payloadSchema = z\n .object({\n content: z.instanceof(Buffer),\n properties: z.object({ contentType: z.string().optional() }),\n })\n // The dispatch codec is whatever the operator declared, never an assumption:\n // `ui/backend` bakes the choice per service node, so two nodes of one task can\n // legitimately arrive under different codecs, and a replica that has just been\n // rolled forward still receives JSON for tasks created before it attached.\n .transform((msg) => decodeWireBody(msg.content, msg.properties.contentType))\n .pipe(\n z.object({\n // Optional because a dispatch may carry no input at all, and the JSON\n // codec drops an `undefined` value rather than encoding one — under zod 4\n // that absence would throw here and fail the node with a message about the\n // envelope. The msgpack codec keeps the key (as nil), so this only ever\n // shows on the JSON wire.\n input: z.unknown().optional(),\n configuration: z.unknown().optional(),\n options: z.object({\n uploadUrl: z.url().optional(),\n streamUrl: z.url().optional(),\n maxPayloadSize: z.number().optional(),\n maxFileSize: z.number().optional(),\n }),\n }),\n )\n\nconst backchannelMessageSchema = z\n .object({\n content: z.instanceof(Buffer),\n properties: z.object({\n correlationId: z.string(),\n contentType: z.string().optional(),\n // The task, for the failure report below. Every backchannel publish stamps\n // it (the operator needs it to hash the unroutable copy onto the task's own\n // shard), so it is here rather than in the payload.\n //\n // `catch` so this can never reject a delivery: the headers are a *reporting*\n // input, and a malformed one must cost the report, not the invocation the\n // message was carrying.\n headers: z\n .object({ taskId: z.uuid().optional() })\n .optional()\n .catch(undefined),\n }),\n })\n // Header-driven like every other decoder on these wires. The backchannel itself\n // stays JSON — it is a low-volume control wire — but reading the header means it\n // is not the one consumer a later codec change has to remember to visit.\n .transform((message) => ({\n ...message,\n content: decodeWireBody(message.content, message.properties.contentType),\n }))\n .pipe(\n z.object({\n content: z.discriminatedUnion('type', [\n z.object({\n type: z.literal('stop'),\n }),\n z.object({\n type: z.literal('callback'),\n callbackId: z.uuid(),\n /**\n * `.optional()` is load-bearing, and it is not decoration: under zod 4\n * an `any` field is NOT optional, so a body with no `arg` key fails to\n * parse — and the parse failure here is a bare `return`, the one path\n * on this consumer that says nothing at all.\n *\n * A body without the key is ordinary: the wire is JSON, and a handler\n * invoked with no argument (`onInject(): void`) serializes to a key\n * `JSON.stringify` deletes. The publisher normalises to `null` now, so\n * this covers a publisher that has not been rolled forward rather than\n * the everyday case.\n */\n arg: z.any().optional(),\n /**\n * Present exactly when this callback IS a connection-bound surface\n * handler invocation (#107): the surface row it came from, so a\n * failure can be stated on the surface the viewer is looking at.\n *\n * A peer callback carries none, and must not: it belongs to a live\n * message that can fail in the ordinary way.\n */\n surface: z.uuid().optional(),\n }),\n ]),\n properties: z.object({\n correlationId: z.string(),\n headers: z\n .object({ taskId: z.uuid().optional() })\n .optional()\n .catch(undefined),\n }),\n }),\n )\n .transform((message) => ({\n payload: message.content,\n messageId: message.properties.correlationId,\n taskId: message.properties.headers?.taskId,\n }))\n\nconst abortSymbol = Symbol()\n\nexport const connectionOptionsSchema = z.object({\n url: z.union([\n z\n .string()\n .regex(/^amqps?:\\/\\/(.+):(.+)@(.+)$/)\n .transform((str) => new URL(str)),\n z\n .instanceof(URL)\n .refine((url) => url.protocol.match(/^amqps?:/), 'Wrong protocol'),\n ]),\n version: z.string(),\n // Author-chosen debugging label announced in the AMQP client properties.\n // Not length-validated on purpose — an over-long label is capped, never a\n // startup failure. Nothing keys off it.\n name: z.string().optional(),\n devOverlay: z.string().optional(),\n silent: z.boolean().optional(),\n prefetch: z.number().int().optional(),\n connectionTimeout: z.number().positive().default(3_000),\n heartbeatInterval: z.number().int().positive().optional(),\n connectionOptions: z.any().optional(),\n // Hard cap on the serialized message body. A body above this is rejected with a\n // clear PayloadTooLargeError *before* it reaches the broker — the broker itself\n // only signals oversize by tearing down the connection, which amqplib surfaces\n // as an opaque \"channel closed\". Set to match the broker's max_message_size.\n maxMessageSize: z\n .number()\n .int()\n .positive()\n .default(128 * 1024 * 1024), // RabbitMQ's historical default max_message_size\n // Undocumented (privileged consumers): skip file/stream/callback rehydration\n // on ingress — claim-checks still resolve; byte references reach the handler\n // as raw `__REQUENCE_type` wire objects. See helpers.ts.\n passthroughByteReferences: z.boolean().optional(),\n})\n\nexport type PrivilegedConnectionOptions = z.output<\n typeof connectionOptionsSchema\n>\nexport type ConnectionOptions = Omit<\n PrivilegedConnectionOptions,\n 'passthroughByteReferences'\n>\n\n// Live connection state, surfaced so a caller (e.g. the logic runtime's health\n// probe) can react to loss/recovery instead of trusting a one-shot startup\n// signal. `connected: false` carries the disconnect error when the broker\n// supplied one; `connected: true` fires on the initial connect and on every\n// subsequent auto-reconnect.\nexport interface ConnectionState {\n connected: boolean\n err?: Error\n}\nexport type ConnectionStateListener = (state: ConnectionState) => void\n\ntype MessageHandlerContext<V> = V extends keyof RequenceService.Version\n ? ServiceContextHelper<V>\n : ContextHelper\ntype MessageHandlerReturnValue<\n V,\n O = null,\n> = V extends keyof RequenceService.Version\n ? O extends OutputName<V>\n ? OutputValue<V, O> | InternalNamedOutput\n : void\n : JSONValue\n\ntype MessageHandlerFunction<V> = (\n context: MessageHandlerContext<V>,\n) => MaybePromise<MessageHandlerReturnValue<V> | void>\n\ntype MessageHandlerGenerator<V> = (\n context: MessageHandlerContext<V>,\n) => Generator<\n MessageHandlerReturnValue<V>,\n MessageHandlerReturnValue<V> | void,\n void\n>\ntype MessageHandlerAsyncGenerator<V> = (\n context: MessageHandlerContext<V>,\n) => AsyncGenerator<\n MessageHandlerReturnValue<V>,\n MessageHandlerReturnValue<V> | void,\n void\n>\n\nexport type MessageHandler<V> = V extends keyof RequenceService.Version\n ? RequenceService.Version[V]['mode'] extends 'LINEAR'\n ? MessageHandlerFunction<V>\n :\n | MessageHandlerAsyncGenerator<V>\n | MessageHandlerGenerator<V>\n | MessageHandlerFunction<V>\n :\n | MessageHandlerAsyncGenerator<V>\n | MessageHandlerGenerator<V>\n | MessageHandlerFunction<V>\n\nfunction isMessageHandlerGenerator<V extends keyof RequenceService.Version>(\n // oxlint-disable-next-line typescript/no-unsafe-function-type\n handler: Function,\n): handler is MessageHandlerGenerator<V> | MessageHandlerAsyncGenerator<V> {\n return (\n handler.constructor.name === 'GeneratorFunction' ||\n handler.constructor.name === 'AsyncGeneratorFunction'\n )\n}\n\nconst activeMessages = new Map<string, Promise<void>>()\n\n/**\n * The codec each in-flight dispatch arrived under, keyed by messageId.\n *\n * **A reply echoes the codec of its dispatch.** That is what keeps this direction\n * of the wire free of any capability logic: the service never chooses, never\n * configures and never negotiates a codec — it answers in the language it was\n * addressed in. The operator's result consumer then reads the content type back\n * off the reply, so the round trip needs no field anywhere in the protocol.\n *\n * A messageId absent from this map means JSON, which is both the pre-migration\n * status quo and the right answer for an operator loopback that never went\n * through a dispatch.\n */\nconst messageCodecs = new Map<string, WireCodec>()\n\n// A delivery tag belongs to the exact channel that delivered the message. When\n// that channel closes (e.g. the connection dropped mid-processing), amqplib\n// turns ack/nack into a synchronous `IllegalOperationError: Channel closed`.\n// The broker has already requeued the delivery for redelivery, so there is\n// nothing left to acknowledge — and we must NOT route this through the\n// reconnecting channelWrapper, which would send the stale tag on the new\n// channel and trip a 406 PRECONDITION_FAILED that kills the fresh channel.\nfunction isChannelClosedError(error: unknown): boolean {\n return error instanceof Error && error.name === 'IllegalOperationError'\n}\n\nfunction safeAck(channel: ConfirmChannel, message: ConsumeMessage) {\n try {\n channel.ack(message)\n } catch (error) {\n if (!isChannelClosedError(error)) {\n throw error\n }\n }\n}\n\nfunction safeNack(channel: ConfirmChannel, message: ConsumeMessage) {\n try {\n channel.nack(message)\n } catch (error) {\n if (!isChannelClosedError(error)) {\n throw error\n }\n }\n}\n\nexport default function createConnection<V>(\n {\n url,\n version,\n prefetch = 1,\n silent = false,\n connectionTimeout,\n // Without a default this is `undefined` and amqp-connection-manager falls\n // back to 5s, which makes any event-loop stall >10s fatal to the connection.\n // Defaulted here rather than per service so every deployed service converges\n // on the same interval on its next release.\n heartbeatInterval = DEFAULT_AMQP_HEARTBEAT_SECONDS,\n connectionOptions,\n name,\n devOverlay = '',\n maxMessageSize,\n onConnectionStateChange,\n ...rest\n }: ConnectionOptions & { onConnectionStateChange?: ConnectionStateListener },\n messageHandler: MessageHandler<V>,\n) {\n const passthroughByteReferences =\n (rest as PrivilegedConnectionOptions).passthroughByteReferences ?? false\n // A non-generator handler's result path already refuses callbacks: its\n // registry entries are deleted the moment the message settles, which for a\n // returning handler is immediately. Same rule for render props — this is the\n // one place it is decided, and it is a property of the handler, not of a\n // message. (Kept separate from the narrowing call in the consume loop, whose\n // job is to type the handler.)\n const canRegisterCallbacks = isMessageHandlerGenerator(messageHandler)\n const baseQueue = `${url.username}@${version}`\n const queue = devOverlay\n ? `${baseQueue}-dev-overlay-${devOverlay}`\n : baseQueue\n const exchange = url.username\n const connection = connect(url.toString(), {\n connectionOptions: {\n ...connectionOptions,\n // Who we are, what we run, what we can decode — declared in the AMQP\n // connection frame so `ui/backend` knows it BEFORE the first dispatch.\n // amqp-connection-manager reuses these options on every reconnect, so\n // the announcement re-lands automatically. Merged LAST: the requence_*\n // keys are the contract and a caller may not shadow them.\n clientProperties: {\n ...connectionOptions?.clientProperties,\n ...buildServiceClientProperties({\n libVersion: libVersion(),\n serviceVersion: version,\n name,\n devOverlay: Boolean(devOverlay),\n }),\n },\n },\n heartbeatIntervalInSeconds: heartbeatInterval,\n })\n\n // amqp-connection-manager auto-reconnects, but without a listener a mid-\n // processing disconnect is completely silent: the raw amqplib channel that an\n // in-flight handler closed over is torn down, and the broker requeues every\n // unacked delivery. Surface it so the drop is at least observable.\n connection.on('disconnect', ({ err }: { err?: Error }) => {\n if (!silent && err) {\n logger.error('Requence AMQP connection lost:', err.message)\n }\n onConnectionStateChange?.({ connected: false, err })\n })\n\n // A reconnect fires 'connect' again, but the connectedPromise's listener has\n // already unsubscribed, so recovery was previously invisible. Track whether\n // we have connected before to distinguish the initial connect from a\n // reconnect: log the recovery (mirroring the loss above) and surface it so\n // the caller can flip its state back. Fires for the initial connect too;\n // callers treat `connected: true` idempotently.\n let hasConnected = false\n connection.on('connect', () => {\n if (hasConnected && !silent) {\n logger.info('Requence AMQP reconnected')\n }\n hasConnected = true\n onConnectionStateChange?.({ connected: true })\n })\n\n const connectedPromise = new Promise<void>((resolve, reject) => {\n const unsubscribe = () => {\n clearTimeout(timeout)\n connection.removeListener('connect', handleConnect)\n connection.removeListener('connectFailed', handleConnectFailed)\n }\n\n const timeout = setTimeout(() => {\n handleConnectFailed({\n err: new RequenceConnectionError('Requence connection timeout'),\n })\n }, connectionTimeout)\n\n const handleConnect = () => {\n unsubscribe()\n resolve()\n }\n\n const handleConnectFailed = ({ err }: { err: Error }) => {\n unsubscribe()\n if (\n err.message.startsWith(\n 'Handshake terminated by server: 403 (ACCESS-REFUSED)',\n )\n ) {\n reject(new RequenceConnectionError('Invalid service credentials'))\n } else {\n reject(err)\n }\n }\n\n connection.addListener('connect', handleConnect)\n connection.addListener('connectFailed', handleConnectFailed)\n })\n\n const connectionId = crypto.randomUUID()\n // The dev session this connection belongs to (#108), or `''` outside dev mode.\n //\n // What every surface this connection draws is stamped with, and what a rebuild\n // names to find them again. Scoped to the **session** rather than the\n // connection precisely so it survives the dev process being restarted: the\n // service, the version it overlays and the developer's token are all still the\n // same afterwards, so the surfaces drawn a moment before the restart are still\n // this session's.\n //\n // The token is hashed rather than carried, because this id comes to rest in\n // ui/backend's `task_surface` and a dev overlay key is a personal access token.\n // The service and version stay readable, which is what makes a stored session\n // id diagnosable at all.\n const devSession = devOverlay\n ? `${baseQueue}#${createHash('sha256').update(devOverlay).digest('hex').slice(0, 16)}`\n : ''\n // Derived from the queue this connection actually consumes, overlay suffix\n // included — NOT from the base name. The operator builds the routing key as\n // `service-<node.name>@<node.version>-backchannel-<connectionId>`, and in a\n // dev session ui/backend has rewritten that node's version to\n // `<version>-dev-overlay-<devKey>` (which is how the dispatch reaches this\n // worker in the first place). Anchoring to the base name instead made every\n // inbound backchannel message of a dev-mode service unroutable — the `stop`\n // that terminates a CONTINUOUS generator and, since surfaces, every callback\n // invocation. The unroutable publish then came back through the alternate\n // exchange and was read as a dead connection, so a click on a perfectly live\n // surface killed it (D5's detect-on-interaction, on a false premise).\n const backchannelQueue = `${queue}-backchannel-${connectionId}`\n // Components whose source has already left this connection, keyed\n // `<taskId>:<hash>`. ui/backend stores bundles hash-addressed and that row\n // outlives every render, so only the first render of a component **into a\n // given task** carries the ≤1 MiB source; later ones carry the hash alone.\n // There is no channel to ask ui/backend what it already has (D16: an unknown\n // hash-only render is an error state), so this set is the whole answer.\n //\n // The task is in the key, and not just the hash, because bundle retention is\n // per-task (D19): the last-referent sweep removes a bundle once NO task\n // references it, and a worker that stays connected for days can outlive every\n // task that referenced its component. Keyed by hash alone, every later render\n // from that connection would carry the hash of a bundle nobody stores —\n // permanently, self-healing only on reconnect, with nothing in the retention\n // path able to fix it (at the moment of the sweep the bundle genuinely has no\n // referents). Keyed by task, the first render into any task always carries the\n // source, so the state the sweep can produce is exactly the state a fresh key\n // repairs. It costs one ≤1 MiB transfer per task per component rather than one\n // per connection.\n //\n // Residual, accepted with D16: this records that the source was *published*,\n // not that it was ingested. If the operator discards that render (a\n // superseded epoch after a re-dispatch), a later render of the same component\n // into the same task carries no source and its surface stays an error state\n // until the process reconnects.\n const sentComponents = new Set<string>()\n const generatorTerminators = new Map<string, (reason: string) => void>()\n // Each registry entry keeps the invocation dispatcher of the message that\n // registered the callback. Entries are deleted when that message settles,\n // so a stored dispatcher is live exactly as long as its callback is — this\n // is what lets a nested function in a callback argument reconstruct as\n // invokable (chaining): its invocations egress through the registering\n // message's context (results stream → operator → peer backchannel).\n const callbacks = new Map<\n string,\n {\n callback: (...args: any[]) => void\n onCallbackInvoke: CallbackIngressContext['onCallbackInvoke']\n }\n >()\n\n // Backchannel ingress (concept invariant 2): a callback argument was\n // egress-transformed by the invoking side (files/streams → references,\n // oversized values → claim-checks), so it must rehydrate here before\n // reaching user code. Connection-scoped: the callback owner is typically a\n // CONTINUOUS service whose lifetime differs from any single message, so no\n // per-message signal applies. `onCallbackInvoke` is supplied per call from\n // the registry entry, so nested functions reconstruct invokable.\n // Passthrough consumers (the logic runtime's guest channel) keep byte/callback\n // references raw here too — claim-checks still resolve, but files/streams/\n // callbacks reach the registered callback as their JSON-safe wire objects so\n // they can cross the guest's process boundary.\n const backchannelInbound = createInboundBoundary(\n passthroughByteReferences\n ? { transformer: passthroughInboundTransformer }\n : {},\n )\n\n const channelWrapper = connection.createChannel({\n async setup(channel: ConfirmChannel) {\n if (devOverlay) {\n await channel.assertQueue(queue)\n await channel.bindQueue(queue, 'service', queue)\n }\n await channel.checkExchange(exchange)\n await channel.checkExchange(`${exchange}-retry`)\n await channel.checkQueue(queue)\n await channel.prefetch(prefetch)\n\n await channel.assertQueue(backchannelQueue, {\n exclusive: true,\n })\n\n await channel.bindQueue(backchannelQueue, 'service', backchannelQueue)\n\n await channel.consume(\n backchannelQueue,\n async (message) => {\n const result = backchannelMessageSchema.safeParse(message)\n\n if (!result.success) {\n return\n }\n\n const backchannelMessage = result.data\n\n switch (backchannelMessage.payload.type) {\n case 'stop': {\n generatorTerminators.get(backchannelMessage.messageId)?.(\n 'task stopped',\n )\n break\n }\n case 'callback': {\n const { surface } = backchannelMessage.payload\n const { taskId } = backchannelMessage\n // Reportable only when both halves are here: an interaction names\n // the surface it came from, and a report needs the task to be\n // routed. A peer callback names neither, and its failures belong to\n // its own live message.\n const report =\n surface && taskId\n ? (message: string) =>\n reportInteractionFailure({ taskId, surface, message })\n : () => {}\n\n const entry = callbacks.get(backchannelMessage.payload.callbackId)\n if (!entry) {\n // Said out loud rather than dropped (#106). This is where a\n // connection-bound surface handler lands, and an entry that is\n // gone means the message that registered it has settled — so the\n // click behind it did nothing and nobody was told. Unconditional\n // for the reason the durable arm's misses are: `silent`\n // suppresses connection noise, not a lost interaction. There is\n // no request left to fail (the mutation returned *accepted* long\n // before) and no failure channel here — the backchannel consumes\n // with noAck, outside any message context. For an *interaction*\n // there is now one more place to put it (#107): the surface.\n logger.warn(\n `Requence: dropped an invocation of callback |${backchannelMessage.payload.callbackId}| — nothing is registered under it, so the message that registered it has settled`,\n )\n report(\n 'the process that drew this surface has finished with it, so nothing ran the handler',\n )\n break\n }\n let arg: unknown\n try {\n arg = await backchannelInbound(backchannelMessage.payload.arg, {\n onCallbackInvoke: entry.onCallbackInvoke,\n })\n } catch (error) {\n // The backchannel consumes with noAck and outside any message\n // context, so a failed rehydration has no failure channel.\n // Never hand user code a raw reference — log and drop the\n // invocation instead.\n logger.warn(\n `dropped callback invocation |${backchannelMessage.payload.callbackId}|: argument rehydration failed`,\n error instanceof Error ? error.message : error,\n )\n report(\n 'the interaction could not be delivered: its argument could not be read',\n )\n break\n }\n try {\n // Awaited so an async handler's rejection is caught here rather\n // than becoming an unhandled rejection in the consume callback —\n // which, `noAck` and outside any message context, was the one way\n // a thrown handler could take the whole process down.\n await entry.callback(arg)\n } catch (error) {\n logger.error(\n `Requence: callback |${backchannelMessage.payload.callbackId}| threw:`,\n error instanceof Error\n ? (error.stack ?? error.message)\n : error,\n )\n report(`the handler failed: ${errorText(error)}`)\n }\n break\n }\n }\n },\n {\n noAck: true,\n },\n )\n },\n })\n\n // ChannelWrapper is an EventEmitter; an unhandled 'error' would otherwise\n // propagate. Observe it rather than letting it surface as an uncaught error.\n channelWrapper.on('error', (err: Error) => {\n if (!silent) {\n logger.error('Requence AMQP channel error:', err.message)\n }\n })\n\n /**\n * Say on the surface that this process could not run an interaction (#107).\n *\n * The only feedback channel an interaction has once it has been accepted. The\n * mutation behind a click returns *accepted* long before the invocation reaches\n * here — for a durable handler, possibly a redeploy before — so there is no\n * request to fail, no message to abort, and for a durable handler no connection\n * the viewer ever had. What is left is the surface itself, which the viewer is\n * still looking at.\n *\n * Published on the ordinary result exchange with a marker header and **no**\n * correlation id or index: a handler invocation is not a dispatch of the\n * operator's, so it has no message to be a result FOR, which is exactly why the\n * operator answers this header before everything else on that path.\n *\n * Fire-and-forget, and never fatal: this is the report of a failure, and a\n * failure to report it must not become a second one. Unconditional, `silent`\n * included, for the reason every miss here is logged unconditionally — `silent`\n * suppresses connection noise, not a lost interaction.\n */\n const reportInteractionFailure = (params: {\n taskId: string\n surface: string\n message: string\n }) => {\n void channelWrapper\n .publish(\n exchange,\n '',\n Buffer.from(\n JSON.stringify({\n surface: params.surface,\n // Truncated at the source as well as in the update schema: what keeps\n // this publish bounded is the cut made before it, and a thrown error's\n // message is author text of no bounded length.\n message: params.message.slice(\n 0,\n MAX_SURFACE_INTERACTION_ERROR_CHARS,\n ),\n }),\n ),\n {\n contentType: 'application/json',\n persistent: true,\n headers: {\n taskId: params.taskId,\n [SURFACE_INTERACTION_ERROR_HEADER]: true,\n },\n },\n )\n .catch((error: unknown) => {\n logger.error(\n `Requence: could not report a failed surface interaction on |${params.surface}|:`,\n error instanceof Error ? error.message : error,\n )\n })\n }\n\n /**\n * The dev loop (#108): a rebuilt component is a **bundle swap**, not a render.\n *\n * A rebuild changes which bytes the frame imports and nothing else, so nothing\n * about the render that drew a surface is an input here — not its props, not\n * its handlers, not whether the message that published it is still unsettled.\n * That last one is what the re-issue this replaced could never get past: a\n * deferring handler returns at the defer, taking its callback registry with it,\n * so a deferred form could not be iterated on without starting a new task for\n * every edit. Now the notice names the session and the component, ui/backend\n * repoints the rows, and every surface — a live panel, a deferred form, one\n * on a task that finished last week — swaps identically.\n *\n * Published on the ordinary result exchange with a marker header and **no**\n * correlation id, index or task: a rebuild is not a result for any dispatch of\n * the operator's, which is why the operator answers this header before it looks\n * for either.\n *\n * Fire-and-forget and never fatal, like the failure report above: the dev loop\n * is an addition to a running service, not a reason for one to fall over.\n */\n const publishBundleSwap = (ui: MutableRequenceUI) => {\n const swap: UiRebuild = {\n devSession,\n uiId: ui.id,\n hash: ui.hash,\n // Always, unlike a render's: this hash is new to everyone by definition,\n // and the surfaces this repoints are exactly the ones that would otherwise\n // name a bundle nobody stored.\n source: ui.source,\n }\n\n void channelWrapper\n .publish(exchange, '', Buffer.from(JSON.stringify(swap)), {\n contentType: 'application/json',\n persistent: true,\n headers: { [UI_REBUILD_HEADER]: true },\n })\n .then(() => {\n if (!silent) {\n logger.info(\n `Requence: component |${ui.id}| rebuilt (${ui.hash.slice(0, 12)}) — swapped on every surface of this dev session`,\n )\n }\n })\n .catch((error: unknown) => {\n logger.error(\n `Requence: could not publish the rebuild of |${ui.id}|:`,\n error instanceof Error ? error.message : error,\n )\n })\n }\n\n // Only a dev-mode connection turns the watch on; `createUI` itself registers\n // unconditionally and starts nothing.\n const stopUIWatch = devSession\n ? watchUIRebuilds({\n onRebuild: publishBundleSwap,\n // The watch is process-global; `silent` is this connection's. It\n // reports, we decide.\n onWarning: (warning) => {\n if (!silent) {\n logger.warn(warning)\n }\n },\n })\n : undefined\n\n /**\n * Runs one durable handler invocation (#103): resolve `(uiId, path)` against\n * the components this process registered at module scope, and call the\n * function sitting there in that UI's default props.\n *\n * No context is injected, deliberately — a durable handler reaches whatever it\n * needs (`service.act()`, its own stores) through its own closure, which is\n * the same closure a module-scope function has in any other process of this\n * version. That is what \"durable\" means here.\n *\n * Every miss is **said out loud** rather than dropped: the click that produced\n * it is long gone, the mutation behind it returned *accepted*, and this\n * process is the only party that can tell an author their component named\n * something that does not exist. Unconditional, `silent` included: `silent`\n * suppresses connection noise, not a lost interaction.\n *\n * And every miss that can name a surface is also **recorded on it** (#107),\n * which is the half a viewer can see: this process's stderr is nowhere near the\n * person who pressed the button, least of all for the case that motivated it — a\n * durable handler running minutes later, in an instance the viewer never had a\n * connection to. A malformed payload is the one exception, and necessarily: it\n * is the only miss that cannot say which surface it was for.\n */\n const runHandlerInvocation = async (raw: unknown) => {\n const parsed = surfaceHandlerInvocationSchema.safeParse(raw)\n if (!parsed.success) {\n logger.error(\n 'Requence: dropped a malformed surface handler invocation:',\n parsed.error.message,\n )\n return\n }\n const { taskId, surface, uiId, path, arg } = parsed.data\n const where = `UI |${uiId}| prop |${path.join('.') || '<root>'}| (task |${taskId}|)`\n const report = (message: string) =>\n reportInteractionFailure({ taskId, surface, message })\n\n const ui = findUIById(uiId)\n if (!ui) {\n logger.error(\n `Requence: no component registered as |${uiId}| — dropped a handler invocation for ${where}`,\n )\n report(\n `the service has no component registered as \"${uiId}\", so nothing ran the handler`,\n )\n return\n }\n\n // Resolved against the DEFAULTS, because that is the only place a durable\n // handler can have been written: a function in a render's own props closes\n // over that render's process and never gets a durable reference. An empty\n // path would name the defaults object itself, which is never a function.\n const handler: unknown = getByPath(\n ui.defaults as Record<string, unknown> | undefined,\n path,\n )\n if (typeof handler !== 'function') {\n logger.error(\n `Requence: no handler at ${where} — the component's defaults have ${\n handler === undefined ? 'nothing' : typeof handler\n } there`,\n )\n report(\n `this component has no handler at \"${path.join('.') || '<root>'}\", so nothing ran`,\n )\n return\n }\n\n try {\n await (handler as (value: unknown) => unknown)(arg)\n } catch (error) {\n // Caught here rather than left to the consumer's own catch, which is one\n // frame too far out to know which surface this was: the *report* needs the\n // parsed invocation. Rethrown so that frame still logs the stack and acks.\n report(`the handler failed: ${errorText(error)}`)\n throw error\n }\n }\n\n // The per-version handler queue, consumed alongside the dispatch queue and on\n // a channel of its own: a durable invocation is not a dispatch, and sharing\n // the dispatch channel would put it behind that channel's prefetch — so one\n // long-running LINEAR message would stall every click on the version.\n //\n // Competing consumers by design: a durable handler belongs to the service\n // VERSION, so whichever instance is free serves it, and an invocation with no\n // instance running waits in the queue instead of being lost.\n const handlerQueue = serviceHandlerQueueName(queue)\n const handlerChannelWrapper = connection.createChannel({\n async setup(channel: ConfirmChannel) {\n // Asserted rather than checked, unlike the dispatch queue: ui/backend's\n // provisioner asserts it too (which is what makes it exist BEFORE any\n // instance runs, so an invocation can wait out a redeploy), but a service\n // must not fail to start against a broker whose version assert has not\n // caught up. Both sides declare the same shared literal, because a\n // mismatch is a 406 that kills this channel. In a dev session the queue is\n // this overlay's own, so nobody else asserts it at all, and these\n // arguments are the only ones it ever gets.\n //\n // The TTL is what stops the queue being a mailbox (#116): an invocation\n // nobody consumes expires instead of running whenever someone next\n // deploys, and dead-letters back to the operator so the viewer is told.\n await channel.assertQueue(handlerQueue, SURFACE_HANDLER_QUEUE_ARGUMENTS)\n await channel.bindQueue(handlerQueue, 'service', handlerQueue)\n await channel.prefetch(prefetch)\n await channel.consume(handlerQueue, async (message) => {\n if (!message) {\n return\n }\n try {\n await runHandlerInvocation(JSON.parse(message.content.toString()))\n } catch (error) {\n // A throwing handler is the author's bug and there is no request left\n // to fail (#107 puts it back on the surface). Reported and acked: a\n // requeue would rerun a side-effecting handler forever.\n logger.error(\n 'Requence: surface handler threw:',\n error instanceof Error ? (error.stack ?? error.message) : error,\n )\n }\n safeAck(channel, message)\n })\n },\n })\n\n handlerChannelWrapper.on('error', (err: Error) => {\n if (!silent) {\n logger.error('Requence AMQP handler channel error:', err.message)\n }\n })\n\n const publish = ({\n data,\n outputName,\n messageId,\n priority,\n ...headers\n }: {\n index: number\n data?: unknown\n outputName?: string | null\n messageId: string\n taskId: string\n priority?: number\n version: string\n debugMethod?: 'log' | 'warn' | 'info' | 'error'\n debug?: boolean\n // Marks a `context.render` payload (component + props + surface). Like\n // `debug`, it is a side-channel the operator forwards as a task update\n // rather than graph output — but it rides the ordered dispatch buffer, so\n // two renders of one surface can never be re-ordered into a stale one.\n render?: boolean\n connectionId?: string\n callbackId?: string\n propertyPath?: (string | number)[]\n begin?: boolean\n deferred?: boolean\n done?: boolean\n // Privileged result protocol: `overwrite` marks a data message whose\n // value replaces (instead of merges into) downstream aggregation;\n // `state` marks a nodeStates writeback. The operator honors both only\n // for privileged nodes. Flow through via `...headers`.\n overwrite?: boolean\n state?: boolean\n // Per-attempt id: identifies this consume-handler invocation so the\n // operator can fence a superseded attempt's stragglers on the same\n // messageId. Flows through via `...headers`.\n epoch?: string\n // Who ran this node, stamped on the `begin` publish ONLY (see\n // `buildServiceIdentityHeaders`). The operator freezes these into the\n // NODE_START update; they are display-only and nothing branches on them.\n libVersion?: string\n serviceName?: string\n capabilities?: string\n }) => {\n const { body, contentType } = encodeWireBody(\n data ?? null,\n messageCodecs.get(messageId) ?? 'json',\n )\n\n // Guard the body size before it hits the broker. An oversized publish makes\n // RabbitMQ drop the whole connection, which amqplib reports as a generic\n // \"channel closed\" for every in-flight message — impossible to attribute to\n // size after the fact. Rejecting here yields a precise, catchable error and\n // leaves the connection intact for other messages.\n if (body.byteLength > maxMessageSize) {\n return Promise.reject(\n new PayloadTooLargeError(body.byteLength, maxMessageSize),\n )\n }\n\n return channelWrapper.publish(exchange, '', body, {\n correlationId: messageId,\n contentType,\n persistent: true,\n priority,\n headers: {\n outputName: outputName ?? null,\n connectionId,\n ...headers,\n },\n })\n }\n\n /**\n * Everything a publish on behalf of one message needs, and the whole of what\n * differs between the two publish paths — the main path's consume handler and an\n * `act()` call. Shared by {@link buildSendApi} and {@link buildRender} so the\n * two cannot drift apart: they publish for the same message, through the same\n * boundary, on the same index counter.\n *\n * `epoch`/`priority` are main-path-only (an `act()` call is not a consume\n * attempt) and are omitted from the published headers when absent, keeping the\n * deferred path's output byte-identical to what it always was.\n */\n type PublishDeps = {\n outbound: OutboundBoundary\n registerCallback: (callback: (...args: any[]) => void) => {\n sourceId: string\n callbackId: string\n }\n taskId: string\n messageId: string\n nextIndex: () => number\n epoch?: string\n priority?: number\n // act() only: wait for the deferring message's own processing to finish.\n gate?: () => Promise<void>\n }\n\n // The privileged send API (unit 05 headers), shared by the main-path handler\n // context and act()'s ActorApi: imperative data/state publishes through the\n // caller's outbound boundary, enrolled in its ledger so `settle()` gates the\n // done marker on them — a final state emission mechanically flushes before\n // `done`.\n const buildSendApi = (deps: PublishDeps) => {\n const base = {\n ...(deps.epoch === undefined ? {} : { epoch: deps.epoch }),\n ...(deps.priority === undefined ? {} : { priority: deps.priority }),\n }\n return {\n async sendToOutput(\n outputName: string,\n data: unknown,\n options?: { overwrite?: boolean },\n ) {\n await deps.gate?.()\n deps.outbound.track(\n publish({\n index: deps.nextIndex(),\n version,\n messageId: deps.messageId,\n taskId: deps.taskId,\n data: await deps.outbound.send(data, {\n outputName: outputName as string | null,\n onCallback: deps.registerCallback,\n }),\n outputName: outputName as string | null,\n // only set when requested — omitted publishes stay identical\n ...(options?.overwrite ? { overwrite: true } : {}),\n ...base,\n }),\n )\n },\n async send(data: unknown, options?: { overwrite?: boolean }) {\n await deps.gate?.()\n deps.outbound.track(\n publish({\n index: deps.nextIndex(),\n version,\n messageId: deps.messageId,\n taskId: deps.taskId,\n data: await deps.outbound.send(data, {\n outputName: null,\n onCallback: deps.registerCallback,\n }),\n ...(options?.overwrite ? { overwrite: true } : {}),\n ...base,\n }),\n )\n },\n async sendState(state: unknown) {\n await deps.gate?.()\n deps.outbound.track(\n publish({\n // out-of-band like callback publishes: state bypasses the\n // operator's ordered dispatch buffer, so it must not consume a\n // publishIndex slot — `done` would otherwise wait on a gap.\n index: 0,\n version,\n messageId: deps.messageId,\n taskId: deps.taskId,\n // through the outbound boundary: a large state blob offloads\n // via claim-check like any large body, and the tracked publish\n // is settled before `done` goes out.\n data: await deps.outbound.send(state, { outputName: null }),\n state: true,\n ...base,\n }),\n )\n },\n }\n }\n\n // The render publish, shared by `context.render` on the main path and\n // `send.render` inside `act()` (#70). Everything that differs between the two\n // paths is a dep — the index counter, the callback registrar, the attempt\n // headers, and act()'s gate on the deferring message's own processing — so a\n // surface behaves identically whoever published it, which is what makes the\n // dev loop, the hash bookkeeping and the liveness rule path-agnostic.\n const buildRender = (deps: PublishDeps) => {\n /**\n * One function prop → one handler reference (#103). The **path decides the\n * lifetime**, because the path is where the function was written:\n *\n * - `defaults.*` — module scope. Any instance of this version can run it,\n * now or after a redeploy, so the reference names only the UI and the prop\n * and the invocation goes to the version's handler queue. Nothing is\n * registered here: there is nothing to keep alive, and that is the point.\n * - `props.*` — written at this render call, closing over the running\n * handler. Only this process can run it, so it registers in the publishing\n * message's own registry and dies with it, exactly as a callback does —\n * including the refusal on a LINEAR handler, whose registry entries are\n * gone the moment it returns.\n *\n * The path the reference carries is relative to the **props the component\n * receives**, not to the payload: the two layers fold into one object at\n * ingestion (#102), and the browser names a path in what it was served.\n */\n const registerSurfaceHandler = (\n ui: RequenceUI,\n handler: (...args: unknown[]) => void,\n payloadPath: ReadonlyArray<string | number>,\n ): SurfaceHandlerObject => {\n const [layer, ...path] = payloadPath\n if (layer === 'defaults') {\n return {\n __REQUENCE_type: SURFACE_HANDLER_TAG,\n lifetime: 'durable',\n uiId: ui.id,\n path,\n }\n }\n if (layer !== 'props') {\n // Only the two author-supplied layers can hold a function; anything\n // else is the SDK's own payload and a function there is a bug here.\n throw new Error(\n `a function in a render payload is only a handler under props or defaults (found at \"${payloadPath.join('.')}\")`,\n )\n }\n const { sourceId, callbackId } = deps.registerCallback(handler)\n return {\n __REQUENCE_type: SURFACE_HANDLER_TAG,\n lifetime: 'connection',\n uiId: ui.id,\n path,\n connectionId: sourceId,\n handlerId: callbackId,\n }\n }\n\n const renderSurface = (params: {\n ui: RequenceUI\n props: unknown\n surfaceId: string\n }): void => {\n // The index is taken NOW, not when the serialization resolves: the\n // operator dispatches a message's results in index order, so\n // allocating here is what makes two renders of one surface arrive\n // in call order. The cost is a hole in the buffer if the\n // serialization fails — moot for a message that settles: the publish is\n // tracked, so the same failure fails the node at the caller's settle gate.\n const index = deps.nextIndex()\n // Per (task, component), never per component: see `sentComponents`. The\n // hash is read at call time, not at registration, because the dev loop\n // rewrites it in place (D10).\n const sentKey = `${deps.taskId}:${params.ui.hash}`\n const withSource = !sentComponents.has(sentKey)\n if (withSource) {\n sentComponents.add(sentKey)\n }\n\n const issue = () =>\n deps.outbound\n .send(\n {\n // `id` rides along on every render, source-carrying or not: it is\n // what a dev-loop bundle swap addresses the surface by (#108), and\n // the surface row it lands on is last-write-wins.\n component: withSource\n ? {\n id: params.ui.id,\n hash: params.ui.hash,\n source: params.ui.source,\n }\n : { id: params.ui.id, hash: params.ui.hash },\n props: params.props,\n // Restated on every render, and deliberately NOT merged into the\n // props above (#102): the receiver folds them *under* the surface's\n // stored props, so a default is overridden by anything any render\n // of that surface ever said, while this render's props override\n // everything. Merging here — what #101 did — would collapse the two\n // ranks into one and let a default clobber an earlier override.\n //\n // Read off the handle at call time, like the hash, so the next\n // render after a rebuild carries whatever it changed them to.\n // Omitted entirely when the component declared none, keeping that\n // payload byte-identical to what it always was.\n ...(params.ui.defaults === undefined\n ? {}\n : { defaults: params.ui.defaults }),\n surfaceId: params.surfaceId,\n // Stamped on every surface this connection draws, so a rebuild can\n // find them again and repoint them (#108) — and find only them: a\n // developer's edit must never reach a production surface of the\n // same component. `null` outside a dev overlay, which is every\n // render a deployed service makes.\n devSession: devSession || null,\n },\n {\n outputName: null,\n // The claim-check may offload an oversized render — but\n // never the bundle: the operator parses `component.hash`\n // out of the body, so a reference there is unreadable.\n // Pinned rather than left to the sizes falling the right\n // way (props larger than the ≤1 MiB source), which only\n // holds while the task's threshold is the 4 MiB default.\n //\n // `defaults` is pinned because it is the base layer of the\n // surface's fold — offloaded, it would silently take every prop\n // the service never restates out of the surface, and every\n // durable handler with them. `props` stays the only candidate,\n // which is what makes an oversized render a named error state\n // rather than a broken surface.\n inlineKeys: ['component', 'defaults'],\n // Switches this send onto the render egress chain, where a\n // function is a surface handler rather than a peer callback\n // (#103). Which of the two lifetimes it gets is decided by where\n // it was written, which the walk reports as the path.\n onSurfaceHandler: (handler, path) =>\n registerSurfaceHandler(params.ui, handler, path),\n },\n )\n .then((data) =>\n publish({\n index,\n version,\n messageId: deps.messageId,\n taskId: deps.taskId,\n data,\n render: true,\n // Omitted rather than passed as `undefined` when absent, so\n // act()'s publishes keep the header set they always had.\n ...(deps.priority === undefined\n ? {}\n : { priority: deps.priority }),\n ...(deps.epoch === undefined ? {} : { epoch: deps.epoch }),\n }),\n )\n\n // The gate is awaited before the payload is built, never before the index\n // is taken — the slot has to be reserved in call order even when the\n // publish itself has to wait.\n const gated = deps.gate?.()\n deps.outbound.track(\n (gated ? gated.then(issue) : issue()).catch((error: unknown) => {\n // The source never left, so the next render of this component into\n // this task must carry it again — otherwise ui/backend would receive a\n // hash it has never seen and show an error state.\n if (withSource) {\n sentComponents.delete(sentKey)\n }\n throw error\n }),\n )\n }\n\n return renderSurface\n }\n\n channelWrapper.addSetup(async (channel: ConfirmChannel) => {\n channel.consume(queue, async (message) => {\n if (!message) {\n return\n }\n\n let publishIndex = 0\n let acked = false\n let terminated = false\n const registeredCallbackIds = new Set<string>()\n let resolveActiveMessage = () => {}\n // Captured for the finally block; header parsing now happens inside the\n // try so a malformed header goes through the error handling below instead\n // of throwing out of this async consumer as an unhandled rejection.\n let messageIdForCleanup: string | undefined\n // One epoch per consume-handler invocation (declared out here so the\n // catch-branch republishes can stamp it too). On redelivery/reconnect a\n // second invocation gets a fresh epoch, letting the operator tell the\n // attempts apart and fence the superseded one.\n const epoch = crypto.randomUUID()\n\n try {\n const { messageId, taskId, mode } = headerSchema.parse(message)\n messageIdForCleanup = messageId\n\n // The capability gate, ahead of everything the dispatch could ask of\n // this build — including its own decoding. A requirement stated in the\n // body would be unreadable exactly when it matters, so it rides in the\n // headers and is checked here, before `payloadSchema` touches the bytes.\n //\n // An empty requirement (every message published before this existed)\n // passes untouched.\n const unsupported = unsupportedCapabilities(\n readRequiredCapabilities(message.properties.headers),\n )\n if (unsupported.length > 0) {\n throw new UnsupportedCapabilityError(unsupported)\n }\n\n // Recorded before anything can publish, so every reply on this message —\n // including one from an error path — echoes the codec it arrived under.\n const dispatchCodec = wireCodecFromContentType(\n message.properties.contentType,\n )\n messageCodecs.set(messageId, dispatchCodec)\n\n let deferred = false\n let deferredReason: string | null = null\n\n const messageExecution = Promise.withResolvers<void>()\n activeMessages.set(messageId, messageExecution.promise)\n messageExecution.promise.then(() => {\n activeMessages.delete(messageId)\n })\n resolveActiveMessage = () => {\n messageExecution.resolve()\n }\n\n const payload = payloadSchema.parse(message)\n\n // The per-message abort controller is hoisted out of\n // createContextHelper so the outbound boundary can share its signal.\n const abortController = new AbortController()\n\n // One callback registrar for every egress sub-path (result, deferred\n // send, callback arg). Registered callbacks carry this message's\n // dispatcher so nested functions in their invocation arguments\n // reconstruct invokable (chaining).\n const registerCallback = (callback: (...args: any[]) => void) => {\n const callbackId = crypto.randomUUID()\n registeredCallbackIds.add(callbackId)\n callbacks.set(callbackId, {\n callback,\n onCallbackInvoke: dispatchInvocation,\n })\n return { sourceId: connectionId, callbackId }\n }\n\n // The component's single outbound boundary: owns ctx construction,\n // the background-upload ledger (done-gate) and the fail policy.\n // Fail-hard sends surface via outbound.settle() before the done\n // marker + ack; best-effort (log) sends degrade to warnings.\n const outbound = createOutboundBoundary({\n uploadUrl: payload.options.uploadUrl,\n streamUrl: payload.options.streamUrl,\n maxPayloadSize: payload.options.maxPayloadSize,\n maxFileSize: payload.options.maxFileSize,\n // Replies echo the dispatch codec, so the claim-check must measure\n // with it too — measured size == published size.\n wireCodec: dispatchCodec,\n signal: abortController.signal,\n warn: (msg, error) =>\n logger.warn(\n `${msg} (task ${taskId})`,\n error instanceof Error ? error.message : (error ?? ''),\n ),\n })\n\n // This message's single invocation egress: callback arguments are\n // real node output (they carry an outputName), so they go through the\n // same boundary as results — nested files offload, nested functions\n // become callbacks. The send + publish are tracked in the boundary's\n // ledger, so a failure fails the task at the settle gate. Used both\n // for callbacks arriving in this message's input (via\n // createContextHelper) and for callbacks this message registers\n // (chained invocations dispatched from the backchannel).\n const dispatchInvocation = (params: {\n sourceId: string\n callbackId: string\n outputName: string | null\n propertyPath: (string | number)[]\n arg: unknown\n }) => {\n outbound.track(\n outbound\n .send(params.arg, {\n outputName: params.outputName,\n onCallback: registerCallback,\n })\n .then((data) =>\n publish({\n index: 0,\n version,\n taskId,\n messageId,\n data,\n outputName: params.outputName,\n connectionId: params.sourceId,\n callbackId: params.callbackId,\n propertyPath: params.propertyPath,\n epoch,\n }),\n ),\n )\n }\n\n // This message's publish context: one index counter, one boundary, one\n // attempt. Shared by the privileged send API below and by the render.\n const publishDeps: PublishDeps = {\n outbound,\n registerCallback,\n taskId,\n messageId,\n nextIndex: () => publishIndex++,\n epoch,\n priority: message.properties.priority,\n }\n\n const onRender = buildRender({\n ...publishDeps,\n // The one deliberate difference on this path: a function written at\n // the render call becomes a reference to THIS message's registry, so\n // it is live exactly as long as the message — and a non-generator\n // handler cannot hold one at all, because its registry entries go the\n // moment it returns.\n //\n // A function in the UI's DEFAULTS never reaches here: it is durable,\n // registers nothing, and is therefore the one handler a LINEAR\n // handler can publish — which is exactly what lets a form outlive the\n // process that drew it (#103).\n //\n // Worded for the surface author rather than reusing the result path's\n // callback wording: what this catches is a function in RENDER PROPS,\n // and naming the fix matters more than naming the rule. The tempting\n // shape is a promise the render's own handler resolves — which would\n // hold the message open for a human-speed wait, on an unacked\n // delivery a redeploy hands to another instance. `defer` plus a\n // durable default is that same form, written so it survives.\n registerCallback: canRegisterCallbacks\n ? registerCallback\n : () => {\n throw new Error(\n 'A LINEAR version handler may not register function props — the registration dies when the handler returns. To wait for a viewer, call context.defer() and declare the handler in the UI defaults instead: a durable handler outlives this process.',\n )\n },\n })\n\n const [extendedContext, terminatePromise] = (await createContextHelper({\n taskId,\n // Rehydration (FileObject/StreamObject -> RequenceFile/RequenceStream)\n // happens inside createContextHelper via its inbound boundary — the\n // signal-aware pass whose instances reach the handler.\n input: payload.input,\n configuration: payload.configuration,\n abortController,\n passthroughByteReferences,\n // Privileged send API on the handler ctx (runtime-only, hidden from\n // the ContextHelper type): shares this message's outbound boundary,\n // publishIndex counter, epoch and priority.\n sends: {\n ...buildSendApi(publishDeps),\n // Passthrough consumers hold raw callback wire refs — this is\n // their invocation egress, routed through the same\n // dispatchInvocation as a rehydrated callback call (fire-and-\n // forget; the outbound ledger settles the publish).\n invokeCallback: (ref, arg) =>\n dispatchInvocation({\n sourceId: ref.sourceId,\n callbackId: ref.callbackId,\n outputName: ref.outputName,\n propertyPath: ref.propertyPath,\n arg,\n }),\n options: payload.options,\n },\n onLog(debugMethod, data) {\n // Best-effort: a debug log must never fail the task. The boundary\n // sanitizes the payload (functions/opaque instances → labels),\n // degrades offload failures to warnings, and keeps the done-gate\n // waiting for the upload without letting it fail the task. On a\n // transform error it resolves `undefined` and nothing is published.\n void outbound.send(data, { bestEffort: true }).then((mapped) => {\n if (mapped === undefined) {\n return\n }\n publish({\n index: publishIndex++,\n version,\n messageId,\n taskId,\n data: mapped,\n debugMethod,\n priority: message.properties.priority,\n debug: true,\n epoch,\n })\n })\n },\n onRender,\n onDefer(reason) {\n deferred = true\n deferredReason = reason || null\n\n return obfuscate(\n taskId,\n messageId,\n payload.options.uploadUrl ?? '',\n payload.options.streamUrl ?? '',\n payload.options.maxPayloadSize?.toString() ?? '',\n payload.options.maxFileSize?.toString() ?? '',\n )\n },\n onCallback: dispatchInvocation,\n })) as unknown as [\n MessageHandlerContext<V>,\n PromiseWithResolvers<string>,\n ]\n\n await publish({\n index: publishIndex++,\n version,\n messageId,\n taskId,\n priority: message.properties.priority,\n begin: true,\n epoch,\n // The one stamp per node execution: this build, this box. It becomes\n // the NODE_START update's `service`, which is written once and never\n // re-derived — so anything absent here is lost for that run.\n ...buildServiceIdentityHeaders({\n libVersion: libVersion(),\n name,\n }),\n })\n\n if (isMessageHandlerGenerator(messageHandler)) {\n if (mode === 'CONTINUOUS') {\n // CONTINUOUS: ACK immediately, operator watchdog supervises. A\n // LINEAR message stays unacked until done — prefetch keeps\n // bounding concurrent work and the broker redelivers on a crash.\n safeAck(channel, message)\n acked = true\n }\n\n const generator = messageHandler(extendedContext)\n const terminationPromise = Promise.withResolvers<typeof abortSymbol>()\n generatorTerminators.set(messageId, (reason) => {\n terminated = true\n // Suppress native AbortError that may reject generator.return() when\n // context.terminated.signal fires and cancels a pending await inside\n // the generator (e.g. node:timers/promises setTimeout with { signal }).\n ;(generator.return() as Promise<unknown>).catch(\n (error: unknown) => {\n if (\n terminated &&\n error instanceof Error &&\n error.name === 'AbortError' &&\n !(error instanceof AbortError)\n ) {\n return\n }\n throw error\n },\n )\n terminationPromise.resolve(abortSymbol)\n terminatePromise.resolve(reason)\n })\n\n await handlerStorage.run(\n extendedContext as ContextHelper,\n async () => {\n while (true) {\n type IterResult = IteratorResult<\n MessageHandlerReturnValue<V, null>,\n void | MessageHandlerReturnValue<V, null>\n >\n // Catch native AbortError from context.terminated.signal so\n // generator implementations don't need their own try/catch.\n const nextPromise = Promise.resolve(generator.next()).then(\n (r) => r,\n (error: unknown) => {\n if (\n terminated &&\n error instanceof Error &&\n error.name === 'AbortError' &&\n !(error instanceof AbortError)\n ) {\n return { value: undefined, done: true } as IterResult\n }\n throw error\n },\n )\n const next = await Promise.race([\n terminationPromise.promise,\n nextPromise,\n ])\n if (next === abortSymbol) {\n break\n }\n\n const { value: result, done } = next\n\n if (deferred) {\n deferred = false\n logger.warn(\n 'returning a value in a deferred message resets the deferred status',\n )\n }\n\n const { value: rawValue, outputName } =\n unwrapOutputValue(result)\n const value = await outbound.send(rawValue, {\n outputName,\n onCallback: registerCallback,\n })\n\n if (!done || typeof value !== 'undefined') {\n await publish({\n index: publishIndex++,\n version,\n messageId,\n taskId,\n data: value,\n priority: message.properties.priority,\n outputName,\n epoch,\n })\n }\n\n if (done) {\n break\n }\n }\n },\n )\n } else {\n const result = await handlerStorage.run(\n extendedContext as ContextHelper,\n () => messageHandler(extendedContext),\n )\n const { value: rawValue, outputName } = unwrapOutputValue(result)\n const value = await outbound.send(rawValue, {\n outputName,\n onCallback: () => {\n throw new Error(\n 'callbacks can only be used in generator functions',\n )\n },\n })\n if (deferred && value) {\n logger.warn(\n 'returning a value in a deferred message resets the deferred status',\n )\n deferred = false\n }\n\n if (!deferred || value) {\n await publish({\n index: publishIndex++,\n version,\n messageId,\n taskId,\n data: value,\n priority: message.properties.priority,\n outputName,\n epoch,\n })\n }\n }\n\n await new Promise<void>((resolve, reject) => {\n setImmediate(async () => {\n try {\n // The boundary's settle gate: waits for every tracked background\n // upload/publish, then throws an AggregateError on any fail-hard\n // failure — which surfaces here and reaches the outer catch ->\n // exception republish -> throwServiceError -> failNode. The done\n // marker + ack only happen once every upload succeeded.\n if (!deferred) {\n await outbound.settle()\n }\n\n await publish({\n index: publishIndex++,\n version,\n messageId,\n taskId,\n data: deferredReason,\n priority: message.properties.priority,\n deferred,\n done: !deferred,\n epoch,\n })\n\n if (!acked) {\n safeAck(channel, message)\n }\n resolve()\n } catch (error) {\n reject(error)\n }\n })\n })\n } catch (error) {\n if (error instanceof SkipError) {\n if (!acked) {\n safeNack(channel, message)\n }\n return\n }\n if (error instanceof RetryError) {\n if (!acked) {\n safeAck(channel, message)\n }\n const properties: Options.Publish = {\n ...message.properties,\n expiration: error.delay || 1_000, // 1s\n }\n channelWrapper\n .publish(\n `${exchange}-retry`,\n version, // to other services\n message.content,\n properties,\n )\n .catch((publishError: unknown) => {\n if (!silent) {\n logger.error(\n 'Failed to republish message for retry:',\n publishError,\n )\n }\n })\n\n return\n }\n\n // A refusal, not a failure: this box is the wrong one, the message is\n // fine. It goes back by REPUBLISHING to `<exchange>-retry`, never by\n // nacking, because a nack can carry no rejection count and a classic\n // queue offers none either — see `CAPABILITY_HEADER_KEYS.mismatch` in\n // `@requence/helpers/protocol` for the full argument, and this file's\n // spec, which pins it. The republish reaches the operator's error\n // consumer, which already counts attempts, delays and fails the node.\n if (error instanceof UnsupportedCapabilityError) {\n if (!silent) {\n logger.error(error.message)\n }\n\n if (!acked) {\n safeAck(channel, message)\n }\n channelWrapper\n .publish(\n `${exchange}-retry`,\n 'operator', // back to operator\n // The dispatch verbatim: a reroute re-dispatches these bytes, and\n // this build never decoded them.\n message.content,\n {\n ...message.properties,\n headers: {\n ...message.properties.headers,\n version,\n [CAPABILITY_HEADER_KEYS.mismatch]: true,\n index: publishIndex++,\n 'error-message': error.message,\n },\n },\n )\n .catch((publishError: unknown) => {\n if (!silent) {\n logger.error(\n 'Failed to publish capability mismatch message:',\n publishError,\n )\n }\n })\n\n return\n }\n\n if (error instanceof AbortError && error.message.length > 0) {\n if (!acked) {\n safeAck(channel, message)\n }\n channelWrapper\n .publish(\n `${exchange}-retry`,\n 'operator', //back to operator\n error.message,\n {\n ...message.properties,\n contentType: 'text/plain',\n headers: {\n ...message.properties.headers,\n index: publishIndex++,\n abort: true,\n },\n },\n )\n .catch((publishError: unknown) => {\n if (!silent) {\n logger.error('Failed to publish abort message:', publishError)\n }\n })\n\n return\n }\n\n // Native AbortError thrown when context.terminated.signal fires\n // (e.g. node:timers/promises setTimeout with { signal: context.terminated.signal }).\n // Only suppress when actually in a terminated state — otherwise a\n // different AbortSignal caused the error and it should propagate.\n if (\n terminated &&\n error instanceof Error &&\n error.name === 'AbortError' &&\n !(error instanceof AbortError)\n ) {\n if (!acked) {\n safeAck(channel, message)\n }\n return\n }\n\n if (error instanceof Error) {\n if (!silent) {\n logger.error('Encountered an error inside service handler:')\n logger.error(error)\n }\n\n if (!acked) {\n safeAck(channel, message)\n }\n channelWrapper\n .publish(\n `${exchange}-retry`,\n 'operator', // back to operator\n message.content,\n {\n ...message.properties,\n headers: {\n ...message.properties.headers,\n version,\n exception: true,\n index: publishIndex++,\n 'error-message': error.message || 'error in service handler',\n },\n },\n )\n .catch((publishError: unknown) => {\n if (!silent) {\n logger.error(\n 'Failed to publish exception message:',\n publishError,\n )\n }\n })\n\n return\n }\n } finally {\n if (messageIdForCleanup) {\n generatorTerminators.delete(messageIdForCleanup)\n // Bounded with the delivery rather than left to accumulate. A publish\n // that outlives the handler — a deferred message's later send — then\n // falls back to JSON, which the operator decodes correctly off the\n // header. It loses the size win for that one message and nothing else:\n // degrading to JSON is always safe, which is why the fallback is JSON\n // and not \"the last codec we saw\".\n messageCodecs.delete(messageIdForCleanup)\n }\n registeredCallbackIds.forEach((id) => callbacks.delete(id))\n resolveActiveMessage()\n }\n })\n })\n\n const activeMessageKeys = new Set<string>()\n const api: ConnectionApi<V> = {\n close: async () => {\n stopUIWatch?.()\n await handlerChannelWrapper.close()\n await channelWrapper.close()\n await connection.close()\n },\n open: () => connectedPromise.then(() => api),\n\n async act(messageKey, actor) {\n if (activeMessageKeys.has(messageKey)) {\n throw new Error('a defer key can only be used once')\n }\n\n activeMessageKeys.add(messageKey)\n\n let publishIndex = 0\n const { taskId, messageId, ...options } =\n messageKeySchema.parse(messageKey)\n\n const activeMessage = async () => {\n if (activeMessages.has(messageId)) {\n await activeMessages.get(messageId)\n }\n }\n\n const registeredCallbackIds = new Set<string>()\n // The deferred path's own outbound boundary: its ledger replaces the\n // old donePromises/uploadErrors pair — errors are caught at\n // registration time (nothing sits unhandled during long generator\n // iteration) and surfaced by settle() after the loop.\n const outbound = createOutboundBoundary(options)\n const registerCallback = (callback: (...args: any[]) => void) => {\n const callbackId = crypto.randomUUID()\n registeredCallbackIds.add(callbackId)\n callbacks.set(callbackId, {\n callback,\n onCallbackInvoke: dispatchInvocation,\n })\n return { sourceId: connectionId, callbackId }\n }\n\n // Deferred-path analogue of the main path's dispatchInvocation: chained\n // invocations of callbacks registered here egress through this deferred\n // message's context (no epoch, matching its other publishes).\n const dispatchInvocation = (params: {\n sourceId: string\n callbackId: string\n outputName: string | null\n propertyPath: (string | number)[]\n arg: unknown\n }) => {\n outbound.track(\n outbound\n .send(params.arg, {\n outputName: params.outputName,\n onCallback: registerCallback,\n })\n .then((data) =>\n publish({\n index: 0,\n version,\n taskId,\n messageId,\n data,\n outputName: params.outputName,\n connectionId: params.sourceId,\n callbackId: params.callbackId,\n propertyPath: params.propertyPath,\n }),\n ),\n )\n }\n\n // This act() call's publish context: its own index counter, its own\n // callback registry, its own active-message gate, and no attempt headers —\n // an acting process is not a consume attempt. Both the send API and the\n // render read it, so the two cannot disagree about which message they\n // publish for.\n const publishDeps: PublishDeps = {\n outbound,\n registerCallback,\n taskId,\n messageId,\n nextIndex: () => publishIndex++,\n gate: activeMessage,\n }\n\n const renderSurface = buildRender(publishDeps)\n\n const sendApi = {\n ...buildSendApi(publishDeps),\n // The live window a deferred node gets (#70): the same render as the\n // main path, publishing into the same last-write-wins surface — so a\n // re-attach after a restart replaces the stale one, with fresh callbacks\n // registered here rather than in a message context that no longer\n // exists. The lock against a second instance doing this concurrently is\n // the author's (D9); see `ConnectionApi.act`.\n render(\n ui: RequenceUI,\n props: unknown,\n renderOptions?: { surfaceId?: string },\n ) {\n // The default mirrors `context.render` in helpers.ts — the public\n // shape of a render is the same on both paths.\n renderSurface({\n ui,\n props,\n surfaceId: renderOptions?.surfaceId ?? DEFAULT_SURFACE_ID,\n })\n },\n async abort(error: string | Error) {\n await activeMessage()\n channelWrapper.publish(\n `${exchange}-retry`,\n 'operator',\n error instanceof Error ? error.message : error,\n {\n persistent: true,\n correlationId: messageId,\n expiration: 0,\n priority: 0,\n contentType: 'text/plain',\n headers: {\n taskId,\n index: publishIndex++,\n abort: true,\n },\n },\n )\n },\n }\n\n const result = await actor(sendApi as ActorApi<V>)\n\n if (\n result != null &&\n typeof result === 'object' &&\n (Symbol.asyncIterator in result || Symbol.iterator in result)\n ) {\n // Generator: iterate and send each yielded value\n const iterable = result as AsyncIterable<unknown> | Iterable<unknown>\n for await (const value of iterable) {\n if (value !== undefined) {\n await sendApi.send(value)\n }\n }\n } else if (result !== undefined) {\n await sendApi.send(result)\n }\n\n await new Promise((resolve) => setImmediate(resolve))\n await activeMessage()\n\n try {\n // Settle gate: waits while sends enqueue more sends, then throws an\n // AggregateError on any failed background upload or publish.\n await outbound.settle()\n } catch (error) {\n // Do not mark the message done with a dangling reference. Signal\n // failure over the deferred-path error channel (abort -> operator\n // fails the node) and throw so act()'s caller sees it too.\n registeredCallbackIds.forEach((id) => callbacks.delete(id))\n const first =\n error instanceof AggregateError && error.errors[0] instanceof Error\n ? error.errors[0]\n : error instanceof Error\n ? error\n : new Error(String(error))\n await sendApi.abort(first)\n activeMessageKeys.delete(messageKey)\n throw error\n }\n\n registeredCallbackIds.forEach((id) => callbacks.delete(id))\n\n await publish({\n index: publishIndex++,\n version,\n messageId,\n taskId,\n done: true,\n })\n\n activeMessageKeys.delete(messageKey)\n },\n }\n\n return api\n}\n",
|
|
19
|
+
"import { Buffer } from 'node:buffer'\n\nimport { Packr, addExtension } from 'msgpackr'\n\n/**\n * THE SHARED MSGPACK LAYER.\n *\n * Three things live here, and only these three:\n *\n * 1. `MSGPACK_EXTENSION_IDS` — the ONE allocation table for msgpack extension\n * type ids used anywhere in this repo.\n * 2. `packCommand` / `unpackCommand` — the AMQP task-command codec, shared by its\n * two parties: `@requence/task-builder` publishes, `@requence/operator`\n * consumes.\n * 3. `packWire` / `unpackWire` / `wireByteLength` — the high-volume AMQP wire\n * codec (service dispatch, service results, task updates). Its parties span\n * two languages, so unlike (2) it is a deliberately narrow, portable subset.\n *\n * It is its own subpath export (`@requence/helpers/msgpack`) so the msgpackr\n * dependency reaches only the packages that actually encode. Twelve packages\n * depend on `@requence/helpers`; most of them do not touch either codec and must\n * not carry a msgpack library into their bundle.\n *\n * Both codecs live in ONE module because `addExtension` is process-global (see\n * `MSGPACK_EXTENSION_IDS`). Splitting them would put the allocation table out of\n * sight of one of its two users, which is exactly the failure the table exists\n * to prevent.\n */\n\n/**\n * Extension type ids, allocated ONCE for the whole repo.\n *\n * **`addExtension` is process-global, not per-`Packr`.** Every instance in a\n * process shares one registry, so two codecs that pick the same id do not get two\n * namespaces — the second registration WINS and the first class silently decodes\n * as the second one. No error, no warning: a `NodeTree` comes back as a\n * `ReferenceCounter` and fails much later, somewhere unrelated. That is why the\n * numbers live in one table instead of next to each `addExtension` call.\n *\n * Ids 1 and 2 are also part of the stored Redis snapshot format, so renumbering\n * either one invalidates every live snapshot (a fleet-wide loud discard and\n * restart — there is no migration path, per the repo no-legacy-support policy).\n * Treat all of these as frozen; allocate a NEW number for anything new.\n */\nexport const MSGPACK_EXTENSION_IDS = {\n /** `@requence/operator`'s `ReferenceCounter` — snapshot path only. */\n referenceCounter: 1,\n /** `NodeTree` — snapshot path only; a command carries a `treeList`. */\n nodeTree: 2,\n /**\n * `URL` — registered below, because BOTH paths need it, and they need OPPOSITE\n * behaviour. See the registration for how one id serves both.\n */\n url: 3,\n} as const\n\n/**\n * Set for the duration of a `packWire` call, so the process-global `URL` extension\n * below can tell which codec is asking. `pack` is synchronous, so this cannot\n * interleave with another encode.\n *\n * Declared above the registration because `addExtension` reads `type` immediately.\n */\nlet packingForWire = false\n\n// THIS EXTENSION BELONGS TO THE SNAPSHOT AND COMMAND CODECS, NOT TO THE WIRE CODEC.\n// It exists because those two replaced superjson, which carried a `URL`;\n// structured-clone mode does not, so without this a `URL` in task input silently\n// becomes a string in transit — the same defect the `Date` handling prevents.\n//\n// The wire codec replaced `JSON.stringify`, which HAS no concept of a `URL` and\n// renders one as its href string. So it wants the opposite answer — and it cannot\n// simply decline this extension, because `addExtension` writes into module-level\n// arrays that every `Packr` in the process reads. There is no per-instance registry.\n//\n// Hence the getter, which is the wire codec's ONLY intrusion here. msgpackr's two\n// halves read `type` differently, and that is what lets one registration serve both:\n//\n// - `pack` reads it on EVERY call — `if (extension.type)` decides whether the ext\n// tag is written. `undefined` skips the tag, so `write`'s return value is encoded\n// as an ordinary string: exactly `JSON.stringify`'s output, with no pre-pack walk.\n// - `unpack` reads it ONCE, at registration (`currentExtensions[type] = …`), so the\n// decoder always knows id 3 and a command still round-trips to a real `URL`.\n//\n// Nothing about the snapshot or command format changes. `index.spec.ts` pins that:\n// a command still emits `d40300` and decodes to a `URL`, `packWire` never latches the\n// flag, and no ext tag reaches the wire — so a msgpackr release that started caching\n// `type` fails there rather than shipping undecodable bytes to a Python service.\naddExtension({\n Class: URL,\n get type() {\n return packingForWire ? undefined : MSGPACK_EXTENSION_IDS.url\n },\n write: (v: URL) => v.href,\n read: (href: string) => new URL(href),\n} as Parameters<typeof addExtension>[0])\n\n// `structuredClone: true` carries `Map`, `Set`, `Date`, `RegExp`, `Error`,\n// `BigInt`, typed arrays and `undefined` in the format itself, so there is no\n// annotation pass — which is the whole reason this beats superjson. `Map`\n// insertion order survives.\n//\n// Known and accepted difference from superjson: msgpack has no signed zero, so\n// `-0` arrives as `0`. No extension can fix it — the format has one zero.\nconst packr = new Packr({ structuredClone: true })\n\n/**\n * Encodes a task command (`CREATE` / `ABORT`) for the AMQP command queue.\n *\n * **Both parties must agree, and there is no negotiation on this queue.** A\n * command encoded by one codec and read by another does not degrade — it fails to\n * parse, and `consumers/tasks.ts` terminally fails that task. So a deploy that\n * changes this format has to move `task-builder` and the operator together;\n * anything in flight across the cutover is lost. That is the repo's\n * no-legacy-support policy applied deliberately: no dual-read, no format sniffing,\n * no version byte.\n */\nexport function packCommand(value: unknown) {\n return packr.pack(value)\n}\n\n/**\n * Decodes a task command off the AMQP command queue.\n *\n * Throws on anything that is not this codec's output — including a\n * superjson-shaped command from a pre-msgpack build, whose leading `{` decodes as\n * a positive fixint and whose trailing JSON text trips msgpack's end-of-buffer\n * check. The caller turns that into a terminal task failure; see `packCommand`\n * on why there is no fallback path.\n */\nexport function unpackCommand<T = unknown>(buffer: Buffer) {\n return packr.unpack(buffer) as T\n}\n\n/**\n * THE HIGH-VOLUME WIRE CODEC — a drop-in replacement for `JSON.stringify` /\n * `JSON.parse` on the three hot AMQP wires (service dispatch, service results,\n * task updates).\n *\n * **It is a codec swap, not a richer data model.** These wires are a\n * cross-language contract (TS service SDK, Python service SDK, `task-builder`),\n * so the format is a portable msgpack subset that any language's msgpack library\n * decodes — NOT the msgpackr dialect `packCommand` uses. Concretely:\n *\n * - `useRecords: false` — record structures are a msgpackr extension. They are\n * the single largest size win on the wide uniform arrays ETL moves (measured\n * -53% vs -17% without), and giving them up is the price of Python being able\n * to read the bytes at all.\n * - `structuredClone: false` — no reference/cycle extension, and no ext-type-0\n * `undefined`.\n * - `encodeUndefinedAsNil` — msgpackr's default `undefined` is ext type 0, which\n * is msgpackr-only. See `packWire` on why nil is still not free.\n * - `mapAsEmptyObject` / `setAsEmptyObject` — `JSON.stringify` renders a `Map` and\n * a `Set` as `{}`; without these msgpack would encode their contents and\n * silently start carrying data the JSON wire never did.\n * - `int64AsType: 'number'` — JSON has one number type, so a 64-bit integer from\n * the Python side must arrive as a `number`, not a `bigint`.\n *\n * A `URL` degrades to its href string, exactly as `JSON.stringify` does — see the\n * `URL` extension above for how it declines its own ext tag on this path.\n */\nconst wirePackr = new Packr({\n useRecords: false,\n structuredClone: false,\n encodeUndefinedAsNil: true,\n mapAsEmptyObject: true,\n setAsEmptyObject: true,\n int64AsType: 'number',\n})\n\n/**\n * **THE CONTRACT: this wire carries the JSON data model, and nothing else.**\n *\n * It replaced `JSON.stringify`, so by construction every value that reaches it is\n * already JSON-representable — task input arrives as JSON over HTTP, a node's output\n * arrives back over this same wire, and the envelope fields the operator adds are\n * strings and numbers. Nothing here has to carry a class.\n *\n * That is what makes the encoding usable from any language: it emits only msgpack's\n * CORE types, so a decoder needs no extension registered and no configuration.\n * `index.spec.ts` enforces this structurally — it walks the emitted bytes and fails\n * on any `ext` marker, over the JSON data model, real dispatch bodies, update\n * envelopes and `__REQUENCE_type` references.\n *\n * Two things to know about the encoding itself:\n *\n * 1. **`undefined` in a record becomes `null` instead of vanishing.** JSON drops the\n * key; msgpack has no way to express \"absent\" for a key it is already writing.\n * This is the one difference that can break a receiver: a Zod `.optional()`\n * accepts an absent key and rejects `null`. Envelope objects assembled on the\n * encode side must therefore omit undefined keys rather than assign them —\n * `omitUndefined` below is the shared way to do it. Values that came through JSON\n * cannot contain `undefined`, so only envelopes need the treatment.\n * 2. **`Uint8Array` becomes msgpack `bin`.** `bin` is a core type, not an extension,\n * so this costs nothing in portability — and it is the one place the wire is\n * denser than the JSON it replaced, which had to base64 (a 1.33x inflation).\n *\n * OUT OF CONTRACT, and deliberately not engineered around: `Date`, `RegExp`, `Error`\n * and any class registered via `addExtension` are not JSON, so they must not be put\n * on this wire. A `Date` in particular would emit msgpack's timestamp ext (-1) —\n * standard, but still an ext, which forfeits the \"decodes anywhere with no setup\"\n * guarantee above. The structural scan in the spec is what catches it if one ever\n * does slip in.\n */\nexport function packWire(value: unknown) {\n packingForWire = true\n try {\n return wirePackr.pack(value)\n } finally {\n packingForWire = false\n }\n}\n\n/** Decodes a body off one of the three high-volume wires. */\nexport function unpackWire<T = unknown>(buffer: Uint8Array) {\n return wirePackr.unpack(buffer) as T\n}\n\n/**\n * The encoded size of `value` under this codec, in bytes.\n *\n * The claim-check decides what to offload by measuring the serialized body, so\n * the codec and the size measurement are coupled: the invariant is **measured\n * size == published size**. A measurement taken with the wrong codec does not\n * fail loudly — it offloads too eagerly (a needless S3 round-trip on the hot\n * path) or too late (`PayloadTooLarge` at the broker). This is the only sanctioned\n * way to measure a body destined for this codec.\n *\n * Which is why it measures THROUGH `packWire` rather than reaching for the same\n * `Packr` itself: `packingForWire` is what makes the process-global `URL`\n * extension stand down, so a bare `wirePackr.pack` here would measure a `URL` as\n * an ext-tagged value and then publish it as a bare href string — the two numbers\n * this function exists to keep equal, unequal. `packCommand` deliberately carries\n * real `URL`s, so task input can put one in a body that is measured here.\n */\nexport function wireByteLength(value: unknown) {\n return packWire(value).length\n}\n\n/**\n * Drops keys whose value is `undefined`, so a record survives `packWire`\n * byte-equivalently to `JSON.stringify`.\n *\n * Needed only for envelope objects assembled right at an encode site (a dispatch\n * body's `options`, an update's optional fields): those are the only places an\n * `undefined` can still be present, per divergence (1) on `packWire`.\n */\nexport function omitUndefined<T extends Record<string, unknown>>(value: T): T {\n const out: Record<string, unknown> = {}\n for (const key of Object.keys(value)) {\n if (value[key] !== undefined) {\n out[key] = value[key]\n }\n }\n return out as T\n}\n\n/**\n * Which codec a body on one of the three high-volume wires is encoded with.\n *\n * `json` is the floor and never goes away: it is what an SDK that has not claimed\n * the `wire:msgpack1` capability speaks, and what every task keeps until it is\n * recreated. A rolling deploy therefore has both live at once, by design.\n */\nexport type WireCodec = 'json' | 'msgpack'\n\nexport const WIRE_CONTENT_TYPES = {\n json: 'application/json',\n msgpack: 'application/msgpack',\n} as const satisfies Record<WireCodec, string>\n\n/**\n * Maps an AMQP `content-type` to the codec that wrote the body.\n *\n * **Every decoder on these wires must go through here rather than assume.** An\n * absent or unrecognised content type is treated as `json`: that is the status\n * quo for anything published before this codec existed, and for any hop that\n * forwards a body without restating the header.\n */\nexport function wireCodecFromContentType(\n contentType: string | undefined,\n): WireCodec {\n return contentType === WIRE_CONTENT_TYPES.msgpack ? 'msgpack' : 'json'\n}\n\n/** Encodes a body for one of the three high-volume wires, with its content type. */\nexport function encodeWireBody(value: unknown, codec: WireCodec) {\n return {\n body:\n codec === 'msgpack'\n ? packWire(value)\n : Buffer.from(JSON.stringify(value ?? null)),\n contentType: WIRE_CONTENT_TYPES[codec],\n }\n}\n\n/**\n * Decodes a body off one of the three high-volume wires, switching on the codec\n * the publisher declared.\n *\n * This is what makes the migration rolling instead of a synchronised cutover: a\n * message already in flight when a deploy lands decodes under whichever codec\n * wrote it, so no queue has to be drained.\n */\nexport function decodeWireBody<T = unknown>(\n content: Uint8Array,\n contentType: string | undefined,\n): T {\n return wireCodecFromContentType(contentType) === 'msgpack'\n ? unpackWire<T>(content)\n : (JSON.parse(Buffer.from(content).toString()) as T)\n}\n\n/**\n * The encoded size of `value` under `codec`, in bytes — the claim-check's sizer.\n *\n * Both codecs are live at once (the choice is baked per service node), so the\n * threshold has to be measured with whichever codec this particular dispatch\n * uses. See `wireByteLength` on why a drifting measurement fails quietly.\n */\nexport function wireBodyByteLength(value: unknown, codec: WireCodec) {\n if (codec === 'msgpack') {\n return wireByteLength(value)\n }\n const json = JSON.stringify(value)\n return json === undefined ? 0 : Buffer.byteLength(json)\n}\n",
|
|
15
20
|
"/**\n * Thrown by a `RequenceStream` remote read when the producer terminated\n * abnormally (or vanished) mid-stream — the explicit alternative to the\n * clean-looking EOF a truncated live relay used to produce. Surfaced through\n * the framed consumer-GET protocol (see `streamFraming.ts`): a TRUNCATED\n * terminal frame, or an EOF with no terminal frame at all.\n */\nexport class RequenceStreamTruncatedError extends Error {\n constructor(message = 'stream truncated') {\n super(message)\n this.name = 'RequenceStreamTruncatedError'\n }\n}\n",
|
|
16
21
|
"import { RequenceStreamTruncatedError } from './errors.ts'\n\n/**\n * Opt-in framed protocol for the consumer stream GET, closing the\n * silent-truncation gap: the server *decides* complete-vs-truncated (Redis\n * EOS/ERR markers) but a plain HTTP body cannot state it — a mid-stream\n * producer abort and a clean end both look like EOF. A client that sends\n * `x-requence-stream-protocol: framed` receives length-prefixed frames ending\n * in an explicit terminal frame; the server echoes the header only when it\n * actually frames. Clients that don't send the header (Python SDK, older TS)\n * get today's raw bytes — compatible in both directions.\n *\n * Frame layout: `type u8 | length u32 BE | payload[length]`.\n */\nexport const STREAM_PROTOCOL_HEADER = 'x-requence-stream-protocol'\nexport const STREAM_PROTOCOL_FRAMED = 'framed'\n\nconst DATA = 0x00\n/** Terminal: the stream is complete. Nothing may follow. */\nconst END = 0x01\n/** Terminal: the producer aborted / vanished. Payload = UTF-8 reason. */\nconst TRUNCATED = 0x02\n\nconst HEADER_BYTES = 5\n\n/** 5-byte DATA frame header; write it, then the chunk itself (no copy). */\nexport function dataFrameHeader(byteLength: number): Uint8Array {\n const header = new Uint8Array(HEADER_BYTES)\n new DataView(header.buffer).setUint32(1, byteLength, false)\n header[0] = DATA\n return header\n}\n\nexport const END_FRAME: Uint8Array = new Uint8Array([END, 0, 0, 0, 0])\n\nexport function truncatedFrame(reason: string): Uint8Array {\n const payload = new TextEncoder().encode(reason)\n const frame = new Uint8Array(HEADER_BYTES + payload.byteLength)\n new DataView(frame.buffer).setUint32(1, payload.byteLength, false)\n frame[0] = TRUNCATED\n frame.set(payload, HEADER_BYTES)\n return frame\n}\n\n/**\n * Decode a framed body back into raw chunks. DATA payloads are re-emitted;\n * END terminates cleanly; TRUNCATED — and an EOF without any terminal frame\n * (transport drop, proxy cut) — error the stream with a typed\n * `RequenceStreamTruncatedError`. Frames may be split across chunk boundaries.\n */\nexport function createFrameDecoder(): TransformStream<Uint8Array, Uint8Array> {\n let buffer: Uint8Array = new Uint8Array(0)\n let terminal = false\n\n return new TransformStream<Uint8Array, Uint8Array>({\n transform(chunk, controller) {\n if (terminal) {\n if (chunk.byteLength > 0) {\n throw new Error('stream protocol error: bytes after terminal frame')\n }\n return\n }\n\n if (buffer.byteLength === 0) {\n buffer = chunk\n } else {\n const merged = new Uint8Array(buffer.byteLength + chunk.byteLength)\n merged.set(buffer, 0)\n merged.set(chunk, buffer.byteLength)\n buffer = merged\n }\n\n while (buffer.byteLength >= HEADER_BYTES) {\n const type = buffer[0]\n const length = new DataView(\n buffer.buffer,\n buffer.byteOffset,\n buffer.byteLength,\n ).getUint32(1, false)\n if (buffer.byteLength < HEADER_BYTES + length) {\n break\n }\n // slice (copy): the emitted chunk must not pin the merge buffer\n const payload = buffer.slice(HEADER_BYTES, HEADER_BYTES + length)\n buffer = buffer.subarray(HEADER_BYTES + length)\n\n switch (type) {\n case DATA: {\n if (payload.byteLength > 0) {\n controller.enqueue(payload)\n }\n break\n }\n case END: {\n terminal = true\n if (buffer.byteLength > 0) {\n throw new Error(\n 'stream protocol error: bytes after terminal frame',\n )\n }\n controller.terminate()\n return\n }\n case TRUNCATED: {\n terminal = true\n controller.error(\n new RequenceStreamTruncatedError(\n new TextDecoder().decode(payload) || undefined,\n ),\n )\n return\n }\n default: {\n throw new Error(`stream protocol error: unknown frame type ${type}`)\n }\n }\n }\n },\n flush(controller) {\n if (!terminal) {\n controller.error(\n new RequenceStreamTruncatedError(\n 'connection closed before terminal frame',\n ),\n )\n }\n },\n })\n}\n",
|
|
17
22
|
"import {\n STREAM_PROTOCOL_FRAMED,\n STREAM_PROTOCOL_HEADER,\n createFrameDecoder,\n} from './streamFraming.ts'\n\ninterface RemoteBodyOptions {\n /**\n * External (task) signal. When it aborts, the in-flight fetch is aborted so a\n * service-task teardown can cancel a hung read.\n */\n signal?: AbortSignal\n /**\n * Inactivity timeout (ms). Opt-in: only enforced when > 0. A read that\n * produces no data within the window aborts the underlying fetch so the\n * consumer errors out instead of blocking forever. Disabled by default so\n * legitimately slow/long transfers are never cut.\n */\n stallTimeoutMs?: number\n /**\n * Request the framed stream protocol (see `streamFraming.ts`): the body then\n * carries an explicit `complete|truncated` terminal signal, and a truncated\n * stream rejects with a typed `RequenceStreamTruncatedError` instead of\n * closing like a clean EOF. Falls back to the raw body when the server does\n * not echo the protocol header (older files service).\n */\n framed?: boolean\n}\n\n/**\n * Shared guarded remote read for the files service. Fetches `url` and exposes\n * the response body as a `ReadableStream` that routes EVERY failure through\n * `controller.error(...)` instead of hanging or piping an error page through as\n * content:\n *\n * - fetch rejection, a non-2xx status (body drained via `response.body?.cancel()`),\n * and a null body all error the returned stream;\n * - a mid-stream read failure surfaces as a thrown read, never a silent close;\n * - cancelling the returned stream, the external signal aborting, or the opt-in\n * stall timeout all abort the in-flight fetch (no connection leak).\n *\n * Used by both `RequenceStream` (streaming reads) and `RequenceFile` (buffered\n * reads + `stream()`).\n */\nexport function remoteBody(\n url: string,\n options: RemoteBodyOptions = {},\n): ReadableStream<Uint8Array> {\n const externalSignal = options.signal\n const timeoutMs =\n options.stallTimeoutMs && options.stallTimeoutMs > 0\n ? options.stallTimeoutMs\n : 0\n\n // Self-contained controller: cancelling the returned stream (or the external\n // task signal, or a stall timeout) aborts the in-flight fetch.\n const controller = new AbortController()\n\n let reader: ReadableStreamDefaultReader<Uint8Array> | null = null\n let timer: ReturnType<typeof setTimeout> | undefined\n let onExternalAbort: (() => void) | undefined\n\n const clearTimer = () => {\n if (timer !== undefined) {\n clearTimeout(timer)\n timer = undefined\n }\n }\n\n const cleanup = () => {\n clearTimer()\n if (externalSignal && onExternalAbort) {\n externalSignal.removeEventListener('abort', onExternalAbort)\n }\n }\n\n // Chain the task signal so a service-task teardown aborts the read.\n if (externalSignal) {\n if (externalSignal.aborted) {\n controller.abort(externalSignal.reason)\n } else {\n onExternalAbort = () => controller.abort(externalSignal.reason)\n externalSignal.addEventListener('abort', onExternalAbort, {\n once: true,\n })\n }\n }\n\n const armTimer = () => {\n if (timeoutMs <= 0) {\n return\n }\n clearTimer()\n timer = setTimeout(() => {\n controller.abort(\n new Error(`remote read stalled: no data for ${timeoutMs}ms`),\n )\n }, timeoutMs)\n }\n\n return new ReadableStream<Uint8Array>({\n async start(streamController) {\n let response: Response\n try {\n response = await fetch(url, {\n signal: controller.signal,\n headers: options.framed\n ? { [STREAM_PROTOCOL_HEADER]: STREAM_PROTOCOL_FRAMED }\n : undefined,\n })\n } catch (error) {\n cleanup()\n streamController.error(error)\n return\n }\n\n if (!response.ok) {\n // Drain the error body so the connection is released, then surface the\n // failure instead of piping the error page through as content.\n await response.body?.cancel()\n cleanup()\n streamController.error(\n new Error(\n `remote read failed: ${response.status} ${response.statusText}`,\n ),\n )\n return\n }\n\n if (!response.body) {\n cleanup()\n streamController.error(new Error('remote read response has no body'))\n return\n }\n\n // The server echoes the protocol header only when it actually frames;\n // without the echo (older server) the raw body is read as before.\n const framed =\n options.framed &&\n response.headers.get(STREAM_PROTOCOL_HEADER) === STREAM_PROTOCOL_FRAMED\n reader = framed\n ? response.body.pipeThrough(createFrameDecoder()).getReader()\n : response.body.getReader()\n },\n async pull(streamController) {\n if (!reader) {\n return\n }\n armTimer()\n try {\n const { done, value } = await reader.read()\n clearTimer()\n if (done) {\n cleanup()\n streamController.close()\n return\n }\n streamController.enqueue(value)\n } catch (error) {\n // A mid-stream connection drop, or an abort (task teardown / stall\n // timeout), surfaces as a thrown read — never a silent close.\n clearTimer()\n cleanup()\n streamController.error(error)\n }\n },\n async cancel(reason) {\n cleanup()\n controller.abort(reason)\n await reader?.cancel(reason)\n },\n })\n}\n",
|
|
@@ -21,19 +26,22 @@
|
|
|
21
26
|
"import type { FileObject } from '@requence/helpers'\nimport { isFileObject, toFileObject } from '@requence/helpers'\nimport type { TransformContext, ValueHandler } from '@requence/transformer'\n\nimport type { FileEgressContext } from './context.ts'\nimport { assertOk } from './transport.ts'\nimport { RequenceFile } from '../RequenceFile.ts'\n\nasync function upload(\n ctx: TransformContext,\n uploadUrl: string,\n body: BodyInit | null,\n contentType?: string | null,\n maxFileSize?: number,\n): Promise<FileObject> {\n const uploadResponse = await ctx.fetch(uploadUrl, {\n method: 'POST',\n signal: ctx.signal,\n headers: {\n ...(contentType ? { 'Content-Type': contentType } : {}),\n // Per-task cap transmitted via task options; the files service\n // enforces it (absent ⇒ its hardcoded fallback cap).\n ...(maxFileSize !== undefined\n ? { 'file-size': String(maxFileSize) }\n : {}),\n },\n body,\n })\n\n await assertOk(uploadResponse, uploadUrl, 'upload')\n\n const data = await uploadResponse.json()\n // Explicit field checks rather than `isFileObject`: the FileObject schema\n // requires a positive size, but a legitimate 0-byte file is valid here.\n if (\n !data ||\n typeof data !== 'object' ||\n typeof (data as { url?: unknown }).url !== 'string' ||\n !(data as { url: string }).url ||\n typeof (data as { mime?: unknown }).mime !== 'string' ||\n typeof (data as { size?: unknown }).size !== 'number'\n ) {\n throw new Error(`malformed upload response (${uploadUrl})`)\n }\n\n return toFileObject(data as { size: number; mime: string; url: string })\n}\n\n/**\n * Value handler owning `RequenceFile` — and, through it, raw `Blob`s (a Blob\n * adapts through RequenceFile; no separate Blob branch exists anywhere else).\n *\n * Egress uploads the bytes via the injected transport and returns the\n * `FileObject` reference (idempotent for an already-remote file). Ingress\n * reconstructs the lazy remote instance.\n */\nexport function createRequenceFileHandler(): ValueHandler<\n RequenceFile | Blob,\n FileObject | null,\n FileEgressContext\n> {\n return {\n tag: 'RequenceFile',\n\n canHandle: (value) => RequenceFile.canHandle(value),\n\n async serialize(value, ctx) {\n // Idempotent: an already-remote file keeps its existing reference.\n if (value instanceof RequenceFile && value.fileObject) {\n return value.fileObject\n }\n\n if (!ctx.uploadUrl) {\n ctx.onOffloadSkip?.()\n return null\n }\n\n try {\n if (value instanceof RequenceFile) {\n return await upload(\n ctx,\n ctx.uploadUrl,\n await value.blob(),\n value.mimeType,\n ctx.maxFileSize,\n )\n }\n return await upload(\n ctx,\n ctx.uploadUrl,\n value,\n value.type,\n ctx.maxFileSize,\n )\n } catch (error) {\n if (!(error instanceof Error)) {\n throw error\n }\n // Fail-hard by default: only swallow (to null) when a caller opts in\n // with `onOffloadFail`. Otherwise propagate so the node/task fails loudly.\n if (ctx.onOffloadFail) {\n ctx.onOffloadFail(error)\n return null\n }\n throw error\n }\n },\n\n isReference: (value): value is FileObject => isFileObject(value),\n\n deserialize(ref, ctx) {\n return RequenceFile.fromFileObject(ref as FileObject, ctx.signal)\n },\n }\n}\n",
|
|
22
27
|
"import { AsyncLocalStorage } from 'node:async_hooks'\n\n/**\n * Ambient collection scope for background stream-body uploads.\n *\n * A `RequenceStream` serializes in two beats: the reference (`StreamObject`) is\n * known right after registration, but the body keeps uploading in the\n * background — that is what lets a consumer join the stream *while* the\n * producer is still pushing. The caller, however, must not treat the transform\n * as durably complete (ack the task, mark it done) until every background body\n * upload has settled.\n *\n * `withRequenceStreams` is that collection point: the stream handler registers\n * its background upload into the ambient store, and the caller receives a\n * single `done` promise to feed its completion gate.\n */\nconst pendingUploads = new AsyncLocalStorage<Array<Promise<void>>>()\n\n/**\n * Run `fn` (typically a `transformOutbound` call) collecting every background\n * stream-body upload started within it. Returns the function's result together\n * with a `done` promise that resolves when all collected uploads settle and\n * rejects on the first failure. `value` is available immediately — publish it\n * while the bodies still stream; await `done` before acking.\n */\nexport async function withRequenceStreams<T>(\n fn: () => Promise<T> | T,\n): Promise<{ value: T; done: Promise<void> }> {\n const uploads: Array<Promise<void>> = []\n const value = await pendingUploads.run(uploads, fn)\n return { value, done: Promise.all(uploads).then(() => undefined) }\n}\n\n/**\n * Hand a background upload to the ambient scope. Returns false when no scope\n * is active — the caller (the stream handler) must then await the work inline:\n * still correct, just not live. Never fire-and-forget.\n *\n * @internal\n */\nexport function registerPendingUpload(work: Promise<void>): boolean {\n const store = pendingUploads.getStore()\n if (!store) {\n return false\n }\n store.push(work)\n return true\n}\n",
|
|
23
28
|
"import type { StreamObject } from '@requence/helpers'\nimport { isStreamObject, toStreamObject } from '@requence/helpers'\nimport type { TransformContext, ValueHandler } from '@requence/transformer'\n\nimport type { StreamEgressContext } from './context.ts'\nimport { assertOk } from './transport.ts'\nimport { RequenceStream } from '../RequenceStream.ts'\nimport { registerPendingUpload } from '../withRequenceStreams.ts'\n\nasync function registerAndUpload(\n ctx: TransformContext,\n streamUrl: string,\n stream: ReadableStream,\n contentType?: string | null,\n maxFileSize?: number,\n): Promise<{ ref: StreamObject; bodyUpload?: Promise<void> }> {\n const [testStream, dataStream] = stream.tee()\n\n // Read the first chunk before firing the body upload: nodejs closes an empty\n // duplex `half` body before the fetch executes, so we must know whether any\n // data exists. `dataStream` keeps the buffered chunk (tee), so no bytes are\n // lost. (Obsolete once we move to bun.)\n const reader = testStream.getReader()\n const { done: isEmpty } = await reader.read()\n reader.cancel()\n\n const streamResponse = await ctx.fetch(streamUrl, {\n method: 'POST',\n signal: ctx.signal,\n headers: {\n ...(contentType ? { 'Content-Type': contentType } : {}),\n // Per-task cap transmitted via task options; the files service stores\n // it with the stream and enforces it during the body upload (absent ⇒\n // its hardcoded fallback cap).\n ...(maxFileSize !== undefined\n ? { 'file-size': String(maxFileSize) }\n : {}),\n },\n })\n\n await assertOk(streamResponse, streamUrl, 'stream registration')\n\n const data = await streamResponse.json()\n if (!isStreamObject(toStreamObject(data as { mime: string; url: string }))) {\n throw new Error(`malformed stream registration response (${streamUrl})`)\n }\n\n const { mime, url } = data as { mime: string; url: string }\n\n if (isEmpty) {\n // Legitimate zero-byte stream: POST a static empty body. The duplex\n // \"wait for first byte\" workaround only applies to a streaming body.\n const emptyResponse = await ctx.fetch(url, {\n method: 'POST',\n signal: ctx.signal,\n headers: contentType ? { 'Content-Type': contentType } : {},\n body: new Uint8Array(0),\n })\n await assertOk(emptyResponse, url, 'stream body upload')\n await emptyResponse.body?.cancel()\n return { ref: toStreamObject({ mime, url }) }\n }\n\n // Not awaited here: the body streams in the background so the reference can\n // be published while data still flows. Completion/failure surfaces through\n // the returned promise, collected by `withRequenceStreams`.\n const bodyUpload = (async () => {\n const bodyResponse = await ctx.fetch(url, {\n method: 'POST',\n signal: ctx.signal,\n duplex: 'half', // not typed but needed for nodejs to handle readable streams\n body: dataStream,\n } as RequestInit)\n await assertOk(bodyResponse, url, 'stream body upload')\n await bodyResponse.body?.cancel()\n })()\n\n return { ref: toStreamObject({ mime, url }), bodyUpload }\n}\n\n/**\n * Value handler owning `RequenceStream` — and, through it, raw `Response`s (a\n * Response body adapts through RequenceStream; no separate Response branch\n * exists anywhere else).\n *\n * Egress registers the stream, returns the `StreamObject` reference\n * immediately, and pushes the body in the background (collected by the ambient\n * `withRequenceStreams` scope; without a scope the upload is awaited inline —\n * still correct, just not live). Ingress reconstructs a lazy stream that reads\n * live-or-durable.\n */\nexport function createRequenceStreamHandler(): ValueHandler<\n RequenceStream | Response,\n StreamObject | null,\n StreamEgressContext\n> {\n return {\n tag: 'RequenceStream',\n\n canHandle: (value) => RequenceStream.canHandle(value),\n\n async serialize(value, ctx) {\n // Idempotent: an already-remote stream keeps its existing reference.\n if (value instanceof RequenceStream && value.streamObject) {\n return value.streamObject\n }\n\n if (!ctx.streamUrl) {\n ctx.onOffloadSkip?.()\n return null\n }\n\n const body =\n value instanceof Response\n ? // A body-less Response is a legitimate empty stream.\n (value.body ??\n new ReadableStream({\n start(controller) {\n controller.close()\n },\n }))\n : value.stream()\n const contentType =\n value instanceof Response\n ? value.headers.get('Content-Type')\n : value.mimeType\n\n try {\n const { ref, bodyUpload } = await registerAndUpload(\n ctx,\n ctx.streamUrl,\n body,\n contentType,\n ctx.maxFileSize,\n )\n if (bodyUpload && !registerPendingUpload(bodyUpload)) {\n // No ambient scope collecting background work: await inline. Correct,\n // just not live — never fire-and-forget.\n await bodyUpload\n }\n return ref\n } catch (error) {\n if (!(error instanceof Error)) {\n throw error\n }\n // Fail-hard by default: only swallow (to null) when a caller opts in\n // with `onOffloadFail`. Otherwise propagate so the node/task fails loudly.\n if (ctx.onOffloadFail) {\n ctx.onOffloadFail(error)\n return null\n }\n throw error\n }\n },\n\n isReference: (value): value is StreamObject => isStreamObject(value),\n\n deserialize(ref, ctx) {\n return RequenceStream.fromStreamObject(ref as StreamObject, ctx.signal)\n },\n }\n}\n",
|
|
24
|
-
"import { Buffer } from 'node:buffer'\n\nimport type { ClaimCheckObject } from '@requence/helpers'\nimport { isClaimCheckObject, toClaimCheckObject } from '@requence/helpers'\nimport type {\n HandlerBundle,\n MessageHandler,\n TransformContext,\n ValueHandler,\n} from '@requence/transformer'\n\nimport type { ClaimCheckEgressContext } from './context.ts'\nimport { assertOk } from './transport.ts'\n\n/**\n * Oversized-message claim-check — one `withHandler` bundle carrying both\n * contract halves:\n *\n * - **Egress** is the bundle's `messageHandler`: it size-checks the already\n * value-serialized body and offloads oversized top-level values to the\n * files service, preserving a record body's top-level keys (the transformer\n * asserts this). A non-record body is offloaded wholesale.\n * - **Ingress** is the bundle's `valueHandler`: a reference can resurface at\n * any depth of a later message once a forwarding hop merged it into other\n * data — only the value walk finds it there.\n *\n * Offload failure always **throws** — deliberately ignoring the\n * `onOffloadFail` swallow-to-null contract, which means \"null *reference*\n * for one value\": a silently nulled body part would corrupt the message, and\n * an oversized body that cannot be offloaded fails at the broker anyway.\n * Without an `uploadUrl` on the ctx the handler skips (status quo: the broker\n * rejects the message exactly as it does today).\n */\n\n/**\n * Fallback offload threshold in bytes when the ctx carries no\n * `maxPayloadSize` (safe headroom under RabbitMQ's 16 MiB default\n * `max_message_size`). The per-task value is minted by the ui backend and\n * arrives via task options, like the upload URL.\n */\nconst DEFAULT_MAX_PAYLOAD_SIZE = 4 * 1024 * 1024\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nasync function offload(\n ctx: TransformContext,\n uploadUrl: string,\n json: string,\n): Promise<ClaimCheckObject> {\n const response = await ctx.fetch(uploadUrl, {\n method: 'POST',\n signal: ctx.signal,\n headers: { 'Content-Type': 'application/json' },\n body: json,\n })\n await assertOk(response, uploadUrl, 'claim-check offload')\n\n const data = (await response.json()) as { url?: unknown; size?: unknown }\n if (\n !data ||\n typeof data !== 'object' ||\n typeof data.url !== 'string' ||\n !data.url ||\n typeof data.size !== 'number'\n ) {\n throw new Error(`malformed claim-check offload response (${uploadUrl})`)\n }\n return toClaimCheckObject({ url: data.url, size: data.size })\n}\n\n/** The historical sizer: correct for any caller still publishing JSON. */\nfunction jsonByteLength(value: unknown) {\n const json = JSON.stringify(value)\n return json === undefined ? 0 : Buffer.byteLength(json)\n}\n\n/** Thrown by the replacer below, caught by its own `toOffloadJson`, never escapes. */\nclass UnserializableValue extends Error {}\n\n/**\n * The bytes PUT in an offloaded object — always JSON, whatever the wire codec,\n * because the ingress half reads them back with `JSON.parse`. `undefined` means\n * JSON cannot carry this value, so it must not be offloaded at all.\n *\n * The msgpack wire made that case reachable: it carries a `Uint8Array` as\n * msgpack `bin`, and the value walk does not claim binary (`RequenceFile`\n * handles only `RequenceFile | Blob`). `JSON.stringify` does not refuse it\n * either — it renders a `Uint8Array` as `{\"0\":1,…}` and a `Buffer` as\n * `{\"type\":\"Buffer\",\"data\":[…]}`. Offloading either is silent corruption (the\n * consumer gets a plain object where bytes were) on top of a ~4x size increase,\n * so binary is rejected at any depth instead. The Python handler gets this for\n * free — `json.dumps` refuses `bytes`.\n *\n * The replacer reads `this[key]` rather than its own second argument because\n * `toJSON` runs BEFORE the replacer: a `Buffer` has already become that plain\n * object by the time the replacer is called. At the root, the holder is\n * `{ '': value }` and the key is `''`, so one expression covers both.\n */\nfunction toOffloadJson(value: unknown) {\n try {\n return JSON.stringify(\n value,\n function (this: Record<string, unknown>, key: string, encoded: unknown) {\n const raw = this[key]\n if (ArrayBuffer.isView(raw) || raw instanceof ArrayBuffer) {\n throw new UnserializableValue()\n }\n return encoded\n },\n )\n } catch (error) {\n if (error instanceof UnserializableValue) {\n return undefined\n }\n throw error\n }\n}\n\nfunction createMessageHandler(): MessageHandler<ClaimCheckEgressContext> {\n return {\n async wrapOutbound(body, ctx) {\n const maxBytes = ctx.maxPayloadSize ?? DEFAULT_MAX_PAYLOAD_SIZE\n if (maxBytes <= 0 || body === undefined) {\n return body\n }\n\n // Two different questions about the same value, and they no longer have the\n // same answer:\n // - how big will this be ON THE WIRE → `measure`, the publisher's codec;\n // - what bytes do we PUT in the offloaded object → JSON, always.\n // The stored object is an HTTP/S3 payload read back by `JSON.parse` in the\n // ingress half below, so it stays JSON regardless of the wire codec. Only\n // the threshold arithmetic follows the codec.\n const measure = ctx.measure ?? jsonByteLength\n\n if (measure(body) <= maxBytes) {\n return body\n }\n const { uploadUrl } = ctx\n if (!uploadUrl) {\n ctx.onOffloadSkip?.()\n return body\n }\n\n if (!isRecord(body)) {\n const json = toOffloadJson(body)\n if (json === undefined) {\n return body\n }\n return offload(ctx, uploadUrl, json)\n }\n\n // Record body: offload oversized top-level values largest-first until\n // the body fits, keys preserved. If every value is offloaded and the\n // body still exceeds the threshold there is nothing more a\n // key-preserving wrap can do — return it and let the broker decide.\n const entries = Object.entries(body)\n .map(([key, value]) => ({\n key,\n valueJson: toOffloadJson(value),\n size: measure(value),\n }))\n .sort((a, b) => b.size - a.size)\n\n const wrapped: Record<string, unknown> = { ...body }\n let total = measure(body)\n for (const entry of entries) {\n // A reference is ~100–150 bytes; offloading a value that small can\n // only grow the body. Entries are sorted largest-first, so stop.\n if (total <= maxBytes || entry.size <= 256) {\n break\n }\n if (entry.valueJson === undefined) {\n // A value JSON cannot carry cannot be offloaded (see `toOffloadJson`).\n // SKIP it rather than stop: entries are largest-first, so stopping here\n // would strand every smaller value that CAN be offloaded — and the whole\n // oversized body would reach the broker.\n continue\n }\n const ref = await offload(ctx, uploadUrl, entry.valueJson)\n wrapped[entry.key] = ref\n total += measure(ref) - entry.size\n }\n return wrapped\n },\n }\n}\n\n/**\n * Ingress half: fetch the offloaded value back and hand it to the walk. The\n * result is re-walked to a fixpoint, so references nested *inside* the\n * offloaded value (files, streams, callbacks) rehydrate as usual.\n * Reconstruction needs only `ctx.fetch`, so transport-less consumers (task\n * watchers, ui) can always unwrap.\n */\nfunction createValueHandler(): ValueHandler<unknown, ClaimCheckObject> {\n return {\n tag: 'ClaimCheck',\n\n canHandle: () => false, // egress happens at message level, never per value\n\n serialize() {\n throw new Error(\n 'ClaimCheck egress is the bundled MessageHandler (wrapOutbound); it never reaches the value walk',\n )\n },\n\n isReference: (value): value is ClaimCheckObject =>\n isClaimCheckObject(value),\n\n async deserialize(ref, ctx) {\n const response = await ctx.fetch(ref.url, { signal: ctx.signal })\n await assertOk(response, ref.url, 'claim-check fetch')\n const text = await response.text()\n try {\n return JSON.parse(text)\n } catch {\n throw new Error(`malformed claim-check payload (${ref.url})`)\n }\n },\n }\n}\n\n/** The claim-check as one composable bundle: message-wrap egress + value-walk ingress. */\nexport function createClaimCheckHandler(): HandlerBundle<\n object,\n object,\n ClaimCheckEgressContext\n> & {\n valueHandler: ValueHandler<unknown, ClaimCheckObject>\n messageHandler: MessageHandler<ClaimCheckEgressContext>\n} {\n return {\n valueHandler: createValueHandler(),\n messageHandler: createMessageHandler(),\n }\n}\n",
|
|
29
|
+
"import { Buffer } from 'node:buffer'\n\nimport type { ClaimCheckObject } from '@requence/helpers'\nimport { isClaimCheckObject, toClaimCheckObject } from '@requence/helpers'\nimport type {\n HandlerBundle,\n MessageHandler,\n TransformContext,\n ValueHandler,\n} from '@requence/transformer'\n\nimport type { ClaimCheckEgressContext } from './context.ts'\nimport { assertOk } from './transport.ts'\n\n/**\n * Oversized-message claim-check — one `withHandler` bundle carrying both\n * contract halves:\n *\n * - **Egress** is the bundle's `messageHandler`: it size-checks the already\n * value-serialized body and offloads oversized top-level values to the\n * files service, preserving a record body's top-level keys (the transformer\n * asserts this). A non-record body is offloaded wholesale.\n * - **Ingress** is the bundle's `valueHandler`: a reference can resurface at\n * any depth of a later message once a forwarding hop merged it into other\n * data — only the value walk finds it there.\n *\n * Offload failure always **throws** — deliberately ignoring the\n * `onOffloadFail` swallow-to-null contract, which means \"null *reference*\n * for one value\": a silently nulled body part would corrupt the message, and\n * an oversized body that cannot be offloaded fails at the broker anyway.\n * Without an `uploadUrl` on the ctx the handler skips (status quo: the broker\n * rejects the message exactly as it does today).\n */\n\n/**\n * Fallback offload threshold in bytes when the ctx carries no\n * `maxPayloadSize` (safe headroom under RabbitMQ's 16 MiB default\n * `max_message_size`). The per-task value is minted by the ui backend and\n * arrives via task options, like the upload URL.\n */\nconst DEFAULT_MAX_PAYLOAD_SIZE = 4 * 1024 * 1024\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nasync function offload(\n ctx: TransformContext,\n uploadUrl: string,\n json: string,\n): Promise<ClaimCheckObject> {\n const response = await ctx.fetch(uploadUrl, {\n method: 'POST',\n signal: ctx.signal,\n headers: { 'Content-Type': 'application/json' },\n body: json,\n })\n await assertOk(response, uploadUrl, 'claim-check offload')\n\n const data = (await response.json()) as { url?: unknown; size?: unknown }\n if (\n !data ||\n typeof data !== 'object' ||\n typeof data.url !== 'string' ||\n !data.url ||\n typeof data.size !== 'number'\n ) {\n throw new Error(`malformed claim-check offload response (${uploadUrl})`)\n }\n return toClaimCheckObject({ url: data.url, size: data.size })\n}\n\n/** The historical sizer: correct for any caller still publishing JSON. */\nfunction jsonByteLength(value: unknown) {\n const json = JSON.stringify(value)\n return json === undefined ? 0 : Buffer.byteLength(json)\n}\n\n/** Thrown by the replacer below, caught by its own `toOffloadJson`, never escapes. */\nclass UnserializableValue extends Error {}\n\n/**\n * The bytes PUT in an offloaded object — always JSON, whatever the wire codec,\n * because the ingress half reads them back with `JSON.parse`. `undefined` means\n * JSON cannot carry this value, so it must not be offloaded at all.\n *\n * The msgpack wire made that case reachable: it carries a `Uint8Array` as\n * msgpack `bin`, and the value walk does not claim binary (`RequenceFile`\n * handles only `RequenceFile | Blob`). `JSON.stringify` does not refuse it\n * either — it renders a `Uint8Array` as `{\"0\":1,…}` and a `Buffer` as\n * `{\"type\":\"Buffer\",\"data\":[…]}`. Offloading either is silent corruption (the\n * consumer gets a plain object where bytes were) on top of a ~4x size increase,\n * so binary is rejected at any depth instead. The Python handler gets this for\n * free — `json.dumps` refuses `bytes`.\n *\n * The replacer reads `this[key]` rather than its own second argument because\n * `toJSON` runs BEFORE the replacer: a `Buffer` has already become that plain\n * object by the time the replacer is called. At the root, the holder is\n * `{ '': value }` and the key is `''`, so one expression covers both.\n */\nfunction toOffloadJson(value: unknown) {\n try {\n return JSON.stringify(\n value,\n function (this: Record<string, unknown>, key: string, encoded: unknown) {\n const raw = this[key]\n if (ArrayBuffer.isView(raw) || raw instanceof ArrayBuffer) {\n throw new UnserializableValue()\n }\n return encoded\n },\n )\n } catch (error) {\n if (error instanceof UnserializableValue) {\n return undefined\n }\n throw error\n }\n}\n\nfunction createMessageHandler(): MessageHandler<ClaimCheckEgressContext> {\n return {\n async wrapOutbound(body, ctx) {\n const maxBytes = ctx.maxPayloadSize ?? DEFAULT_MAX_PAYLOAD_SIZE\n if (maxBytes <= 0 || body === undefined) {\n return body\n }\n\n // Two different questions about the same value, and they no longer have the\n // same answer:\n // - how big will this be ON THE WIRE → `measure`, the publisher's codec;\n // - what bytes do we PUT in the offloaded object → JSON, always.\n // The stored object is an HTTP/S3 payload read back by `JSON.parse` in the\n // ingress half below, so it stays JSON regardless of the wire codec. Only\n // the threshold arithmetic follows the codec.\n const measure = ctx.measure ?? jsonByteLength\n\n if (measure(body) <= maxBytes) {\n return body\n }\n const { uploadUrl } = ctx\n if (!uploadUrl) {\n ctx.onOffloadSkip?.()\n return body\n }\n\n if (!isRecord(body)) {\n const json = toOffloadJson(body)\n if (json === undefined) {\n return body\n }\n return offload(ctx, uploadUrl, json)\n }\n\n // Record body: offload oversized top-level values largest-first until\n // the body fits, keys preserved. If every value is offloaded and the\n // body still exceeds the threshold there is nothing more a\n // key-preserving wrap can do — return it and let the broker decide.\n // `inlineKeys` are excluded from the candidates entirely, so a pinned\n // value is never the offload target no matter how the sizes fall.\n const entries = Object.entries(body)\n .filter(([key]) => !ctx.inlineKeys?.includes(key))\n .map(([key, value]) => ({\n key,\n valueJson: toOffloadJson(value),\n size: measure(value),\n }))\n .sort((a, b) => b.size - a.size)\n\n const wrapped: Record<string, unknown> = { ...body }\n let total = measure(body)\n for (const entry of entries) {\n // A reference is ~100–150 bytes; offloading a value that small can\n // only grow the body. Entries are sorted largest-first, so stop.\n if (total <= maxBytes || entry.size <= 256) {\n break\n }\n if (entry.valueJson === undefined) {\n // A value JSON cannot carry cannot be offloaded (see `toOffloadJson`).\n // SKIP it rather than stop: entries are largest-first, so stopping here\n // would strand every smaller value that CAN be offloaded — and the whole\n // oversized body would reach the broker.\n continue\n }\n const ref = await offload(ctx, uploadUrl, entry.valueJson)\n wrapped[entry.key] = ref\n total += measure(ref) - entry.size\n }\n return wrapped\n },\n }\n}\n\n/**\n * Ingress half: fetch the offloaded value back and hand it to the walk. The\n * result is re-walked to a fixpoint, so references nested *inside* the\n * offloaded value (files, streams, callbacks) rehydrate as usual.\n * Reconstruction needs only `ctx.fetch`, so transport-less consumers (task\n * watchers, ui) can always unwrap.\n */\nfunction createValueHandler(): ValueHandler<unknown, ClaimCheckObject> {\n return {\n tag: 'ClaimCheck',\n\n canHandle: () => false, // egress happens at message level, never per value\n\n serialize() {\n throw new Error(\n 'ClaimCheck egress is the bundled MessageHandler (wrapOutbound); it never reaches the value walk',\n )\n },\n\n isReference: (value): value is ClaimCheckObject =>\n isClaimCheckObject(value),\n\n async deserialize(ref, ctx) {\n const response = await ctx.fetch(ref.url, { signal: ctx.signal })\n await assertOk(response, ref.url, 'claim-check fetch')\n const text = await response.text()\n try {\n return JSON.parse(text)\n } catch {\n throw new Error(`malformed claim-check payload (${ref.url})`)\n }\n },\n }\n}\n\n/** The claim-check as one composable bundle: message-wrap egress + value-walk ingress. */\nexport function createClaimCheckHandler(): HandlerBundle<\n object,\n object,\n ClaimCheckEgressContext\n> & {\n valueHandler: ValueHandler<unknown, ClaimCheckObject>\n messageHandler: MessageHandler<ClaimCheckEgressContext>\n} {\n return {\n valueHandler: createValueHandler(),\n messageHandler: createMessageHandler(),\n }\n}\n",
|
|
25
30
|
"import { mapData } from '@requence/helpers'\n\nimport { RequenceFile } from './RequenceFile.ts'\nimport { RequenceStream } from './RequenceStream.ts'\n\n/**\n * Best-effort pre-pass for log/console payloads: a log must never fail the\n * task/node or mint a live callback registration, so everything the\n * transformer would loudly reject is rendered to a readable label instead.\n * Requence types pass through untouched (the handlers offload them), plain\n * data and toJSON-serializable instances pass through (JSON parity),\n * everything else becomes a string.\n */\nexport function sanitizeLogData(data: unknown) {\n return mapData(data, {\n Function: () => '[Function]',\n Symbol: (sym) => String(sym),\n Object(obj) {\n if (RequenceFile.canHandle(obj) || RequenceStream.canHandle(obj)) {\n return undefined\n }\n const proto = Object.getPrototypeOf(obj)\n if (proto === null || proto === Object.prototype) {\n return undefined\n }\n if (typeof (obj as { toJSON?: unknown }).toJSON === 'function') {\n return undefined\n }\n return String(obj)\n },\n })\n}\n",
|
|
26
31
|
"import type { CallbackObject } from '@requence/helpers'\nimport { isCallbackObject } from '@requence/helpers'\nimport type { ValueHandler } from '@requence/transformer'\n\nimport type {\n CallbackEgressContext,\n CallbackIngressContext,\n} from './context.ts'\n\ntype ReconstructedCallback = (arg: unknown) => void\n\n/**\n * Bidirectional handler owning the `RequenceCallback` reference tag.\n *\n * Egress serializes any function into a full callback reference: identity\n * (`callbackId`/`sourceId`) comes from `ctx.onCallback`, the emission from\n * `ctx.outputName`, and the position from the walk's `path` — the reference's\n * public identity (the operator validates invocation args against the output\n * schema at `propertyPath`). A boundary that cannot register callbacks (no\n * `ctx.onCallback`) fails loud.\n *\n * Ingress reconstructs the reference into a callable function that dispatches\n * through `ctx.onCallbackInvoke` — with no `onCallbackInvoke` provided,\n * invoking the callback is a no-op; callers that forbid callbacks pass a\n * throwing implementation.\n */\nexport function createRequenceCallbackHandler(): ValueHandler<\n ReconstructedCallback,\n CallbackObject,\n CallbackEgressContext,\n CallbackIngressContext\n> {\n return {\n tag: 'RequenceCallback',\n\n canHandle: (value) => typeof value === 'function',\n\n serialize(callback, ctx, path) {\n if (!ctx.onCallback) {\n // handler throws are not path-wrapped by the transformer — carry the\n // position in the message ourselves\n throw new Error(\n `functions are not serializable on this boundary (no ctx.onCallback) at path \"${path.join('.')}\"`,\n )\n }\n return {\n ...ctx.onCallback(callback),\n outputName: ctx.outputName ?? null,\n propertyPath: [...path],\n __REQUENCE_type: 'RequenceCallback',\n }\n },\n\n isReference: (value): value is CallbackObject => isCallbackObject(value),\n\n deserialize(ref, ctx) {\n return (arg: unknown) => {\n ctx.onCallbackInvoke?.({ ...(ref as CallbackObject), arg })\n }\n },\n }\n}\n",
|
|
27
32
|
"/** A position in the message tree, as visited by the walk. */\nexport type TransformPath = ReadonlyArray<string | number>\n\n/** Render a path as a readable dotted/indexed accessor, e.g. `data.items[2].file`. */\nexport function formatPath(path: TransformPath): string {\n if (path.length === 0) {\n return '<root>'\n }\n let out = ''\n for (const segment of path) {\n out +=\n typeof segment === 'number'\n ? `[${segment}]`\n : out\n ? `.${segment}`\n : segment\n }\n return out\n}\n\n/**\n * Thrown when the transformer cannot fully resolve a message: a complex value\n * on egress that no registered `ValueHandler` claims, or a reference tag on\n * ingress that no handler owns. The message names the offending type/tag and\n * its path so the failure is diagnosable rather than a silent pass-through.\n */\nexport class TransformError extends Error {\n readonly path: TransformPath\n readonly detail: string\n\n constructor(detail: string, path: TransformPath) {\n super(`${detail} at ${formatPath(path)}`)\n this.name = 'TransformError'\n this.path = path\n this.detail = detail\n }\n}\n",
|
|
28
33
|
"/** The reference marker key. A handler's `tag` is mirrored here on the wire. */\nexport const REFERENCE_TAG_KEY = '__REQUENCE_type'\n\n/**\n * A plain data object: an object literal or a null-prototype object — never a\n * class instance (`Blob`, `RequenceFile`, …), whose prototype chain differs.\n * This is what lets the walk tell traversable structure apart from an opaque\n * complex value a handler must own.\n */\nexport function isPlainObject(\n value: unknown,\n): value is Record<string, unknown> {\n if (value === null || typeof value !== 'object') {\n return false\n }\n const proto = Object.getPrototypeOf(value)\n return proto === null || proto === Object.prototype\n}\n\n/**\n * A value that is neither a JSON primitive nor traversable structure — a class\n * instance, function, symbol, or bigint. On egress every such value must be\n * claimed by a handler; anything left over is unresolvable.\n */\nexport function isComplexValue(value: unknown): boolean {\n if (value === null) {\n return false\n }\n const type = typeof value\n if (type === 'object') {\n return !Array.isArray(value) && !isPlainObject(value)\n }\n return type === 'function' || type === 'symbol' || type === 'bigint'\n}\n\n/** Does a plain object carry the reference marker key? */\nexport function hasReferenceTag(value: unknown): boolean {\n return isPlainObject(value) && REFERENCE_TAG_KEY in value\n}\n",
|
|
29
34
|
"import type { TransformPath } from './errors.ts'\nimport { TransformError } from './errors.ts'\nimport { isPlainObject } from './guards.ts'\n\n/**\n * A visitor's verdict for one (already child-recursed) node:\n * - `recurse` — keep the node as-is (its children are already transformed).\n * - `replace` — the node was transformed; the walk re-processes the replacement\n * so a handler output that still embeds complex values / references resolves\n * to a fixpoint.\n */\nexport type WalkVerdict =\n | { readonly kind: 'recurse' }\n | { readonly kind: 'replace'; readonly value: unknown }\n\nexport const recurse: WalkVerdict = { kind: 'recurse' }\nexport const replaceWith = (value: unknown): WalkVerdict => ({\n kind: 'replace',\n value,\n})\n\nexport type WalkVisitor = (\n value: unknown,\n path: TransformPath,\n) => WalkVerdict | Promise<WalkVerdict>\n\n/**\n * Guard against a handler that returns a value it also claims: without a cap\n * the fixpoint re-walk would spin forever. Chosen well above any legitimate\n * nesting depth so it only ever fires on a genuine non-terminating handler.\n */\nconst MAX_REPLACE_DEPTH = 100\n\n/**\n * Generic async tree-walk — successor to `packages/helpers/src/utils/mapData`.\n *\n * Post-order: a node's array/record children are transformed first, then the\n * node itself is offered to `visit`. This makes both directions symmetric — a\n * serialize output is re-walked so nested complex values are offloaded, and a\n * reference's nested references are reconstructed *before* its handler\n * deserializes it. Concrete policy (what is handled, what throws) lives in the\n * visitor, keeping this purely structural.\n *\n * Identity dedupe (the same instance offloaded once) is owned by the visitor's\n * own memo; because the visitor's synchronous prefix runs before the walk\n * awaits, concurrent siblings sharing an instance can't race the memo.\n */\nexport async function walk(\n root: unknown,\n visit: WalkVisitor,\n): Promise<unknown> {\n const go = async (\n value: unknown,\n path: TransformPath,\n replaceDepth: number,\n ): Promise<unknown> => {\n let node = value\n\n if (Array.isArray(node)) {\n node = await Promise.all(\n node.map((item, index) => go(item, [...path, index], 0)),\n )\n } else if (isPlainObject(node)) {\n const entries = await Promise.all(\n Object.entries(node).map(\n async ([key, item]) =>\n [key, await go(item, [...path, key], 0)] as const,\n ),\n )\n node = Object.fromEntries(entries)\n }\n\n const verdict = await visit(node, path)\n\n if (verdict.kind === 'replace') {\n if (replaceDepth >= MAX_REPLACE_DEPTH) {\n throw new TransformError(\n 'transform did not reach a fixpoint (a handler keeps producing handleable output)',\n path,\n )\n }\n return go(verdict.value, path, replaceDepth + 1)\n }\n\n return node\n }\n\n return go(root, [], 0)\n}\n",
|
|
30
35
|
"import type { TransformContext } from './context.ts'\nimport { TransformError } from './errors.ts'\nimport { hasReferenceTag, isComplexValue, isPlainObject } from './guards.ts'\nimport type { MessageHandler } from './messageHandler.ts'\nimport type { ValueHandler } from './valueHandler.ts'\nimport type { WalkVisitor } from './walk.ts'\nimport { recurse, replaceWith, walk } from './walk.ts'\n\n/**\n * A value handler paired with an optional message handler that produces the\n * same reference tag — e.g. the claim-check, whose egress is a message-level\n * wrap and whose ingress is an ordinary value handler. Composing the pair in\n * one `withHandler` call keeps the two halves together.\n */\nexport interface HandlerBundle<\n ValueEgress extends object = object,\n ValueIngress extends object = object,\n MessageEgress extends object = object,\n> {\n valueHandler?: ValueHandler<any, any, ValueEgress, ValueIngress>\n messageHandler?: MessageHandler<MessageEgress>\n}\n\n/**\n * An immutable, composed transformer instance. There is no global registry:\n * each runtime builds its own instance from exactly the handlers it needs, and\n * the ctx types of `outbound`/`inbound` accumulate the composed handlers'\n * declared capabilities — the compiler tells a runtime which transport it must\n * supply.\n *\n * `withHandler` returns a NEW transformer; instances are never mutated, so a\n * base composition can be safely extended per call site.\n */\nexport interface Transformer<\n OutCtx extends object = object,\n InCtx extends object = object,\n> {\n /** Compose a value handler. */\n withHandler<VOut extends object, VIn extends object>(\n handler: ValueHandler<any, any, VOut, VIn>,\n ): Transformer<OutCtx & VOut, InCtx & VIn>\n /** Compose a bundle: a value handler and/or a paired message handler. */\n withHandler<\n VOut extends object = object,\n VIn extends object = object,\n MOut extends object = object,\n >(\n handler: HandlerBundle<VOut, VIn, MOut>,\n ): Transformer<OutCtx & VOut & MOut, InCtx & VIn>\n\n /**\n * Egress: complex → serializable. Value-walk (first matching `ValueHandler`\n * serializes each complex value; its output is re-walked to a fixpoint),\n * then message-wrap (every `MessageHandler.wrapOutbound`, in composition\n * order; a record body must keep its top-level keys — asserted after each\n * handler). A complex value no handler owns throws a path-annotated\n * `TransformError`.\n */\n outbound(value: unknown, ctx: TransformContext & OutCtx): Promise<unknown>\n\n /**\n * Ingress: serializable → complex. Value-walk only — there is no\n * message-level inbound hook (message-handler references are ordinary\n * references, owned by a `ValueHandler`, so they are reconstructed wherever\n * they appear). Each reference is routed by `isReference` to its handler's\n * `deserialize`; output is re-walked to a fixpoint. A reference tag no\n * handler owns throws a path-annotated `TransformError`.\n */\n inbound(value: unknown, ctx: TransformContext & InCtx): Promise<unknown>\n}\n\n/** Create an empty transformer to compose handlers onto. */\nexport function createTransformer(): Transformer {\n return build([], [])\n}\n\nfunction build(\n valueHandlers: readonly ValueHandler<any, any, any, any>[],\n messageHandlers: readonly MessageHandler<any>[],\n): Transformer<any, any> {\n const transformer: Transformer<any, any> = {\n withHandler(\n handler: ValueHandler<any, any, any, any> | HandlerBundle<any, any, any>,\n ) {\n const bundle: HandlerBundle<any, any, any> =\n 'tag' in handler ? { valueHandler: handler } : handler\n if (!bundle.valueHandler && !bundle.messageHandler) {\n throw new Error(\n 'withHandler: bundle provides neither a valueHandler nor a messageHandler',\n )\n }\n if (bundle.valueHandler) {\n // Two handlers sharing a tag is a wiring bug — the tag is the\n // on-the-wire discriminator, so a duplicate makes ingress routing\n // ambiguous. Caught here, at composition, rather than at transform time.\n const { tag } = bundle.valueHandler\n if (valueHandlers.some((existing) => existing.tag === tag)) {\n throw new Error(\n `withHandler: a ValueHandler with tag \"${tag}\" is already composed`,\n )\n }\n }\n return build(\n bundle.valueHandler\n ? [...valueHandlers, bundle.valueHandler]\n : valueHandlers,\n bundle.messageHandler\n ? [...messageHandlers, bundle.messageHandler]\n : messageHandlers,\n )\n },\n\n async outbound(value: unknown, ctx: TransformContext): Promise<unknown> {\n // Dedupe by instance identity: the same instance at multiple paths is\n // serialized once and every position gets the same reference. The memo\n // is set synchronously (before the first `await`) so concurrent siblings\n // can't race.\n const seen = new Map<object, Promise<unknown>>()\n\n const visit: WalkVisitor = (node, path) => {\n if (!isComplexValue(node)) {\n return recurse\n }\n\n const handler = valueHandlers.find((candidate) =>\n candidate.canHandle(node),\n )\n if (!handler) {\n // JSON.stringify parity: a value that declares its own JSON form via\n // `toJSON` (Date, Buffer, …) is not unresolvable — replace it with\n // that form and re-walk. Handlers match first, so a composed type\n // never falls through to its own toJSON here. Values with neither an\n // owner nor a toJSON stay a loud error: they would otherwise\n // silently collapse.\n const withToJSON = node as { toJSON?: () => unknown }\n if (\n typeof node === 'object' &&\n typeof withToJSON.toJSON === 'function'\n ) {\n return replaceWith(withToJSON.toJSON())\n }\n const label =\n node?.constructor?.name ??\n (typeof node === 'function' ? 'function' : typeof node)\n throw new TransformError(\n `no composed ValueHandler for complex value of type ${label}`,\n path,\n )\n }\n\n if (typeof node === 'object' && node !== null) {\n // The memo only ever caches object-identity values, whose references\n // are path-independent (file/stream) — the cached branch replays the\n // first-seen path. Non-object complex values (functions) bypass it,\n // so a path-bearing handler sees the correct path per occurrence. A\n // future path-bearing *object* handler must not rely on the memo.\n const cached = seen.get(node)\n if (cached) {\n return cached.then(replaceWith)\n }\n const pending = Promise.resolve(handler.serialize(node, ctx, path))\n seen.set(node, pending)\n return pending.then(replaceWith)\n }\n\n return Promise.resolve(handler.serialize(node, ctx, path)).then(\n replaceWith,\n )\n }\n\n const valueTransformed = await walk(value, visit)\n\n let body = valueTransformed\n for (const [index, handler] of messageHandlers.entries()) {\n const wrapped = await handler.wrapOutbound(body, ctx)\n assertTopLevelKeysPreserved(body, wrapped, index)\n body = wrapped\n }\n return body\n },\n\n async inbound(value: unknown, ctx: TransformContext): Promise<unknown> {\n const visit: WalkVisitor = (node, path) => {\n if (!isPlainObject(node)) {\n return recurse\n }\n\n const handler = valueHandlers.find((candidate) =>\n candidate.isReference(node),\n )\n if (handler) {\n // Passthrough handlers own the tag but keep the reference verbatim\n // (kept as-is, not re-walked — identity replacement would never\n // reach the fixpoint).\n if (handler.passthrough) {\n return recurse\n }\n return Promise.resolve(handler.deserialize(node, ctx, path)).then(\n replaceWith,\n )\n }\n\n if (hasReferenceTag(node)) {\n const tag = (node as Record<string, unknown>).__REQUENCE_type\n throw new TransformError(\n `no composed ValueHandler owns reference tag ${JSON.stringify(tag)}`,\n path,\n )\n }\n\n return recurse\n }\n\n return walk(value, visit)\n },\n }\n\n return transformer\n}\n\n/**\n * The `MessageHandler` shape constraint: a record body keeps its top-level\n * keys (values under them may become references, the record itself never\n * does), so forwarding hops that shallow-merge record bodies always see real\n * keys. A non-record body may be replaced wholesale.\n */\nfunction assertTopLevelKeysPreserved(\n body: unknown,\n wrapped: unknown,\n handlerIndex: number,\n): void {\n if (!isPlainObject(body)) {\n return\n }\n const label = `MessageHandler #${handlerIndex}`\n if (!isPlainObject(wrapped)) {\n throw new TransformError(\n `${label} replaced a record body wholesale — wrapOutbound must preserve a record's top-level keys`,\n [],\n )\n }\n const before = Object.keys(body)\n const after = new Set(Object.keys(wrapped))\n const removed = before.filter((key) => !after.has(key))\n const added = [...after].filter((key) => !before.includes(key))\n if (removed.length > 0 || added.length > 0) {\n throw new TransformError(\n `${label} changed a record body's top-level keys (removed: [${removed.join(\n ', ',\n )}], added: [${added.join(', ')}]) — wrapOutbound must preserve them`,\n [],\n )\n }\n}\n",
|
|
31
|
-
"import {
|
|
32
|
-
"import
|
|
33
|
-
"import {
|
|
36
|
+
"import type { SurfaceHandlerObject } from '@requence/helpers'\nimport { SURFACE_HANDLER_TAG, isSurfaceHandlerObject } from '@requence/helpers'\nimport type { ValueHandler } from '@requence/transformer'\n\n/** What a render's egress needs to turn one function prop into a reference. */\nexport interface SurfaceHandlerEgressContext {\n /**\n * Register a function found in a render payload and return its reference.\n *\n * Takes the value's **path in the payload**, which is the whole of what\n * decides the reference's lifetime: a function under `defaults` was written at\n * module scope and is durable, one under `props` was written at the render\n * call and belongs to the publishing connection (#103). Nothing else about\n * the function can tell the two apart, and the walk is the only place the\n * position is known.\n *\n * Absent ⇒ this boundary is not a render boundary and a function on it is the\n * ordinary callback case; see `transformer.ts`.\n */\n onSurfaceHandler(\n handler: (...args: unknown[]) => void,\n path: ReadonlyArray<string | number>,\n ): SurfaceHandlerObject\n}\n\n/**\n * The `RequenceHandler` tag's egress half, composed onto the **render**\n * transformer only (`transformer.ts`).\n *\n * It claims functions exactly as the callback handler does, which is why the two\n * live on different transformer instances rather than one: a function in a render\n * payload is a surface handler, a function anywhere else in a service's output is\n * a peer callback, and `canHandle` cannot see the difference.\n *\n * There is no ingress. A handler reference travels service → operator →\n * ui/backend → browser and is never transformed back into a function by anyone:\n * the browser holds a props path, and the invocation comes back as its own\n * message. A reference reaching an inbound walk is therefore a routing bug, and\n * says so.\n */\nexport function createSurfaceHandlerValueHandler(): ValueHandler<\n (...args: unknown[]) => void,\n SurfaceHandlerObject,\n SurfaceHandlerEgressContext\n> {\n return {\n tag: SURFACE_HANDLER_TAG,\n\n canHandle: (value) => typeof value === 'function',\n\n serialize(handler, ctx, path) {\n return ctx.onSurfaceHandler(handler, path)\n },\n\n isReference: (value): value is SurfaceHandlerObject =>\n isSurfaceHandlerObject(value),\n\n deserialize() {\n throw new Error(\n 'a surface handler reference is outbound-only — it is invoked by its own message, never reconstructed',\n )\n },\n }\n}\n",
|
|
37
|
+
"import { createRequenceCallbackHandler } from '@requence/callbacks'\nimport {\n createClaimCheckHandler,\n createRequenceFileHandler,\n createRequenceStreamHandler,\n} from '@requence/files'\nimport { type ValueHandler, createTransformer } from '@requence/transformer'\n\nimport { createSurfaceHandlerValueHandler } from './surfaceHandler.ts'\n\n/**\n * What every service payload carries whatever else it is: the byte references.\n * Shared by the two instances below so the pair cannot drift — `withHandler`\n * returns a NEW transformer, so extending this twice is safe.\n */\nconst byteReferences = createTransformer()\n .withHandler(createRequenceFileHandler())\n .withHandler(createRequenceStreamHandler())\n\n/**\n * The service runtime's composed transformer: byte references (file, stream,\n * claim-check) plus callbacks. The instance's `outbound`/`inbound` ctx types\n * accumulate the composed handlers' declared capabilities — the boundary\n * (`boundary.ts`) is the only place that builds those ctx objects.\n */\nexport const transformer = byteReferences\n .withHandler(createRequenceCallbackHandler())\n .withHandler(createClaimCheckHandler())\n\n/**\n * The **render** payload's egress chain: the same byte references, with the\n * callback handler swapped for the surface-handler one (#103).\n *\n * A second instance rather than a fifth handler on the first, because both\n * claim every function and `canHandle` gets nothing to tell them apart. Which\n * of the two is right is a property of the *payload*, not of the value: a\n * function in a render is a handler prop the browser will press, a function\n * anywhere else in a service's output is a callback a peer service will call.\n * Choosing per boundary is the only place that distinction actually exists.\n *\n * Outbound-only in practice — nothing ever inbound-transforms a render.\n */\nexport const renderTransformer = byteReferences\n .withHandler(createSurfaceHandlerValueHandler())\n .withHandler(createClaimCheckHandler())\n\n// Owns a reference tag on ingress but keeps the reference verbatim (the\n// transformer would otherwise fail loud on the unowned tag). Inbound-only.\nconst passthroughHandler = (handler: {\n tag: string\n isReference(value: unknown): boolean\n}): ValueHandler => ({\n tag: handler.tag,\n passthrough: true,\n canHandle: () => false,\n serialize() {\n throw new Error(`passthrough handler \"${handler.tag}\" is inbound-only`)\n },\n isReference: (value): value is unknown => handler.isReference(value),\n deserialize(ref) {\n // unreachable — `passthrough: true` keeps the reference verbatim\n return ref\n },\n})\n\n/**\n * Inbound chain for passthrough consumers (the logic runtime): claim-checks\n * still resolve — a state seed may arrive as a ClaimCheck reference — but\n * file/stream/callback references stay raw `__REQUENCE_type` wire objects,\n * JSON-safe for forwarding across a process boundary the full instances could\n * not cross. A tag owned by none of these still fails loud.\n */\nexport const passthroughInboundTransformer = createTransformer()\n .withHandler(passthroughHandler(createRequenceFileHandler()))\n .withHandler(passthroughHandler(createRequenceStreamHandler()))\n .withHandler(passthroughHandler(createRequenceCallbackHandler()))\n .withHandler(createClaimCheckHandler())\n",
|
|
38
|
+
"import type {\n CallbackEgressContext,\n CallbackIngressContext,\n} from '@requence/callbacks'\nimport { sanitizeLogData, withRequenceStreams } from '@requence/files'\nimport type { WireCodec } from '@requence/helpers/msgpack'\nimport { wireBodyByteLength } from '@requence/helpers/msgpack'\nimport logger from '@requence/logger/simple'\n\nimport type { SurfaceHandlerEgressContext } from './surfaceHandler.ts'\nimport { renderTransformer, transformer } from './transformer.ts'\n\n/**\n * The service runtime's two serialization chokepoints (issue 07): one\n * outbound boundary and one inbound boundary, both delegating to the\n * runtime's composed transformer instance (`transformer.ts`). Every sub-path\n * (main result, deferred send, log, callback arg) routes through them. The\n * boundary owns ctx construction, the background-upload done-gate, and the\n * fail policy — this is *service policy*, which is why it lives here and not\n * in a shared package; call sites only say *what* to send and on which\n * emission.\n */\n\ntype OutboundCtx = Parameters<typeof transformer.outbound>[1]\ntype InboundCtx = Parameters<typeof transformer.inbound>[1]\n\nexport interface OutboundBoundaryOptions {\n uploadUrl?: string\n streamUrl?: string\n /** Claim-check offload threshold in bytes, transmitted via task options. */\n maxPayloadSize?: number\n /** Upload/stream cap in bytes, transmitted via task options. */\n maxFileSize?: number\n /**\n * The codec this boundary's publishes will use — the codec of the dispatch\n * being replied to, since a reply echoes it.\n *\n * The claim-check offloads on the SERIALIZED size, so the threshold has to be\n * measured with the codec the body actually goes out under. Both are live at\n * once (the choice is baked per service node), so the boundary cannot assume\n * either. Defaults to `json`: the pre-migration status quo, and the right\n * answer for the deferred path, which has no dispatch to echo.\n */\n wireCodec?: WireCodec\n signal?: AbortSignal\n fetch?: typeof globalThis.fetch\n /** Sink for best-effort degradation notices. Defaults to `logger.warn`. */\n warn?(message: string, error?: unknown): void\n}\n\nexport interface OutboundSendOptions {\n /** The emission this value belongs to (embedded in callback references). */\n outputName?: string | null\n /** Callback registrar for this emission; absent ⇒ functions fail loud. */\n onCallback?: CallbackEgressContext['onCallback']\n /**\n * Surface-handler registrar (#103). Supplying it switches this send to the\n * **render** egress chain, on which a function is a handler prop rather than\n * a peer callback — the render payload is the only place that is true, and\n * this option is what says so.\n */\n onSurfaceHandler?: SurfaceHandlerEgressContext['onSurfaceHandler']\n /**\n * Top-level keys of a record payload the claim-check must leave inline (the\n * render payload's `component`, whose hash the operator parses).\n */\n inlineKeys?: readonly string[]\n /**\n * Log policy: sanitize the payload first (functions/opaque instances become\n * labels), degrade offload failures to warnings, and never reject — a log\n * line must not fail the task. On a transform error resolves to `undefined`\n * (callers skip publishing).\n */\n bestEffort?: boolean\n}\n\nexport interface OutboundBoundary {\n /**\n * Serialize a value through the composed transformer inside a\n * `withRequenceStreams` scope. The returned promise resolves with the\n * serialized value as soon as references exist (stream bodies may still be\n * uploading); background completion is tracked in the boundary's ledger and\n * surfaced by `settle()`.\n */\n send(data: unknown, opts?: OutboundSendOptions): Promise<unknown>\n /** Enroll an external promise (e.g. a publish) in the done-gate. */\n track(promise: Promise<unknown>): void\n /**\n * The done-gate: wait until the ledger stops growing (sends may enqueue\n * more sends), then throw an `AggregateError` if any fail-hard work failed.\n * Ledger entries are pre-caught at registration time, so nothing ever\n * rejects unhandled while the gate is not yet attached.\n */\n settle(): Promise<void>\n}\n\nexport function createOutboundBoundary(\n base: OutboundBoundaryOptions,\n): OutboundBoundary {\n const warn =\n base.warn ??\n ((message: string, error?: unknown) =>\n error === undefined ? logger.warn(message) : logger.warn(message, error))\n\n const ledger: Array<Promise<void>> = []\n const errors: Error[] = []\n\n // Bound once: a JSON measurement of a msgpack body offloads at the wrong\n // point, and it fails quietly either way — too eager is a needless S3\n // round-trip on the hot path, too late is a rejection at the broker.\n const codec = base.wireCodec ?? 'json'\n const measure = (value: unknown) => wireBodyByteLength(value, codec)\n\n const track = (promise: Promise<unknown>) => {\n ledger.push(\n promise.then(\n () => {},\n (error: unknown) => {\n errors.push(error instanceof Error ? error : new Error(String(error)))\n },\n ),\n )\n }\n\n return {\n track,\n\n async send(data, opts = {}) {\n const ctx: OutboundCtx = {\n fetch: base.fetch ?? globalThis.fetch,\n signal: base.signal,\n uploadUrl: base.uploadUrl,\n streamUrl: base.streamUrl,\n maxPayloadSize: base.maxPayloadSize,\n maxFileSize: base.maxFileSize,\n measure,\n outputName: opts.outputName ?? null,\n onCallback: opts.onCallback,\n inlineKeys: opts.inlineKeys,\n ...(opts.bestEffort\n ? {\n onOffloadFail: (error: Error) =>\n warn('offload failed (best-effort log path):', error),\n onOffloadSkip: () =>\n warn('offload skipped: no upload transport configured'),\n }\n : {}),\n }\n\n if (opts.bestEffort) {\n try {\n const { value, done } = await withRequenceStreams(() =>\n transformer.outbound(sanitizeLogData(data), ctx),\n )\n // resolve-only: the gate waits for the upload but cannot fail on it\n ledger.push(\n done.then(\n () => {},\n (error: unknown) => warn('log stream upload failed:', error),\n ),\n )\n return value\n } catch (error) {\n warn('log offload errored:', error)\n return undefined\n }\n }\n\n // A render goes down the chain where a function is a handler prop, and it\n // is the only send that can supply the capability that chain needs — so\n // the option and the instance are chosen together, and the plain chain\n // never has to carry a registrar it has no handler for.\n const { value, done } = await withRequenceStreams(() =>\n opts.onSurfaceHandler\n ? renderTransformer.outbound(data, {\n ...ctx,\n onSurfaceHandler: opts.onSurfaceHandler,\n })\n : transformer.outbound(data, ctx),\n )\n track(done)\n return value\n },\n\n async settle() {\n for (;;) {\n const count = ledger.length\n await Promise.all(ledger)\n if (count === ledger.length) {\n break\n }\n }\n if (errors.length > 0) {\n const failed = errors.splice(0)\n throw new AggregateError(failed, failed[0].message)\n }\n },\n }\n}\n\nexport interface InboundBoundaryOptions {\n fetch?: typeof globalThis.fetch\n /** Cancellation for lazy remote reads of reconstructed values. */\n signal?: AbortSignal\n /** Per-boundary rehydration timeout; composed with `signal` per call. */\n timeoutMs?: number\n /** Default invocation dispatch for reconstructed callbacks. */\n onCallbackInvoke?: CallbackIngressContext['onCallbackInvoke']\n /**\n * Transformer override for this boundary; defaults to the full composed\n * chain. Passthrough consumers substitute the claim-check-only instance\n * (`transformer.ts`) so byte references stay raw wire objects.\n */\n transformer?: { inbound(data: unknown, ctx: InboundCtx): Promise<unknown> }\n}\n\nexport interface InboundReceiveOptions {\n onCallbackInvoke?: CallbackIngressContext['onCallbackInvoke']\n}\n\n/**\n * The single place the service's ingress cancellation/timeout policy lives:\n * every inbound transform of the runtime goes through one of these.\n */\nexport function createInboundBoundary(base: InboundBoundaryOptions = {}) {\n return (\n data: unknown,\n opts: InboundReceiveOptions = {},\n ): Promise<unknown> => {\n const timeout =\n base.timeoutMs && base.timeoutMs > 0\n ? AbortSignal.timeout(base.timeoutMs)\n : undefined\n const signal =\n base.signal && timeout\n ? AbortSignal.any([base.signal, timeout])\n : (timeout ?? base.signal)\n\n const ctx: InboundCtx = {\n fetch: base.fetch ?? globalThis.fetch,\n signal,\n onCallbackInvoke: opts.onCallbackInvoke ?? base.onCallbackInvoke,\n }\n return (base.transformer ?? transformer).inbound(data, ctx)\n }\n}\n",
|
|
39
|
+
"import { AsyncLocalStorage } from 'node:async_hooks'\n\nimport type { CallbackObject } from '@requence/helpers'\nimport { DEFAULT_SURFACE_ID } from '@requence/helpers'\n\nimport { createInboundBoundary } from './boundary.ts'\nimport { passthroughInboundTransformer } from './transformer.ts'\nimport type { RenderProps, RequenceUI } from './ui.ts'\n\nexport type JSONValue =\n | string\n | number\n | boolean\n | { [x: string]: JSONValue }\n | Array<JSONValue>\n | null\n | undefined\n\nexport class RetryError extends Error {\n constructor(public delay?: number) {\n super()\n }\n}\n\nexport class SkipError extends Error {}\n\nexport class AbortError extends Error {}\n\nconst OUTPUT_VALUE = Symbol('output_value')\n\ntype OutputValue = {\n [OUTPUT_VALUE]: string | null\n value: any\n}\n\nfunction isOutputValue(value: unknown): value is OutputValue {\n return value !== null && typeof value === 'object' && OUTPUT_VALUE in value\n}\n\n/**\n * Unwrap the `context.toOutput(...)` symbol wrapper into its raw value and\n * output name. Pure — serialization happens at the component's outbound\n * boundary (`createOutboundBoundary`), not here.\n */\nexport function unwrapOutputValue(result: unknown): {\n value: unknown\n outputName: string | null\n} {\n if (isOutputValue(result)) {\n return { value: result.value, outputName: result[OUTPUT_VALUE] }\n }\n return { value: result, outputName: null }\n}\n\n// The privileged send API (unit 05 headers, main-path variant). Runtime-attached\n// to every handler context but deliberately absent from the inferred\n// `ContextHelper` type — ordinary services must not discover it via typing.\n// Privileged consumers (the reserved requence-logic runtime) cast their context\n// to `PrivilegedContext`.\nexport interface PrivilegedSends {\n send(data: unknown, options?: { overwrite?: boolean }): void\n sendToOutput(\n name: string,\n data: unknown,\n options?: { overwrite?: boolean },\n ): void\n sendState(state: unknown): void\n // Fire-and-forget invocation of a raw RequenceCallback wire ref (todo/11):\n // passthrough consumers receive callback refs un-rehydrated, so this is\n // their dispatch path. The arg goes through the message's outbound boundary\n // like any callback invocation; failures surface at the settle gate, not\n // here.\n invokeCallback(ref: CallbackObject, arg: unknown): void\n // The dispatch's transport options (payload.options, verbatim) so a\n // privileged consumer can forward upload targets across its own boundary.\n options: {\n uploadUrl?: string\n streamUrl?: string\n maxPayloadSize?: number\n maxFileSize?: number\n }\n}\n\nexport default async function createContextHelper(options: {\n taskId: string\n input: unknown\n configuration: unknown\n // Hoisted per-message controller (shared with the outbound boundary);\n // created here when the caller does not provide one.\n abortController?: AbortController\n // Skip file/stream/callback rehydration on ingress (claim-checks still\n // resolve): byte references reach the handler as their raw JSON-safe\n // `__REQUENCE_type` wire objects. Used by consumers that forward values\n // across a JSON process boundary (the logic runtime's guest channel).\n passthroughByteReferences?: boolean\n onLog: (method: 'log' | 'warn' | 'info' | 'error', data: any[]) => void\n onDefer: (reason?: string) => string\n onCallback: (params: {\n sourceId: string\n callbackId: string\n outputName: string | null\n propertyPath: (string | number)[]\n arg: unknown\n }) => void\n onRender: (params: {\n ui: RequenceUI\n props: unknown\n surfaceId: string\n }) => void\n sends: PrivilegedSends\n}) {\n const terminatePromise = Promise.withResolvers<string>()\n const abortController = options.abortController ?? new AbortController()\n terminatePromise.promise.then(() => abortController.abort())\n\n const terminated = Object.assign(terminatePromise.promise, {\n signal: abortController.signal,\n })\n\n // Rehydration (FileObject/StreamObject → RequenceFile/RequenceStream,\n // RequenceCallback → function) — the component's single signal-aware\n // inbound boundary, called once per inbound sub-path. Passthrough mode swaps\n // in the chain that resolves claim-checks but keeps byte references raw.\n const inbound = createInboundBoundary({\n signal: abortController.signal,\n ...(options.passthroughByteReferences\n ? { transformer: passthroughInboundTransformer }\n : {}),\n })\n const [input, configuration] = await Promise.all([\n inbound(options.input, { onCallbackInvoke: options.onCallback }),\n inbound(options.configuration, {\n onCallbackInvoke: () => {\n throw new Error('configuration may not have callbacks')\n },\n }),\n ])\n\n const context = {\n taskId: options.taskId,\n input,\n configuration,\n\n toOutput(name: string | null, value: unknown): OutputValue {\n return {\n [OUTPUT_VALUE]: name,\n value,\n }\n },\n defer: options.onDefer,\n\n /**\n * Renders a UI component on this node in the task canvas. `props` is a\n * plain object and that is the entire contract — functions inside it arrive\n * in the component as invokable handlers, through the same transform a\n * peer service's payload goes through.\n *\n * Fire-and-forget, like a data send: the publish is enrolled in the\n * message's ledger, so a failure fails the node at the settle gate rather\n * than at this call site.\n *\n * **Where you write a function decides how long it can be pressed** (#103).\n * One written here closes over this handler, so it is connection-bound: it\n * needs a generator handler (a non-generator's registry goes the moment it\n * returns) and it dies with the message. One written in the UI's own\n * defaults — `createUI(url, { onSubmit })` — closes over module scope, so\n * any instance of this version can run it, and an invocation waits in the\n * version's handler queue when none is up. That is the honest answer to a\n * wait measured in days: a form's `onSubmit` belongs in the defaults, and\n * the handler that renders it is free to defer and exit.\n *\n * `props` is type-checked against the `ui`'s declared props\n * (`createUI<Props>`) — but every prop is optional, because **a render is a\n * patch** (#102). What the surface shows is the fold of the UI's defaults,\n * everything previously rendered onto that surface, and this render, so a\n * redraw carries only what changed and a prop nobody restates simply stays.\n * The flip side is that TypeScript can no longer tell a patch from a first\n * render that forgot half its props: the fold is the service's to complete.\n */\n render<Props>(\n ui: RequenceUI<Props>,\n props: RenderProps<Props>,\n renderOptions?: { surfaceId?: string },\n ) {\n options.onRender({\n ui,\n props,\n surfaceId: renderOptions?.surfaceId ?? DEFAULT_SURFACE_ID,\n })\n },\n\n debug: {\n log(...data: any[]) {\n options.onLog('log', data)\n },\n info(...data: any[]) {\n options.onLog('info', data)\n },\n warn(...data: any[]) {\n options.onLog('warn', data)\n },\n error(...data: any[]) {\n options.onLog('error', data)\n },\n },\n retry(delay?: number) {\n throw new RetryError(delay)\n },\n abort(reason?: string) {\n throw new AbortError(reason)\n },\n skip() {\n throw new SkipError()\n },\n terminated,\n }\n\n // Attached at runtime only: `context`'s inferred type (and therefore the\n // public `ContextHelper`) must not include the privileged send API.\n Object.assign(context, options.sends)\n\n return [context, terminatePromise] as const\n}\n\nexport type ContextHelper = Awaited<ReturnType<typeof createContextHelper>>[0]\n\n// Undocumented — the context shape privileged consumers (requence-logic) cast\n// to. The send methods are present at runtime on every handler context but\n// hidden from `ContextHelper`; the operator honors their `state`/`overwrite`\n// headers only for privileged nodes.\nexport type PrivilegedContext = ContextHelper & PrivilegedSends\n\nexport const handlerStorage = new AsyncLocalStorage<ContextHelper>()\n",
|
|
40
|
+
"import { createHash } from 'node:crypto'\nimport fs from 'node:fs'\nimport path from 'node:path'\n\nimport { MAX_UI_SOURCE_BYTES } from '@requence/helpers'\n\nimport type { RequenceUI } from './ui.ts'\n\n/**\n * A component handle as the watcher holds it — the object `createUI` returned,\n * with every field writable. Derived from {@link RequenceUI} rather than\n * restated, so a field added there cannot go unwatched. The public type keeps\n * them `readonly`: rewriting them is this module's job and nobody else's.\n *\n * \"Writable\" is wider than \"rewritten\": a rebuild only ever replaces `hash` and\n * `source`, because they are the only fields that come out of the file. The rest\n * (`id`, `defaults`) are mutable here purely because `createUI` builds\n * the handle as this type — `id` in particular is the one field a rebuild must\n * NOT touch (#103).\n *\n * (The import is type-only, so `ui.ts` importing this module back is not a\n * runtime cycle.)\n */\nexport type MutableRequenceUI = {\n -readonly [K in keyof Omit<RequenceUI, '__props'>]: RequenceUI[K]\n}\n\nexport interface UIWatchListener {\n /**\n * A watched component's built file changed content. The handle already\n * carries the new bytes; announcing the swap is the listener's job.\n */\n onRebuild: (ui: MutableRequenceUI) => void\n /**\n * Something the author needs to hear about the watch itself. Reported rather\n * than logged because this module is process-global and `silent` is a\n * per-connection option — only the subscriber knows whether to print. Fanned\n * out to every subscriber; in the normal case that is the one dev connection\n * that turned the loop on.\n */\n onWarning: (message: string) => void\n}\n\n/**\n * Coalescing window for a burst of writes. A build tool rarely produces one\n * write per output file, and a read taken between two of them yields a\n * half-written bundle — which would render, fail, and be replaced a beat later\n * by the good one (D16's error state, flashing). Long enough to swallow an\n * ordinary bundler's burst, short enough to feel immediate.\n */\nconst REBUILD_DEBOUNCE_MS = 100\n\ninterface Registration {\n ui: MutableRequenceUI\n path: string\n /** Present exactly while this registration is being watched. */\n stop?: () => void\n /**\n * The last build refused for breaking the cap. Kept so an author who has to\n * go and shrink their bundle is told once, not once per write anywhere in the\n * directory.\n */\n refusedHash?: string\n}\n\nconst registrations = new Set<Registration>()\nconst listeners = new Set<UIWatchListener>()\nlet watching = false\n\nfunction warn(message: string) {\n listeners.forEach((listener) => listener.onWarning(message))\n}\n\n/**\n * Records a component built by `createUI`, so the dev loop can find it later.\n *\n * Unconditional, in every mode: `createUI` runs at module scope and cannot know\n * whether the service it belongs to will connect with a dev token. Registration\n * costs one object in a set and starts nothing — a watcher exists only once\n * {@link watchUIRebuilds} is called, which only a dev-mode connection does.\n */\nexport function registerUI(ui: MutableRequenceUI, filePath: string) {\n // The id is what a durable handler invocation names (#103), so two handles\n // claiming one makes it ambiguous — and the symptom would be a click running\n // the wrong component's handler, which reads like a bug in the component.\n // Thrown here, at module scope, so it is a startup failure with both paths in\n // it and the fix (`createUI({ url, id })`) named.\n //\n // Registering the SAME file twice is a clash too, not a re-registration: two\n // handles can carry different defaults, so `findUIById` would still have to\n // pick one. There is no id under which a process holds two components.\n const clash = [...registrations].find((existing) => existing.ui.id === ui.id)\n if (clash) {\n throw new Error(\n `two components share the UI id \"${ui.id}\" (${clash.path} and ${filePath}) — pass an explicit id: createUI({ url, id: '…' })`,\n )\n }\n\n const registration: Registration = { ui, path: filePath }\n registrations.add(registration)\n if (watching) {\n startWatching(registration)\n }\n}\n\n/**\n * The UI a durable handler invocation names (#103), or `undefined` when this\n * process has none under that id.\n *\n * Process-global, like the registry itself: a durable handler belongs to the\n * *service version*, not to a connection, so whichever connection consumed the\n * invocation resolves it against the same set of components the process\n * registered at module scope.\n */\nexport function findUIById(id: string): MutableRequenceUI | undefined {\n return [...registrations].find((entry) => entry.ui.id === id)?.ui\n}\n\n/**\n * Turns the dev loop on (D10): watch every registered component's built file\n * and call `onRebuild` whenever one of them changes content.\n *\n * The handle itself is rewritten before the listener runs, so two things follow\n * from one rebuild: every later render carries the new bundle (the render path\n * reads the handle at call time), and the listener announces the swap for every\n * surface already drawn (#108). Neither is a re-render — a rebuild changes which\n * bytes the frame imports and nothing else — which is why the swap reaches a\n * surface whose message has long since settled.\n *\n * Returns an unsubscribe. The last one out stops the watchers.\n */\nexport function watchUIRebuilds(listener: UIWatchListener): () => void {\n listeners.add(listener)\n\n if (!watching) {\n watching = true\n registrations.forEach(startWatching)\n }\n\n return () => {\n listeners.delete(listener)\n if (listeners.size > 0) {\n return\n }\n watching = false\n for (const registration of registrations) {\n registration.stop?.()\n registration.stop = undefined\n }\n }\n}\n\nfunction startWatching(registration: Registration) {\n if (registration.stop) {\n return\n }\n\n // The **directory**, not the file. A build that writes a temp file and\n // renames it over the target replaces the inode, and a watch on the file\n // follows the old one into oblivion — silently: no error, just no more\n // events. The directory sees the rename, and the delete-then-recreate case\n // with it.\n //\n // Unfiltered, deliberately: the reported name cannot carry the filter. Bun's\n // directory watch announces a rename under the *source* name only (verified —\n // a temp file renamed over the target reports the temp name twice, never the\n // target's), so matching on it would drop exactly the case the directory\n // watch exists for. The filter is content-addressing instead: a neighbour's\n // write costs one debounced read and hash, which matches and returns.\n const directory = path.dirname(registration.path)\n\n let timer: ReturnType<typeof setTimeout> | undefined\n let watcher: fs.FSWatcher\n\n try {\n watcher = fs.watch(directory, () => {\n clearTimeout(timer)\n timer = setTimeout(() => reload(registration), REBUILD_DEBOUNCE_MS)\n timer.unref?.()\n })\n } catch (error) {\n // An unwatchable path degrades the dev loop to nothing and must never take\n // the service with it — the author still gets a rebuild on restart.\n warn(\n `Requence: cannot watch ${registration.path} for rebuilds: ${error instanceof Error ? error.message : String(error)}`,\n )\n return\n }\n\n // Never hold the process open, and never crash it: the dev loop is an\n // addition to a running service, not a reason for one to live or die.\n watcher.unref?.()\n watcher.on('error', (error: Error) => {\n warn(`Requence: stopped watching ${registration.path}: ${error.message}`)\n })\n\n registration.stop = () => {\n clearTimeout(timer)\n watcher.close()\n }\n}\n\nfunction reload(registration: Registration) {\n let bundle: Buffer\n try {\n bundle = fs.readFileSync(registration.path)\n } catch {\n // Mid-write, or gone. Nothing to report: the write that follows re-triggers\n // this, and a build that never finishes is the author's own signal.\n return\n }\n\n const hash = createHash('sha256').update(bundle).digest('hex')\n if (hash === registration.ui.hash) {\n // Touched, not changed — a rebuild that produced identical output, an\n // editor's save of an unmodified file, or one of the file's neighbours\n // moving. Re-rendering would remount every surface for nothing.\n return\n }\n\n if (bundle.byteLength > MAX_UI_SOURCE_BYTES) {\n // The cap is `createUI`'s throw at registration (D4), but there is no call\n // site to throw at here — so the rebuild is refused and the previous bundle\n // stays live, which is the only outcome that keeps the surfaces working.\n if (hash !== registration.refusedHash) {\n registration.refusedHash = hash\n warn(\n `Requence: rebuilt component ${registration.path} is ${bundle.byteLength} bytes, over the ${MAX_UI_SOURCE_BYTES} limit — keeping the previous bundle`,\n )\n }\n return\n }\n\n // Mutating the handle in place **is** the mechanism. `context.render` reads\n // `ui.hash`/`ui.source` at call time, so from here on every render the service\n // makes carries the new bundle through the unchanged production path — and the\n // listener below repoints the surfaces that were already drawn.\n registration.ui.hash = hash\n registration.ui.source = bundle.toString('utf-8')\n\n for (const listener of [...listeners]) {\n listener.onRebuild(registration.ui)\n }\n}\n",
|
|
41
|
+
"import { createHash } from 'node:crypto'\nimport fs from 'node:fs'\nimport { basename } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nimport type { WrappedRequenceCallback } from '@requence/helpers'\nimport { MAX_UI_SOURCE_BYTES } from '@requence/helpers'\n\nimport { UITooLargeError } from './errors.ts'\nimport { type MutableRequenceUI, registerUI } from './uiWatch.ts'\n\n/**\n * A registered UI component: the built module's source plus its content hash.\n * Opaque to the author at the value level — the only thing to do with it is pass\n * it to `context.render(ui, props)`.\n *\n * `Props` is a phantom type parameter (never present at runtime) carrying the\n * shape the service sends to this component. It is what makes `render(ui, props)`\n * type-check against the service's own TypeScript, and what the component author\n * reads back with {@link PropsOf} to type `mount`. Declare it once, at\n * `createUI<Props>(url)`.\n */\nexport interface RequenceUI<Props = unknown> {\n /**\n * This component's **stable identity** — what a durable handler reference\n * names (#103), and the one thing about a UI that a rebuild must not change.\n *\n * The content hash cannot serve: a rebuild changes it while the module-scope\n * function in the defaults stays the same function, so a durable reference\n * keyed on the hash would stop resolving the moment the component was rebuilt\n * — and would never resolve at all in a process that started after the render.\n * Defaults to the built module's **file name**, which survives both a rebuild\n * and a restart; {@link CreateUIOptions.id} overrides it.\n *\n * Unique per process, enforced at registration: two components sharing an id\n * would make a durable invocation ambiguous, and the failure would be a click\n * reaching the wrong handler rather than anything visible.\n */\n readonly id: string\n /**\n * The bundle's content hash. `readonly` to the author but not immutable: in\n * service dev mode a rebuild of the watched file rewrites this and `source`\n * in place (D10), which is what makes the next ordinary render carry the new\n * bundle. Read it at use, never cache it.\n */\n readonly hash: string\n readonly source: string\n /**\n * The props this component always has, as declared at `createUI` — restated on\n * every render of it, so a service states once what does not change per\n * message and a render carries only what differs.\n *\n * Sent as their own field of the render payload rather than merged into the\n * render's props, because the receiver ranks them **lowest** (#102): a default\n * is what a surface shows until some render says otherwise, and it never\n * overrides what one already did. Merging them here would rank them highest\n * instead, which is the one thing a default must not be.\n *\n * Absent rather than empty when none were declared, so the payload of a\n * component without defaults is exactly what it always was.\n *\n * Deliberately **not** part of the hash: they are what the service sends, not\n * what the browser loads, so two registrations of one built file still dedupe\n * on the same bundle.\n */\n readonly defaults?: Partial<Props>\n /**\n * Phantom carrier for the props type — optional and never assigned, so it\n * adds no runtime surface. Only `render`/{@link PropsOf} read it at the type\n * level.\n */\n readonly __props?: Props\n}\n\n/**\n * What every invokable prop carries in the component, beside being callable.\n *\n * `reachable` is the answer to \"would pressing this do anything\", **per prop**\n * (#106) — because one surface can carry handlers of both lifetimes at once and\n * a surface-wide flag necessarily lies about one of them:\n *\n * ```\n * reachable(durable) = the task is still running\n * reachable(connection) = …and this surface's own connection is alive, with the\n * reference belonging to its current render\n * ```\n *\n * Read it *with* `ctx.canInvoke`, never instead of it: that one is permission,\n * this one is whether there is anything at the other end. A control should be\n * offered when both hold.\n *\n * Calling an unreachable handler **throws** (D32), naming the prop and the reason,\n * and sends nothing. Catch it on `error.name === 'RequenceUnreachableHandlerError'`\n * — the frame and your component share a realm but no module, so the name is the\n * whole contract:\n *\n * ```js\n * try {\n * props.onSubmit(answer)\n * } catch (error) {\n * if (error.name === 'RequenceUnreachableHandlerError') showNotice(error.message)\n * else throw error\n * }\n * ```\n *\n * It used to warn instead, which could not be handled: a component had no signal\n * that the click went nowhere, and `reachable` — readable before the call — races\n * a flip that lands between the render and the press. Reading `reachable` to\n * withhold the control is still right; the throw is what covers the race and the\n * component that does not check.\n *\n * **The viewer is told either way.** The frame also reports the refusal to the\n * canvas, which shows it beneath the surface in the same strip a permission or\n * byte-cap refusal uses. So catching is about saying something *better* in your\n * own words and your own layout — not about whether the failure is visible.\n */\nexport type HandlerReachability = {\n readonly reachable: boolean\n}\n\n/**\n * An invokable prop as the component holds it: the function the service put in\n * the props, plus {@link HandlerReachability}.\n */\nexport type RequenceHandler<Arg> = ((arg: Arg) => void) & HandlerReachability\n\n/**\n * How a single prop value looks to the component.\n *\n * Every function among the props is a **handler** the browser can invoke, so it\n * arrives callable and carrying its own `reachable` flag. A callback sent by the\n * service arrives rehydrated the same way (the browser is one more consumer of\n * the same inbound transform a peer service uses), so the service-only\n * `WrappedRequenceCallback` — its extra `.response()` — is reduced to what the\n * component actually holds. Everything else passes through untouched, so branded\n * values (`RequenceFile`, `RequenceStream`) and plain data keep their type\n * exactly.\n *\n * The parameter list is preserved rather than collapsed to `RequenceHandler`'s\n * single `Arg`, so a prop declared `onClose(): void` stays callable with no\n * argument.\n */\ntype ComponentPropValue<V> =\n V extends WrappedRequenceCallback<infer Arg>\n ? RequenceHandler<Arg>\n : V extends (...args: infer Args) => unknown\n ? ((...args: Args) => void) & HandlerReachability\n : V\n\n/**\n * The props as the component receives them: the service-declared props with\n * every top-level callback presented in its invokable form.\n */\nexport type ComponentProps<Props> = Props extends object\n ? { [K in keyof Props]: ComponentPropValue<Props[K]> }\n : Props\n\n/**\n * Extracts the component-facing props type from a `ui` handle, so a component\n * author can type `mount` straight off the value they imported:\n * `SurfaceContext<PropsOf<typeof ui>>`.\n */\nexport type PropsOf<U> =\n U extends RequenceUI<infer Props> ? ComponentProps<Props> : never\n\n/**\n * The props one render may supply: **any subset** of the component's props.\n *\n * A render is a patch, not a whole value (#102) — what the surface shows is the\n * fold of the UI's defaults, everything previously rendered onto that surface,\n * and this render — so omitting a prop is the normal case and cannot be an\n * error. A handler that redraws one field is the reason the fold exists, and the\n * clearest instance of it is a handler that *cannot* restate the rest: a durable\n * one, running in a process that never saw the original render.\n *\n * The accepted cost, and it is a real one: TypeScript cannot see the accumulated\n * state, so it can no longer tell a legitimate patch from a first render that\n * forgot half its props. `PropsOf` — the component's side — stays whole and\n * required, because the component genuinely does receive the folded object; it\n * is the service's responsibility that the fold covers it.\n */\nexport type RenderProps<Props> = Partial<Props>\n\n/**\n * What a component is handed, re-exported from the one place all three readers\n * share (#113): the SDK, the frame protocol and the shared runtime's\n * `createSurface`. Declared in `@requence/helpers/utils/surfaceComponent.ts`,\n * which is where the documentation lives — an author reads them from here.\n */\nexport type {\n Mount,\n SurfaceContext,\n SurfaceState,\n SurfaceTheme,\n} from '@requence/helpers'\n\nexport interface CreateUIOptions {\n /**\n * Where the built module is — `new URL('./component.js', import.meta.url)`.\n *\n * A URL rather than a path because it is the one form that resolves against\n * the *module that wrote it*: a relative path resolves against the process's\n * working directory, so a service started from anywhere but its own package\n * silently failed to find its own component.\n */\n url: URL\n /**\n * Override this component's stable id ({@link RequenceUI.id}), which defaults\n * to the built module's file name.\n *\n * Three reasons to set it, and the first two are about the default being a\n * file name: two components in different directories that build to `index.js`\n * collide, and renaming a built file silently retires every durable handler\n * reference already sitting in a queue or stored on a surface. The third is\n * registering **one** file twice — two handles with different defaults — which\n * is a collision like any other.\n *\n * A collision throws at registration, at module scope, so it is a startup\n * error rather than a click resolving against the wrong component's defaults.\n */\n id?: string\n}\n\n/**\n * Registers a UI component from an already-built ES module — one default export\n * `mount(element, ctx)`. Requence never bundles: the author builds with their\n * own toolchain, and this only reads the result and hashes it, which is what\n * keeps the contract portable across SDKs.\n *\n * Called at module scope, next to `createService`, so an oversized bundle fails\n * at registration rather than on the first render in production\n * (knowledge/service-ui-surfaces.md D4).\n *\n * ```ts\n * const askUI = createUI<{ question: string }>(\n * new URL('./ask.mount.js', import.meta.url), // or { url, id: 'ask' }\n * )\n * ```\n *\n * Nothing here declares how the bundle was built. A component may leave `react`,\n * `react-dom/client`, `react/jsx-runtime` and `@requence/surface-ui` **external**\n * and let the surface host's shared runtime resolve them — the import map is\n * installed for every surface, so importing the facade is the whole opt-in, and\n * its price is stated where that import is declared\n * (`@requence/service/surface-ui`). A bundle that ships its own framework has no\n * bare specifier left for the map to bind and is unaffected either way.\n *\n * Declare the props the service will send as the `Props` type argument: it is\n * erased at runtime but flows to `render(ui, props)` and back to the component\n * through {@link PropsOf}.\n *\n * `defaults` is any subset of `Props`, restated on every render of this\n * component, so a service declares once what does not change per message:\n *\n * ```ts\n * const panelUI = createUI<{ title: string; dense: boolean }>(\n * new URL('./panel.js', import.meta.url),\n * { dense: true },\n * )\n *\n * context.render(panelUI, { title: 'Processing' }) // dense comes along\n * ```\n *\n * They are the **weakest** layer of the surface's fold (#102): a render that\n * names a defaulted prop overrides it, and it stays overridden for every later\n * render that stays silent about it. A default answers \"what does this surface\n * show until something says otherwise\", not \"what does it show unless this\n * render says otherwise\".\n *\n * A function among them is a **durable** handler (D24): written at module scope, it\n * closes over nothing one message owns, so any instance of the version can run it —\n * including one started after the process that rendered has exited. That is the\n * opposite of a function written inline at `context.render`, which dies with the\n * message that published it. Where you write it is the whole decision.\n */\nexport function createUI<Props = unknown>(\n target: URL | CreateUIOptions,\n defaults?: Partial<Props>,\n): RequenceUI<Props> {\n const options = target instanceof URL ? { url: target } : target\n\n // The one thing `createUI` validates at run time, and it covers every way the\n // argument can be wrong at once: a path string (what it used to take), an\n // options object without a `url`, and a URL that names something other than a\n // file (`http://…` to a hosted bundle — Requence reads the bytes here, it does\n // not fetch them). Said here rather than left to `fileURLToPath`, whose\n // complaint is about an argument the author never wrote.\n if (!(options?.url instanceof URL) || options.url.protocol !== 'file:') {\n throw new Error(\n \"createUI needs a file URL to the built component: new URL('./component.js', import.meta.url)\",\n )\n }\n\n const path = fileURLToPath(options.url)\n const bundle = fs.readFileSync(path)\n\n if (bundle.byteLength > MAX_UI_SOURCE_BYTES) {\n throw new UITooLargeError(path, bundle.byteLength, MAX_UI_SOURCE_BYTES)\n }\n\n const ui: MutableRequenceUI = {\n // The stable half of the identity (#103), and the deliberate opposite of\n // the hash below: taken off the file's NAME, which a rebuild leaves alone.\n id: options.id ?? basename(path),\n // Content-addressed, so identical bundles dedupe across renders, replicas\n // and tasks — and so a rebuild yields a new identity by construction.\n hash: createHash('sha256').update(bundle).digest('hex'),\n source: bundle.toString('utf-8'),\n // Copied, so the object the author passed cannot change what a render sends\n // after registration. One level only — a nested default value stays shared,\n // exactly like any other prop value a service reuses across renders.\n ...(defaults === undefined ? {} : { defaults: { ...defaults } }),\n }\n\n // Recorded in every mode, watched in none of them by itself: this runs at\n // module scope, long before anything knows whether the service will connect\n // with a dev token, so the decision belongs to the connection (D10).\n registerUI(ui, path)\n\n return ui as RequenceUI<Props>\n}\n",
|
|
34
42
|
"import { handlerStorage } from './helpers.ts'\n\nfunction isAsyncIterable<T>(\n iterable: Iterable<T> | AsyncIterable<T>,\n): iterable is AsyncIterable<T> {\n return typeof (iterable as any)[Symbol.asyncIterator] === 'function'\n}\n\nexport function wrapIterable<T extends Iterable<any> | AsyncIterable<any>>(\n iterable: T,\n): T {\n const context = handlerStorage.getStore()\n\n if (!context) {\n return iterable\n }\n\n let terminated = false\n\n context.terminated.then(() => {\n terminated = true\n })\n\n if (isAsyncIterable(iterable)) {\n return {\n [Symbol.asyncIterator]() {\n const iterator = iterable[Symbol.asyncIterator]()\n\n return {\n async next() {\n const result = await Promise.race([\n context.terminated,\n iterator.next(),\n ])\n\n if (terminated) {\n return { done: true, value: undefined }\n }\n\n return result\n },\n }\n },\n } as T\n }\n\n return {\n [Symbol.iterator]() {\n const iterator = iterable[Symbol.iterator]()\n\n return {\n next() {\n if (terminated) {\n return { done: true, value: undefined }\n }\n const result = iterator.next()\n return result\n },\n }\n },\n } as T\n}\n\nexport function asyncEventEmitter<T>(initial: Array<T> = []) {\n const context = handlerStorage.getStore()\n\n let terminated = false\n context?.terminated.then(() => {\n terminated = true\n })\n\n let resolve: (value: T) => void\n const initialValues = structuredClone(initial)\n return {\n push: (value: T) => {\n if (resolve) {\n resolve(value)\n } else {\n initialValues.push(value)\n }\n },\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return {\n async next() {\n if (initialValues.length > 0) {\n return { value: initialValues.shift()!, done: false }\n }\n const defer = Promise.withResolvers<T>()\n resolve = defer.resolve\n\n if (context) {\n const value = await Promise.race([\n defer.promise,\n context.terminated,\n ])\n\n return terminated\n ? { done: true, value: undefined }\n : { done: false, value: value as Awaited<T> }\n }\n\n return { value: await defer.promise, done: false }\n },\n }\n },\n }\n}\n"
|
|
35
43
|
],
|
|
36
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;;;ACAA;AAEA,IAAM,eAAe,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC;AAC9C,SAAS,QAAQ,CAAC,MAAgD;AAAA,EACvE,OAAO,aAAa,UAAU,IAAI,EAAE;AAAA;AAGtC,IAAM,aAAa,EAAE,KAAK;;;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