@canmi/seam-server 0.5.31 → 0.5.36
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 +13 -10
- package/dist/index.d.ts +103 -86
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +692 -531
- package/dist/index.js.map +1 -1
- package/package.json +7 -7
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["primitives","DEFAULT_HEARTBEAT_MS"],"sources":["../src/types/schema.ts","../src/types/primitives.ts","../src/types/composites.ts","../src/types/index.ts","../src/validation/index.ts","../src/errors.ts","../src/context.ts","../src/manifest/index.ts","../src/page/route-matcher.ts","../src/router/handler.ts","../src/router/categorize.ts","../src/page/head.ts","../src/page/loader-error.ts","../src/page/projection.ts","../src/page/handler.ts","../src/resolve.ts","../src/router/helpers.ts","../src/router/state.ts","../src/router/index.ts","../src/factory.ts","../src/seam-router.ts","../src/channel.ts","../src/page/index.ts","../src/mime.ts","../src/http.ts","../src/page/build-loader.ts","../src/subscription.ts","../src/ws.ts","../src/proxy.ts","../src/dev/reload-watcher.ts"],"sourcesContent":["/* src/server/core/typescript/src/types/schema.ts */\n\nimport type { Schema } from 'jtd'\n\nexport type JTDSchema = Schema\n\nexport interface SchemaNode<TOutput = unknown> {\n\treadonly _schema: JTDSchema\n\t/** Phantom type marker — never exists at runtime */\n\treadonly _output: TOutput\n}\n\nexport interface OptionalSchemaNode<TOutput = unknown> extends SchemaNode<TOutput> {\n\treadonly _optional: true\n}\n\nexport type Infer<T extends SchemaNode> = T['_output']\n\nexport function createSchemaNode<T>(schema: JTDSchema): SchemaNode<T> {\n\treturn { _schema: schema } as SchemaNode<T>\n}\n\nexport function createOptionalSchemaNode<T>(schema: JTDSchema): OptionalSchemaNode<T> {\n\treturn { _schema: schema, _optional: true } as OptionalSchemaNode<T>\n}\n","/* src/server/core/typescript/src/types/primitives.ts */\n\nimport type { SchemaNode } from './schema.js'\nimport { createSchemaNode } from './schema.js'\n\nexport function string(): SchemaNode<string> {\n\treturn createSchemaNode<string>({ type: 'string' })\n}\n\nexport function boolean(): SchemaNode<boolean> {\n\treturn createSchemaNode<boolean>({ type: 'boolean' })\n}\n\nexport function int8(): SchemaNode<number> {\n\treturn createSchemaNode<number>({ type: 'int8' })\n}\n\nexport function int16(): SchemaNode<number> {\n\treturn createSchemaNode<number>({ type: 'int16' })\n}\n\nexport function int32(): SchemaNode<number> {\n\treturn createSchemaNode<number>({ type: 'int32' })\n}\n\nexport function uint8(): SchemaNode<number> {\n\treturn createSchemaNode<number>({ type: 'uint8' })\n}\n\nexport function uint16(): SchemaNode<number> {\n\treturn createSchemaNode<number>({ type: 'uint16' })\n}\n\nexport function uint32(): SchemaNode<number> {\n\treturn createSchemaNode<number>({ type: 'uint32' })\n}\n\nexport function float32(): SchemaNode<number> {\n\treturn createSchemaNode<number>({ type: 'float32' })\n}\n\nexport function float64(): SchemaNode<number> {\n\treturn createSchemaNode<number>({ type: 'float64' })\n}\n\nexport function timestamp(): SchemaNode<string> {\n\treturn createSchemaNode<string>({ type: 'timestamp' })\n}\n\nexport function html(): SchemaNode<string> {\n\treturn createSchemaNode<string>({ type: 'string', metadata: { format: 'html' } })\n}\n","/* src/server/core/typescript/src/types/composites.ts */\n\nimport type { SchemaNode, OptionalSchemaNode, Infer, JTDSchema } from './schema.js'\nimport { createSchemaNode, createOptionalSchemaNode } from './schema.js'\n\n// -- Type-level utilities --\n\ntype Simplify<T> = { [K in keyof T]: T[K] } & {}\n\ntype RequiredKeys<T extends Record<string, SchemaNode>> = {\n\t[K in keyof T]: T[K] extends OptionalSchemaNode ? never : K\n}[keyof T]\n\ntype OptionalKeys<T extends Record<string, SchemaNode>> = {\n\t[K in keyof T]: T[K] extends OptionalSchemaNode ? K : never\n}[keyof T]\n\ntype InferObject<T extends Record<string, SchemaNode>> = Simplify<\n\t{ [K in RequiredKeys<T>]: Infer<T[K]> } & { [K in OptionalKeys<T>]?: Infer<T[K]> }\n>\n\n// -- Builders --\n\nexport function object<T extends Record<string, SchemaNode>>(\n\tfields: T,\n): SchemaNode<InferObject<T>> {\n\tconst properties: Record<string, JTDSchema> = {}\n\tconst optionalProperties: Record<string, JTDSchema> = {}\n\n\tfor (const [key, node] of Object.entries(fields)) {\n\t\tif ('_optional' in node && node._optional === true) {\n\t\t\toptionalProperties[key] = node._schema\n\t\t} else {\n\t\t\tproperties[key] = node._schema\n\t\t}\n\t}\n\n\tconst schema: Record<string, unknown> = {}\n\tif (Object.keys(properties).length > 0 || Object.keys(optionalProperties).length === 0) {\n\t\tschema.properties = properties\n\t}\n\tif (Object.keys(optionalProperties).length > 0) {\n\t\tschema.optionalProperties = optionalProperties\n\t}\n\n\treturn createSchemaNode<InferObject<T>>(schema as JTDSchema)\n}\n\nexport function optional<T>(node: SchemaNode<T>): OptionalSchemaNode<T> {\n\treturn createOptionalSchemaNode<T>(node._schema)\n}\n\nexport function array<T>(node: SchemaNode<T>): SchemaNode<T[]> {\n\treturn createSchemaNode<T[]>({ elements: node._schema })\n}\n\nexport function nullable<T>(node: SchemaNode<T>): SchemaNode<T | null> {\n\treturn createSchemaNode<T | null>({ ...node._schema, nullable: true } as JTDSchema)\n}\n\nexport function enumType<const T extends readonly string[]>(values: T): SchemaNode<T[number]> {\n\treturn createSchemaNode<T[number]>({ enum: [...values] } as JTDSchema)\n}\n\nexport function values<T>(node: SchemaNode<T>): SchemaNode<Record<string, T>> {\n\treturn createSchemaNode<Record<string, T>>({ values: node._schema })\n}\n\ntype DiscriminatorUnion<TTag extends string, TMapping extends Record<string, SchemaNode>> = {\n\t[K in keyof TMapping & string]: Simplify<{ [P in TTag]: K } & Infer<TMapping[K]>>\n}[keyof TMapping & string]\n\nexport function discriminator<\n\tTTag extends string,\n\tTMapping extends Record<string, SchemaNode<Record<string, unknown>>>,\n>(tag: TTag, mapping: TMapping): SchemaNode<DiscriminatorUnion<TTag, TMapping>> {\n\tconst jtdMapping: Record<string, JTDSchema> = {}\n\tfor (const [key, node] of Object.entries(mapping)) {\n\t\tjtdMapping[key] = node._schema\n\t}\n\treturn createSchemaNode<DiscriminatorUnion<TTag, TMapping>>({\n\t\tdiscriminator: tag,\n\t\tmapping: jtdMapping,\n\t} as JTDSchema)\n}\n","/* src/server/core/typescript/src/types/index.ts */\n\nimport * as primitives from './primitives.js'\nimport { object, optional, array, nullable, enumType, values, discriminator } from './composites.js'\n\nexport const t = {\n\t...primitives,\n\tobject,\n\toptional,\n\tarray,\n\tnullable,\n\tenum: enumType,\n\tvalues,\n\tdiscriminator,\n} as const\n","/* src/server/core/typescript/src/validation/index.ts */\n\nimport { validate } from 'jtd'\nimport type { Schema, ValidationError as JTDValidationError } from 'jtd'\n\nexport interface ValidationResult {\n\tvalid: boolean\n\terrors: JTDValidationError[]\n}\n\nexport interface ValidationDetail {\n\tpath: string\n\texpected?: string\n\tactual?: string\n}\n\nexport function validateInput(schema: Schema, data: unknown): ValidationResult {\n\tconst errors = validate(schema, data, { maxDepth: 32, maxErrors: 10 })\n\treturn {\n\t\tvalid: errors.length === 0,\n\t\terrors,\n\t}\n}\n\nexport function formatValidationErrors(errors: JTDValidationError[]): string {\n\treturn errors\n\t\t.map((e) => {\n\t\t\tconst path = e.instancePath.length > 0 ? e.instancePath.join('/') : '(root)'\n\t\t\tconst schema = e.schemaPath.join('/')\n\t\t\treturn `${path} (schema: ${schema})`\n\t\t})\n\t\t.join('; ')\n}\n\n/** Walk a nested object along a key path, returning undefined if unreachable */\nfunction walkPath(obj: unknown, keys: string[]): unknown {\n\tlet cur = obj\n\tfor (const k of keys) {\n\t\tif (cur === null || cur === undefined || typeof cur !== 'object') return undefined\n\t\tcur = (cur as Record<string, unknown>)[k]\n\t}\n\treturn cur\n}\n\n/** Extract structured details from JTD validation errors (best-effort) */\nexport function formatValidationDetails(\n\terrors: JTDValidationError[],\n\tschema: Schema,\n\tdata: unknown,\n): ValidationDetail[] {\n\treturn errors.map((e) => {\n\t\tconst path = '/' + e.instancePath.join('/')\n\t\tconst detail: ValidationDetail = { path }\n\n\t\t// Extract expected type by walking schemaPath — when it ends with \"type\",\n\t\t// the value at that path in the schema is the JTD type keyword\n\t\tconst schemaValue = walkPath(schema, e.schemaPath)\n\t\tif (typeof schemaValue === 'string') {\n\t\t\tdetail.expected = schemaValue\n\t\t}\n\n\t\t// Extract actual type from the data at instancePath\n\t\tconst actualValue = walkPath(data, e.instancePath)\n\t\tif (actualValue !== undefined) {\n\t\t\tdetail.actual = typeof actualValue\n\t\t} else if (e.instancePath.length === 0) {\n\t\t\tdetail.actual = typeof data\n\t\t}\n\n\t\treturn detail\n\t})\n}\n","/* src/server/core/typescript/src/errors.ts */\n\nexport type ErrorCode =\n\t| 'VALIDATION_ERROR'\n\t| 'NOT_FOUND'\n\t| 'UNAUTHORIZED'\n\t| 'FORBIDDEN'\n\t| 'RATE_LIMITED'\n\t| 'INTERNAL_ERROR'\n\t| (string & {})\n\nexport const DEFAULT_STATUS: Record<string, number> = {\n\tVALIDATION_ERROR: 400,\n\tUNAUTHORIZED: 401,\n\tFORBIDDEN: 403,\n\tNOT_FOUND: 404,\n\tRATE_LIMITED: 429,\n\tINTERNAL_ERROR: 500,\n}\n\nexport class SeamError extends Error {\n\treadonly code: string\n\treadonly status: number\n\treadonly details?: unknown[]\n\n\tconstructor(code: string, message: string, status?: number, details?: unknown[]) {\n\t\tsuper(message)\n\t\tthis.code = code\n\t\tthis.status = status ?? DEFAULT_STATUS[code] ?? 500\n\t\tthis.details = details\n\t\tthis.name = 'SeamError'\n\t}\n\n\ttoJSON() {\n\t\tconst error: Record<string, unknown> = {\n\t\t\tcode: this.code,\n\t\t\tmessage: this.message,\n\t\t\ttransient: false,\n\t\t}\n\t\tif (this.details) error.details = this.details\n\t\treturn { ok: false, error }\n\t}\n}\n","/* src/server/core/typescript/src/context.ts */\n\nimport type { SchemaNode } from './types/schema.js'\nimport { validateInput, formatValidationErrors } from './validation/index.js'\nimport { SeamError } from './errors.js'\n\nexport interface ContextFieldDef {\n\textract: string\n\tschema: SchemaNode\n}\n\nexport type ContextConfig = Record<string, ContextFieldDef>\nexport type RawContextMap = Record<string, string | null>\n\n/** Parse extract rule into source type and key, e.g. \"header:authorization\" -> { source: \"header\", key: \"authorization\" } */\nexport function parseExtractRule(rule: string): { source: string; key: string } {\n\tconst idx = rule.indexOf(':')\n\tif (idx === -1) {\n\t\tthrow new Error(`Invalid extract rule \"${rule}\": expected \"source:key\" format`)\n\t}\n\tconst source = rule.slice(0, idx)\n\tconst key = rule.slice(idx + 1)\n\tif (!source || !key) {\n\t\tthrow new Error(`Invalid extract rule \"${rule}\": source and key must be non-empty`)\n\t}\n\treturn { source, key }\n}\n\n/** Check whether any context fields are defined */\nexport function contextHasExtracts(config: ContextConfig): boolean {\n\treturn Object.keys(config).length > 0\n}\n\n/** Parse a Cookie header into key-value pairs */\nexport function parseCookieHeader(header: string): Record<string, string> {\n\tconst result: Record<string, string> = {}\n\tfor (const pair of header.split(';')) {\n\t\tconst idx = pair.indexOf('=')\n\t\tif (idx > 0) {\n\t\t\tresult[pair.slice(0, idx).trim()] = pair.slice(idx + 1).trim()\n\t\t}\n\t}\n\treturn result\n}\n\n/** Build a RawContextMap keyed by config key from request headers, cookies, and query params */\nexport function buildRawContext(\n\tconfig: ContextConfig,\n\theaderFn: ((name: string) => string | null) | undefined,\n\turl: URL,\n): RawContextMap {\n\tconst raw: RawContextMap = {}\n\tlet cookieCache: Record<string, string> | undefined\n\tfor (const [key, field] of Object.entries(config)) {\n\t\tconst { source, key: extractKey } = parseExtractRule(field.extract)\n\t\tswitch (source) {\n\t\t\tcase 'header':\n\t\t\t\traw[key] = headerFn?.(extractKey) ?? null\n\t\t\t\tbreak\n\t\t\tcase 'cookie': {\n\t\t\t\tif (!cookieCache) {\n\t\t\t\t\tcookieCache = parseCookieHeader(headerFn?.('cookie') ?? '')\n\t\t\t\t}\n\t\t\t\traw[key] = cookieCache[extractKey] ?? null\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase 'query':\n\t\t\t\traw[key] = url.searchParams.get(extractKey) ?? null\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\traw[key] = null\n\t\t}\n\t}\n\treturn raw\n}\n\n/**\n * Resolve raw strings into validated context object.\n *\n * For each requested key:\n * - If raw value is null/missing -> pass null to JTD; schema decides via nullable()\n * - If schema expects string -> use raw value directly\n * - If schema expects object -> JSON.parse then validate\n */\nexport function resolveContext(\n\tconfig: ContextConfig,\n\traw: RawContextMap,\n\trequestedKeys: string[],\n): Record<string, unknown> {\n\tconst result: Record<string, unknown> = {}\n\n\tfor (const key of requestedKeys) {\n\t\tconst field = config[key]\n\t\tif (!field) {\n\t\t\tthrow new SeamError(\n\t\t\t\t'CONTEXT_ERROR',\n\t\t\t\t`Context field \"${key}\" is not defined in router context config`,\n\t\t\t\t400,\n\t\t\t)\n\t\t}\n\n\t\tconst rawValue = raw[key] ?? null\n\n\t\tlet value: unknown\n\t\tif (rawValue === null) {\n\t\t\tvalue = null\n\t\t} else {\n\t\t\tconst schema = field.schema._schema\n\t\t\t// If the root schema is { type: \"string\" } or nullable string, use raw value directly\n\t\t\tconst isStringSchema =\n\t\t\t\t'type' in schema && schema.type === 'string' && !('nullable' in schema && schema.nullable)\n\t\t\tconst isNullableStringSchema =\n\t\t\t\t'type' in schema && schema.type === 'string' && 'nullable' in schema && schema.nullable\n\n\t\t\tif (isStringSchema || isNullableStringSchema) {\n\t\t\t\tvalue = rawValue\n\t\t\t} else {\n\t\t\t\t// Attempt JSON parse for complex types\n\t\t\t\ttry {\n\t\t\t\t\tvalue = JSON.parse(rawValue)\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new SeamError(\n\t\t\t\t\t\t'CONTEXT_ERROR',\n\t\t\t\t\t\t`Context field \"${key}\": failed to parse value as JSON`,\n\t\t\t\t\t\t400,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst validation = validateInput(field.schema._schema, value)\n\t\tif (!validation.valid) {\n\t\t\tconst details = formatValidationErrors(validation.errors)\n\t\t\tthrow new SeamError(\n\t\t\t\t'CONTEXT_ERROR',\n\t\t\t\t`Context field \"${key}\" validation failed: ${details}`,\n\t\t\t\t400,\n\t\t\t)\n\t\t}\n\n\t\tresult[key] = value\n\t}\n\n\treturn result\n}\n\n/** Syntax sugar for building extract rules; the underlying \"source:key\" format is unchanged. */\nexport const extract = {\n\theader: (name: string): string => `header:${name}`,\n\tcookie: (name: string): string => `cookie:${name}`,\n\tquery: (name: string): string => `query:${name}`,\n}\n","/* src/server/core/typescript/src/manifest/index.ts */\n\nimport type { Schema } from 'jtd'\nimport type { SchemaNode } from '../types/schema.js'\nimport type { ChannelMeta } from '../channel.js'\nimport type { ContextConfig } from '../context.js'\n\nexport type ProcedureType = 'query' | 'command' | 'subscription' | 'stream' | 'upload'\n\nexport interface NormalizedMappingValue {\n\tfrom: string\n\teach?: boolean\n}\n\nexport interface NormalizedInvalidateTarget {\n\tquery: string\n\tmapping?: Record<string, NormalizedMappingValue>\n}\n\nexport interface ContextManifestEntry {\n\textract: string\n\tschema: Schema\n}\n\nexport interface ProcedureEntry {\n\tkind: ProcedureType\n\tinput: Schema\n\toutput?: Schema\n\tchunkOutput?: Schema\n\terror?: Schema\n\tinvalidates?: NormalizedInvalidateTarget[]\n\tcontext?: string[]\n\ttransport?: { prefer: string; fallback?: string[] }\n\tsuppress?: string[]\n\tcache?: false | { ttl: number }\n}\n\nexport interface ProcedureManifest {\n\tversion: number\n\tcontext: Record<string, ContextManifestEntry>\n\tprocedures: Record<string, ProcedureEntry>\n\tchannels?: Record<string, ChannelMeta>\n\ttransportDefaults: Record<string, { prefer: string; fallback?: string[] }>\n}\n\ntype InvalidateInput = Array<\n\t| string\n\t| {\n\t\t\tquery: string\n\t\t\tmapping?: Record<string, string | { from: string; each?: boolean }>\n\t }\n>\n\nfunction normalizeInvalidates(targets: InvalidateInput): NormalizedInvalidateTarget[] {\n\treturn targets.map((t) => {\n\t\tif (typeof t === 'string') return { query: t }\n\t\tconst normalized: NormalizedInvalidateTarget = { query: t.query }\n\t\tif (t.mapping) {\n\t\t\tnormalized.mapping = Object.fromEntries(\n\t\t\t\tObject.entries(t.mapping).map(([k, v]) => [k, typeof v === 'string' ? { from: v } : v]),\n\t\t\t)\n\t\t}\n\t\treturn normalized\n\t})\n}\n\nexport function buildManifest(\n\tdefinitions: Record<\n\t\tstring,\n\t\t{\n\t\t\tinput: SchemaNode\n\t\t\toutput: SchemaNode\n\t\t\tkind?: string\n\t\t\ttype?: string\n\t\t\terror?: SchemaNode\n\t\t\tcontext?: string[]\n\t\t\tinvalidates?: InvalidateInput\n\t\t}\n\t>,\n\tchannels?: Record<string, ChannelMeta>,\n\tcontextConfig?: ContextConfig,\n\ttransportDefaults?: Record<string, { prefer: string; fallback?: string[] }>,\n): ProcedureManifest {\n\tconst mapped: ProcedureManifest['procedures'] = {}\n\n\tfor (const [name, def] of Object.entries(definitions)) {\n\t\tconst k = def.kind ?? def.type\n\t\tconst kind: ProcedureType =\n\t\t\tk === 'upload'\n\t\t\t\t? 'upload'\n\t\t\t\t: k === 'stream'\n\t\t\t\t\t? 'stream'\n\t\t\t\t\t: k === 'subscription'\n\t\t\t\t\t\t? 'subscription'\n\t\t\t\t\t\t: k === 'command'\n\t\t\t\t\t\t\t? 'command'\n\t\t\t\t\t\t\t: 'query'\n\t\tconst entry: ProcedureEntry = { kind, input: def.input._schema }\n\t\tif (kind === 'stream') {\n\t\t\tentry.chunkOutput = def.output._schema\n\t\t} else {\n\t\t\tentry.output = def.output._schema\n\t\t}\n\t\tif (def.error) {\n\t\t\tentry.error = def.error._schema\n\t\t}\n\t\tif (kind === 'command' && def.invalidates && def.invalidates.length > 0) {\n\t\t\tentry.invalidates = normalizeInvalidates(def.invalidates)\n\t\t}\n\t\tif (def.context && def.context.length > 0) {\n\t\t\tentry.context = def.context\n\t\t}\n\t\tconst defAny = def as Record<string, unknown>\n\t\tif (defAny.transport) {\n\t\t\tentry.transport = defAny.transport as { prefer: string; fallback?: string[] }\n\t\t}\n\t\tif (defAny.suppress) {\n\t\t\tentry.suppress = defAny.suppress as string[]\n\t\t}\n\t\tif (defAny.cache !== undefined) {\n\t\t\tentry.cache = defAny.cache as false | { ttl: number }\n\t\t}\n\t\tmapped[name] = entry\n\t}\n\n\tconst context: Record<string, ContextManifestEntry> = {}\n\tif (contextConfig) {\n\t\tfor (const [key, field] of Object.entries(contextConfig)) {\n\t\t\tcontext[key] = { extract: field.extract, schema: field.schema._schema }\n\t\t}\n\t}\n\n\tconst manifest: ProcedureManifest = {\n\t\tversion: 2,\n\t\tcontext,\n\t\tprocedures: mapped,\n\t\ttransportDefaults: transportDefaults ?? {},\n\t}\n\tif (channels && Object.keys(channels).length > 0) {\n\t\tmanifest.channels = channels\n\t}\n\treturn manifest\n}\n","/* src/server/core/typescript/src/page/route-matcher.ts */\n\ninterface CompiledRoute {\n\tsegments: RouteSegment[]\n}\n\ntype RouteSegment =\n\t| { kind: 'static'; value: string }\n\t| { kind: 'param'; name: string }\n\t| { kind: 'catch-all'; name: string; optional: boolean }\n\nfunction compileRoute(pattern: string): CompiledRoute {\n\tconst segments: RouteSegment[] = pattern\n\t\t.split('/')\n\t\t.filter(Boolean)\n\t\t.map((seg) => {\n\t\t\tif (seg.startsWith('*')) {\n\t\t\t\tconst optional = seg.endsWith('?')\n\t\t\t\tconst name = optional ? seg.slice(1, -1) : seg.slice(1)\n\t\t\t\treturn { kind: 'catch-all' as const, name, optional }\n\t\t\t}\n\t\t\tif (seg.startsWith(':')) {\n\t\t\t\treturn { kind: 'param' as const, name: seg.slice(1) }\n\t\t\t}\n\t\t\treturn { kind: 'static' as const, value: seg }\n\t\t})\n\treturn { segments }\n}\n\nfunction matchRoute(segments: RouteSegment[], pathParts: string[]): Record<string, string> | null {\n\tconst params: Record<string, string> = {}\n\tfor (let i = 0; i < segments.length; i++) {\n\t\tconst seg = segments[i] as RouteSegment\n\t\tif (seg.kind === 'catch-all') {\n\t\t\t// Catch-all must be the last segment\n\t\t\tconst rest = pathParts.slice(i)\n\t\t\tif (rest.length === 0 && !seg.optional) return null\n\t\t\tparams[seg.name] = rest.join('/')\n\t\t\treturn params\n\t\t}\n\t\tif (i >= pathParts.length) return null\n\t\tif (seg.kind === 'static') {\n\t\t\tif (seg.value !== pathParts[i]) return null\n\t\t} else {\n\t\t\tparams[seg.name] = pathParts[i] as string\n\t\t}\n\t}\n\t// All segments consumed — path must also be fully consumed\n\tif (segments.length !== pathParts.length) return null\n\treturn params\n}\n\nexport class RouteMatcher<T> {\n\tprivate routes: { pattern: string; compiled: CompiledRoute; value: T }[] = []\n\n\tadd(pattern: string, value: T): void {\n\t\tthis.routes.push({ pattern, compiled: compileRoute(pattern), value })\n\t}\n\n\tmatch(path: string): { value: T; params: Record<string, string>; pattern: string } | null {\n\t\tconst parts = path.split('/').filter(Boolean)\n\t\tfor (const route of this.routes) {\n\t\t\tconst params = matchRoute(route.compiled.segments, parts)\n\t\t\tif (params) return { value: route.value, params, pattern: route.pattern }\n\t\t}\n\t\treturn null\n\t}\n}\n","/* src/server/core/typescript/src/router/handler.ts */\n\nimport { SeamError } from '../errors.js'\nimport type {\n\tHandleResult,\n\tInternalProcedure,\n\tInternalSubscription,\n\tInternalStream,\n\tInternalUpload,\n\tSeamFileHandle,\n} from '../procedure.js'\nimport {\n\tvalidateInput,\n\tformatValidationErrors,\n\tformatValidationDetails,\n} from '../validation/index.js'\n\nexport type { HandleResult, InternalProcedure } from '../procedure.js'\n\nexport async function handleRequest(\n\tprocedures: Map<string, InternalProcedure>,\n\tprocedureName: string,\n\trawBody: unknown,\n\tshouldValidateInput: boolean = true,\n\tvalidateOutput?: boolean,\n\tctx?: Record<string, unknown>,\n): Promise<HandleResult> {\n\tconst procedure = procedures.get(procedureName)\n\tif (!procedure) {\n\t\treturn {\n\t\t\tstatus: 404,\n\t\t\tbody: new SeamError('NOT_FOUND', `Procedure '${procedureName}' not found`).toJSON(),\n\t\t}\n\t}\n\n\tif (shouldValidateInput) {\n\t\tconst validation = validateInput(procedure.inputSchema, rawBody)\n\t\tif (!validation.valid) {\n\t\t\tconst details = formatValidationDetails(validation.errors, procedure.inputSchema, rawBody)\n\t\t\tconst summary = formatValidationErrors(validation.errors)\n\t\t\treturn {\n\t\t\t\tstatus: 400,\n\t\t\t\tbody: new SeamError(\n\t\t\t\t\t'VALIDATION_ERROR',\n\t\t\t\t\t`Input validation failed for procedure '${procedureName}': ${summary}`,\n\t\t\t\t\tundefined,\n\t\t\t\t\tdetails,\n\t\t\t\t).toJSON(),\n\t\t\t}\n\t\t}\n\t}\n\n\ttry {\n\t\tconst result = await procedure.handler({ input: rawBody, ctx: ctx ?? {} })\n\n\t\tif (validateOutput) {\n\t\t\tconst outValidation = validateInput(procedure.outputSchema, result)\n\t\t\tif (!outValidation.valid) {\n\t\t\t\tconst summary = formatValidationErrors(outValidation.errors)\n\t\t\t\treturn {\n\t\t\t\t\tstatus: 500,\n\t\t\t\t\tbody: new SeamError('INTERNAL_ERROR', `Output validation failed: ${summary}`).toJSON(),\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn { status: 200, body: { ok: true, data: result } }\n\t} catch (error) {\n\t\tif (error instanceof SeamError) {\n\t\t\treturn { status: error.status, body: error.toJSON() }\n\t\t}\n\t\tconst message = error instanceof Error ? error.message : 'Unknown error'\n\t\treturn {\n\t\t\tstatus: 500,\n\t\t\tbody: new SeamError('INTERNAL_ERROR', message).toJSON(),\n\t\t}\n\t}\n}\n\nexport interface BatchCall {\n\tprocedure: string\n\tinput: unknown\n}\n\nexport type BatchResultItem =\n\t| { ok: true; data: unknown }\n\t| { ok: false; error: { code: string; message: string; transient: boolean } }\n\nexport async function handleBatchRequest(\n\tprocedures: Map<string, InternalProcedure>,\n\tcalls: BatchCall[],\n\tshouldValidateInput: boolean = true,\n\tvalidateOutput?: boolean,\n\tctxResolver?: (procedureName: string) => Record<string, unknown>,\n): Promise<{ results: BatchResultItem[] }> {\n\tconst results = await Promise.all(\n\t\tcalls.map(async (call) => {\n\t\t\tconst ctx = ctxResolver ? ctxResolver(call.procedure) : undefined\n\t\t\tconst result = await handleRequest(\n\t\t\t\tprocedures,\n\t\t\t\tcall.procedure,\n\t\t\t\tcall.input,\n\t\t\t\tshouldValidateInput,\n\t\t\t\tvalidateOutput,\n\t\t\t\tctx,\n\t\t\t)\n\t\t\tif (result.status === 200) {\n\t\t\t\tconst envelope = result.body as { ok: true; data: unknown }\n\t\t\t\treturn { ok: true as const, data: envelope.data }\n\t\t\t}\n\t\t\tconst envelope = result.body as {\n\t\t\t\tok: false\n\t\t\t\terror: { code: string; message: string; transient: boolean }\n\t\t\t}\n\t\t\treturn { ok: false as const, error: envelope.error }\n\t\t}),\n\t)\n\treturn { results }\n}\n\nexport async function* handleSubscription(\n\tsubscriptions: Map<string, InternalSubscription>,\n\tname: string,\n\trawInput: unknown,\n\tshouldValidateInput: boolean = true,\n\tvalidateOutput?: boolean,\n\tctx?: Record<string, unknown>,\n\tlastEventId?: string,\n): AsyncIterable<unknown> {\n\tconst sub = subscriptions.get(name)\n\tif (!sub) {\n\t\tthrow new SeamError('NOT_FOUND', `Subscription '${name}' not found`)\n\t}\n\n\tif (shouldValidateInput) {\n\t\tconst validation = validateInput(sub.inputSchema, rawInput)\n\t\tif (!validation.valid) {\n\t\t\tconst details = formatValidationDetails(validation.errors, sub.inputSchema, rawInput)\n\t\t\tconst summary = formatValidationErrors(validation.errors)\n\t\t\tthrow new SeamError(\n\t\t\t\t'VALIDATION_ERROR',\n\t\t\t\t`Input validation failed: ${summary}`,\n\t\t\t\tundefined,\n\t\t\t\tdetails,\n\t\t\t)\n\t\t}\n\t}\n\n\tfor await (const value of sub.handler({ input: rawInput, ctx: ctx ?? {}, lastEventId })) {\n\t\tif (validateOutput) {\n\t\t\tconst outValidation = validateInput(sub.outputSchema, value)\n\t\t\tif (!outValidation.valid) {\n\t\t\t\tconst summary = formatValidationErrors(outValidation.errors)\n\t\t\t\tthrow new SeamError('INTERNAL_ERROR', `Output validation failed: ${summary}`)\n\t\t\t}\n\t\t}\n\t\tyield value\n\t}\n}\n\nexport async function handleUploadRequest(\n\tuploads: Map<string, InternalUpload>,\n\tprocedureName: string,\n\trawBody: unknown,\n\tfile: SeamFileHandle,\n\tshouldValidateInput: boolean = true,\n\tvalidateOutput?: boolean,\n\tctx?: Record<string, unknown>,\n): Promise<HandleResult> {\n\tconst upload = uploads.get(procedureName)\n\tif (!upload) {\n\t\treturn {\n\t\t\tstatus: 404,\n\t\t\tbody: new SeamError('NOT_FOUND', `Procedure '${procedureName}' not found`).toJSON(),\n\t\t}\n\t}\n\n\tif (shouldValidateInput) {\n\t\tconst validation = validateInput(upload.inputSchema, rawBody)\n\t\tif (!validation.valid) {\n\t\t\tconst details = formatValidationDetails(validation.errors, upload.inputSchema, rawBody)\n\t\t\tconst summary = formatValidationErrors(validation.errors)\n\t\t\treturn {\n\t\t\t\tstatus: 400,\n\t\t\t\tbody: new SeamError(\n\t\t\t\t\t'VALIDATION_ERROR',\n\t\t\t\t\t`Input validation failed for procedure '${procedureName}': ${summary}`,\n\t\t\t\t\tundefined,\n\t\t\t\t\tdetails,\n\t\t\t\t).toJSON(),\n\t\t\t}\n\t\t}\n\t}\n\n\ttry {\n\t\tconst result = await upload.handler({ input: rawBody, file, ctx: ctx ?? {} })\n\n\t\tif (validateOutput) {\n\t\t\tconst outValidation = validateInput(upload.outputSchema, result)\n\t\t\tif (!outValidation.valid) {\n\t\t\t\tconst summary = formatValidationErrors(outValidation.errors)\n\t\t\t\treturn {\n\t\t\t\t\tstatus: 500,\n\t\t\t\t\tbody: new SeamError('INTERNAL_ERROR', `Output validation failed: ${summary}`).toJSON(),\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn { status: 200, body: { ok: true, data: result } }\n\t} catch (error) {\n\t\tif (error instanceof SeamError) {\n\t\t\treturn { status: error.status, body: error.toJSON() }\n\t\t}\n\t\tconst message = error instanceof Error ? error.message : 'Unknown error'\n\t\treturn {\n\t\t\tstatus: 500,\n\t\t\tbody: new SeamError('INTERNAL_ERROR', message).toJSON(),\n\t\t}\n\t}\n}\n\nexport async function* handleStream(\n\tstreams: Map<string, InternalStream>,\n\tname: string,\n\trawInput: unknown,\n\tshouldValidateInput: boolean = true,\n\tvalidateOutput?: boolean,\n\tctx?: Record<string, unknown>,\n): AsyncGenerator<unknown> {\n\tconst stream = streams.get(name)\n\tif (!stream) {\n\t\tthrow new SeamError('NOT_FOUND', `Stream '${name}' not found`)\n\t}\n\n\tif (shouldValidateInput) {\n\t\tconst validation = validateInput(stream.inputSchema, rawInput)\n\t\tif (!validation.valid) {\n\t\t\tconst details = formatValidationDetails(validation.errors, stream.inputSchema, rawInput)\n\t\t\tconst summary = formatValidationErrors(validation.errors)\n\t\t\tthrow new SeamError(\n\t\t\t\t'VALIDATION_ERROR',\n\t\t\t\t`Input validation failed: ${summary}`,\n\t\t\t\tundefined,\n\t\t\t\tdetails,\n\t\t\t)\n\t\t}\n\t}\n\n\tfor await (const value of stream.handler({ input: rawInput, ctx: ctx ?? {} })) {\n\t\tif (validateOutput) {\n\t\t\tconst outValidation = validateInput(stream.chunkOutputSchema, value)\n\t\t\tif (!outValidation.valid) {\n\t\t\t\tconst summary = formatValidationErrors(outValidation.errors)\n\t\t\t\tthrow new SeamError('INTERNAL_ERROR', `Output validation failed: ${summary}`)\n\t\t\t}\n\t\t}\n\t\tyield value\n\t}\n}\n","/* src/server/core/typescript/src/router/categorize.ts */\n\nimport type { DefinitionMap, ProcedureKind } from './index.js'\nimport type { InternalProcedure } from '../procedure.js'\nimport type { InternalSubscription, InternalStream, InternalUpload } from '../procedure.js'\nimport type { ContextConfig } from '../context.js'\n\nfunction resolveKind(name: string, def: DefinitionMap[string]): ProcedureKind {\n\tif ('kind' in def && def.kind) return def.kind\n\tif ('type' in def && def.type) {\n\t\tconsole.warn(\n\t\t\t`[seam] \"${name}\": \"type\" field in procedure definition is deprecated, use \"kind\" instead`,\n\t\t)\n\t\treturn def.type\n\t}\n\treturn 'query'\n}\n\nexport interface CategorizedProcedures {\n\tprocedureMap: Map<string, InternalProcedure>\n\tsubscriptionMap: Map<string, InternalSubscription>\n\tstreamMap: Map<string, InternalStream>\n\tuploadMap: Map<string, InternalUpload>\n\tkindMap: Map<string, ProcedureKind>\n}\n\n/** Split a flat definition map into typed procedure/subscription/stream maps */\nexport function categorizeProcedures(\n\tdefinitions: DefinitionMap,\n\tcontextConfig?: ContextConfig,\n): CategorizedProcedures {\n\tconst procedureMap = new Map<string, InternalProcedure>()\n\tconst subscriptionMap = new Map<string, InternalSubscription>()\n\tconst streamMap = new Map<string, InternalStream>()\n\tconst uploadMap = new Map<string, InternalUpload>()\n\tconst kindMap = new Map<string, ProcedureKind>()\n\n\tfor (const [name, def] of Object.entries(definitions)) {\n\t\tif (name.startsWith('seam.')) {\n\t\t\tthrow new Error(`Procedure name \"${name}\" uses reserved \"seam.\" namespace`)\n\t\t}\n\t\tconst kind = resolveKind(name, def)\n\t\tkindMap.set(name, kind)\n\t\tconst contextKeys = (def as { context?: string[] }).context ?? []\n\n\t\t// Validate context keys reference defined fields\n\t\tif (contextConfig && contextKeys.length > 0) {\n\t\t\tfor (const key of contextKeys) {\n\t\t\t\tif (!(key in contextConfig)) {\n\t\t\t\t\tthrow new Error(`Procedure \"${name}\" references undefined context field \"${key}\"`)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (kind === 'upload') {\n\t\t\tuploadMap.set(name, {\n\t\t\t\tinputSchema: def.input._schema,\n\t\t\t\toutputSchema: def.output._schema,\n\t\t\t\tcontextKeys,\n\t\t\t\thandler: def.handler as InternalUpload['handler'],\n\t\t\t})\n\t\t} else if (kind === 'stream') {\n\t\t\tstreamMap.set(name, {\n\t\t\t\tinputSchema: def.input._schema,\n\t\t\t\tchunkOutputSchema: def.output._schema,\n\t\t\t\tcontextKeys,\n\t\t\t\thandler: def.handler as InternalStream['handler'],\n\t\t\t})\n\t\t} else if (kind === 'subscription') {\n\t\t\tsubscriptionMap.set(name, {\n\t\t\t\tinputSchema: def.input._schema,\n\t\t\t\toutputSchema: def.output._schema,\n\t\t\t\tcontextKeys,\n\t\t\t\thandler: def.handler as InternalSubscription['handler'],\n\t\t\t})\n\t\t} else {\n\t\t\tprocedureMap.set(name, {\n\t\t\t\tinputSchema: def.input._schema,\n\t\t\t\toutputSchema: def.output._schema,\n\t\t\t\tcontextKeys,\n\t\t\t\thandler: def.handler as InternalProcedure['handler'],\n\t\t\t})\n\t\t}\n\t}\n\n\treturn { procedureMap, subscriptionMap, streamMap, uploadMap, kindMap }\n}\n","/* src/server/core/typescript/src/page/head.ts */\n\nimport { escapeHtml } from '@canmi/seam-engine'\n\ninterface HeadMeta {\n\t[key: string]: string | undefined\n}\n\ninterface HeadLink {\n\t[key: string]: string | undefined\n}\n\ninterface HeadConfig {\n\ttitle?: string\n\tmeta?: HeadMeta[]\n\tlink?: HeadLink[]\n}\n\nexport type HeadFn = (data: Record<string, unknown>) => HeadConfig\n\n/**\n * Convert a HeadConfig with real values into escaped HTML.\n * Used at request-time by TS server backends.\n */\nexport function headConfigToHtml(config: HeadConfig): string {\n\tlet html = ''\n\tif (config.title !== undefined) {\n\t\thtml += `<title>${escapeHtml(config.title)}</title>`\n\t}\n\tfor (const meta of config.meta ?? []) {\n\t\thtml += '<meta'\n\t\tfor (const [k, v] of Object.entries(meta)) {\n\t\t\tif (v !== undefined) html += ` ${k}=\"${escapeHtml(v)}\"`\n\t\t}\n\t\thtml += '>'\n\t}\n\tfor (const link of config.link ?? []) {\n\t\thtml += '<link'\n\t\tfor (const [k, v] of Object.entries(link)) {\n\t\t\tif (v !== undefined) html += ` ${k}=\"${escapeHtml(v)}\"`\n\t\t}\n\t\thtml += '>'\n\t}\n\treturn html\n}\n","/* src/server/core/typescript/src/page/loader-error.ts */\n\nexport interface LoaderError {\n\t__error: true\n\tcode: string\n\tmessage: string\n}\n\nexport function isLoaderError(value: unknown): value is LoaderError {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t(value as Record<string, unknown>).__error === true &&\n\t\ttypeof (value as Record<string, unknown>).code === 'string' &&\n\t\ttypeof (value as Record<string, unknown>).message === 'string'\n\t)\n}\n","/* src/server/core/typescript/src/page/projection.ts */\n\nimport { isLoaderError } from './loader-error.js'\n\nexport type ProjectionMap = Record<string, string[]>\n\n/** Set a nested field by dot-separated path, creating intermediate objects as needed. */\nfunction setNestedField(target: Record<string, unknown>, path: string, value: unknown): void {\n\tconst parts = path.split('.')\n\tlet current: Record<string, unknown> = target\n\tfor (let i = 0; i < parts.length - 1; i++) {\n\t\tconst key = parts[i] as string\n\t\tif (!(key in current) || typeof current[key] !== 'object' || current[key] === null) {\n\t\t\tcurrent[key] = {}\n\t\t}\n\t\tcurrent = current[key] as Record<string, unknown>\n\t}\n\tcurrent[parts[parts.length - 1] as string] = value\n}\n\n/** Get a nested field by dot-separated path. */\nfunction getNestedField(source: Record<string, unknown>, path: string): unknown {\n\tconst parts = path.split('.')\n\tlet current: unknown = source\n\tfor (const part of parts) {\n\t\tif (current === null || current === undefined || typeof current !== 'object') {\n\t\t\treturn undefined\n\t\t}\n\t\tcurrent = (current as Record<string, unknown>)[part]\n\t}\n\treturn current\n}\n\n/** Prune a single value according to its projected field paths. */\nfunction pruneValue(value: unknown, fields: string[]): unknown {\n\t// Separate $ paths (array element fields) from plain paths\n\tconst arrayFields: string[] = []\n\tconst plainFields: string[] = []\n\n\tfor (const f of fields) {\n\t\tif (f === '$') {\n\t\t\t// Standalone $ means keep entire array elements — return value as-is\n\t\t\treturn value\n\t\t} else if (f.startsWith('$.')) {\n\t\t\tarrayFields.push(f.slice(2))\n\t\t} else {\n\t\t\tplainFields.push(f)\n\t\t}\n\t}\n\n\tif (arrayFields.length > 0 && Array.isArray(value)) {\n\t\treturn value.map((item: unknown) => {\n\t\t\tif (typeof item !== 'object' || item === null) return item\n\t\t\tconst pruned: Record<string, unknown> = {}\n\t\t\tfor (const field of arrayFields) {\n\t\t\t\tconst val = getNestedField(item as Record<string, unknown>, field)\n\t\t\t\tif (val !== undefined) {\n\t\t\t\t\tsetNestedField(pruned, field, val)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn pruned\n\t\t})\n\t}\n\n\tif (plainFields.length > 0 && typeof value === 'object' && value !== null) {\n\t\tconst source = value as Record<string, unknown>\n\t\tconst pruned: Record<string, unknown> = {}\n\t\tfor (const field of plainFields) {\n\t\t\tconst val = getNestedField(source, field)\n\t\t\tif (val !== undefined) {\n\t\t\t\tsetNestedField(pruned, field, val)\n\t\t\t}\n\t\t}\n\t\treturn pruned\n\t}\n\n\treturn value\n}\n\n/** Prune data to only include projected fields. Missing projection = keep all. */\nexport function applyProjection(\n\tdata: Record<string, unknown>,\n\tprojections: ProjectionMap | undefined,\n): Record<string, unknown> {\n\tif (!projections) return data\n\n\tconst result: Record<string, unknown> = {}\n\tfor (const [key, value] of Object.entries(data)) {\n\t\tif (isLoaderError(value)) {\n\t\t\tresult[key] = value\n\t\t\tcontinue\n\t\t}\n\t\tconst fields = projections[key]\n\t\tif (!fields) {\n\t\t\tresult[key] = value\n\t\t} else {\n\t\t\tresult[key] = pruneValue(value, fields)\n\t\t}\n\t}\n\treturn result\n}\n","/* src/server/core/typescript/src/page/handler.ts */\n\nimport { readFileSync, existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { renderPage, escapeHtml } from '@canmi/seam-engine'\nimport { SeamError } from '../errors.js'\nimport type { InternalProcedure } from '../procedure.js'\nimport type { PageDef, LayoutDef, LoaderFn, I18nConfig } from './index.js'\nimport { headConfigToHtml } from './head.js'\nimport type { LoaderError } from './loader-error.js'\nimport { applyProjection } from './projection.js'\nimport { validateInput, formatValidationErrors } from '../validation/index.js'\n\nexport interface PageTiming {\n\t/** Procedure execution time in milliseconds */\n\tdataFetch: number\n\t/** Template injection time in milliseconds */\n\tinject: number\n}\n\nexport interface HandlePageResult {\n\tstatus: number\n\thtml: string\n\ttiming?: PageTiming\n}\n\nexport interface I18nOpts {\n\tlocale: string\n\tconfig: I18nConfig\n\t/** Route pattern for hash-based message lookup */\n\troutePattern: string\n}\n\ninterface LoaderResults {\n\tdata: Record<string, unknown>\n\tmeta: Record<string, { procedure: string; input: unknown; error?: true }>\n}\n\n/** Execute loaders, returning keyed results and metadata.\n * Each loader is wrapped in its own try-catch so a single failure\n * does not abort sibling loaders — the page renders at 200 with partial data. */\nasync function executeLoaders(\n\tloaders: Record<string, LoaderFn>,\n\tparams: Record<string, string>,\n\tprocedures: Map<string, InternalProcedure>,\n\tsearchParams?: URLSearchParams,\n\tctxResolver?: (proc: InternalProcedure) => Record<string, unknown>,\n\tshouldValidateInput?: boolean,\n): Promise<LoaderResults> {\n\tconst entries = Object.entries(loaders)\n\tconst results = await Promise.all(\n\t\tentries.map(async ([key, loader]) => {\n\t\t\tconst { procedure, input } = loader(params, searchParams)\n\t\t\ttry {\n\t\t\t\tconst proc = procedures.get(procedure)\n\t\t\t\tif (!proc) {\n\t\t\t\t\tthrow new SeamError('INTERNAL_ERROR', `Procedure '${procedure}' not found`)\n\t\t\t\t}\n\t\t\t\tif (shouldValidateInput) {\n\t\t\t\t\tconst v = validateInput(proc.inputSchema, input)\n\t\t\t\t\tif (!v.valid) {\n\t\t\t\t\t\tconst summary = formatValidationErrors(v.errors)\n\t\t\t\t\t\tthrow new SeamError('VALIDATION_ERROR', `Input validation failed: ${summary}`)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst ctx = ctxResolver ? ctxResolver(proc) : {}\n\t\t\t\tconst result = await proc.handler({ input, ctx })\n\t\t\t\treturn { key, result, procedure, input }\n\t\t\t} catch (err) {\n\t\t\t\tconst code = err instanceof SeamError ? err.code : 'INTERNAL_ERROR'\n\t\t\t\tconst message = err instanceof Error ? err.message : 'Unknown error'\n\t\t\t\tconsole.error(`[seam] Loader \"${key}\" failed:`, err)\n\t\t\t\tconst marker: LoaderError = { __error: true, code, message }\n\t\t\t\treturn { key, result: marker as unknown, procedure, input, error: true as const }\n\t\t\t}\n\t\t}),\n\t)\n\treturn {\n\t\tdata: Object.fromEntries(results.map((r) => [r.key, r.result])),\n\t\tmeta: Object.fromEntries(\n\t\t\tresults.map((r) => {\n\t\t\t\tconst entry: { procedure: string; input: unknown; error?: true } = {\n\t\t\t\t\tprocedure: r.procedure,\n\t\t\t\t\tinput: r.input,\n\t\t\t\t}\n\t\t\t\tif (r.error) entry.error = true\n\t\t\t\treturn [r.key, entry]\n\t\t\t}),\n\t\t),\n\t}\n}\n\n/** Select the template for a given locale, falling back to the default template */\nfunction selectTemplate(\n\tdefaultTemplate: string,\n\tlocaleTemplates: Record<string, string> | undefined,\n\tlocale: string | undefined,\n): string {\n\tif (locale && localeTemplates) {\n\t\treturn localeTemplates[locale] ?? defaultTemplate\n\t}\n\treturn defaultTemplate\n}\n\n/** Look up pre-resolved messages for a route + locale. Zero merge, zero filter. */\nfunction lookupMessages(\n\tconfig: I18nConfig,\n\troutePattern: string,\n\tlocale: string,\n): Record<string, string> {\n\tconst routeHash = config.routeHashes[routePattern]\n\tif (!routeHash) return {}\n\n\tif (config.mode === 'paged' && config.distDir) {\n\t\tconst filePath = join(config.distDir, 'i18n', routeHash, `${locale}.json`)\n\t\tif (existsSync(filePath)) {\n\t\t\treturn JSON.parse(readFileSync(filePath, 'utf-8')) as Record<string, string>\n\t\t}\n\t\treturn {}\n\t}\n\n\treturn config.messages[locale]?.[routeHash] ?? {}\n}\n\n/** Build JSON payload for engine i18n injection */\nfunction buildI18nPayload(opts: I18nOpts): string {\n\tconst { config: i18nConfig, routePattern, locale } = opts\n\tconst messages = lookupMessages(i18nConfig, routePattern, locale)\n\tconst routeHash = i18nConfig.routeHashes[routePattern]\n\tconst i18nData: Record<string, unknown> = {\n\t\tlocale,\n\t\tdefault_locale: i18nConfig.default,\n\t\tmessages,\n\t}\n\tif (i18nConfig.cache && routeHash) {\n\t\ti18nData.hash = i18nConfig.contentHashes[routeHash]?.[locale]\n\t\ti18nData.router = i18nConfig.contentHashes\n\t}\n\treturn JSON.stringify(i18nData)\n}\n\nexport async function handlePageRequest(\n\tpage: PageDef,\n\tparams: Record<string, string>,\n\tprocedures: Map<string, InternalProcedure>,\n\ti18nOpts?: I18nOpts,\n\tsearchParams?: URLSearchParams,\n\tctxResolver?: (proc: InternalProcedure) => Record<string, unknown>,\n\tshouldValidateInput?: boolean,\n): Promise<HandlePageResult> {\n\ttry {\n\t\tconst t0 = performance.now()\n\t\tconst layoutChain = page.layoutChain ?? []\n\t\tconst locale = i18nOpts?.locale\n\n\t\t// Execute all loaders (layout chain + page) in parallel\n\t\tconst loaderResults = await Promise.all([\n\t\t\t...layoutChain.map((layout) =>\n\t\t\t\texecuteLoaders(\n\t\t\t\t\tlayout.loaders,\n\t\t\t\t\tparams,\n\t\t\t\t\tprocedures,\n\t\t\t\t\tsearchParams,\n\t\t\t\t\tctxResolver,\n\t\t\t\t\tshouldValidateInput,\n\t\t\t\t),\n\t\t\t),\n\t\t\texecuteLoaders(\n\t\t\t\tpage.loaders,\n\t\t\t\tparams,\n\t\t\t\tprocedures,\n\t\t\t\tsearchParams,\n\t\t\t\tctxResolver,\n\t\t\t\tshouldValidateInput,\n\t\t\t),\n\t\t])\n\n\t\tconst t1 = performance.now()\n\n\t\t// Merge all loader data and metadata into single objects\n\t\tconst allData: Record<string, unknown> = {}\n\t\tconst allMeta: Record<string, { procedure: string; input: unknown; error?: true }> = {}\n\t\tfor (const { data, meta } of loaderResults) {\n\t\t\tObject.assign(allData, data)\n\t\t\tObject.assign(allMeta, meta)\n\t\t}\n\n\t\t// Prune to projected fields before template injection\n\t\tconst prunedData = applyProjection(allData, page.projections)\n\n\t\t// Compose template: nest page inside layouts via outlet substitution\n\t\tconst pageTemplate = selectTemplate(page.template, page.localeTemplates, locale)\n\t\tlet composedTemplate = pageTemplate\n\t\tfor (let i = layoutChain.length - 1; i >= 0; i--) {\n\t\t\tconst layout = layoutChain[i] as LayoutDef\n\t\t\tconst layoutTemplate = selectTemplate(layout.template, layout.localeTemplates, locale)\n\t\t\tcomposedTemplate = layoutTemplate.replace('<!--seam:outlet-->', composedTemplate)\n\t\t}\n\n\t\t// Resolve head metadata from headFn (overrides manifest head_meta)\n\t\tlet resolvedHeadMeta = page.headMeta\n\t\tif (page.headFn) {\n\t\t\ttry {\n\t\t\t\tconst headConfig = page.headFn(allData)\n\t\t\t\tresolvedHeadMeta = headConfigToHtml(headConfig)\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error('[seam] head function failed:', err)\n\t\t\t}\n\t\t}\n\n\t\t// Build PageConfig for engine\n\t\tconst config: Record<string, unknown> = {\n\t\t\tlayout_chain: layoutChain.map((l) => ({\n\t\t\t\tid: l.id,\n\t\t\t\tloader_keys: Object.keys(l.loaders),\n\t\t\t})),\n\t\t\tdata_id: page.dataId ?? '__data',\n\t\t\thead_meta: resolvedHeadMeta,\n\t\t\tloader_metadata: allMeta,\n\t\t}\n\t\tif (page.pageAssets) {\n\t\t\tconfig.page_assets = page.pageAssets\n\t\t}\n\n\t\tconst i18nOptsJson = i18nOpts ? buildI18nPayload(i18nOpts) : undefined\n\n\t\t// Single WASM call: inject slots, compose data script, apply locale/meta\n\t\tconst html = renderPage(\n\t\t\tcomposedTemplate,\n\t\t\tJSON.stringify(prunedData),\n\t\t\tJSON.stringify(config),\n\t\t\ti18nOptsJson,\n\t\t)\n\n\t\tconst t2 = performance.now()\n\n\t\treturn {\n\t\t\tstatus: 200,\n\t\t\thtml,\n\t\t\ttiming: { dataFetch: t1 - t0, inject: t2 - t1 },\n\t\t}\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : 'Unknown error'\n\t\treturn {\n\t\t\tstatus: 500,\n\t\t\thtml: `<!DOCTYPE html><html><body><h1>500 Internal Server Error</h1><p>${escapeHtml(message)}</p></body></html>`,\n\t\t\ttiming: { dataFetch: 0, inject: 0 },\n\t\t}\n\t}\n}\n","/* src/server/core/typescript/src/resolve.ts */\n\n// -- New strategy-based API --\n\nexport interface ResolveStrategy {\n\treadonly kind: string\n\tresolve(data: ResolveData): string | null\n}\n\nexport interface ResolveData {\n\treadonly url: string\n\treadonly pathLocale: string | null\n\treadonly cookie: string | undefined\n\treadonly acceptLanguage: string | undefined\n\treadonly locales: string[]\n\treadonly defaultLocale: string\n}\n\n/** URL prefix strategy: trusts pathLocale if it is a known locale */\nexport function fromUrlPrefix(): ResolveStrategy {\n\treturn {\n\t\tkind: 'url_prefix',\n\t\tresolve(data) {\n\t\t\tif (data.pathLocale && data.locales.includes(data.pathLocale)) {\n\t\t\t\treturn data.pathLocale\n\t\t\t}\n\t\t\treturn null\n\t\t},\n\t}\n}\n\n/** Cookie strategy: reads a named cookie and validates against known locales */\nexport function fromCookie(name = 'seam-locale'): ResolveStrategy {\n\treturn {\n\t\tkind: 'cookie',\n\t\tresolve(data) {\n\t\t\tif (!data.cookie) return null\n\t\t\tfor (const pair of data.cookie.split(';')) {\n\t\t\t\tconst parts = pair.trim().split('=')\n\t\t\t\tconst k = parts[0]\n\t\t\t\tconst v = parts[1]\n\t\t\t\tif (k === name && v && data.locales.includes(v)) return v\n\t\t\t}\n\t\t\treturn null\n\t\t},\n\t}\n}\n\n/** Accept-Language strategy: parses header with q-value sorting + prefix match */\nexport function fromAcceptLanguage(): ResolveStrategy {\n\treturn {\n\t\tkind: 'accept_language',\n\t\tresolve(data) {\n\t\t\tif (!data.acceptLanguage) return null\n\t\t\tconst entries: { lang: string; q: number }[] = []\n\t\t\tfor (const part of data.acceptLanguage.split(',')) {\n\t\t\t\tconst trimmed = part.trim()\n\t\t\t\tconst parts = trimmed.split(';')\n\t\t\t\tconst lang = parts[0] as string\n\t\t\t\tlet q = 1\n\t\t\t\tfor (let j = 1; j < parts.length; j++) {\n\t\t\t\t\tconst match = (parts[j] as string).trim().match(/^q=(\\d+(?:\\.\\d+)?)$/)\n\t\t\t\t\tif (match) q = parseFloat(match[1] as string)\n\t\t\t\t}\n\t\t\t\tentries.push({ lang: lang.trim(), q })\n\t\t\t}\n\t\t\tentries.sort((a, b) => b.q - a.q)\n\t\t\tconst localeSet = new Set(data.locales)\n\t\t\tfor (const { lang } of entries) {\n\t\t\t\tif (localeSet.has(lang)) return lang\n\t\t\t\t// Prefix match: zh-CN -> zh\n\t\t\t\tconst prefix = lang.split('-')[0] as string\n\t\t\t\tif (prefix !== lang && localeSet.has(prefix)) return prefix\n\t\t\t}\n\t\t\treturn null\n\t\t},\n\t}\n}\n\n/** URL query strategy: reads a query parameter and validates against known locales */\nexport function fromUrlQuery(param = 'lang'): ResolveStrategy {\n\treturn {\n\t\tkind: 'url_query',\n\t\tresolve(data) {\n\t\t\tif (!data.url) return null\n\t\t\ttry {\n\t\t\t\tconst url = new URL(data.url, 'http://localhost')\n\t\t\t\tconst value = url.searchParams.get(param)\n\t\t\t\tif (value && data.locales.includes(value)) return value\n\t\t\t} catch {\n\t\t\t\t// Invalid URL — skip\n\t\t\t}\n\t\t\treturn null\n\t\t},\n\t}\n}\n\n/** Run strategies in order; first non-null wins, otherwise defaultLocale */\nexport function resolveChain(strategies: ResolveStrategy[], data: ResolveData): string {\n\tfor (const s of strategies) {\n\t\tconst result = s.resolve(data)\n\t\tif (result !== null) return result\n\t}\n\treturn data.defaultLocale\n}\n\n/** Default strategy chain: url_prefix -> cookie -> accept_language */\nexport function defaultStrategies(): ResolveStrategy[] {\n\treturn [fromUrlPrefix(), fromCookie(), fromAcceptLanguage()]\n}\n","/* src/server/core/typescript/src/router/helpers.ts */\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { HandleResult, InternalProcedure } from './handler.js'\nimport type { HandlePageResult } from '../page/handler.js'\nimport type { PageDef, I18nConfig } from '../page/index.js'\nimport type { ChannelResult, ChannelMeta } from '../channel.js'\nimport type { ContextConfig, RawContextMap } from '../context.js'\nimport { resolveContext } from '../context.js'\nimport { SeamError } from '../errors.js'\nimport { handlePageRequest } from '../page/handler.js'\nimport { defaultStrategies, resolveChain } from '../resolve.js'\nimport type { ResolveStrategy } from '../resolve.js'\nimport type { ValidationMode, RouterOptions, PageRequestHeaders } from './index.js'\n\n/** Resolve a ValidationMode to a boolean flag */\nexport function resolveValidationMode(mode: ValidationMode | undefined): boolean {\n\tconst m = mode ?? 'dev'\n\tif (m === 'always') return true\n\tif (m === 'never') return false\n\treturn typeof process !== 'undefined' && process.env.NODE_ENV !== 'production'\n}\n\n/** Build the resolve strategy list from options */\nexport function buildStrategies(opts?: RouterOptions): {\n\tstrategies: ResolveStrategy[]\n\thasUrlPrefix: boolean\n} {\n\tconst strategies = opts?.resolve ?? defaultStrategies()\n\treturn {\n\t\tstrategies,\n\t\thasUrlPrefix: strategies.some((s) => s.kind === 'url_prefix'),\n\t}\n}\n\n/** Register built-in seam.i18n.query procedure (route-hash-based lookup) */\nexport function registerI18nQuery(\n\tprocedureMap: Map<string, InternalProcedure>,\n\tconfig: I18nConfig,\n): void {\n\tconst localeSet = new Set(config.locales)\n\tprocedureMap.set('seam.i18n.query', {\n\t\tinputSchema: {},\n\t\toutputSchema: {},\n\t\tcontextKeys: [],\n\t\thandler: ({ input }) => {\n\t\t\tconst { route, locale: rawLocale } = input as { route: string; locale: string }\n\t\t\tconst locale = localeSet.has(rawLocale) ? rawLocale : config.default\n\t\t\tconst messages = lookupI18nMessages(config, route, locale)\n\t\t\tconst hash = config.contentHashes[route]?.[locale] ?? ''\n\t\t\treturn { hash, messages }\n\t\t},\n\t})\n}\n\n/** Look up messages by route hash + locale for RPC query */\nfunction lookupI18nMessages(\n\tconfig: I18nConfig,\n\trouteHash: string,\n\tlocale: string,\n): Record<string, string> {\n\tif (config.mode === 'paged' && config.distDir) {\n\t\tconst filePath = join(config.distDir, 'i18n', routeHash, `${locale}.json`)\n\t\tif (existsSync(filePath)) {\n\t\t\treturn JSON.parse(readFileSync(filePath, 'utf-8')) as Record<string, string>\n\t\t}\n\t\treturn {}\n\t}\n\treturn config.messages[locale]?.[routeHash] ?? {}\n}\n\n/** Collect channel metadata from channel results for manifest */\nexport function collectChannelMeta(\n\tchannels: ChannelResult[] | undefined,\n): Record<string, ChannelMeta> | undefined {\n\tif (!channels || channels.length === 0) return undefined\n\treturn Object.fromEntries(\n\t\tchannels.map((ch) => {\n\t\t\tconst firstKey = Object.keys(ch.procedures)[0] ?? ''\n\t\t\tconst name = firstKey.includes('.') ? firstKey.slice(0, firstKey.indexOf('.')) : firstKey\n\t\t\treturn [name, ch.channelMeta]\n\t\t}),\n\t)\n}\n\n/** Resolve context for a procedure, returning undefined if no context needed */\nexport function resolveCtxFor(\n\tmap: Map<string, { contextKeys: string[] }>,\n\tname: string,\n\trawCtx: RawContextMap | undefined,\n\tctxConfig: ContextConfig,\n): Record<string, unknown> | undefined {\n\tif (!rawCtx) return undefined\n\tconst proc = map.get(name)\n\tif (!proc || proc.contextKeys.length === 0) return undefined\n\treturn resolveContext(ctxConfig, rawCtx, proc.contextKeys)\n}\n\n/** Resolve locale and match page route */\nexport async function matchAndHandlePage(\n\tpageMatcher: {\n\t\tmatch(path: string): { value: PageDef; params: Record<string, string>; pattern: string } | null\n\t},\n\tprocedureMap: Map<string, InternalProcedure>,\n\ti18nConfig: I18nConfig | null,\n\tstrategies: ResolveStrategy[],\n\thasUrlPrefix: boolean,\n\tpath: string,\n\theaders?: PageRequestHeaders,\n\trawCtx?: RawContextMap,\n\tctxConfig?: ContextConfig,\n\tshouldValidateInput?: boolean,\n): Promise<HandlePageResult | null> {\n\tlet pathLocale: string | null = null\n\tlet routePath = path\n\n\tif (hasUrlPrefix && i18nConfig) {\n\t\tconst segments = path.split('/').filter(Boolean)\n\t\tconst localeSet = new Set(i18nConfig.locales)\n\t\tconst first = segments[0]\n\t\tif (first && localeSet.has(first)) {\n\t\t\tpathLocale = first\n\t\t\troutePath = '/' + segments.slice(1).join('/') || '/'\n\t\t}\n\t}\n\n\tlet locale: string | undefined\n\tif (i18nConfig) {\n\t\tlocale = resolveChain(strategies, {\n\t\t\turl: headers?.url ?? '',\n\t\t\tpathLocale,\n\t\t\tcookie: headers?.cookie,\n\t\t\tacceptLanguage: headers?.acceptLanguage,\n\t\t\tlocales: i18nConfig.locales,\n\t\t\tdefaultLocale: i18nConfig.default,\n\t\t})\n\t}\n\n\tconst match = pageMatcher.match(routePath)\n\tif (!match) return null\n\n\t// SSG short-circuit: serve pre-rendered HTML without loader execution\n\tif (match.value.prerender && match.value.staticDir) {\n\t\tconst htmlPath = join(match.value.staticDir, routePath === '/' ? '' : routePath, 'index.html')\n\t\ttry {\n\t\t\tconst html = readFileSync(htmlPath, 'utf-8')\n\t\t\treturn { status: 200, html }\n\t\t} catch {\n\t\t\t// Fall through to dynamic rendering (graceful degradation)\n\t\t}\n\t}\n\n\tlet searchParams: URLSearchParams | undefined\n\tif (headers?.url) {\n\t\ttry {\n\t\t\tconst url = new URL(headers.url, 'http://localhost')\n\t\t\tif (url.search) searchParams = url.searchParams\n\t\t} catch {\n\t\t\t// Malformed URL — ignore\n\t\t}\n\t}\n\n\tconst i18nOpts =\n\t\tlocale && i18nConfig ? { locale, config: i18nConfig, routePattern: match.pattern } : undefined\n\n\tconst ctxResolver = rawCtx\n\t\t? (proc: { contextKeys: string[] }) => {\n\t\t\t\tif (proc.contextKeys.length === 0) return {}\n\t\t\t\treturn resolveContext(ctxConfig ?? {}, rawCtx, proc.contextKeys)\n\t\t\t}\n\t\t: undefined\n\n\treturn handlePageRequest(\n\t\tmatch.value,\n\t\tmatch.params,\n\t\tprocedureMap,\n\t\ti18nOpts,\n\t\tsearchParams,\n\t\tctxResolver,\n\t\tshouldValidateInput,\n\t)\n}\n\n/** Catch context resolution errors and return them as HandleResult */\nexport function resolveCtxSafe(\n\tmap: Map<string, { contextKeys: string[] }>,\n\tname: string,\n\trawCtx: RawContextMap | undefined,\n\tctxConfig: ContextConfig,\n): { ctx?: Record<string, unknown>; error?: HandleResult } {\n\ttry {\n\t\treturn { ctx: resolveCtxFor(map, name, rawCtx, ctxConfig) }\n\t} catch (err) {\n\t\tif (err instanceof SeamError) {\n\t\t\treturn { error: { status: err.status, body: err.toJSON() } }\n\t\t}\n\t\tthrow err\n\t}\n}\n","/* src/server/core/typescript/src/router/state.ts */\n\nimport { readFileSync, existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { contextHasExtracts } from '../context.js'\nimport { buildManifest } from '../manifest/index.js'\nimport type { PageDef } from '../page/index.js'\nimport { RouteMatcher } from '../page/route-matcher.js'\nimport {\n\thandleRequest,\n\thandleSubscription,\n\thandleStream,\n\thandleBatchRequest,\n\thandleUploadRequest,\n} from './handler.js'\nimport { categorizeProcedures } from './categorize.js'\nimport {\n\tresolveValidationMode,\n\tbuildStrategies,\n\tregisterI18nQuery,\n\tcollectChannelMeta,\n\tresolveCtxFor,\n\tresolveCtxSafe,\n\tmatchAndHandlePage,\n} from './helpers.js'\nimport type { DefinitionMap, RouterOptions, Router } from './index.js'\n\n/** Build all shared state that createRouter methods close over */\nexport function initRouterState(procedures: DefinitionMap, opts?: RouterOptions) {\n\tconst ctxConfig = opts?.context ?? {}\n\tconst { procedureMap, subscriptionMap, streamMap, uploadMap, kindMap } = categorizeProcedures(\n\t\tprocedures,\n\t\tObject.keys(ctxConfig).length > 0 ? ctxConfig : undefined,\n\t)\n\tconst shouldValidateInput = resolveValidationMode(opts?.validation?.input)\n\tconst shouldValidateOutput =\n\t\topts?.validateOutput ??\n\t\t(typeof process !== 'undefined' && process.env.NODE_ENV !== 'production')\n\tconst pageMatcher = new RouteMatcher<PageDef>()\n\tconst pages = opts?.pages\n\tif (pages) {\n\t\tfor (const [pattern, page] of Object.entries(pages)) {\n\t\t\tpageMatcher.add(pattern, page)\n\t\t}\n\t}\n\tconst i18nConfig = opts?.i18n ?? null\n\tconst { strategies, hasUrlPrefix } = buildStrategies(opts)\n\tif (i18nConfig) registerI18nQuery(procedureMap, i18nConfig)\n\tconst channelsMeta = collectChannelMeta(opts?.channels)\n\tconst hasCtx = contextHasExtracts(ctxConfig)\n\treturn {\n\t\tctxConfig,\n\t\tprocedureMap,\n\t\tsubscriptionMap,\n\t\tstreamMap,\n\t\tuploadMap,\n\t\tkindMap,\n\t\tshouldValidateInput,\n\t\tshouldValidateOutput,\n\t\tpageMatcher,\n\t\tpages,\n\t\ti18nConfig,\n\t\tstrategies,\n\t\thasUrlPrefix,\n\t\tchannelsMeta,\n\t\thasCtx,\n\t}\n}\n\n/** Build request-response methods: handle, handleBatch, handleUpload */\nfunction buildRpcMethods(\n\tstate: ReturnType<typeof initRouterState>,\n): Pick<Router<DefinitionMap>, 'handle' | 'handleBatch' | 'handleUpload'> {\n\treturn {\n\t\tasync handle(procedureName, body, rawCtx) {\n\t\t\tconst { ctx, error } = resolveCtxSafe(\n\t\t\t\tstate.procedureMap,\n\t\t\t\tprocedureName,\n\t\t\t\trawCtx,\n\t\t\t\tstate.ctxConfig,\n\t\t\t)\n\t\t\tif (error) return error\n\t\t\treturn handleRequest(\n\t\t\t\tstate.procedureMap,\n\t\t\t\tprocedureName,\n\t\t\t\tbody,\n\t\t\t\tstate.shouldValidateInput,\n\t\t\t\tstate.shouldValidateOutput,\n\t\t\t\tctx,\n\t\t\t)\n\t\t},\n\t\thandleBatch(calls, rawCtx) {\n\t\t\tconst ctxResolver = rawCtx\n\t\t\t\t? (name: string) => resolveCtxFor(state.procedureMap, name, rawCtx, state.ctxConfig) ?? {}\n\t\t\t\t: undefined\n\t\t\treturn handleBatchRequest(\n\t\t\t\tstate.procedureMap,\n\t\t\t\tcalls,\n\t\t\t\tstate.shouldValidateInput,\n\t\t\t\tstate.shouldValidateOutput,\n\t\t\t\tctxResolver,\n\t\t\t)\n\t\t},\n\t\tasync handleUpload(name, body, file, rawCtx) {\n\t\t\tconst { ctx, error } = resolveCtxSafe(state.uploadMap, name, rawCtx, state.ctxConfig)\n\t\t\tif (error) return error\n\t\t\treturn handleUploadRequest(\n\t\t\t\tstate.uploadMap,\n\t\t\t\tname,\n\t\t\t\tbody,\n\t\t\t\tfile,\n\t\t\t\tstate.shouldValidateInput,\n\t\t\t\tstate.shouldValidateOutput,\n\t\t\t\tctx,\n\t\t\t)\n\t\t},\n\t}\n}\n\n/** Build all Router method implementations from shared state */\nexport function buildRouterMethods(\n\tstate: ReturnType<typeof initRouterState>,\n\tprocedures: DefinitionMap,\n\topts?: RouterOptions,\n): Omit<Router<DefinitionMap>, 'procedures' | 'rpcHashMap'> {\n\treturn {\n\t\thasPages: !!state.pages && Object.keys(state.pages).length > 0,\n\t\tctxConfig: state.ctxConfig,\n\t\thasContext() {\n\t\t\treturn state.hasCtx\n\t\t},\n\t\tmanifest() {\n\t\t\treturn buildManifest(procedures, state.channelsMeta, state.ctxConfig, opts?.transportDefaults)\n\t\t},\n\t\t...buildRpcMethods(state),\n\t\thandleSubscription(name, input, rawCtx, lastEventId) {\n\t\t\tconst ctx = resolveCtxFor(state.subscriptionMap, name, rawCtx, state.ctxConfig)\n\t\t\treturn handleSubscription(\n\t\t\t\tstate.subscriptionMap,\n\t\t\t\tname,\n\t\t\t\tinput,\n\t\t\t\tstate.shouldValidateInput,\n\t\t\t\tstate.shouldValidateOutput,\n\t\t\t\tctx,\n\t\t\t\tlastEventId,\n\t\t\t)\n\t\t},\n\t\thandleStream(name, input, rawCtx) {\n\t\t\tconst ctx = resolveCtxFor(state.streamMap, name, rawCtx, state.ctxConfig)\n\t\t\treturn handleStream(\n\t\t\t\tstate.streamMap,\n\t\t\t\tname,\n\t\t\t\tinput,\n\t\t\t\tstate.shouldValidateInput,\n\t\t\t\tstate.shouldValidateOutput,\n\t\t\t\tctx,\n\t\t\t)\n\t\t},\n\t\tgetKind(name) {\n\t\t\treturn state.kindMap.get(name) ?? null\n\t\t},\n\t\thandlePage(path, headers, rawCtx) {\n\t\t\treturn matchAndHandlePage(\n\t\t\t\tstate.pageMatcher,\n\t\t\t\tstate.procedureMap,\n\t\t\t\tstate.i18nConfig,\n\t\t\t\tstate.strategies,\n\t\t\t\tstate.hasUrlPrefix,\n\t\t\t\tpath,\n\t\t\t\theaders,\n\t\t\t\trawCtx,\n\t\t\t\tstate.ctxConfig,\n\t\t\t\tstate.shouldValidateInput,\n\t\t\t)\n\t\t},\n\t\thandlePageData(path) {\n\t\t\tconst match = state.pageMatcher?.match(path)\n\t\t\tif (!match) return Promise.resolve(null)\n\t\t\tconst page = match.value\n\t\t\tif (!page.prerender || !page.staticDir) return Promise.resolve(null)\n\t\t\tconst dataPath = join(page.staticDir, path === '/' ? '' : path, '__data.json')\n\t\t\ttry {\n\t\t\t\tif (!existsSync(dataPath)) return Promise.resolve(null)\n\t\t\t\treturn Promise.resolve(JSON.parse(readFileSync(dataPath, 'utf-8')) as unknown)\n\t\t\t} catch {\n\t\t\t\treturn Promise.resolve(null)\n\t\t\t}\n\t\t},\n\t}\n}\n","/* src/server/core/typescript/src/router/index.ts */\n\nimport type { RpcHashMap } from '../http.js'\nimport type { SchemaNode } from '../types/schema.js'\nimport type { ProcedureManifest } from '../manifest/index.js'\nimport type { HandleResult } from './handler.js'\nimport type { SeamFileHandle } from '../procedure.js'\nimport type { HandlePageResult } from '../page/handler.js'\nimport type { PageDef, I18nConfig } from '../page/index.js'\nimport type { ChannelResult } from '../channel.js'\nimport type { ContextConfig, RawContextMap } from '../context.js'\nimport type { ResolveStrategy } from '../resolve.js'\nimport type { BatchCall, BatchResultItem } from './handler.js'\nimport { initRouterState, buildRouterMethods } from './state.js'\n\nexport type ProcedureKind = 'query' | 'command' | 'subscription' | 'stream' | 'upload'\n\nexport type ValidationMode = 'dev' | 'always' | 'never'\n\nexport interface ValidationConfig {\n\tinput?: ValidationMode\n}\n\nexport type MappingValue = string | { from: string; each?: boolean }\n\nexport type InvalidateTarget =\n\t| string\n\t| {\n\t\t\tquery: string\n\t\t\tmapping?: Record<string, MappingValue>\n\t }\n\nexport type TransportPreference = 'http' | 'sse' | 'ws' | 'ipc'\n\nexport interface TransportConfig {\n\tprefer: TransportPreference\n\tfallback?: TransportPreference[]\n}\n\nexport type CacheConfig = false | { ttl: number }\n\n/** @deprecated Use QueryDef instead */\nexport interface ProcedureDef<TIn = unknown, TOut = unknown> {\n\tkind?: 'query'\n\t/** @deprecated Use `kind` instead */\n\ttype?: 'query'\n\tinput: SchemaNode<TIn>\n\toutput: SchemaNode<TOut>\n\terror?: SchemaNode\n\tcontext?: string[]\n\ttransport?: TransportConfig\n\tsuppress?: string[]\n\tcache?: CacheConfig\n\thandler: (params: { input: TIn; ctx: Record<string, unknown> }) => TOut | Promise<TOut>\n}\n\nexport type QueryDef<TIn = unknown, TOut = unknown> = ProcedureDef<TIn, TOut>\n\nexport interface CommandDef<TIn = unknown, TOut = unknown> {\n\tkind?: 'command'\n\t/** @deprecated Use `kind` instead */\n\ttype?: 'command'\n\tinput: SchemaNode<TIn>\n\toutput: SchemaNode<TOut>\n\terror?: SchemaNode\n\tcontext?: string[]\n\tinvalidates?: InvalidateTarget[]\n\ttransport?: TransportConfig\n\tsuppress?: string[]\n\thandler: (params: { input: TIn; ctx: Record<string, unknown> }) => TOut | Promise<TOut>\n}\n\nexport interface SubscriptionDef<TIn = unknown, TOut = unknown> {\n\tkind?: 'subscription'\n\t/** @deprecated Use `kind` instead */\n\ttype?: 'subscription'\n\tinput: SchemaNode<TIn>\n\toutput: SchemaNode<TOut>\n\terror?: SchemaNode\n\tcontext?: string[]\n\ttransport?: TransportConfig\n\tsuppress?: string[]\n\thandler: (params: {\n\t\tinput: TIn\n\t\tctx: Record<string, unknown>\n\t\tlastEventId?: string\n\t}) => AsyncIterable<TOut>\n}\n\nexport interface StreamDef<TIn = unknown, TChunk = unknown> {\n\tkind: 'stream'\n\tinput: SchemaNode<TIn>\n\toutput: SchemaNode<TChunk>\n\terror?: SchemaNode\n\tcontext?: string[]\n\ttransport?: TransportConfig\n\tsuppress?: string[]\n\thandler: (params: { input: TIn; ctx: Record<string, unknown> }) => AsyncGenerator<TChunk>\n}\n\nexport interface UploadDef<TIn = unknown, TOut = unknown> {\n\tkind: 'upload'\n\tinput: SchemaNode<TIn>\n\toutput: SchemaNode<TOut>\n\terror?: SchemaNode\n\tcontext?: string[]\n\ttransport?: TransportConfig\n\tsuppress?: string[]\n\thandler: (params: {\n\t\tinput: TIn\n\t\tfile: SeamFileHandle\n\t\tctx: Record<string, unknown>\n\t}) => TOut | Promise<TOut>\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport type DefinitionMap = Record<\n\tstring,\n\t| QueryDef<any, any>\n\t| CommandDef<any, any>\n\t| SubscriptionDef<any, any>\n\t| StreamDef<any, any>\n\t| UploadDef<any, any>\n>\n\ntype NestedDefinitionValue =\n\t| QueryDef<any, any>\n\t| CommandDef<any, any>\n\t| SubscriptionDef<any, any>\n\t| StreamDef<any, any>\n\t| UploadDef<any, any>\n\t| { [key: string]: NestedDefinitionValue }\n\nexport type NestedDefinitionMap = Record<string, NestedDefinitionValue>\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\nfunction isProcedureDef(value: unknown): value is DefinitionMap[string] {\n\treturn typeof value === 'object' && value !== null && 'input' in value && 'handler' in value\n}\n\nfunction flattenDefinitions(nested: NestedDefinitionMap, prefix = ''): DefinitionMap {\n\tconst flat: DefinitionMap = {}\n\tfor (const [key, value] of Object.entries(nested)) {\n\t\tconst fullKey = prefix ? `${prefix}.${key}` : key\n\t\tif (isProcedureDef(value)) {\n\t\t\tflat[fullKey] = value\n\t\t} else {\n\t\t\tObject.assign(flat, flattenDefinitions(value as NestedDefinitionMap, fullKey))\n\t\t}\n\t}\n\treturn flat\n}\n\nexport interface RouterOptions {\n\tpages?: Record<string, PageDef>\n\trpcHashMap?: RpcHashMap\n\ti18n?: I18nConfig | null\n\tvalidateOutput?: boolean\n\tvalidation?: ValidationConfig\n\tresolve?: ResolveStrategy[]\n\tchannels?: ChannelResult[]\n\tcontext?: ContextConfig\n\ttransportDefaults?: Partial<Record<ProcedureKind, TransportConfig>>\n}\n\nexport interface PageRequestHeaders {\n\turl?: string\n\tcookie?: string\n\tacceptLanguage?: string\n}\n\nexport interface Router<T extends DefinitionMap> {\n\tmanifest(): ProcedureManifest\n\thandle(procedureName: string, body: unknown, rawCtx?: RawContextMap): Promise<HandleResult>\n\thandleBatch(calls: BatchCall[], rawCtx?: RawContextMap): Promise<{ results: BatchResultItem[] }>\n\thandleSubscription(\n\t\tname: string,\n\t\tinput: unknown,\n\t\trawCtx?: RawContextMap,\n\t\tlastEventId?: string,\n\t): AsyncIterable<unknown>\n\thandleStream(name: string, input: unknown, rawCtx?: RawContextMap): AsyncGenerator<unknown>\n\thandleUpload(\n\t\tname: string,\n\t\tbody: unknown,\n\t\tfile: SeamFileHandle,\n\t\trawCtx?: RawContextMap,\n\t): Promise<HandleResult>\n\tgetKind(name: string): ProcedureKind | null\n\thandlePage(\n\t\tpath: string,\n\t\theaders?: PageRequestHeaders,\n\t\trawCtx?: RawContextMap,\n\t): Promise<HandlePageResult | null>\n\t/** Serve __data.json for a prerendered page (SPA navigation) */\n\thandlePageData(path: string): Promise<unknown>\n\thasContext(): boolean\n\treadonly ctxConfig: ContextConfig\n\treadonly hasPages: boolean\n\treadonly rpcHashMap: RpcHashMap | undefined\n\t/** Exposed for adapter access to the definitions */\n\treadonly procedures: T\n}\n\nexport function createRouter<T extends DefinitionMap>(\n\tprocedures: T | NestedDefinitionMap,\n\topts?: RouterOptions,\n): Router<T> {\n\tconst flat = flattenDefinitions(procedures as NestedDefinitionMap) as T\n\tconst state = initRouterState(flat, opts)\n\treturn {\n\t\tprocedures: flat,\n\t\trpcHashMap: opts?.rpcHashMap,\n\t\t...buildRouterMethods(state, flat, opts),\n\t}\n}\n","/* src/server/core/typescript/src/factory.ts */\n\nimport type { QueryDef, CommandDef, SubscriptionDef, StreamDef, UploadDef } from './router/index.js'\n\nexport function query<TIn, TOut>(\n\tdef: Omit<QueryDef<TIn, TOut>, 'kind' | 'type'>,\n): QueryDef<TIn, TOut> {\n\treturn { ...def, kind: 'query' } as QueryDef<TIn, TOut>\n}\n\nexport function command<TIn, TOut>(\n\tdef: Omit<CommandDef<TIn, TOut>, 'kind' | 'type'>,\n): CommandDef<TIn, TOut> {\n\treturn { ...def, kind: 'command' } as CommandDef<TIn, TOut>\n}\n\nexport function subscription<TIn, TOut>(\n\tdef: Omit<SubscriptionDef<TIn, TOut>, 'kind' | 'type'>,\n): SubscriptionDef<TIn, TOut> {\n\treturn { ...def, kind: 'subscription' } as SubscriptionDef<TIn, TOut>\n}\n\nexport function stream<TIn, TChunk>(\n\tdef: Omit<StreamDef<TIn, TChunk>, 'kind'>,\n): StreamDef<TIn, TChunk> {\n\treturn { ...def, kind: 'stream' } as StreamDef<TIn, TChunk>\n}\n\nexport function upload<TIn, TOut>(def: Omit<UploadDef<TIn, TOut>, 'kind'>): UploadDef<TIn, TOut> {\n\treturn { ...def, kind: 'upload' } as UploadDef<TIn, TOut>\n}\n","/* src/server/core/typescript/src/seam-router.ts */\n\nimport type { SchemaNode } from './types/schema.js'\nimport type {\n\tQueryDef,\n\tCommandDef,\n\tSubscriptionDef,\n\tStreamDef,\n\tUploadDef,\n\tDefinitionMap,\n\tRouter,\n\tRouterOptions,\n\tInvalidateTarget,\n\tTransportConfig,\n\tCacheConfig,\n} from './router/index.js'\nimport type { SeamFileHandle } from './procedure.js'\nimport { createRouter } from './router/index.js'\n\n// -- Type-level context inference --\n\nexport interface TypedContextFieldDef<T = unknown> {\n\textract: string\n\tschema: SchemaNode<T>\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\ntype InferContextMap<T extends Record<string, TypedContextFieldDef<any>>> = {\n\t[K in keyof T]: T[K] extends TypedContextFieldDef<infer U> ? U : never\n}\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\ntype PickContext<TMap, TKeys extends readonly string[]> = Pick<TMap, TKeys[number] & keyof TMap>\n\n// -- Per-kind def types with typed ctx --\n\ntype QueryDefWithCtx<TIn, TOut, TCtx> = {\n\tinput: SchemaNode<TIn>\n\toutput: SchemaNode<TOut>\n\terror?: SchemaNode\n\tcontext?: readonly string[]\n\ttransport?: TransportConfig\n\tsuppress?: string[]\n\tcache?: CacheConfig\n\thandler: (params: { input: TIn; ctx: TCtx }) => TOut | Promise<TOut>\n}\n\ntype CommandDefWithCtx<TIn, TOut, TCtx> = {\n\tinput: SchemaNode<TIn>\n\toutput: SchemaNode<TOut>\n\terror?: SchemaNode\n\tcontext?: readonly string[]\n\tinvalidates?: InvalidateTarget[]\n\ttransport?: TransportConfig\n\tsuppress?: string[]\n\thandler: (params: { input: TIn; ctx: TCtx }) => TOut | Promise<TOut>\n}\n\ntype SubscriptionDefWithCtx<TIn, TOut, TCtx> = {\n\tinput: SchemaNode<TIn>\n\toutput: SchemaNode<TOut>\n\terror?: SchemaNode\n\tcontext?: readonly string[]\n\ttransport?: TransportConfig\n\tsuppress?: string[]\n\thandler: (params: { input: TIn; ctx: TCtx }) => AsyncIterable<TOut>\n}\n\ntype StreamDefWithCtx<TIn, TChunk, TCtx> = {\n\tinput: SchemaNode<TIn>\n\toutput: SchemaNode<TChunk>\n\terror?: SchemaNode\n\tcontext?: readonly string[]\n\ttransport?: TransportConfig\n\tsuppress?: string[]\n\thandler: (params: { input: TIn; ctx: TCtx }) => AsyncGenerator<TChunk>\n}\n\ntype UploadDefWithCtx<TIn, TOut, TCtx> = {\n\tinput: SchemaNode<TIn>\n\toutput: SchemaNode<TOut>\n\terror?: SchemaNode\n\tcontext?: readonly string[]\n\ttransport?: TransportConfig\n\tsuppress?: string[]\n\thandler: (params: { input: TIn; file: SeamFileHandle; ctx: TCtx }) => TOut | Promise<TOut>\n}\n\n// -- SeamDefine interface --\n\nexport interface SeamDefine<TCtxMap extends Record<string, unknown>> {\n\tquery<TIn, TOut, const TKeys extends readonly (keyof TCtxMap & string)[] = []>(\n\t\tdef: QueryDefWithCtx<TIn, TOut, PickContext<TCtxMap, TKeys>> & { context?: TKeys },\n\t): QueryDef<TIn, TOut>\n\n\tcommand<TIn, TOut, const TKeys extends readonly (keyof TCtxMap & string)[] = []>(\n\t\tdef: CommandDefWithCtx<TIn, TOut, PickContext<TCtxMap, TKeys>> & { context?: TKeys },\n\t): CommandDef<TIn, TOut>\n\n\tsubscription<TIn, TOut, const TKeys extends readonly (keyof TCtxMap & string)[] = []>(\n\t\tdef: SubscriptionDefWithCtx<TIn, TOut, PickContext<TCtxMap, TKeys>> & { context?: TKeys },\n\t): SubscriptionDef<TIn, TOut>\n\n\tstream<TIn, TChunk, const TKeys extends readonly (keyof TCtxMap & string)[] = []>(\n\t\tdef: StreamDefWithCtx<TIn, TChunk, PickContext<TCtxMap, TKeys>> & { context?: TKeys },\n\t): StreamDef<TIn, TChunk>\n\n\tupload<TIn, TOut, const TKeys extends readonly (keyof TCtxMap & string)[] = []>(\n\t\tdef: UploadDefWithCtx<TIn, TOut, PickContext<TCtxMap, TKeys>> & { context?: TKeys },\n\t): UploadDef<TIn, TOut>\n}\n\n// -- createSeamRouter --\n\n/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return */\nexport function createSeamRouter<const T extends Record<string, TypedContextFieldDef<any>>>(\n\tconfig: { context: T } & Omit<RouterOptions, 'context'>,\n): {\n\trouter: <P extends DefinitionMap>(\n\t\tprocedures: P,\n\t\textraOpts?: Omit<RouterOptions, 'context'>,\n\t) => Router<P>\n\tdefine: SeamDefine<InferContextMap<T>>\n} {\n\tconst { context, ...restConfig } = config\n\n\tconst define: SeamDefine<InferContextMap<T>> = {\n\t\tquery(def) {\n\t\t\treturn { ...def, kind: 'query' } as any\n\t\t},\n\t\tcommand(def) {\n\t\t\treturn { ...def, kind: 'command' } as any\n\t\t},\n\t\tsubscription(def) {\n\t\t\treturn { ...def, kind: 'subscription' } as any\n\t\t},\n\t\tstream(def) {\n\t\t\treturn { ...def, kind: 'stream' } as any\n\t\t},\n\t\tupload(def) {\n\t\t\treturn { ...def, kind: 'upload' } as any\n\t\t},\n\t}\n\n\tfunction router<P extends DefinitionMap>(\n\t\tprocedures: P,\n\t\textraOpts?: Omit<RouterOptions, 'context'>,\n\t): Router<P> {\n\t\treturn createRouter(procedures, { ...restConfig, context, ...extraOpts })\n\t}\n\n\treturn { router, define }\n}\n/* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return */\n","/* src/server/core/typescript/src/channel.ts */\n\nimport type { Schema } from 'jtd'\nimport type { SchemaNode, Infer, JTDSchema } from './types/schema.js'\nimport type { CommandDef, SubscriptionDef, DefinitionMap, TransportConfig } from './router/index.js'\n\n// -- Public types --\n\nexport interface IncomingDef<TIn = unknown, TOut = unknown> {\n\tinput: SchemaNode<TIn>\n\toutput: SchemaNode<TOut>\n\terror?: SchemaNode\n\thandler: (params: { input: TIn }) => TOut | Promise<TOut>\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport interface ChannelDef<\n\tTChannelIn = unknown,\n\tTIncoming extends Record<string, IncomingDef<any, any>> = Record<string, IncomingDef<any, any>>,\n\tTOutgoing extends Record<string, SchemaNode<Record<string, unknown>>> = Record<\n\t\tstring,\n\t\tSchemaNode<Record<string, unknown>>\n\t>,\n> {\n\tinput: SchemaNode<TChannelIn>\n\tincoming: TIncoming\n\toutgoing: TOutgoing\n\tsubscribe: (params: { input: TChannelIn }) => AsyncIterable<ChannelEvent<TOutgoing>>\n\ttransport?: TransportConfig\n}\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\ntype ChannelEvent<TOutgoing extends Record<string, SchemaNode<Record<string, unknown>>>> = {\n\t[K in keyof TOutgoing & string]: { type: K; payload: Infer<TOutgoing[K]> }\n}[keyof TOutgoing & string]\n\n/** IR hint stored in the manifest `channels` field */\nexport interface ChannelMeta {\n\tinput: Schema\n\tincoming: Record<string, { input: Schema; output: Schema; error?: Schema }>\n\toutgoing: Record<string, Schema>\n\ttransport?: { prefer: string; fallback?: string[] }\n}\n\nexport interface ChannelResult {\n\t/** Expanded Level 0 procedure definitions — spread into createRouter */\n\tprocedures: DefinitionMap\n\t/** IR hint for codegen */\n\tchannelMeta: ChannelMeta\n}\n\n// -- Helpers --\n\n/** Merge channel-level and message-level JTD properties schemas */\nfunction mergeObjectSchemas(channel: JTDSchema, message: JTDSchema): JTDSchema {\n\tconst channelProps = (channel as Record<string, unknown>).properties as\n\t\t| Record<string, JTDSchema>\n\t\t| undefined\n\tconst channelOptional = (channel as Record<string, unknown>).optionalProperties as\n\t\t| Record<string, JTDSchema>\n\t\t| undefined\n\tconst msgProps = (message as Record<string, unknown>).properties as\n\t\t| Record<string, JTDSchema>\n\t\t| undefined\n\tconst msgOptional = (message as Record<string, unknown>).optionalProperties as\n\t\t| Record<string, JTDSchema>\n\t\t| undefined\n\n\tconst merged: Record<string, unknown> = {}\n\n\tconst props = { ...channelProps, ...msgProps }\n\tif (Object.keys(props).length > 0) {\n\t\tmerged.properties = props\n\t}\n\n\tconst optProps = { ...channelOptional, ...msgOptional }\n\tif (Object.keys(optProps).length > 0) {\n\t\tmerged.optionalProperties = optProps\n\t}\n\n\t// Empty object schema needs at least empty properties\n\tif (!merged.properties && !merged.optionalProperties) {\n\t\tmerged.properties = {}\n\t}\n\n\treturn merged as JTDSchema\n}\n\n/** Build a tagged union schema from outgoing event definitions */\nfunction buildOutgoingUnionSchema(\n\toutgoing: Record<string, SchemaNode<Record<string, unknown>>>,\n): JTDSchema {\n\tconst mapping: Record<string, JTDSchema> = {}\n\tfor (const [eventName, node] of Object.entries(outgoing)) {\n\t\t// Wrap each outgoing payload as a \"payload\" property\n\t\tmapping[eventName] = {\n\t\t\tproperties: { payload: node._schema },\n\t\t} as JTDSchema\n\t}\n\treturn { discriminator: 'type', mapping } as JTDSchema\n}\n\n// -- Main API --\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport function createChannel<\n\tTChannelIn,\n\tTIncoming extends Record<string, IncomingDef<any, any>>,\n\tTOutgoing extends Record<string, SchemaNode<Record<string, unknown>>>,\n>(name: string, def: ChannelDef<TChannelIn, TIncoming, TOutgoing>): ChannelResult {\n\tconst procedures: DefinitionMap = {}\n\tconst channelInputSchema = def.input._schema\n\n\t// Expand incoming messages to command procedures\n\tfor (const [msgName, msgDef] of Object.entries(def.incoming)) {\n\t\tconst mergedInputSchema = mergeObjectSchemas(channelInputSchema, msgDef.input._schema)\n\n\t\tconst command: CommandDef<any, any> = {\n\t\t\tkind: 'command',\n\t\t\tinput: { _schema: mergedInputSchema } as SchemaNode<any>,\n\t\t\toutput: msgDef.output,\n\t\t\thandler: msgDef.handler as CommandDef<any, any>['handler'],\n\t\t}\n\t\tif (msgDef.error) {\n\t\t\tcommand.error = msgDef.error\n\t\t}\n\t\tprocedures[`${name}.${msgName}`] = command\n\t}\n\n\t// Expand subscribe to a subscription with tagged union output\n\tconst unionSchema = buildOutgoingUnionSchema(def.outgoing)\n\tconst subscription: SubscriptionDef<any, any> = {\n\t\tkind: 'subscription',\n\t\tinput: def.input as SchemaNode<any>,\n\t\toutput: { _schema: unionSchema } as SchemaNode<any>,\n\t\thandler: def.subscribe as SubscriptionDef<any, any>['handler'],\n\t}\n\tprocedures[`${name}.events`] = subscription\n\n\t// Build channel metadata for manifest IR hint\n\tconst incomingMeta: ChannelMeta['incoming'] = {}\n\tfor (const [msgName, msgDef] of Object.entries(def.incoming)) {\n\t\tconst entry: { input: Schema; output: Schema; error?: Schema } = {\n\t\t\tinput: msgDef.input._schema,\n\t\t\toutput: msgDef.output._schema,\n\t\t}\n\t\tif (msgDef.error) {\n\t\t\tentry.error = msgDef.error._schema\n\t\t}\n\t\tincomingMeta[msgName] = entry\n\t}\n\n\tconst outgoingMeta: ChannelMeta['outgoing'] = {}\n\tfor (const [eventName, node] of Object.entries(def.outgoing)) {\n\t\toutgoingMeta[eventName] = node._schema\n\t}\n\n\tconst channelMeta: ChannelMeta = {\n\t\tinput: channelInputSchema,\n\t\tincoming: incomingMeta,\n\t\toutgoing: outgoingMeta,\n\t}\n\tif (def.transport) {\n\t\tchannelMeta.transport = def.transport\n\t}\n\n\treturn { procedures, channelMeta }\n}\n/* eslint-enable @typescript-eslint/no-explicit-any */\n","/* src/server/core/typescript/src/page/index.ts */\n\nexport interface LoaderResult {\n\tprocedure: string\n\tinput: unknown\n}\n\nexport type LoaderFn = (\n\tparams: Record<string, string>,\n\tsearchParams?: URLSearchParams,\n) => LoaderResult\n\nexport interface LayoutDef {\n\tid: string\n\ttemplate: string\n\tlocaleTemplates?: Record<string, string>\n\tloaders: Record<string, LoaderFn>\n\ti18nKeys?: string[]\n}\n\nexport interface PageAssets {\n\tstyles: string[]\n\tscripts: string[]\n\tpreload: string[]\n\tprefetch: string[]\n}\n\nexport type HeadFn = (data: Record<string, unknown>) => {\n\ttitle?: string\n\tmeta?: Record<string, string | undefined>[]\n\tlink?: Record<string, string | undefined>[]\n}\n\nexport interface PageDef {\n\ttemplate: string\n\tlocaleTemplates?: Record<string, string>\n\tloaders: Record<string, LoaderFn>\n\tlayoutChain?: LayoutDef[]\n\theadMeta?: string\n\theadFn?: HeadFn\n\tdataId?: string\n\ti18nKeys?: string[]\n\tpageAssets?: PageAssets\n\tprojections?: Record<string, string[]>\n\t/** SSG: page was pre-rendered at build time */\n\tprerender?: boolean\n\t/** SSG: directory containing pre-rendered HTML and __data.json */\n\tstaticDir?: string\n}\n\nexport interface I18nConfig {\n\tlocales: string[]\n\tdefault: string\n\tmode: 'memory' | 'paged'\n\tcache: boolean\n\trouteHashes: Record<string, string>\n\tcontentHashes: Record<string, Record<string, string>>\n\t/** Memory mode: locale → routeHash → messages */\n\tmessages: Record<string, Record<string, Record<string, string>>>\n\t/** Paged mode: base directory for on-demand reads */\n\tdistDir?: string\n}\n\nexport function definePage(config: PageDef): PageDef {\n\treturn { ...config, layoutChain: config.layoutChain ?? [] }\n}\n","/* src/server/core/typescript/src/mime.ts */\n\nexport const MIME_TYPES: Record<string, string> = {\n\t'.js': 'application/javascript',\n\t'.mjs': 'application/javascript',\n\t'.css': 'text/css',\n\t'.html': 'text/html',\n\t'.json': 'application/json',\n\t'.svg': 'image/svg+xml',\n\t'.png': 'image/png',\n\t'.jpg': 'image/jpeg',\n\t'.jpeg': 'image/jpeg',\n\t'.gif': 'image/gif',\n\t'.woff': 'font/woff',\n\t'.woff2': 'font/woff2',\n\t'.ttf': 'font/ttf',\n\t'.ico': 'image/x-icon',\n\t'.map': 'application/json',\n\t'.ts': 'application/javascript',\n\t'.tsx': 'application/javascript',\n}\n","/* src/server/core/typescript/src/http.ts */\n\nimport { readFile } from 'node:fs/promises'\nimport { join, extname } from 'node:path'\nimport type { Router, DefinitionMap } from './router/index.js'\nimport type { RawContextMap } from './context.js'\nimport { buildRawContext } from './context.js'\nimport type { SeamFileHandle } from './procedure.js'\nimport { SeamError } from './errors.js'\nimport { MIME_TYPES } from './mime.js'\n\nexport interface HttpRequest {\n\tmethod: string\n\turl: string\n\tbody: () => Promise<unknown>\n\theader?: (name: string) => string | null\n\tfile?: () => Promise<SeamFileHandle | null>\n}\n\nexport interface HttpBodyResponse {\n\tstatus: number\n\theaders: Record<string, string>\n\tbody: unknown\n}\n\nexport interface HttpStreamResponse {\n\tstatus: number\n\theaders: Record<string, string>\n\tstream: AsyncIterable<string>\n\tonCancel?: () => void\n}\n\nexport type HttpResponse = HttpBodyResponse | HttpStreamResponse\n\nexport type HttpHandler = (req: HttpRequest) => Promise<HttpResponse>\n\nexport interface RpcHashMap {\n\tprocedures: Record<string, string>\n\tbatch: string\n}\n\nexport interface SseOptions {\n\theartbeatInterval?: number // ms, default 21_000\n\tsseIdleTimeout?: number // ms, default 30_000, 0 disables\n}\n\nexport interface HttpHandlerOptions {\n\tstaticDir?: string\n\tfallback?: HttpHandler\n\trpcHashMap?: RpcHashMap\n\tsseOptions?: SseOptions\n}\n\nconst PROCEDURE_PREFIX = '/_seam/procedure/'\nconst PAGE_PREFIX = '/_seam/page/'\nconst DATA_PREFIX = '/_seam/data/'\nconst STATIC_PREFIX = '/_seam/static/'\nconst MANIFEST_PATH = '/_seam/manifest.json'\n\nconst JSON_HEADER = { 'Content-Type': 'application/json' }\nconst HTML_HEADER = { 'Content-Type': 'text/html; charset=utf-8' }\nconst SSE_HEADER = {\n\t'Content-Type': 'text/event-stream',\n\t'Cache-Control': 'no-cache',\n\tConnection: 'keep-alive',\n}\nconst IMMUTABLE_CACHE = 'public, max-age=31536000, immutable'\n\nfunction jsonResponse(status: number, body: unknown): HttpBodyResponse {\n\treturn { status, headers: JSON_HEADER, body }\n}\n\nfunction errorResponse(status: number, code: string, message: string): HttpBodyResponse {\n\treturn jsonResponse(status, new SeamError(code, message).toJSON())\n}\n\nasync function handleStaticAsset(assetPath: string, staticDir: string): Promise<HttpBodyResponse> {\n\tif (assetPath.includes('..')) {\n\t\treturn errorResponse(403, 'VALIDATION_ERROR', 'Forbidden')\n\t}\n\n\tconst filePath = join(staticDir, assetPath)\n\ttry {\n\t\tconst content = await readFile(filePath, 'utf-8')\n\t\tconst ext = extname(filePath)\n\t\tconst contentType = MIME_TYPES[ext] || 'application/octet-stream'\n\t\treturn {\n\t\t\tstatus: 200,\n\t\t\theaders: {\n\t\t\t\t'Content-Type': contentType,\n\t\t\t\t'Cache-Control': IMMUTABLE_CACHE,\n\t\t\t},\n\t\t\tbody: content,\n\t\t}\n\t} catch {\n\t\treturn errorResponse(404, 'NOT_FOUND', 'Asset not found')\n\t}\n}\n\n/** Format a single SSE data event */\nexport function sseDataEvent(data: unknown): string {\n\treturn `event: data\\ndata: ${JSON.stringify(data)}\\n\\n`\n}\n\n/** Format an SSE data event with a sequence id (for streams) */\nexport function sseDataEventWithId(data: unknown, id: number): string {\n\treturn `event: data\\nid: ${id}\\ndata: ${JSON.stringify(data)}\\n\\n`\n}\n\n/** Format an SSE error event */\nexport function sseErrorEvent(code: string, message: string, transient = false): string {\n\treturn `event: error\\ndata: ${JSON.stringify({ code, message, transient })}\\n\\n`\n}\n\n/** Format an SSE complete event */\nexport function sseCompleteEvent(): string {\n\treturn 'event: complete\\ndata: {}\\n\\n'\n}\n\nfunction formatSseError(error: unknown): string {\n\tif (error instanceof SeamError) {\n\t\treturn sseErrorEvent(error.code, error.message)\n\t}\n\tconst message = error instanceof Error ? error.message : 'Unknown error'\n\treturn sseErrorEvent('INTERNAL_ERROR', message)\n}\n\nconst DEFAULT_HEARTBEAT_MS = 21_000\nconst DEFAULT_SSE_IDLE_MS = 30_000\n\nasync function* withSseLifecycle(\n\tinner: AsyncIterable<string>,\n\topts?: SseOptions,\n): AsyncGenerator<string> {\n\tconst heartbeatMs = opts?.heartbeatInterval ?? DEFAULT_HEARTBEAT_MS\n\tconst idleMs = opts?.sseIdleTimeout ?? DEFAULT_SSE_IDLE_MS\n\tconst idleEnabled = idleMs > 0\n\n\t// Queue-based approach: background drains inner generator\n\tconst queue: Array<\n\t\t{ type: 'data'; value: string } | { type: 'done' } | { type: 'heartbeat' } | { type: 'idle' }\n\t> = []\n\tlet resolve: (() => void) | null = null\n\tconst signal = () => {\n\t\tif (resolve) {\n\t\t\tresolve()\n\t\t\tresolve = null\n\t\t}\n\t}\n\n\tlet idleTimer: ReturnType<typeof setTimeout> | null = null\n\tconst resetIdle = () => {\n\t\tif (!idleEnabled) return\n\t\tif (idleTimer) clearTimeout(idleTimer)\n\t\tidleTimer = setTimeout(() => {\n\t\t\tqueue.push({ type: 'idle' })\n\t\t\tsignal()\n\t\t}, idleMs)\n\t}\n\n\tconst heartbeatTimer = setInterval(() => {\n\t\tqueue.push({ type: 'heartbeat' })\n\t\tsignal()\n\t}, heartbeatMs)\n\n\t// Start idle timer\n\tresetIdle()\n\n\t// Background: drain inner generator\n\tvoid (async () => {\n\t\ttry {\n\t\t\tfor await (const chunk of inner) {\n\t\t\t\tqueue.push({ type: 'data', value: chunk })\n\t\t\t\tresetIdle()\n\t\t\t\tsignal()\n\t\t\t}\n\t\t} catch {\n\t\t\t// Inner generator error\n\t\t}\n\t\tqueue.push({ type: 'done' })\n\t\tsignal()\n\t})()\n\n\ttry {\n\t\tfor (;;) {\n\t\t\twhile (queue.length === 0) {\n\t\t\t\tawait new Promise<void>((r) => {\n\t\t\t\t\tresolve = r\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst item = queue.shift()\n\t\t\tif (!item) continue\n\t\t\tif (item.type === 'data') {\n\t\t\t\tyield item.value\n\t\t\t} else if (item.type === 'heartbeat') {\n\t\t\t\tyield ': heartbeat\\n\\n'\n\t\t\t} else if (item.type === 'idle') {\n\t\t\t\tyield sseCompleteEvent()\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\t// done\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tclearInterval(heartbeatTimer)\n\t\tif (idleTimer) clearTimeout(idleTimer)\n\t}\n}\n\nasync function* sseStream<T extends DefinitionMap>(\n\trouter: Router<T>,\n\tname: string,\n\tinput: unknown,\n\trawCtx?: RawContextMap,\n\tlastEventId?: string,\n): AsyncIterable<string> {\n\ttry {\n\t\tlet seq = 0\n\t\tfor await (const value of router.handleSubscription(name, input, rawCtx, lastEventId)) {\n\t\t\tyield sseDataEventWithId(value, seq++)\n\t\t}\n\t\tyield sseCompleteEvent()\n\t} catch (error) {\n\t\tyield formatSseError(error)\n\t}\n}\n\nasync function* sseStreamForStream<T extends DefinitionMap>(\n\trouter: Router<T>,\n\tname: string,\n\tinput: unknown,\n\tsignal?: AbortSignal,\n\trawCtx?: RawContextMap,\n): AsyncGenerator<string> {\n\tconst gen = router.handleStream(name, input, rawCtx)\n\t// Wire abort signal to terminate the generator\n\tif (signal) {\n\t\tsignal.addEventListener(\n\t\t\t'abort',\n\t\t\t() => {\n\t\t\t\tvoid gen.return(undefined)\n\t\t\t},\n\t\t\t{ once: true },\n\t\t)\n\t}\n\ttry {\n\t\tlet seq = 0\n\t\tfor await (const value of gen) {\n\t\t\tyield sseDataEventWithId(value, seq++)\n\t\t}\n\t\tyield sseCompleteEvent()\n\t} catch (error) {\n\t\tyield formatSseError(error)\n\t}\n}\n\nasync function handleBatchHttp<T extends DefinitionMap>(\n\treq: HttpRequest,\n\trouter: Router<T>,\n\thashToName: Map<string, string> | null,\n\trawCtx?: RawContextMap,\n): Promise<HttpBodyResponse> {\n\tlet body: unknown\n\ttry {\n\t\tbody = await req.body()\n\t} catch {\n\t\treturn errorResponse(400, 'VALIDATION_ERROR', 'Invalid JSON body')\n\t}\n\tif (!body || typeof body !== 'object' || !Array.isArray((body as { calls?: unknown }).calls)) {\n\t\treturn errorResponse(400, 'VALIDATION_ERROR', \"Batch request must have a 'calls' array\")\n\t}\n\tconst calls = (body as { calls: Array<{ procedure?: unknown; input?: unknown }> }).calls.map(\n\t\t(c) => ({\n\t\t\tprocedure:\n\t\t\t\ttypeof c.procedure === 'string' ? (hashToName?.get(c.procedure) ?? c.procedure) : '',\n\t\t\tinput: c.input ?? {},\n\t\t}),\n\t)\n\tconst result = await router.handleBatch(calls, rawCtx)\n\treturn jsonResponse(200, { ok: true, data: result })\n}\n\n/** Resolve hash -> original name when obfuscation is active. Accepts both hashed and raw names. */\nfunction resolveHashName(hashToName: Map<string, string> | null, name: string): string {\n\tif (!hashToName) return name\n\treturn hashToName.get(name) ?? name\n}\n\nasync function handleProcedurePost<T extends DefinitionMap>(\n\treq: HttpRequest,\n\trouter: Router<T>,\n\tname: string,\n\trawCtx?: RawContextMap,\n\tsseOptions?: SseOptions,\n): Promise<HttpResponse> {\n\tlet body: unknown\n\ttry {\n\t\tbody = await req.body()\n\t} catch {\n\t\treturn errorResponse(400, 'VALIDATION_ERROR', 'Invalid JSON body')\n\t}\n\n\tif (router.getKind(name) === 'stream') {\n\t\tconst controller = new AbortController()\n\t\treturn {\n\t\t\tstatus: 200,\n\t\t\theaders: SSE_HEADER,\n\t\t\tstream: withSseLifecycle(\n\t\t\t\tsseStreamForStream(router, name, body, controller.signal, rawCtx),\n\t\t\t\tsseOptions,\n\t\t\t),\n\t\t\tonCancel: () => controller.abort(),\n\t\t}\n\t}\n\n\tif (router.getKind(name) === 'upload') {\n\t\tif (!req.file) {\n\t\t\treturn errorResponse(400, 'VALIDATION_ERROR', 'Upload requires multipart/form-data')\n\t\t}\n\t\tconst file = await req.file()\n\t\tif (!file) {\n\t\t\treturn errorResponse(400, 'VALIDATION_ERROR', 'Upload requires file in multipart body')\n\t\t}\n\t\tconst result = await router.handleUpload(name, body, file, rawCtx)\n\t\treturn jsonResponse(result.status, result.body)\n\t}\n\n\tconst result = await router.handle(name, body, rawCtx)\n\treturn jsonResponse(result.status, result.body)\n}\n\nexport function createHttpHandler<T extends DefinitionMap>(\n\trouter: Router<T>,\n\topts?: HttpHandlerOptions,\n): HttpHandler {\n\t// Explicit option overrides; fall back to router's stored value\n\tconst effectiveHashMap = opts?.rpcHashMap ?? router.rpcHashMap\n\t// Build reverse lookup (hash -> original name) when obfuscation is active\n\tconst hashToName: Map<string, string> | null = effectiveHashMap\n\t\t? new Map(Object.entries(effectiveHashMap.procedures).map(([n, h]) => [h, n]))\n\t\t: null\n\t// Built-in procedures bypass hash obfuscation (identity mapping)\n\tif (hashToName) {\n\t\thashToName.set('seam.i18n.query', 'seam.i18n.query')\n\t}\n\tconst batchHash = effectiveHashMap?.batch ?? null\n\tconst hasCtx = router.hasContext()\n\n\treturn async (req) => {\n\t\tconst url = new URL(req.url, 'http://localhost')\n\t\tconst { pathname } = url\n\n\t\t// Build raw context map from request headers/cookies/query when context fields are defined\n\t\tconst rawCtx: RawContextMap | undefined = hasCtx\n\t\t\t? buildRawContext(router.ctxConfig, req.header, url)\n\t\t\t: undefined\n\n\t\tif (req.method === 'GET' && pathname === MANIFEST_PATH) {\n\t\t\tif (effectiveHashMap) return errorResponse(403, 'FORBIDDEN', 'Manifest disabled')\n\t\t\treturn jsonResponse(200, router.manifest())\n\t\t}\n\n\t\tif (pathname.startsWith(PROCEDURE_PREFIX)) {\n\t\t\tconst rawName = pathname.slice(PROCEDURE_PREFIX.length)\n\t\t\tif (!rawName) {\n\t\t\t\treturn errorResponse(404, 'NOT_FOUND', 'Empty procedure name')\n\t\t\t}\n\n\t\t\tif (req.method === 'POST') {\n\t\t\t\tif (rawName === '_batch' || (batchHash && rawName === batchHash)) {\n\t\t\t\t\treturn handleBatchHttp(req, router, hashToName, rawCtx)\n\t\t\t\t}\n\t\t\t\tconst name = resolveHashName(hashToName, rawName)\n\t\t\t\treturn handleProcedurePost(req, router, name, rawCtx, opts?.sseOptions)\n\t\t\t}\n\n\t\t\tif (req.method === 'GET') {\n\t\t\t\tconst name = resolveHashName(hashToName, rawName)\n\n\t\t\t\tconst rawInput = url.searchParams.get('input')\n\t\t\t\tlet input: unknown\n\t\t\t\ttry {\n\t\t\t\t\tinput = rawInput ? JSON.parse(rawInput) : {}\n\t\t\t\t} catch {\n\t\t\t\t\treturn errorResponse(400, 'VALIDATION_ERROR', 'Invalid input query parameter')\n\t\t\t\t}\n\n\t\t\t\tconst lastEventId = req.header?.('last-event-id') ?? undefined\n\t\t\t\treturn {\n\t\t\t\t\tstatus: 200,\n\t\t\t\t\theaders: SSE_HEADER,\n\t\t\t\t\tstream: withSseLifecycle(\n\t\t\t\t\t\tsseStream(router, name, input, rawCtx, lastEventId),\n\t\t\t\t\t\topts?.sseOptions,\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Pages are served under /_seam/page/* prefix only.\n\t\t// Root-path serving is the application's responsibility — see the\n\t\t// github-dashboard ts-hono example for the fallback pattern.\n\t\tif (req.method === 'GET' && pathname.startsWith(PAGE_PREFIX) && router.hasPages) {\n\t\t\tconst pagePath = '/' + pathname.slice(PAGE_PREFIX.length)\n\t\t\tconst headers = req.header\n\t\t\t\t? {\n\t\t\t\t\t\turl: req.url,\n\t\t\t\t\t\tcookie: req.header('cookie') ?? undefined,\n\t\t\t\t\t\tacceptLanguage: req.header('accept-language') ?? undefined,\n\t\t\t\t\t}\n\t\t\t\t: undefined\n\t\t\tconst result = await router.handlePage(pagePath, headers, rawCtx)\n\t\t\tif (result) {\n\t\t\t\treturn { status: result.status, headers: HTML_HEADER, body: result.html }\n\t\t\t}\n\t\t}\n\n\t\t// Page data endpoint: serves __data.json for prerendered pages (SPA navigation)\n\t\tif (req.method === 'GET' && pathname.startsWith(DATA_PREFIX) && router.hasPages) {\n\t\t\tconst pagePath = '/' + pathname.slice(DATA_PREFIX.length).replace(/\\/$/, '')\n\t\t\tconst dataResult = await router.handlePageData(pagePath)\n\t\t\tif (dataResult !== null) {\n\t\t\t\treturn jsonResponse(200, dataResult)\n\t\t\t}\n\t\t}\n\n\t\tif (req.method === 'GET' && pathname.startsWith(STATIC_PREFIX) && opts?.staticDir) {\n\t\t\tconst assetPath = pathname.slice(STATIC_PREFIX.length)\n\t\t\treturn handleStaticAsset(assetPath, opts.staticDir)\n\t\t}\n\n\t\tif (opts?.fallback) return opts.fallback(req)\n\t\treturn errorResponse(404, 'NOT_FOUND', 'Not found')\n\t}\n}\n\nexport function serialize(body: unknown): string {\n\treturn typeof body === 'string' ? body : JSON.stringify(body)\n}\n\n/** Consume an async stream chunk-by-chunk; return false from write to stop early. */\nexport async function drainStream(\n\tstream: AsyncIterable<string>,\n\twrite: (chunk: string) => boolean | void,\n): Promise<void> {\n\ttry {\n\t\tfor await (const chunk of stream) {\n\t\t\tif (write(chunk) === false) break\n\t\t}\n\t} catch {\n\t\t// Client disconnected\n\t}\n}\n\n/** Convert an HttpResponse to a Web API Response (for adapters using fetch-compatible runtimes) */\nexport function toWebResponse(result: HttpResponse): Response {\n\tif ('stream' in result) {\n\t\tconst stream = result.stream\n\t\tconst onCancel = result.onCancel\n\t\tconst encoder = new TextEncoder()\n\t\tconst readable = new ReadableStream({\n\t\t\tasync start(controller) {\n\t\t\t\tawait drainStream(stream, (chunk) => {\n\t\t\t\t\tcontroller.enqueue(encoder.encode(chunk))\n\t\t\t\t})\n\t\t\t\tcontroller.close()\n\t\t\t},\n\t\t\tcancel() {\n\t\t\t\tonCancel?.()\n\t\t\t},\n\t\t})\n\t\treturn new Response(readable, { status: result.status, headers: result.headers })\n\t}\n\treturn new Response(serialize(result.body), { status: result.status, headers: result.headers })\n}\n","/* src/server/core/typescript/src/page/build-loader.ts */\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { PageDef, PageAssets, LayoutDef, LoaderFn, LoaderResult, I18nConfig } from './index.js'\nimport type { RpcHashMap } from '../http.js'\n\ninterface RouteManifest {\n\tlayouts?: Record<string, LayoutManifestEntry>\n\troutes: Record<string, RouteManifestEntry>\n\tdata_id?: string\n\ti18n?: {\n\t\tlocales: string[]\n\t\tdefault: string\n\t\tmode?: string\n\t\tcache?: boolean\n\t\troute_hashes?: Record<string, string>\n\t\tcontent_hashes?: Record<string, Record<string, string>>\n\t}\n}\n\ninterface LayoutManifestEntry {\n\ttemplate?: string\n\ttemplates?: Record<string, string>\n\tloaders?: Record<string, LoaderConfig>\n\tparent?: string\n\ti18n_keys?: string[]\n}\n\ninterface RouteManifestEntry {\n\ttemplate?: string\n\ttemplates?: Record<string, string>\n\tlayout?: string\n\tloaders: Record<string, LoaderConfig>\n\thead_meta?: string\n\ti18n_keys?: string[]\n\tassets?: PageAssets\n\tprojections?: Record<string, string[]>\n\tprerender?: boolean\n}\n\ninterface LoaderConfig {\n\tprocedure: string\n\tparams?: Record<string, string | ParamConfig>\n\thandoff?: 'client'\n}\n\ninterface ParamConfig {\n\tfrom: 'route' | 'query'\n\ttype?: 'string' | 'int'\n}\n\nfunction normalizeParamConfig(value: string | ParamConfig): ParamConfig {\n\treturn typeof value === 'string' ? { from: value as ParamConfig['from'] } : value\n}\n\nfunction buildLoaderFn(config: LoaderConfig): LoaderFn {\n\treturn (params, searchParams): LoaderResult => {\n\t\tconst input: Record<string, unknown> = {}\n\t\tif (config.params) {\n\t\t\tfor (const [key, raw_mapping] of Object.entries(config.params)) {\n\t\t\t\tconst mapping = normalizeParamConfig(raw_mapping)\n\t\t\t\tconst raw = mapping.from === 'query' ? (searchParams?.get(key) ?? undefined) : params[key]\n\t\t\t\tif (raw !== undefined) {\n\t\t\t\t\tinput[key] = mapping.type === 'int' ? Number(raw) : raw\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn { procedure: config.procedure, input }\n\t}\n}\n\nfunction buildLoaderFns(configs: Record<string, LoaderConfig>): Record<string, LoaderFn> {\n\tconst fns: Record<string, LoaderFn> = {}\n\tfor (const [key, config] of Object.entries(configs)) {\n\t\tfns[key] = buildLoaderFn(config)\n\t}\n\treturn fns\n}\n\nfunction resolveTemplatePath(\n\tentry: { template?: string; templates?: Record<string, string> },\n\tdefaultLocale: string | undefined,\n): string {\n\tif (entry.template) return entry.template\n\tif (entry.templates) {\n\t\tconst locale = defaultLocale ?? (Object.keys(entry.templates)[0] as string)\n\t\tconst path = entry.templates[locale]\n\t\tif (!path) throw new Error(`No template for locale \"${locale}\"`)\n\t\treturn path\n\t}\n\tthrow new Error(\"Manifest entry has neither 'template' nor 'templates'\")\n}\n\n/** Load all locale templates for a manifest entry, keyed by locale */\nfunction loadLocaleTemplates(\n\tentry: { templates?: Record<string, string> },\n\tdistDir: string,\n): Record<string, string> | undefined {\n\tif (!entry.templates) return undefined\n\tconst result: Record<string, string> = {}\n\tfor (const [locale, relPath] of Object.entries(entry.templates)) {\n\t\tresult[locale] = readFileSync(join(distDir, relPath), 'utf-8')\n\t}\n\treturn result\n}\n\n/** Callback that returns template + localeTemplates for a layout entry */\ntype TemplateGetter = (\n\tid: string,\n\tentry: LayoutManifestEntry,\n) => { template: string; localeTemplates?: Record<string, string> }\n\n/** Resolve parent chain for a layout, returning outer-to-inner order */\nfunction resolveLayoutChain(\n\tlayoutId: string,\n\tlayoutEntries: Record<string, LayoutManifestEntry>,\n\tgetTemplates: TemplateGetter,\n): LayoutDef[] {\n\tconst chain: LayoutDef[] = []\n\tlet currentId: string | undefined = layoutId\n\n\twhile (currentId) {\n\t\tconst entry: LayoutManifestEntry | undefined = layoutEntries[currentId]\n\t\tif (!entry) break\n\t\tconst { template, localeTemplates } = getTemplates(currentId, entry)\n\t\tchain.push({\n\t\t\tid: currentId,\n\t\t\ttemplate,\n\t\t\tlocaleTemplates,\n\t\t\tloaders: buildLoaderFns(entry.loaders ?? {}),\n\t\t})\n\t\tcurrentId = entry.parent\n\t}\n\n\t// Reverse: we walked inner->outer, but want outer->inner\n\tchain.reverse()\n\treturn chain\n}\n\n/** Create a proxy object that lazily reads locale templates from disk */\nfunction makeLocaleTemplateGetters(\n\ttemplates: Record<string, string>,\n\tdistDir: string,\n): Record<string, string> {\n\tconst obj: Record<string, string> = {}\n\tfor (const [locale, relPath] of Object.entries(templates)) {\n\t\tconst fullPath = join(distDir, relPath)\n\t\tObject.defineProperty(obj, locale, {\n\t\t\tget: () => readFileSync(fullPath, 'utf-8'),\n\t\t\tenumerable: true,\n\t\t})\n\t}\n\treturn obj\n}\n\n/** Merge i18n_keys from route + layout chain into a single list */\nfunction mergeI18nKeys(\n\troute: RouteManifestEntry,\n\tlayoutEntries: Record<string, LayoutManifestEntry>,\n): string[] | undefined {\n\tconst keys: string[] = []\n\tif (route.layout) {\n\t\tlet currentId: string | undefined = route.layout\n\t\twhile (currentId) {\n\t\t\tconst entry: LayoutManifestEntry | undefined = layoutEntries[currentId]\n\t\t\tif (!entry) break\n\t\t\tif (entry.i18n_keys) keys.push(...entry.i18n_keys)\n\t\t\tcurrentId = entry.parent\n\t\t}\n\t}\n\tif (route.i18n_keys) keys.push(...route.i18n_keys)\n\treturn keys.length > 0 ? keys : undefined\n}\n\nexport interface BuildOutput {\n\tpages: Record<string, PageDef>\n\trpcHashMap: RpcHashMap | undefined\n\ti18n: I18nConfig | null\n}\n\n/** Load all build artifacts (pages, rpcHashMap, i18n) in one call */\nexport function loadBuild(distDir: string): BuildOutput {\n\treturn {\n\t\tpages: loadBuildOutput(distDir),\n\t\trpcHashMap: loadRpcHashMap(distDir),\n\t\ti18n: loadI18nMessages(distDir),\n\t}\n}\n\n/** Load all build artifacts with lazy template getters (for dev mode) */\nexport function loadBuildDev(distDir: string): BuildOutput {\n\treturn {\n\t\tpages: loadBuildOutputDev(distDir),\n\t\trpcHashMap: loadRpcHashMap(distDir),\n\t\ti18n: loadI18nMessages(distDir),\n\t}\n}\n\n/** Load the RPC hash map from build output (returns undefined when obfuscation is off) */\nexport function loadRpcHashMap(distDir: string): RpcHashMap | undefined {\n\tconst hashMapPath = join(distDir, 'rpc-hash-map.json')\n\ttry {\n\t\treturn JSON.parse(readFileSync(hashMapPath, 'utf-8')) as RpcHashMap\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\n/** Load i18n config and messages from build output */\nexport function loadI18nMessages(distDir: string): I18nConfig | null {\n\tconst manifestPath = join(distDir, 'route-manifest.json')\n\ttry {\n\t\tconst manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as RouteManifest\n\t\tif (!manifest.i18n) return null\n\n\t\tconst mode = (manifest.i18n.mode ?? 'memory') as 'memory' | 'paged'\n\t\tconst cache = manifest.i18n.cache ?? false\n\t\tconst routeHashes = manifest.i18n.route_hashes ?? {}\n\t\tconst contentHashes = manifest.i18n.content_hashes ?? {}\n\n\t\t// Memory mode: preload all route messages per locale\n\t\t// Paged mode: store distDir for on-demand reads\n\t\tconst messages: Record<string, Record<string, Record<string, string>>> = {}\n\t\tif (mode === 'memory') {\n\t\t\tconst i18nDir = join(distDir, 'i18n')\n\t\t\tfor (const locale of manifest.i18n.locales) {\n\t\t\t\tconst localePath = join(i18nDir, `${locale}.json`)\n\t\t\t\tif (existsSync(localePath)) {\n\t\t\t\t\tmessages[locale] = JSON.parse(readFileSync(localePath, 'utf-8')) as Record<\n\t\t\t\t\t\tstring,\n\t\t\t\t\t\tRecord<string, string>\n\t\t\t\t\t>\n\t\t\t\t} else {\n\t\t\t\t\tmessages[locale] = {}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tlocales: manifest.i18n.locales,\n\t\t\tdefault: manifest.i18n.default,\n\t\t\tmode,\n\t\t\tcache,\n\t\t\trouteHashes,\n\t\t\tcontentHashes,\n\t\t\tmessages,\n\t\t\tdistDir: mode === 'paged' ? distDir : undefined,\n\t\t}\n\t} catch {\n\t\treturn null\n\t}\n}\n\nexport function loadBuildOutput(distDir: string): Record<string, PageDef> {\n\tconst manifestPath = join(distDir, 'route-manifest.json')\n\tconst raw = readFileSync(manifestPath, 'utf-8')\n\tconst manifest = JSON.parse(raw) as RouteManifest\n\tconst defaultLocale = manifest.i18n?.default\n\n\t// Load layout templates (default + all locales)\n\tconst layoutTemplates: Record<string, string> = {}\n\tconst layoutLocaleTemplates: Record<string, Record<string, string>> = {}\n\tconst layoutEntries = manifest.layouts ?? {}\n\tfor (const [id, entry] of Object.entries(layoutEntries)) {\n\t\tlayoutTemplates[id] = readFileSync(\n\t\t\tjoin(distDir, resolveTemplatePath(entry, defaultLocale)),\n\t\t\t'utf-8',\n\t\t)\n\t\tconst lt = loadLocaleTemplates(entry, distDir)\n\t\tif (lt) layoutLocaleTemplates[id] = lt\n\t}\n\n\t// Static dir for prerendered pages (adjacent to output dir)\n\tconst staticDir = join(distDir, '..', 'static')\n\tconst hasStaticDir = existsSync(staticDir)\n\n\tconst pages: Record<string, PageDef> = {}\n\tfor (const [path, entry] of Object.entries(manifest.routes)) {\n\t\tconst templatePath = join(distDir, resolveTemplatePath(entry, defaultLocale))\n\t\tconst template = readFileSync(templatePath, 'utf-8')\n\n\t\tconst loaders = buildLoaderFns(entry.loaders)\n\t\tconst layoutChain = entry.layout\n\t\t\t? resolveLayoutChain(entry.layout, layoutEntries, (id) => ({\n\t\t\t\t\ttemplate: layoutTemplates[id] ?? '',\n\t\t\t\t\tlocaleTemplates: layoutLocaleTemplates[id],\n\t\t\t\t}))\n\t\t\t: []\n\n\t\t// Merge i18n_keys from layout chain + route\n\t\tconst i18nKeys = mergeI18nKeys(entry, layoutEntries)\n\n\t\tconst page: PageDef = {\n\t\t\ttemplate,\n\t\t\tlocaleTemplates: loadLocaleTemplates(entry, distDir),\n\t\t\tloaders,\n\t\t\tlayoutChain,\n\t\t\theadMeta: entry.head_meta,\n\t\t\tdataId: manifest.data_id,\n\t\t\ti18nKeys,\n\t\t\tpageAssets: entry.assets,\n\t\t\tprojections: entry.projections,\n\t\t}\n\n\t\tif (entry.prerender && hasStaticDir) {\n\t\t\tpage.prerender = true\n\t\t\tpage.staticDir = staticDir\n\t\t}\n\n\t\tpages[path] = page\n\t}\n\treturn pages\n}\n\n/** Load build output with lazy template getters -- templates re-read from disk on each access */\nexport function loadBuildOutputDev(distDir: string): Record<string, PageDef> {\n\tconst manifestPath = join(distDir, 'route-manifest.json')\n\tconst raw = readFileSync(manifestPath, 'utf-8')\n\tconst manifest = JSON.parse(raw) as RouteManifest\n\tconst defaultLocale = manifest.i18n?.default\n\n\tconst layoutEntries = manifest.layouts ?? {}\n\n\tconst pages: Record<string, PageDef> = {}\n\tfor (const [path, entry] of Object.entries(manifest.routes)) {\n\t\tconst templatePath = join(distDir, resolveTemplatePath(entry, defaultLocale))\n\t\tconst loaders = buildLoaderFns(entry.loaders)\n\t\tconst layoutChain = entry.layout\n\t\t\t? resolveLayoutChain(entry.layout, layoutEntries, (id, layoutEntry) => {\n\t\t\t\t\tconst tmplPath = join(distDir, resolveTemplatePath(layoutEntry, defaultLocale))\n\t\t\t\t\tconst def = {\n\t\t\t\t\t\ttemplate: '',\n\t\t\t\t\t\tlocaleTemplates: layoutEntry.templates\n\t\t\t\t\t\t\t? makeLocaleTemplateGetters(layoutEntry.templates, distDir)\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t}\n\t\t\t\t\tObject.defineProperty(def, 'template', {\n\t\t\t\t\t\tget: () => readFileSync(tmplPath, 'utf-8'),\n\t\t\t\t\t\tenumerable: true,\n\t\t\t\t\t})\n\t\t\t\t\treturn def\n\t\t\t\t})\n\t\t\t: []\n\n\t\tconst localeTemplates = entry.templates\n\t\t\t? makeLocaleTemplateGetters(entry.templates, distDir)\n\t\t\t: undefined\n\n\t\t// Merge i18n_keys from layout chain + route\n\t\tconst i18nKeys = mergeI18nKeys(entry, layoutEntries)\n\n\t\tconst page: PageDef = {\n\t\t\ttemplate: '', // placeholder, overridden by getter\n\t\t\tlocaleTemplates,\n\t\t\tloaders,\n\t\t\tlayoutChain,\n\t\t\tdataId: manifest.data_id,\n\t\t\ti18nKeys,\n\t\t\tpageAssets: entry.assets,\n\t\t\tprojections: entry.projections,\n\t\t}\n\t\tObject.defineProperty(page, 'template', {\n\t\t\tget: () => readFileSync(templatePath, 'utf-8'),\n\t\t\tenumerable: true,\n\t\t})\n\t\tpages[path] = page\n\t}\n\treturn pages\n}\n","/* src/server/core/typescript/src/subscription.ts */\n\n/**\n * Bridge callback-style event sources to an AsyncGenerator.\n *\n * Usage:\n * const stream = fromCallback<string>(({ emit, end, error }) => {\n * emitter.on(\"data\", emit);\n * emitter.on(\"end\", end);\n * emitter.on(\"error\", error);\n * return () => emitter.removeAllListeners();\n * });\n */\nexport interface CallbackSink<T> {\n\temit: (value: T) => void\n\tend: () => void\n\terror: (err: Error) => void\n}\n\ntype QueueItem<T> = { type: 'value'; value: T } | { type: 'end' } | { type: 'error'; error: Error }\n\nexport function fromCallback<T>(\n\tsetup: (sink: CallbackSink<T>) => (() => void) | void,\n): AsyncGenerator<T, void, undefined> {\n\tconst queue: QueueItem<T>[] = []\n\tlet resolve: (() => void) | null = null\n\tlet done = false\n\tfunction notify() {\n\t\tif (resolve) {\n\t\t\tconst r = resolve\n\t\t\tresolve = null\n\t\t\tr()\n\t\t}\n\t}\n\n\tconst sink: CallbackSink<T> = {\n\t\temit(value) {\n\t\t\tif (done) return\n\t\t\tqueue.push({ type: 'value', value })\n\t\t\tnotify()\n\t\t},\n\t\tend() {\n\t\t\tif (done) return\n\t\t\tdone = true\n\t\t\tqueue.push({ type: 'end' })\n\t\t\tnotify()\n\t\t},\n\t\terror(err) {\n\t\t\tif (done) return\n\t\t\tdone = true\n\t\t\tqueue.push({ type: 'error', error: err })\n\t\t\tnotify()\n\t\t},\n\t}\n\n\tconst cleanup = setup(sink)\n\n\tasync function* generate(): AsyncGenerator<T, void, undefined> {\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tif (queue.length === 0) {\n\t\t\t\t\tawait new Promise<void>((r) => {\n\t\t\t\t\t\tresolve = r\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t\twhile (queue.length > 0) {\n\t\t\t\t\tconst item = queue.shift() as QueueItem<T>\n\t\t\t\t\tif (item.type === 'value') {\n\t\t\t\t\t\tyield item.value\n\t\t\t\t\t} else if (item.type === 'error') {\n\t\t\t\t\t\tthrow item.error\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tdone = true\n\t\t\tif (cleanup) cleanup()\n\t\t}\n\t}\n\n\treturn generate()\n}\n","/* src/server/core/typescript/src/ws.ts */\n\nimport type { Router, DefinitionMap } from './router/index.js'\nimport { SeamError } from './errors.js'\n\nexport interface WsSink {\n\tsend(data: string): void\n\tping?: () => void\n\tclose?: () => void\n}\n\nexport interface ChannelWsSession {\n\tonMessage(data: string): void\n\tonPong(): void\n\tclose(): void\n}\n\nexport interface ChannelWsOptions {\n\theartbeatInterval?: number\n\tpongTimeout?: number\n}\n\ninterface UplinkMessage {\n\tid: string\n\tprocedure: string\n\tinput?: unknown\n}\n\nconst DEFAULT_HEARTBEAT_MS = 21_000\nconst DEFAULT_PONG_TIMEOUT_MS = 5_000\n\nfunction sendError(ws: WsSink, id: string | null, code: string, message: string): void {\n\tws.send(JSON.stringify({ id, ok: false, error: { code, message, transient: false } }))\n}\n\n/** Validate uplink message fields and channel scope */\nfunction parseUplink(ws: WsSink, data: string, channelName: string): UplinkMessage | null {\n\tlet msg: UplinkMessage\n\ttry {\n\t\tmsg = JSON.parse(data) as UplinkMessage\n\t} catch {\n\t\tsendError(ws, null, 'VALIDATION_ERROR', 'Invalid JSON')\n\t\treturn null\n\t}\n\tif (!msg.id || typeof msg.id !== 'string') {\n\t\tsendError(ws, null, 'VALIDATION_ERROR', \"Missing 'id' field\")\n\t\treturn null\n\t}\n\tif (!msg.procedure || typeof msg.procedure !== 'string') {\n\t\tsendError(ws, msg.id, 'VALIDATION_ERROR', \"Missing 'procedure' field\")\n\t\treturn null\n\t}\n\tconst prefix = channelName + '.'\n\tif (!msg.procedure.startsWith(prefix) || msg.procedure === `${channelName}.events`) {\n\t\tsendError(\n\t\t\tws,\n\t\t\tmsg.id,\n\t\t\t'VALIDATION_ERROR',\n\t\t\t`Procedure '${msg.procedure}' is not a command of channel '${channelName}'`,\n\t\t)\n\t\treturn null\n\t}\n\treturn msg\n}\n\n/** Dispatch validated uplink command through the router */\nfunction dispatchUplink<T extends DefinitionMap>(\n\trouter: Router<T>,\n\tws: WsSink,\n\tmsg: UplinkMessage,\n\tchannelInput: unknown,\n): void {\n\tconst mergedInput = {\n\t\t...(channelInput as Record<string, unknown>),\n\t\t...((msg.input ?? {}) as Record<string, unknown>),\n\t}\n\tvoid (async () => {\n\t\ttry {\n\t\t\tconst result = await router.handle(msg.procedure, mergedInput)\n\t\t\tif (result.status === 200) {\n\t\t\t\tconst envelope = result.body as { ok: true; data: unknown }\n\t\t\t\tws.send(JSON.stringify({ id: msg.id, ok: true, data: envelope.data }))\n\t\t\t} else {\n\t\t\t\tconst envelope = result.body as {\n\t\t\t\t\tok: false\n\t\t\t\t\terror: { code: string; message: string; transient: boolean }\n\t\t\t\t}\n\t\t\t\tws.send(JSON.stringify({ id: msg.id, ok: false, error: envelope.error }))\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tconst message = err instanceof Error ? err.message : 'Unknown error'\n\t\t\tsendError(ws, msg.id, 'INTERNAL_ERROR', message)\n\t\t}\n\t})()\n}\n\n/**\n * Start a WebSocket session for a channel.\n *\n * Reuses `router.handleSubscription` for the event stream and\n * `router.handle` for uplink command dispatch — no Router changes needed.\n */\nexport function startChannelWs<T extends DefinitionMap>(\n\trouter: Router<T>,\n\tchannelName: string,\n\tchannelInput: unknown,\n\tws: WsSink,\n\topts?: ChannelWsOptions,\n): ChannelWsSession {\n\tconst heartbeatMs = opts?.heartbeatInterval ?? DEFAULT_HEARTBEAT_MS\n\tconst pongTimeoutMs = opts?.pongTimeout ?? DEFAULT_PONG_TIMEOUT_MS\n\tlet closed = false\n\tlet pongTimer: ReturnType<typeof setTimeout> | null = null\n\n\t// Heartbeat timer — also sends ping frame when sink supports it\n\tconst heartbeatTimer = setInterval(() => {\n\t\tif (closed) return\n\t\tws.send(JSON.stringify({ heartbeat: true }))\n\t\tif (ws.ping) {\n\t\t\tws.ping()\n\t\t\tif (pongTimer) clearTimeout(pongTimer)\n\t\t\tpongTimer = setTimeout(() => {\n\t\t\t\tif (!closed) {\n\t\t\t\t\tclosed = true\n\t\t\t\t\tclearInterval(heartbeatTimer)\n\t\t\t\t\tvoid iter.return?.(undefined)\n\t\t\t\t\tws.close?.()\n\t\t\t\t}\n\t\t\t}, pongTimeoutMs)\n\t\t}\n\t}, heartbeatMs)\n\n\t// Start subscription and forward events as { event, payload }\n\tconst subIterable = router.handleSubscription(`${channelName}.events`, channelInput)\n\tconst iter = subIterable[Symbol.asyncIterator]()\n\n\tvoid (async () => {\n\t\ttry {\n\t\t\tfor (;;) {\n\t\t\t\tconst result: IteratorResult<unknown> = await iter.next()\n\t\t\t\tif (result.done || closed) break\n\t\t\t\tconst ev = result.value as { type: string; payload: unknown }\n\t\t\t\tws.send(JSON.stringify({ event: ev.type, payload: ev.payload }))\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tif (!closed) {\n\t\t\t\tconst code = err instanceof SeamError ? err.code : 'INTERNAL_ERROR'\n\t\t\t\tconst message = err instanceof Error ? err.message : 'Subscription error'\n\t\t\t\tws.send(JSON.stringify({ event: '__error', payload: { code, message } }))\n\t\t\t}\n\t\t}\n\t})()\n\n\treturn {\n\t\tonMessage(data: string) {\n\t\t\tif (closed) return\n\t\t\tconst msg = parseUplink(ws, data, channelName)\n\t\t\tif (msg) dispatchUplink(router, ws, msg, channelInput)\n\t\t},\n\n\t\tonPong() {\n\t\t\tif (pongTimer) {\n\t\t\t\tclearTimeout(pongTimer)\n\t\t\t\tpongTimer = null\n\t\t\t}\n\t\t},\n\n\t\tclose() {\n\t\t\tif (closed) return\n\t\t\tclosed = true\n\t\t\tclearInterval(heartbeatTimer)\n\t\t\tif (pongTimer) clearTimeout(pongTimer)\n\t\t\tvoid iter.return?.(undefined)\n\t\t},\n\t}\n}\n","/* src/server/core/typescript/src/proxy.ts */\n\nimport { readFile } from 'node:fs/promises'\nimport { join, extname } from 'node:path'\nimport type { HttpHandler, HttpBodyResponse } from './http.js'\nimport { MIME_TYPES } from './mime.js'\n\nexport interface DevProxyOptions {\n\t/** Target URL to forward requests to (e.g. \"http://localhost:5173\") */\n\ttarget: string\n}\n\nexport interface StaticHandlerOptions {\n\t/** Directory to serve static files from */\n\tdir: string\n}\n\n/** Forward non-seam requests to a dev server (e.g. Vite) */\nexport function createDevProxy(opts: DevProxyOptions): HttpHandler {\n\tconst target = opts.target.replace(/\\/$/, '')\n\n\treturn async (req) => {\n\t\tconst url = new URL(req.url, 'http://localhost')\n\t\tconst proxyUrl = `${target}${url.pathname}${url.search}`\n\n\t\ttry {\n\t\t\tconst resp = await fetch(proxyUrl, {\n\t\t\t\tmethod: req.method,\n\t\t\t\theaders: { Accept: '*/*' },\n\t\t\t})\n\n\t\t\tconst body = await resp.text()\n\t\t\tconst headers: Record<string, string> = {}\n\t\t\tresp.headers.forEach((value, key) => {\n\t\t\t\theaders[key] = value\n\t\t\t})\n\n\t\t\treturn { status: resp.status, headers, body }\n\t\t} catch {\n\t\t\treturn {\n\t\t\t\tstatus: 502,\n\t\t\t\theaders: { 'Content-Type': 'text/plain' },\n\t\t\t\tbody: `Bad Gateway: failed to connect to ${target}`,\n\t\t\t}\n\t\t}\n\t}\n}\n\n/** Serve static files from a directory, with index.html fallback for directories */\nexport function createStaticHandler(opts: StaticHandlerOptions): HttpHandler {\n\tconst dir = opts.dir\n\n\treturn async (req): Promise<HttpBodyResponse> => {\n\t\tconst url = new URL(req.url, 'http://localhost')\n\t\tlet filePath = url.pathname\n\n\t\tif (filePath.includes('..')) {\n\t\t\treturn {\n\t\t\t\tstatus: 403,\n\t\t\t\theaders: { 'Content-Type': 'text/plain' },\n\t\t\t\tbody: 'Forbidden',\n\t\t\t}\n\t\t}\n\n\t\t// Serve index.html for directory paths\n\t\tif (filePath.endsWith('/')) {\n\t\t\tfilePath += 'index.html'\n\t\t}\n\n\t\tconst fullPath = join(dir, filePath)\n\t\ttry {\n\t\t\tconst content = await readFile(fullPath)\n\t\t\tconst ext = extname(fullPath)\n\t\t\tconst contentType = MIME_TYPES[ext] || 'application/octet-stream'\n\t\t\treturn {\n\t\t\t\tstatus: 200,\n\t\t\t\theaders: { 'Content-Type': contentType },\n\t\t\t\tbody: content.toString(),\n\t\t\t}\n\t\t} catch {\n\t\t\treturn {\n\t\t\t\tstatus: 404,\n\t\t\t\theaders: { 'Content-Type': 'text/plain' },\n\t\t\t\tbody: 'Not found',\n\t\t\t}\n\t\t}\n\t}\n}\n","/* src/server/core/typescript/src/dev/reload-watcher.ts */\n\nimport { watch, type FSWatcher } from 'node:fs'\nimport { join } from 'node:path'\n\nexport interface ReloadWatcher {\n\tclose(): void\n\t/** Resolves on the next reload event. Rejects if the watcher is already closed. */\n\tnextReload(): Promise<void>\n}\n\nexport function watchReloadTrigger(distDir: string, onReload: () => void): ReloadWatcher {\n\tconst triggerPath = join(distDir, '.reload-trigger')\n\tlet watcher: FSWatcher | null = null\n\tlet closed = false\n\tlet pending: Array<{ resolve: () => void; reject: (e: Error) => void }> = []\n\n\tconst notify = () => {\n\t\tonReload()\n\t\tconst batch = pending\n\t\tpending = []\n\t\tfor (const p of batch) p.resolve()\n\t}\n\n\tconst nextReload = (): Promise<void> => {\n\t\tif (closed) return Promise.reject(new Error('watcher closed'))\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tpending.push({ resolve, reject })\n\t\t})\n\t}\n\n\tconst closeAll = () => {\n\t\tclosed = true\n\t\tconst batch = pending\n\t\tpending = []\n\t\tconst err = new Error('watcher closed')\n\t\tfor (const p of batch) p.reject(err)\n\t}\n\n\ttry {\n\t\twatcher = watch(triggerPath, () => notify())\n\t} catch {\n\t\t// Trigger file may not exist yet; watch directory until it appears\n\t\tconst dirWatcher = watch(distDir, (_event, filename) => {\n\t\t\tif (filename === '.reload-trigger') {\n\t\t\t\tdirWatcher.close()\n\t\t\t\twatcher = watch(triggerPath, () => notify())\n\t\t\t\t// First creation IS the reload signal -- fire immediately\n\t\t\t\tnotify()\n\t\t\t}\n\t\t})\n\t\treturn {\n\t\t\tclose() {\n\t\t\t\tdirWatcher.close()\n\t\t\t\twatcher?.close()\n\t\t\t\tcloseAll()\n\t\t\t},\n\t\t\tnextReload,\n\t\t}\n\t}\n\treturn {\n\t\tclose() {\n\t\t\twatcher?.close()\n\t\t\tcloseAll()\n\t\t},\n\t\tnextReload,\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAkBA,SAAgB,iBAAoB,QAAkC;AACrE,QAAO,EAAE,SAAS,QAAQ;;AAG3B,SAAgB,yBAA4B,QAA0C;AACrF,QAAO;EAAE,SAAS;EAAQ,WAAW;EAAM;;;;;;;;;;;;;;;;;;;AClB5C,SAAgB,SAA6B;AAC5C,QAAO,iBAAyB,EAAE,MAAM,UAAU,CAAC;;AAGpD,SAAgB,UAA+B;AAC9C,QAAO,iBAA0B,EAAE,MAAM,WAAW,CAAC;;AAGtD,SAAgB,OAA2B;AAC1C,QAAO,iBAAyB,EAAE,MAAM,QAAQ,CAAC;;AAGlD,SAAgB,QAA4B;AAC3C,QAAO,iBAAyB,EAAE,MAAM,SAAS,CAAC;;AAGnD,SAAgB,QAA4B;AAC3C,QAAO,iBAAyB,EAAE,MAAM,SAAS,CAAC;;AAGnD,SAAgB,QAA4B;AAC3C,QAAO,iBAAyB,EAAE,MAAM,SAAS,CAAC;;AAGnD,SAAgB,SAA6B;AAC5C,QAAO,iBAAyB,EAAE,MAAM,UAAU,CAAC;;AAGpD,SAAgB,SAA6B;AAC5C,QAAO,iBAAyB,EAAE,MAAM,UAAU,CAAC;;AAGpD,SAAgB,UAA8B;AAC7C,QAAO,iBAAyB,EAAE,MAAM,WAAW,CAAC;;AAGrD,SAAgB,UAA8B;AAC7C,QAAO,iBAAyB,EAAE,MAAM,WAAW,CAAC;;AAGrD,SAAgB,YAAgC;AAC/C,QAAO,iBA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B,aAAa;IACxC,MAAM,QAAQ,UAAU;IACxB;UACM;AACP,UAAO;IACN,QAAQ;IACR,SAAS,EAAE,gBAAgB,cAAc;IACzC,MAAM;IACN;;;;;;;ACzEJ,SAAgB,mBAAmB,SAAiB,UAAqC;CACxF,MAAM,cAAc,KAAK,SAAS,kBAAkB;CACpD,IAAI,UAA4B;CAChC,IAAI,SAAS;CACb,IAAI,UAAsE,EAAE;CAE5E,MAAM,eAAe;AACpB,YAAU;EACV,MAAM,QAAQ;AACd,YAAU,EAAE;AACZ,OAAK,MAAM,KAAK,MAAO,GAAE,SAAS;;CAGnC,MAAM,mBAAkC;AACvC,MAAI,OAAQ,QAAO,QAAQ,uBAAO,IAAI,MAAM,iBAAiB,CAAC;AAC9D,SAAO,IAAI,SAAS,SAAS,WAAW;AACvC,WAAQ,KAAK;IAAE;IAAS;IAAQ,CAAC;IAChC;;CAGH,MAAM,iBAAiB;AACtB,WAAS;EACT,MAAM,QAAQ;AACd,YAAU,EAAE;EACZ,MAAM,sBAAM,IAAI,MAAM,iBAAiB;AACvC,OAAK,MAAM,KAAK,MAAO,GAAE,OAAO,IAAI;;AAGrC,KAAI;AACH,YAAU,MAAM,mBAAmB,QAAQ,CAAC;SACrC;EAEP,MAAM,aAAa,MAAM,UAAU,QAAQ,aAAa;AACvD,OAAI,aAAa,mBAAmB;AACnC,eAAW,OAAO;AAClB,cAAU,MAAM,mBAAmB,QAAQ,CAAC;AAE5C,YAAQ;;IAER;AACF,SAAO;GACN,QAAQ;AACP,eAAW,OAAO;AAClB,aAAS,OAAO;AAChB,cAAU;;GAEX;GACA;;AAEF,QAAO;EACN,QAAQ;AACP,YAAS,OAAO;AAChB,aAAU;;EAEX;EACA"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["primitives","DEFAULT_HEARTBEAT_MS"],"sources":["../src/types/schema.ts","../src/types/primitives.ts","../src/types/composites.ts","../src/types/index.ts","../src/validation/index.ts","../src/errors.ts","../src/context.ts","../src/manifest/index.ts","../src/page/route-matcher.ts","../src/router/handler.ts","../src/router/categorize.ts","../src/page/head.ts","../src/page/loader-error.ts","../src/page/projection.ts","../src/page/handler.ts","../src/resolve.ts","../src/router/helpers.ts","../src/router/state.ts","../src/router/index.ts","../src/factory.ts","../src/seam-router.ts","../src/channel.ts","../src/page/index.ts","../src/dev/reload-watcher.ts","../src/page/build-loader.ts","../src/http-sse.ts","../src/mime.ts","../src/http-response.ts","../src/http.ts","../src/subscription.ts","../src/ws.ts","../src/proxy.ts"],"sourcesContent":["/* src/server/core/typescript/src/types/schema.ts */\n\nimport type { Schema } from 'jtd'\n\nexport type JTDSchema = Schema\n\nexport interface SchemaNode<TOutput = unknown> {\n\treadonly _schema: JTDSchema\n\t/** Phantom type marker — never exists at runtime */\n\treadonly _output: TOutput\n}\n\nexport interface OptionalSchemaNode<TOutput = unknown> extends SchemaNode<TOutput> {\n\treadonly _optional: true\n}\n\nexport type Infer<T extends SchemaNode> = T['_output']\n\nexport function createSchemaNode<T>(schema: JTDSchema): SchemaNode<T> {\n\treturn { _schema: schema } as SchemaNode<T>\n}\n\nexport function createOptionalSchemaNode<T>(schema: JTDSchema): OptionalSchemaNode<T> {\n\treturn { _schema: schema, _optional: true } as OptionalSchemaNode<T>\n}\n","/* src/server/core/typescript/src/types/primitives.ts */\n\nimport type { SchemaNode } from './schema.js'\nimport { createSchemaNode } from './schema.js'\n\nexport function string(): SchemaNode<string> {\n\treturn createSchemaNode<string>({ type: 'string' })\n}\n\nexport function boolean(): SchemaNode<boolean> {\n\treturn createSchemaNode<boolean>({ type: 'boolean' })\n}\n\nexport function int8(): SchemaNode<number> {\n\treturn createSchemaNode<number>({ type: 'int8' })\n}\n\nexport function int16(): SchemaNode<number> {\n\treturn createSchemaNode<number>({ type: 'int16' })\n}\n\nexport function int32(): SchemaNode<number> {\n\treturn createSchemaNode<number>({ type: 'int32' })\n}\n\nexport function uint8(): SchemaNode<number> {\n\treturn createSchemaNode<number>({ type: 'uint8' })\n}\n\nexport function uint16(): SchemaNode<number> {\n\treturn createSchemaNode<number>({ type: 'uint16' })\n}\n\nexport function uint32(): SchemaNode<number> {\n\treturn createSchemaNode<number>({ type: 'uint32' })\n}\n\nexport function float32(): SchemaNode<number> {\n\treturn createSchemaNode<number>({ type: 'float32' })\n}\n\nexport function float64(): SchemaNode<number> {\n\treturn createSchemaNode<number>({ type: 'float64' })\n}\n\nexport function timestamp(): SchemaNode<string> {\n\treturn createSchemaNode<string>({ type: 'timestamp' })\n}\n\nexport function html(): SchemaNode<string> {\n\treturn createSchemaNode<string>({ type: 'string', metadata: { format: 'html' } })\n}\n","/* src/server/core/typescript/src/types/composites.ts */\n\nimport type { SchemaNode, OptionalSchemaNode, Infer, JTDSchema } from './schema.js'\nimport { createSchemaNode, createOptionalSchemaNode } from './schema.js'\n\n// -- Type-level utilities --\n\ntype Simplify<T> = { [K in keyof T]: T[K] } & {}\n\ntype RequiredKeys<T extends Record<string, SchemaNode>> = {\n\t[K in keyof T]: T[K] extends OptionalSchemaNode ? never : K\n}[keyof T]\n\ntype OptionalKeys<T extends Record<string, SchemaNode>> = {\n\t[K in keyof T]: T[K] extends OptionalSchemaNode ? K : never\n}[keyof T]\n\ntype InferObject<T extends Record<string, SchemaNode>> = Simplify<\n\t{ [K in RequiredKeys<T>]: Infer<T[K]> } & { [K in OptionalKeys<T>]?: Infer<T[K]> }\n>\n\n// -- Builders --\n\nexport function object<T extends Record<string, SchemaNode>>(\n\tfields: T,\n): SchemaNode<InferObject<T>> {\n\tconst properties: Record<string, JTDSchema> = {}\n\tconst optionalProperties: Record<string, JTDSchema> = {}\n\n\tfor (const [key, node] of Object.entries(fields)) {\n\t\tif ('_optional' in node && node._optional === true) {\n\t\t\toptionalProperties[key] = node._schema\n\t\t} else {\n\t\t\tproperties[key] = node._schema\n\t\t}\n\t}\n\n\tconst schema: Record<string, unknown> = {}\n\tif (Object.keys(properties).length > 0 || Object.keys(optionalProperties).length === 0) {\n\t\tschema.properties = properties\n\t}\n\tif (Object.keys(optionalProperties).length > 0) {\n\t\tschema.optionalProperties = optionalProperties\n\t}\n\n\treturn createSchemaNode<InferObject<T>>(schema as JTDSchema)\n}\n\nexport function optional<T>(node: SchemaNode<T>): OptionalSchemaNode<T> {\n\treturn createOptionalSchemaNode<T>(node._schema)\n}\n\nexport function array<T>(node: SchemaNode<T>): SchemaNode<T[]> {\n\treturn createSchemaNode<T[]>({ elements: node._schema })\n}\n\nexport function nullable<T>(node: SchemaNode<T>): SchemaNode<T | null> {\n\treturn createSchemaNode<T | null>({ ...node._schema, nullable: true } as JTDSchema)\n}\n\nexport function enumType<const T extends readonly string[]>(values: T): SchemaNode<T[number]> {\n\treturn createSchemaNode<T[number]>({ enum: [...values] } as JTDSchema)\n}\n\nexport function values<T>(node: SchemaNode<T>): SchemaNode<Record<string, T>> {\n\treturn createSchemaNode<Record<string, T>>({ values: node._schema })\n}\n\ntype DiscriminatorUnion<TTag extends string, TMapping extends Record<string, SchemaNode>> = {\n\t[K in keyof TMapping & string]: Simplify<{ [P in TTag]: K } & Infer<TMapping[K]>>\n}[keyof TMapping & string]\n\nexport function discriminator<\n\tTTag extends string,\n\tTMapping extends Record<string, SchemaNode<Record<string, unknown>>>,\n>(tag: TTag, mapping: TMapping): SchemaNode<DiscriminatorUnion<TTag, TMapping>> {\n\tconst jtdMapping: Record<string, JTDSchema> = {}\n\tfor (const [key, node] of Object.entries(mapping)) {\n\t\tjtdMapping[key] = node._schema\n\t}\n\treturn createSchemaNode<DiscriminatorUnion<TTag, TMapping>>({\n\t\tdiscriminator: tag,\n\t\tmapping: jtdMapping,\n\t} as JTDSchema)\n}\n","/* src/server/core/typescript/src/types/index.ts */\n\nimport * as primitives from './primitives.js'\nimport { object, optional, array, nullable, enumType, values, discriminator } from './composites.js'\n\nexport const t = {\n\t...primitives,\n\tobject,\n\toptional,\n\tarray,\n\tnullable,\n\tenum: enumType,\n\tvalues,\n\tdiscriminator,\n} as const\n","/* src/server/core/typescript/src/validation/index.ts */\n\nimport { validate } from 'jtd'\nimport type { Schema, ValidationError as JTDValidationError } from 'jtd'\n\nexport interface ValidationResult {\n\tvalid: boolean\n\terrors: JTDValidationError[]\n}\n\nexport interface ValidationDetail {\n\tpath: string\n\texpected?: string\n\tactual?: string\n}\n\nexport function validateInput(schema: Schema, data: unknown): ValidationResult {\n\tconst errors = validate(schema, data, { maxDepth: 32, maxErrors: 10 })\n\treturn {\n\t\tvalid: errors.length === 0,\n\t\terrors,\n\t}\n}\n\nexport function formatValidationErrors(errors: JTDValidationError[]): string {\n\treturn errors\n\t\t.map((e) => {\n\t\t\tconst path = e.instancePath.length > 0 ? e.instancePath.join('/') : '(root)'\n\t\t\tconst schema = e.schemaPath.join('/')\n\t\t\treturn `${path} (schema: ${schema})`\n\t\t})\n\t\t.join('; ')\n}\n\n/** Walk a nested object along a key path, returning undefined if unreachable */\nfunction walkPath(obj: unknown, keys: string[]): unknown {\n\tlet cur = obj\n\tfor (const k of keys) {\n\t\tif (cur === null || cur === undefined || typeof cur !== 'object') return undefined\n\t\tcur = (cur as Record<string, unknown>)[k]\n\t}\n\treturn cur\n}\n\n/** Extract structured details from JTD validation errors (best-effort) */\nexport function formatValidationDetails(\n\terrors: JTDValidationError[],\n\tschema: Schema,\n\tdata: unknown,\n): ValidationDetail[] {\n\treturn errors.map((e) => {\n\t\tconst path = '/' + e.instancePath.join('/')\n\t\tconst detail: ValidationDetail = { path }\n\n\t\t// Extract expected type by walking schemaPath — when it ends with \"type\",\n\t\t// the value at that path in the schema is the JTD type keyword\n\t\tconst schemaValue = walkPath(schema, e.schemaPath)\n\t\tif (typeof schemaValue === 'string') {\n\t\t\tdetail.expected = schemaValue\n\t\t}\n\n\t\t// Extract actual type from the data at instancePath\n\t\tconst actualValue = walkPath(data, e.instancePath)\n\t\tif (actualValue !== undefined) {\n\t\t\tdetail.actual = typeof actualValue\n\t\t} else if (e.instancePath.length === 0) {\n\t\t\tdetail.actual = typeof data\n\t\t}\n\n\t\treturn detail\n\t})\n}\n","/* src/server/core/typescript/src/errors.ts */\n\nexport type ErrorCode =\n\t| 'VALIDATION_ERROR'\n\t| 'NOT_FOUND'\n\t| 'UNAUTHORIZED'\n\t| 'FORBIDDEN'\n\t| 'RATE_LIMITED'\n\t| 'INTERNAL_ERROR'\n\t| (string & {})\n\nexport const DEFAULT_STATUS: Record<string, number> = {\n\tVALIDATION_ERROR: 400,\n\tUNAUTHORIZED: 401,\n\tFORBIDDEN: 403,\n\tNOT_FOUND: 404,\n\tRATE_LIMITED: 429,\n\tINTERNAL_ERROR: 500,\n}\n\nexport class SeamError extends Error {\n\treadonly code: string\n\treadonly status: number\n\treadonly details?: unknown[]\n\n\tconstructor(code: string, message: string, status?: number, details?: unknown[]) {\n\t\tsuper(message)\n\t\tthis.code = code\n\t\tthis.status = status ?? DEFAULT_STATUS[code] ?? 500\n\t\tthis.details = details\n\t\tthis.name = 'SeamError'\n\t}\n\n\ttoJSON() {\n\t\tconst error: Record<string, unknown> = {\n\t\t\tcode: this.code,\n\t\t\tmessage: this.message,\n\t\t\ttransient: false,\n\t\t}\n\t\tif (this.details) error.details = this.details\n\t\treturn { ok: false, error }\n\t}\n}\n","/* src/server/core/typescript/src/context.ts */\n\nimport type { SchemaNode } from './types/schema.js'\nimport { validateInput, formatValidationErrors } from './validation/index.js'\nimport { SeamError } from './errors.js'\n\nexport interface ContextFieldDef {\n\textract: string\n\tschema: SchemaNode\n}\n\nexport type ContextConfig = Record<string, ContextFieldDef>\nexport type RawContextMap = Record<string, string | null>\n\n/** Parse extract rule into source type and key, e.g. \"header:authorization\" -> { source: \"header\", key: \"authorization\" } */\nexport function parseExtractRule(rule: string): { source: string; key: string } {\n\tconst idx = rule.indexOf(':')\n\tif (idx === -1) {\n\t\tthrow new Error(`Invalid extract rule \"${rule}\": expected \"source:key\" format`)\n\t}\n\tconst source = rule.slice(0, idx)\n\tconst key = rule.slice(idx + 1)\n\tif (!source || !key) {\n\t\tthrow new Error(`Invalid extract rule \"${rule}\": source and key must be non-empty`)\n\t}\n\treturn { source, key }\n}\n\n/** Check whether any context fields are defined */\nexport function contextHasExtracts(config: ContextConfig): boolean {\n\treturn Object.keys(config).length > 0\n}\n\n/** Parse a Cookie header into key-value pairs */\nexport function parseCookieHeader(header: string): Record<string, string> {\n\tconst result: Record<string, string> = {}\n\tfor (const pair of header.split(';')) {\n\t\tconst idx = pair.indexOf('=')\n\t\tif (idx > 0) {\n\t\t\tresult[pair.slice(0, idx).trim()] = pair.slice(idx + 1).trim()\n\t\t}\n\t}\n\treturn result\n}\n\n/** Build a RawContextMap keyed by config key from request headers, cookies, and query params */\nexport function buildRawContext(\n\tconfig: ContextConfig,\n\theaderFn: ((name: string) => string | null) | undefined,\n\turl: URL,\n): RawContextMap {\n\tconst raw: RawContextMap = {}\n\tlet cookieCache: Record<string, string> | undefined\n\tfor (const [key, field] of Object.entries(config)) {\n\t\tconst { source, key: extractKey } = parseExtractRule(field.extract)\n\t\tswitch (source) {\n\t\t\tcase 'header':\n\t\t\t\traw[key] = headerFn?.(extractKey) ?? null\n\t\t\t\tbreak\n\t\t\tcase 'cookie': {\n\t\t\t\tif (!cookieCache) {\n\t\t\t\t\tcookieCache = parseCookieHeader(headerFn?.('cookie') ?? '')\n\t\t\t\t}\n\t\t\t\traw[key] = cookieCache[extractKey] ?? null\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase 'query':\n\t\t\t\traw[key] = url.searchParams.get(extractKey) ?? null\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\traw[key] = null\n\t\t}\n\t}\n\treturn raw\n}\n\n/**\n * Resolve raw strings into validated context object.\n *\n * For each requested key:\n * - If raw value is null/missing -> pass null to JTD; schema decides via nullable()\n * - If schema expects string -> use raw value directly\n * - If schema expects object -> JSON.parse then validate\n */\nexport function resolveContext(\n\tconfig: ContextConfig,\n\traw: RawContextMap,\n\trequestedKeys: string[],\n): Record<string, unknown> {\n\tconst result: Record<string, unknown> = {}\n\n\tfor (const key of requestedKeys) {\n\t\tconst field = config[key]\n\t\tif (!field) {\n\t\t\tthrow new SeamError(\n\t\t\t\t'CONTEXT_ERROR',\n\t\t\t\t`Context field \"${key}\" is not defined in router context config`,\n\t\t\t\t400,\n\t\t\t)\n\t\t}\n\n\t\tconst rawValue = raw[key] ?? null\n\n\t\tlet value: unknown\n\t\tif (rawValue === null) {\n\t\t\tvalue = null\n\t\t} else {\n\t\t\tconst schema = field.schema._schema\n\t\t\t// If the root schema is { type: \"string\" } or nullable string, use raw value directly\n\t\t\tconst isStringSchema =\n\t\t\t\t'type' in schema && schema.type === 'string' && !('nullable' in schema && schema.nullable)\n\t\t\tconst isNullableStringSchema =\n\t\t\t\t'type' in schema && schema.type === 'string' && 'nullable' in schema && schema.nullable\n\n\t\t\tif (isStringSchema || isNullableStringSchema) {\n\t\t\t\tvalue = rawValue\n\t\t\t} else {\n\t\t\t\t// Attempt JSON parse for complex types\n\t\t\t\ttry {\n\t\t\t\t\tvalue = JSON.parse(rawValue)\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new SeamError(\n\t\t\t\t\t\t'CONTEXT_ERROR',\n\t\t\t\t\t\t`Context field \"${key}\": failed to parse value as JSON`,\n\t\t\t\t\t\t400,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst validation = validateInput(field.schema._schema, value)\n\t\tif (!validation.valid) {\n\t\t\tconst details = formatValidationErrors(validation.errors)\n\t\t\tthrow new SeamError(\n\t\t\t\t'CONTEXT_ERROR',\n\t\t\t\t`Context field \"${key}\" validation failed: ${details}`,\n\t\t\t\t400,\n\t\t\t)\n\t\t}\n\n\t\tresult[key] = value\n\t}\n\n\treturn result\n}\n\n/** Syntax sugar for building extract rules; the underlying \"source:key\" format is unchanged. */\nexport const extract = {\n\theader: (name: string): string => `header:${name}`,\n\tcookie: (name: string): string => `cookie:${name}`,\n\tquery: (name: string): string => `query:${name}`,\n}\n","/* src/server/core/typescript/src/manifest/index.ts */\n\nimport type { Schema } from 'jtd'\nimport type { SchemaNode } from '../types/schema.js'\nimport type { ChannelMeta } from '../channel.js'\nimport type { ContextConfig } from '../context.js'\n\nexport type ProcedureType = 'query' | 'command' | 'subscription' | 'stream' | 'upload'\n\nexport interface NormalizedMappingValue {\n\tfrom: string\n\teach?: boolean\n}\n\nexport interface NormalizedInvalidateTarget {\n\tquery: string\n\tmapping?: Record<string, NormalizedMappingValue>\n}\n\nexport interface ContextManifestEntry {\n\textract: string\n\tschema: Schema\n}\n\nexport interface ProcedureEntry {\n\tkind: ProcedureType\n\tinput: Schema\n\toutput?: Schema\n\tchunkOutput?: Schema\n\terror?: Schema\n\tinvalidates?: NormalizedInvalidateTarget[]\n\tcontext?: string[]\n\ttransport?: { prefer: string; fallback?: string[] }\n\tsuppress?: string[]\n\tcache?: false | { ttl: number }\n}\n\nexport interface ProcedureManifest {\n\tversion: number\n\tcontext: Record<string, ContextManifestEntry>\n\tprocedures: Record<string, ProcedureEntry>\n\tchannels?: Record<string, ChannelMeta>\n\ttransportDefaults: Record<string, { prefer: string; fallback?: string[] }>\n}\n\ntype InvalidateInput = Array<\n\t| string\n\t| {\n\t\t\tquery: string\n\t\t\tmapping?: Record<string, string | { from: string; each?: boolean }>\n\t }\n>\n\nfunction normalizeInvalidates(targets: InvalidateInput): NormalizedInvalidateTarget[] {\n\treturn targets.map((t) => {\n\t\tif (typeof t === 'string') return { query: t }\n\t\tconst normalized: NormalizedInvalidateTarget = { query: t.query }\n\t\tif (t.mapping) {\n\t\t\tnormalized.mapping = Object.fromEntries(\n\t\t\t\tObject.entries(t.mapping).map(([k, v]) => [k, typeof v === 'string' ? { from: v } : v]),\n\t\t\t)\n\t\t}\n\t\treturn normalized\n\t})\n}\n\nexport function buildManifest(\n\tdefinitions: Record<\n\t\tstring,\n\t\t{\n\t\t\tinput: SchemaNode\n\t\t\toutput: SchemaNode\n\t\t\tkind?: string\n\t\t\ttype?: string\n\t\t\terror?: SchemaNode\n\t\t\tcontext?: string[]\n\t\t\tinvalidates?: InvalidateInput\n\t\t}\n\t>,\n\tchannels?: Record<string, ChannelMeta>,\n\tcontextConfig?: ContextConfig,\n\ttransportDefaults?: Record<string, { prefer: string; fallback?: string[] }>,\n): ProcedureManifest {\n\tconst mapped: ProcedureManifest['procedures'] = {}\n\n\tfor (const [name, def] of Object.entries(definitions)) {\n\t\tconst k = def.kind ?? def.type\n\t\tconst kind: ProcedureType =\n\t\t\tk === 'upload'\n\t\t\t\t? 'upload'\n\t\t\t\t: k === 'stream'\n\t\t\t\t\t? 'stream'\n\t\t\t\t\t: k === 'subscription'\n\t\t\t\t\t\t? 'subscription'\n\t\t\t\t\t\t: k === 'command'\n\t\t\t\t\t\t\t? 'command'\n\t\t\t\t\t\t\t: 'query'\n\t\tconst entry: ProcedureEntry = { kind, input: def.input._schema }\n\t\tif (kind === 'stream') {\n\t\t\tentry.chunkOutput = def.output._schema\n\t\t} else {\n\t\t\tentry.output = def.output._schema\n\t\t}\n\t\tif (def.error) {\n\t\t\tentry.error = def.error._schema\n\t\t}\n\t\tif (kind === 'command' && def.invalidates && def.invalidates.length > 0) {\n\t\t\tentry.invalidates = normalizeInvalidates(def.invalidates)\n\t\t}\n\t\tif (def.context && def.context.length > 0) {\n\t\t\tentry.context = def.context\n\t\t}\n\t\tconst defAny = def as Record<string, unknown>\n\t\tif (defAny.transport) {\n\t\t\tentry.transport = defAny.transport as { prefer: string; fallback?: string[] }\n\t\t}\n\t\tif (defAny.suppress) {\n\t\t\tentry.suppress = defAny.suppress as string[]\n\t\t}\n\t\tif (defAny.cache !== undefined) {\n\t\t\tentry.cache = defAny.cache as false | { ttl: number }\n\t\t}\n\t\tmapped[name] = entry\n\t}\n\n\tconst context: Record<string, ContextManifestEntry> = {}\n\tif (contextConfig) {\n\t\tfor (const [key, field] of Object.entries(contextConfig)) {\n\t\t\tcontext[key] = { extract: field.extract, schema: field.schema._schema }\n\t\t}\n\t}\n\n\tconst manifest: ProcedureManifest = {\n\t\tversion: 2,\n\t\tcontext,\n\t\tprocedures: mapped,\n\t\ttransportDefaults: transportDefaults ?? {},\n\t}\n\tif (channels && Object.keys(channels).length > 0) {\n\t\tmanifest.channels = channels\n\t}\n\treturn manifest\n}\n","/* src/server/core/typescript/src/page/route-matcher.ts */\n\ninterface CompiledRoute {\n\tsegments: RouteSegment[]\n}\n\ntype RouteSegment =\n\t| { kind: 'static'; value: string }\n\t| { kind: 'param'; name: string }\n\t| { kind: 'catch-all'; name: string; optional: boolean }\n\nfunction compileRoute(pattern: string): CompiledRoute {\n\tconst segments: RouteSegment[] = pattern\n\t\t.split('/')\n\t\t.filter(Boolean)\n\t\t.map((seg) => {\n\t\t\tif (seg.startsWith('*')) {\n\t\t\t\tconst optional = seg.endsWith('?')\n\t\t\t\tconst name = optional ? seg.slice(1, -1) : seg.slice(1)\n\t\t\t\treturn { kind: 'catch-all' as const, name, optional }\n\t\t\t}\n\t\t\tif (seg.startsWith(':')) {\n\t\t\t\treturn { kind: 'param' as const, name: seg.slice(1) }\n\t\t\t}\n\t\t\treturn { kind: 'static' as const, value: seg }\n\t\t})\n\treturn { segments }\n}\n\nfunction matchRoute(segments: RouteSegment[], pathParts: string[]): Record<string, string> | null {\n\tconst params: Record<string, string> = {}\n\tfor (let i = 0; i < segments.length; i++) {\n\t\tconst seg = segments[i] as RouteSegment\n\t\tif (seg.kind === 'catch-all') {\n\t\t\t// Catch-all must be the last segment\n\t\t\tconst rest = pathParts.slice(i)\n\t\t\tif (rest.length === 0 && !seg.optional) return null\n\t\t\tparams[seg.name] = rest.join('/')\n\t\t\treturn params\n\t\t}\n\t\tif (i >= pathParts.length) return null\n\t\tif (seg.kind === 'static') {\n\t\t\tif (seg.value !== pathParts[i]) return null\n\t\t} else {\n\t\t\tparams[seg.name] = pathParts[i] as string\n\t\t}\n\t}\n\t// All segments consumed — path must also be fully consumed\n\tif (segments.length !== pathParts.length) return null\n\treturn params\n}\n\nexport class RouteMatcher<T> {\n\tprivate routes: { pattern: string; compiled: CompiledRoute; value: T }[] = []\n\n\tadd(pattern: string, value: T): void {\n\t\tthis.routes.push({ pattern, compiled: compileRoute(pattern), value })\n\t}\n\n\tclear(): void {\n\t\tthis.routes = []\n\t}\n\n\tget size(): number {\n\t\treturn this.routes.length\n\t}\n\n\tmatch(path: string): { value: T; params: Record<string, string>; pattern: string } | null {\n\t\tconst parts = path.split('/').filter(Boolean)\n\t\tfor (const route of this.routes) {\n\t\t\tconst params = matchRoute(route.compiled.segments, parts)\n\t\t\tif (params) return { value: route.value, params, pattern: route.pattern }\n\t\t}\n\t\treturn null\n\t}\n}\n","/* src/server/core/typescript/src/router/handler.ts */\n\nimport { SeamError } from '../errors.js'\nimport type {\n\tHandleResult,\n\tInternalProcedure,\n\tInternalSubscription,\n\tInternalStream,\n\tInternalUpload,\n\tSeamFileHandle,\n} from '../procedure.js'\nimport {\n\tvalidateInput,\n\tformatValidationErrors,\n\tformatValidationDetails,\n} from '../validation/index.js'\n\nexport type { HandleResult, InternalProcedure } from '../procedure.js'\n\nexport async function handleRequest(\n\tprocedures: Map<string, InternalProcedure>,\n\tprocedureName: string,\n\trawBody: unknown,\n\tshouldValidateInput: boolean = true,\n\tvalidateOutput?: boolean,\n\tctx?: Record<string, unknown>,\n\tstate?: unknown,\n): Promise<HandleResult> {\n\tconst procedure = procedures.get(procedureName)\n\tif (!procedure) {\n\t\treturn {\n\t\t\tstatus: 404,\n\t\t\tbody: new SeamError('NOT_FOUND', `Procedure '${procedureName}' not found`).toJSON(),\n\t\t}\n\t}\n\n\tif (shouldValidateInput) {\n\t\tconst validation = validateInput(procedure.inputSchema, rawBody)\n\t\tif (!validation.valid) {\n\t\t\tconst details = formatValidationDetails(validation.errors, procedure.inputSchema, rawBody)\n\t\t\tconst summary = formatValidationErrors(validation.errors)\n\t\t\treturn {\n\t\t\t\tstatus: 400,\n\t\t\t\tbody: new SeamError(\n\t\t\t\t\t'VALIDATION_ERROR',\n\t\t\t\t\t`Input validation failed for procedure '${procedureName}': ${summary}`,\n\t\t\t\t\tundefined,\n\t\t\t\t\tdetails,\n\t\t\t\t).toJSON(),\n\t\t\t}\n\t\t}\n\t}\n\n\ttry {\n\t\tconst result = await procedure.handler({ input: rawBody, ctx: ctx ?? {}, state })\n\n\t\tif (validateOutput) {\n\t\t\tconst outValidation = validateInput(procedure.outputSchema, result)\n\t\t\tif (!outValidation.valid) {\n\t\t\t\tconst summary = formatValidationErrors(outValidation.errors)\n\t\t\t\treturn {\n\t\t\t\t\tstatus: 500,\n\t\t\t\t\tbody: new SeamError('INTERNAL_ERROR', `Output validation failed: ${summary}`).toJSON(),\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn { status: 200, body: { ok: true, data: result } }\n\t} catch (error) {\n\t\tif (error instanceof SeamError) {\n\t\t\treturn { status: error.status, body: error.toJSON() }\n\t\t}\n\t\tconst message = error instanceof Error ? error.message : 'Unknown error'\n\t\treturn {\n\t\t\tstatus: 500,\n\t\t\tbody: new SeamError('INTERNAL_ERROR', message).toJSON(),\n\t\t}\n\t}\n}\n\nexport interface BatchCall {\n\tprocedure: string\n\tinput: unknown\n}\n\nexport type BatchResultItem =\n\t| { ok: true; data: unknown }\n\t| { ok: false; error: { code: string; message: string; transient: boolean } }\n\nexport async function handleBatchRequest(\n\tprocedures: Map<string, InternalProcedure>,\n\tcalls: BatchCall[],\n\tshouldValidateInput: boolean = true,\n\tvalidateOutput?: boolean,\n\tctxResolver?: (procedureName: string) => Record<string, unknown>,\n\tstate?: unknown,\n): Promise<{ results: BatchResultItem[] }> {\n\tconst results = await Promise.all(\n\t\tcalls.map(async (call) => {\n\t\t\tconst ctx = ctxResolver ? ctxResolver(call.procedure) : undefined\n\t\t\tconst result = await handleRequest(\n\t\t\t\tprocedures,\n\t\t\t\tcall.procedure,\n\t\t\t\tcall.input,\n\t\t\t\tshouldValidateInput,\n\t\t\t\tvalidateOutput,\n\t\t\t\tctx,\n\t\t\t\tstate,\n\t\t\t)\n\t\t\tif (result.status === 200) {\n\t\t\t\tconst envelope = result.body as { ok: true; data: unknown }\n\t\t\t\treturn { ok: true as const, data: envelope.data }\n\t\t\t}\n\t\t\tconst envelope = result.body as {\n\t\t\t\tok: false\n\t\t\t\terror: { code: string; message: string; transient: boolean }\n\t\t\t}\n\t\t\treturn { ok: false as const, error: envelope.error }\n\t\t}),\n\t)\n\treturn { results }\n}\n\nexport async function* handleSubscription(\n\tsubscriptions: Map<string, InternalSubscription>,\n\tname: string,\n\trawInput: unknown,\n\tshouldValidateInput: boolean = true,\n\tvalidateOutput?: boolean,\n\tctx?: Record<string, unknown>,\n\tstate?: unknown,\n\tlastEventId?: string,\n): AsyncIterable<unknown> {\n\tconst sub = subscriptions.get(name)\n\tif (!sub) {\n\t\tthrow new SeamError('NOT_FOUND', `Subscription '${name}' not found`)\n\t}\n\n\tif (shouldValidateInput) {\n\t\tconst validation = validateInput(sub.inputSchema, rawInput)\n\t\tif (!validation.valid) {\n\t\t\tconst details = formatValidationDetails(validation.errors, sub.inputSchema, rawInput)\n\t\t\tconst summary = formatValidationErrors(validation.errors)\n\t\t\tthrow new SeamError(\n\t\t\t\t'VALIDATION_ERROR',\n\t\t\t\t`Input validation failed: ${summary}`,\n\t\t\t\tundefined,\n\t\t\t\tdetails,\n\t\t\t)\n\t\t}\n\t}\n\n\tfor await (const value of sub.handler({\n\t\tinput: rawInput,\n\t\tctx: ctx ?? {},\n\t\tstate,\n\t\tlastEventId,\n\t})) {\n\t\tif (validateOutput) {\n\t\t\tconst outValidation = validateInput(sub.outputSchema, value)\n\t\t\tif (!outValidation.valid) {\n\t\t\t\tconst summary = formatValidationErrors(outValidation.errors)\n\t\t\t\tthrow new SeamError('INTERNAL_ERROR', `Output validation failed: ${summary}`)\n\t\t\t}\n\t\t}\n\t\tyield value\n\t}\n}\n\nexport async function handleUploadRequest(\n\tuploads: Map<string, InternalUpload>,\n\tprocedureName: string,\n\trawBody: unknown,\n\tfile: SeamFileHandle,\n\tshouldValidateInput: boolean = true,\n\tvalidateOutput?: boolean,\n\tctx?: Record<string, unknown>,\n\tstate?: unknown,\n): Promise<HandleResult> {\n\tconst upload = uploads.get(procedureName)\n\tif (!upload) {\n\t\treturn {\n\t\t\tstatus: 404,\n\t\t\tbody: new SeamError('NOT_FOUND', `Procedure '${procedureName}' not found`).toJSON(),\n\t\t}\n\t}\n\n\tif (shouldValidateInput) {\n\t\tconst validation = validateInput(upload.inputSchema, rawBody)\n\t\tif (!validation.valid) {\n\t\t\tconst details = formatValidationDetails(validation.errors, upload.inputSchema, rawBody)\n\t\t\tconst summary = formatValidationErrors(validation.errors)\n\t\t\treturn {\n\t\t\t\tstatus: 400,\n\t\t\t\tbody: new SeamError(\n\t\t\t\t\t'VALIDATION_ERROR',\n\t\t\t\t\t`Input validation failed for procedure '${procedureName}': ${summary}`,\n\t\t\t\t\tundefined,\n\t\t\t\t\tdetails,\n\t\t\t\t).toJSON(),\n\t\t\t}\n\t\t}\n\t}\n\n\ttry {\n\t\tconst result = await upload.handler({ input: rawBody, file, ctx: ctx ?? {}, state })\n\n\t\tif (validateOutput) {\n\t\t\tconst outValidation = validateInput(upload.outputSchema, result)\n\t\t\tif (!outValidation.valid) {\n\t\t\t\tconst summary = formatValidationErrors(outValidation.errors)\n\t\t\t\treturn {\n\t\t\t\t\tstatus: 500,\n\t\t\t\t\tbody: new SeamError('INTERNAL_ERROR', `Output validation failed: ${summary}`).toJSON(),\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn { status: 200, body: { ok: true, data: result } }\n\t} catch (error) {\n\t\tif (error instanceof SeamError) {\n\t\t\treturn { status: error.status, body: error.toJSON() }\n\t\t}\n\t\tconst message = error instanceof Error ? error.message : 'Unknown error'\n\t\treturn {\n\t\t\tstatus: 500,\n\t\t\tbody: new SeamError('INTERNAL_ERROR', message).toJSON(),\n\t\t}\n\t}\n}\n\nexport async function* handleStream(\n\tstreams: Map<string, InternalStream>,\n\tname: string,\n\trawInput: unknown,\n\tshouldValidateInput: boolean = true,\n\tvalidateOutput?: boolean,\n\tctx?: Record<string, unknown>,\n\tstate?: unknown,\n): AsyncGenerator<unknown> {\n\tconst stream = streams.get(name)\n\tif (!stream) {\n\t\tthrow new SeamError('NOT_FOUND', `Stream '${name}' not found`)\n\t}\n\n\tif (shouldValidateInput) {\n\t\tconst validation = validateInput(stream.inputSchema, rawInput)\n\t\tif (!validation.valid) {\n\t\t\tconst details = formatValidationDetails(validation.errors, stream.inputSchema, rawInput)\n\t\t\tconst summary = formatValidationErrors(validation.errors)\n\t\t\tthrow new SeamError(\n\t\t\t\t'VALIDATION_ERROR',\n\t\t\t\t`Input validation failed: ${summary}`,\n\t\t\t\tundefined,\n\t\t\t\tdetails,\n\t\t\t)\n\t\t}\n\t}\n\n\tfor await (const value of stream.handler({ input: rawInput, ctx: ctx ?? {}, state })) {\n\t\tif (validateOutput) {\n\t\t\tconst outValidation = validateInput(stream.chunkOutputSchema, value)\n\t\t\tif (!outValidation.valid) {\n\t\t\t\tconst summary = formatValidationErrors(outValidation.errors)\n\t\t\t\tthrow new SeamError('INTERNAL_ERROR', `Output validation failed: ${summary}`)\n\t\t\t}\n\t\t}\n\t\tyield value\n\t}\n}\n","/* src/server/core/typescript/src/router/categorize.ts */\n\nimport type { DefinitionMap, ProcedureKind } from './index.js'\nimport type { InternalProcedure } from '../procedure.js'\nimport type { InternalSubscription, InternalStream, InternalUpload } from '../procedure.js'\nimport type { ContextConfig } from '../context.js'\n\nfunction resolveKind(name: string, def: DefinitionMap[string]): ProcedureKind {\n\tif ('kind' in def && def.kind) return def.kind\n\tif ('type' in def && def.type) {\n\t\tconsole.warn(\n\t\t\t`[seam] \"${name}\": \"type\" field in procedure definition is deprecated, use \"kind\" instead`,\n\t\t)\n\t\treturn def.type\n\t}\n\treturn 'query'\n}\n\nexport interface CategorizedProcedures {\n\tprocedureMap: Map<string, InternalProcedure>\n\tsubscriptionMap: Map<string, InternalSubscription>\n\tstreamMap: Map<string, InternalStream>\n\tuploadMap: Map<string, InternalUpload>\n\tkindMap: Map<string, ProcedureKind>\n}\n\n/** Split a flat definition map into typed procedure/subscription/stream maps */\nexport function categorizeProcedures(\n\tdefinitions: DefinitionMap,\n\tcontextConfig?: ContextConfig,\n): CategorizedProcedures {\n\tconst procedureMap = new Map<string, InternalProcedure>()\n\tconst subscriptionMap = new Map<string, InternalSubscription>()\n\tconst streamMap = new Map<string, InternalStream>()\n\tconst uploadMap = new Map<string, InternalUpload>()\n\tconst kindMap = new Map<string, ProcedureKind>()\n\n\tfor (const [name, def] of Object.entries(definitions)) {\n\t\tif (name.startsWith('seam.')) {\n\t\t\tthrow new Error(`Procedure name \"${name}\" uses reserved \"seam.\" namespace`)\n\t\t}\n\t\tconst kind = resolveKind(name, def)\n\t\tkindMap.set(name, kind)\n\t\tconst contextKeys = (def as { context?: string[] }).context ?? []\n\n\t\t// Validate context keys reference defined fields\n\t\tif (contextConfig && contextKeys.length > 0) {\n\t\t\tfor (const key of contextKeys) {\n\t\t\t\tif (!(key in contextConfig)) {\n\t\t\t\t\tthrow new Error(`Procedure \"${name}\" references undefined context field \"${key}\"`)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (kind === 'upload') {\n\t\t\tuploadMap.set(name, {\n\t\t\t\tinputSchema: def.input._schema,\n\t\t\t\toutputSchema: def.output._schema,\n\t\t\t\tcontextKeys,\n\t\t\t\thandler: def.handler as InternalUpload['handler'],\n\t\t\t})\n\t\t} else if (kind === 'stream') {\n\t\t\tstreamMap.set(name, {\n\t\t\t\tinputSchema: def.input._schema,\n\t\t\t\tchunkOutputSchema: def.output._schema,\n\t\t\t\tcontextKeys,\n\t\t\t\thandler: def.handler as InternalStream['handler'],\n\t\t\t})\n\t\t} else if (kind === 'subscription') {\n\t\t\tsubscriptionMap.set(name, {\n\t\t\t\tinputSchema: def.input._schema,\n\t\t\t\toutputSchema: def.output._schema,\n\t\t\t\tcontextKeys,\n\t\t\t\thandler: def.handler as InternalSubscription['handler'],\n\t\t\t})\n\t\t} else {\n\t\t\tprocedureMap.set(name, {\n\t\t\t\tinputSchema: def.input._schema,\n\t\t\t\toutputSchema: def.output._schema,\n\t\t\t\tcontextKeys,\n\t\t\t\thandler: def.handler as InternalProcedure['handler'],\n\t\t\t})\n\t\t}\n\t}\n\n\treturn { procedureMap, subscriptionMap, streamMap, uploadMap, kindMap }\n}\n","/* src/server/core/typescript/src/page/head.ts */\n\nimport { escapeHtml } from '@canmi/seam-engine'\n\ninterface HeadMeta {\n\t[key: string]: string | undefined\n}\n\ninterface HeadLink {\n\t[key: string]: string | undefined\n}\n\ninterface HeadConfig {\n\ttitle?: string\n\tmeta?: HeadMeta[]\n\tlink?: HeadLink[]\n}\n\nexport type HeadFn = (data: Record<string, unknown>) => HeadConfig\n\n/**\n * Convert a HeadConfig with real values into escaped HTML.\n * Used at request-time by TS server backends.\n */\nexport function headConfigToHtml(config: HeadConfig): string {\n\tlet html = ''\n\tif (config.title !== undefined) {\n\t\thtml += `<title>${escapeHtml(config.title)}</title>`\n\t}\n\tfor (const meta of config.meta ?? []) {\n\t\thtml += '<meta'\n\t\tfor (const [k, v] of Object.entries(meta)) {\n\t\t\tif (v !== undefined) html += ` ${k}=\"${escapeHtml(v)}\"`\n\t\t}\n\t\thtml += '>'\n\t}\n\tfor (const link of config.link ?? []) {\n\t\thtml += '<link'\n\t\tfor (const [k, v] of Object.entries(link)) {\n\t\t\tif (v !== undefined) html += ` ${k}=\"${escapeHtml(v)}\"`\n\t\t}\n\t\thtml += '>'\n\t}\n\treturn html\n}\n","/* src/server/core/typescript/src/page/loader-error.ts */\n\nexport interface LoaderError {\n\t__error: true\n\tcode: string\n\tmessage: string\n}\n\nexport function isLoaderError(value: unknown): value is LoaderError {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t(value as Record<string, unknown>).__error === true &&\n\t\ttypeof (value as Record<string, unknown>).code === 'string' &&\n\t\ttypeof (value as Record<string, unknown>).message === 'string'\n\t)\n}\n","/* src/server/core/typescript/src/page/projection.ts */\n\nimport { isLoaderError } from './loader-error.js'\n\nexport type ProjectionMap = Record<string, string[]>\n\n/** Set a nested field by dot-separated path, creating intermediate objects as needed. */\nfunction setNestedField(target: Record<string, unknown>, path: string, value: unknown): void {\n\tconst parts = path.split('.')\n\tlet current: Record<string, unknown> = target\n\tfor (let i = 0; i < parts.length - 1; i++) {\n\t\tconst key = parts[i] as string\n\t\tif (key === '__proto__' || key === 'prototype' || key === 'constructor') return\n\t\tif (!(key in current) || typeof current[key] !== 'object' || current[key] === null) {\n\t\t\tcurrent[key] = {}\n\t\t}\n\t\tcurrent = current[key] as Record<string, unknown>\n\t}\n\tconst lastPart = parts[parts.length - 1] as string\n\tif (lastPart === '__proto__' || lastPart === 'prototype' || lastPart === 'constructor') return\n\tcurrent[lastPart] = value\n}\n\n/** Get a nested field by dot-separated path. */\nfunction getNestedField(source: Record<string, unknown>, path: string): unknown {\n\tconst parts = path.split('.')\n\tlet current: unknown = source\n\tfor (const part of parts) {\n\t\tif (current === null || current === undefined || typeof current !== 'object') {\n\t\t\treturn undefined\n\t\t}\n\t\tcurrent = (current as Record<string, unknown>)[part]\n\t}\n\treturn current\n}\n\n/** Prune a single value according to its projected field paths. */\nfunction pruneValue(value: unknown, fields: string[]): unknown {\n\t// Separate $ paths (array element fields) from plain paths\n\tconst arrayFields: string[] = []\n\tconst plainFields: string[] = []\n\n\tfor (const f of fields) {\n\t\tif (f === '$') {\n\t\t\t// Standalone $ means keep entire array elements — return value as-is\n\t\t\treturn value\n\t\t} else if (f.startsWith('$.')) {\n\t\t\tarrayFields.push(f.slice(2))\n\t\t} else {\n\t\t\tplainFields.push(f)\n\t\t}\n\t}\n\n\tif (arrayFields.length > 0 && Array.isArray(value)) {\n\t\treturn value.map((item: unknown) => {\n\t\t\tif (typeof item !== 'object' || item === null) return item\n\t\t\tconst pruned: Record<string, unknown> = {}\n\t\t\tfor (const field of arrayFields) {\n\t\t\t\tconst val = getNestedField(item as Record<string, unknown>, field)\n\t\t\t\tif (val !== undefined) {\n\t\t\t\t\tsetNestedField(pruned, field, val)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn pruned\n\t\t})\n\t}\n\n\tif (plainFields.length > 0 && typeof value === 'object' && value !== null) {\n\t\tconst source = value as Record<string, unknown>\n\t\tconst pruned: Record<string, unknown> = {}\n\t\tfor (const field of plainFields) {\n\t\t\tconst val = getNestedField(source, field)\n\t\t\tif (val !== undefined) {\n\t\t\t\tsetNestedField(pruned, field, val)\n\t\t\t}\n\t\t}\n\t\treturn pruned\n\t}\n\n\treturn value\n}\n\n/** Prune data to only include projected fields. Missing projection = keep all. */\nexport function applyProjection(\n\tdata: Record<string, unknown>,\n\tprojections: ProjectionMap | undefined,\n): Record<string, unknown> {\n\tif (!projections) return data\n\n\tconst result: Record<string, unknown> = {}\n\tfor (const [key, value] of Object.entries(data)) {\n\t\tif (isLoaderError(value)) {\n\t\t\tresult[key] = value\n\t\t\tcontinue\n\t\t}\n\t\tconst fields = projections[key]\n\t\tif (!fields) {\n\t\t\tresult[key] = value\n\t\t} else {\n\t\t\tresult[key] = pruneValue(value, fields)\n\t\t}\n\t}\n\treturn result\n}\n","/* src/server/core/typescript/src/page/handler.ts */\n\nimport { readFileSync, existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { renderPage, escapeHtml } from '@canmi/seam-engine'\nimport { SeamError } from '../errors.js'\nimport type { InternalProcedure } from '../procedure.js'\nimport type { PageDef, LayoutDef, LoaderFn, I18nConfig } from './index.js'\nimport { headConfigToHtml } from './head.js'\nimport type { LoaderError } from './loader-error.js'\nimport { applyProjection } from './projection.js'\nimport { validateInput, formatValidationErrors } from '../validation/index.js'\n\nexport interface PageTiming {\n\t/** Procedure execution time in milliseconds */\n\tdataFetch: number\n\t/** Template injection time in milliseconds */\n\tinject: number\n}\n\nexport interface HandlePageResult {\n\tstatus: number\n\thtml: string\n\ttiming?: PageTiming\n}\n\nexport interface I18nOpts {\n\tlocale: string\n\tconfig: I18nConfig\n\t/** Route pattern for hash-based message lookup */\n\troutePattern: string\n}\n\ninterface LoaderResults {\n\tdata: Record<string, unknown>\n\tmeta: Record<string, { procedure: string; input: unknown; error?: true }>\n}\n\n/** Execute loaders, returning keyed results and metadata.\n * Each loader is wrapped in its own try-catch so a single failure\n * does not abort sibling loaders — the page renders at 200 with partial data. */\nasync function executeLoaders(\n\tloaders: Record<string, LoaderFn>,\n\tparams: Record<string, string>,\n\tprocedures: Map<string, InternalProcedure>,\n\tsearchParams?: URLSearchParams,\n\tctxResolver?: (proc: InternalProcedure) => Record<string, unknown>,\n\tappState?: unknown,\n\tshouldValidateInput?: boolean,\n): Promise<LoaderResults> {\n\tconst entries = Object.entries(loaders)\n\tconst results = await Promise.all(\n\t\tentries.map(async ([key, loader]) => {\n\t\t\tconst { procedure, input } = loader(params, searchParams)\n\t\t\ttry {\n\t\t\t\tconst proc = procedures.get(procedure)\n\t\t\t\tif (!proc) {\n\t\t\t\t\tthrow new SeamError('INTERNAL_ERROR', `Procedure '${procedure}' not found`)\n\t\t\t\t}\n\t\t\t\tif (shouldValidateInput) {\n\t\t\t\t\tconst v = validateInput(proc.inputSchema, input)\n\t\t\t\t\tif (!v.valid) {\n\t\t\t\t\t\tconst summary = formatValidationErrors(v.errors)\n\t\t\t\t\t\tthrow new SeamError('VALIDATION_ERROR', `Input validation failed: ${summary}`)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst ctx = ctxResolver ? ctxResolver(proc) : {}\n\t\t\t\tconst result = await proc.handler({ input, ctx, state: appState })\n\t\t\t\treturn { key, result, procedure, input }\n\t\t\t} catch (err) {\n\t\t\t\tconst code = err instanceof SeamError ? err.code : 'INTERNAL_ERROR'\n\t\t\t\tconst message = err instanceof Error ? err.message : 'Unknown error'\n\t\t\t\tconsole.error(`[seam] Loader \"${key}\" failed:`, err)\n\t\t\t\tconst marker: LoaderError = { __error: true, code, message }\n\t\t\t\treturn { key, result: marker as unknown, procedure, input, error: true as const }\n\t\t\t}\n\t\t}),\n\t)\n\treturn {\n\t\tdata: Object.fromEntries(results.map((r) => [r.key, r.result])),\n\t\tmeta: Object.fromEntries(\n\t\t\tresults.map((r) => {\n\t\t\t\tconst entry: { procedure: string; input: unknown; error?: true } = {\n\t\t\t\t\tprocedure: r.procedure,\n\t\t\t\t\tinput: r.input,\n\t\t\t\t}\n\t\t\t\tif (r.error) entry.error = true\n\t\t\t\treturn [r.key, entry]\n\t\t\t}),\n\t\t),\n\t}\n}\n\n/** Select the template for a given locale, falling back to the default template */\nfunction selectTemplate(\n\tdefaultTemplate: string,\n\tlocaleTemplates: Record<string, string> | undefined,\n\tlocale: string | undefined,\n): string {\n\tif (locale && localeTemplates) {\n\t\treturn localeTemplates[locale] ?? defaultTemplate\n\t}\n\treturn defaultTemplate\n}\n\n/** Look up pre-resolved messages for a route + locale. Zero merge, zero filter. */\nfunction lookupMessages(\n\tconfig: I18nConfig,\n\troutePattern: string,\n\tlocale: string,\n): Record<string, string> {\n\tconst routeHash = config.routeHashes[routePattern]\n\tif (!routeHash) return {}\n\n\tif (config.mode === 'paged' && config.distDir) {\n\t\tconst filePath = join(config.distDir, 'i18n', routeHash, `${locale}.json`)\n\t\tif (existsSync(filePath)) {\n\t\t\treturn JSON.parse(readFileSync(filePath, 'utf-8')) as Record<string, string>\n\t\t}\n\t\treturn {}\n\t}\n\n\treturn config.messages[locale]?.[routeHash] ?? {}\n}\n\n/** Build JSON payload for engine i18n injection */\nfunction buildI18nPayload(opts: I18nOpts): string {\n\tconst { config: i18nConfig, routePattern, locale } = opts\n\tconst messages = lookupMessages(i18nConfig, routePattern, locale)\n\tconst routeHash = i18nConfig.routeHashes[routePattern]\n\tconst i18nData: Record<string, unknown> = {\n\t\tlocale,\n\t\tdefault_locale: i18nConfig.default,\n\t\tmessages,\n\t}\n\tif (i18nConfig.cache && routeHash) {\n\t\ti18nData.hash = i18nConfig.contentHashes[routeHash]?.[locale]\n\t\ti18nData.router = i18nConfig.contentHashes\n\t}\n\treturn JSON.stringify(i18nData)\n}\n\nexport async function handlePageRequest(\n\tpage: PageDef,\n\tparams: Record<string, string>,\n\tprocedures: Map<string, InternalProcedure>,\n\ti18nOpts?: I18nOpts,\n\tsearchParams?: URLSearchParams,\n\tctxResolver?: (proc: InternalProcedure) => Record<string, unknown>,\n\tappState?: unknown,\n\tshouldValidateInput?: boolean,\n): Promise<HandlePageResult> {\n\ttry {\n\t\tconst t0 = performance.now()\n\t\tconst layoutChain = page.layoutChain ?? []\n\t\tconst locale = i18nOpts?.locale\n\n\t\t// Execute all loaders (layout chain + page) in parallel\n\t\tconst loaderResults = await Promise.all([\n\t\t\t...layoutChain.map((layout) =>\n\t\t\t\texecuteLoaders(\n\t\t\t\t\tlayout.loaders,\n\t\t\t\t\tparams,\n\t\t\t\t\tprocedures,\n\t\t\t\t\tsearchParams,\n\t\t\t\t\tctxResolver,\n\t\t\t\t\tappState,\n\t\t\t\t\tshouldValidateInput,\n\t\t\t\t),\n\t\t\t),\n\t\t\texecuteLoaders(\n\t\t\t\tpage.loaders,\n\t\t\t\tparams,\n\t\t\t\tprocedures,\n\t\t\t\tsearchParams,\n\t\t\t\tctxResolver,\n\t\t\t\tappState,\n\t\t\t\tshouldValidateInput,\n\t\t\t),\n\t\t])\n\n\t\tconst t1 = performance.now()\n\n\t\t// Merge all loader data and metadata into single objects\n\t\tconst allData: Record<string, unknown> = {}\n\t\tconst allMeta: Record<string, { procedure: string; input: unknown; error?: true }> = {}\n\t\tfor (const { data, meta } of loaderResults) {\n\t\t\tObject.assign(allData, data)\n\t\t\tObject.assign(allMeta, meta)\n\t\t}\n\n\t\t// Prune to projected fields before template injection\n\t\tconst prunedData = applyProjection(allData, page.projections)\n\n\t\t// Compose template: nest page inside layouts via outlet substitution\n\t\tconst pageTemplate = selectTemplate(page.template, page.localeTemplates, locale)\n\t\tlet composedTemplate = pageTemplate\n\t\tfor (let i = layoutChain.length - 1; i >= 0; i--) {\n\t\t\tconst layout = layoutChain[i] as LayoutDef\n\t\t\tconst layoutTemplate = selectTemplate(layout.template, layout.localeTemplates, locale)\n\t\t\tcomposedTemplate = layoutTemplate.replace('<!--seam:outlet-->', composedTemplate)\n\t\t}\n\n\t\t// Resolve head metadata from headFn (overrides manifest head_meta)\n\t\tlet resolvedHeadMeta = page.headMeta\n\t\tif (page.headFn) {\n\t\t\ttry {\n\t\t\t\tconst headConfig = page.headFn(allData)\n\t\t\t\tresolvedHeadMeta = headConfigToHtml(headConfig)\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error('[seam] head function failed:', err)\n\t\t\t}\n\t\t}\n\n\t\t// Build PageConfig for engine\n\t\tconst config: Record<string, unknown> = {\n\t\t\tlayout_chain: layoutChain.map((l) => ({\n\t\t\t\tid: l.id,\n\t\t\t\tloader_keys: Object.keys(l.loaders),\n\t\t\t})),\n\t\t\tdata_id: page.dataId ?? '__data',\n\t\t\thead_meta: resolvedHeadMeta,\n\t\t\tloader_metadata: allMeta,\n\t\t}\n\t\tif (page.pageAssets) {\n\t\t\tconfig.page_assets = page.pageAssets\n\t\t}\n\n\t\tconst i18nOptsJson = i18nOpts ? buildI18nPayload(i18nOpts) : undefined\n\n\t\t// Single WASM call: inject slots, compose data script, apply locale/meta\n\t\tconst html = renderPage(\n\t\t\tcomposedTemplate,\n\t\t\tJSON.stringify(prunedData),\n\t\t\tJSON.stringify(config),\n\t\t\ti18nOptsJson,\n\t\t)\n\n\t\tconst t2 = performance.now()\n\n\t\treturn {\n\t\t\tstatus: 200,\n\t\t\thtml,\n\t\t\ttiming: { dataFetch: t1 - t0, inject: t2 - t1 },\n\t\t}\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : 'Unknown error'\n\t\treturn {\n\t\t\tstatus: 500,\n\t\t\thtml: `<!DOCTYPE html><html><body><h1>500 Internal Server Error</h1><p>${escapeHtml(message)}</p></body></html>`,\n\t\t\ttiming: { dataFetch: 0, inject: 0 },\n\t\t}\n\t}\n}\n","/* src/server/core/typescript/src/resolve.ts */\n\n// -- New strategy-based API --\n\nexport interface ResolveStrategy {\n\treadonly kind: string\n\tresolve(data: ResolveData): string | null\n}\n\nexport interface ResolveData {\n\treadonly url: string\n\treadonly pathLocale: string | null\n\treadonly cookie: string | undefined\n\treadonly acceptLanguage: string | undefined\n\treadonly locales: string[]\n\treadonly defaultLocale: string\n}\n\n/** URL prefix strategy: trusts pathLocale if it is a known locale */\nexport function fromUrlPrefix(): ResolveStrategy {\n\treturn {\n\t\tkind: 'url_prefix',\n\t\tresolve(data) {\n\t\t\tif (data.pathLocale && data.locales.includes(data.pathLocale)) {\n\t\t\t\treturn data.pathLocale\n\t\t\t}\n\t\t\treturn null\n\t\t},\n\t}\n}\n\n/** Cookie strategy: reads a named cookie and validates against known locales */\nexport function fromCookie(name = 'seam-locale'): ResolveStrategy {\n\treturn {\n\t\tkind: 'cookie',\n\t\tresolve(data) {\n\t\t\tif (!data.cookie) return null\n\t\t\tfor (const pair of data.cookie.split(';')) {\n\t\t\t\tconst parts = pair.trim().split('=')\n\t\t\t\tconst k = parts[0]\n\t\t\t\tconst v = parts[1]\n\t\t\t\tif (k === name && v && data.locales.includes(v)) return v\n\t\t\t}\n\t\t\treturn null\n\t\t},\n\t}\n}\n\n/** Accept-Language strategy: parses header with q-value sorting + prefix match */\nexport function fromAcceptLanguage(): ResolveStrategy {\n\treturn {\n\t\tkind: 'accept_language',\n\t\tresolve(data) {\n\t\t\tif (!data.acceptLanguage) return null\n\t\t\tconst entries: { lang: string; q: number }[] = []\n\t\t\tfor (const part of data.acceptLanguage.split(',')) {\n\t\t\t\tconst trimmed = part.trim()\n\t\t\t\tconst parts = trimmed.split(';')\n\t\t\t\tconst lang = parts[0] as string\n\t\t\t\tlet q = 1\n\t\t\t\tfor (let j = 1; j < parts.length; j++) {\n\t\t\t\t\tconst match = (parts[j] as string).trim().match(/^q=(\\d+(?:\\.\\d+)?)$/)\n\t\t\t\t\tif (match) q = parseFloat(match[1] as string)\n\t\t\t\t}\n\t\t\t\tentries.push({ lang: lang.trim(), q })\n\t\t\t}\n\t\t\tentries.sort((a, b) => b.q - a.q)\n\t\t\tconst localeSet = new Set(data.locales)\n\t\t\tfor (const { lang } of entries) {\n\t\t\t\tif (localeSet.has(lang)) return lang\n\t\t\t\t// Prefix match: zh-CN -> zh\n\t\t\t\tconst prefix = lang.split('-')[0] as string\n\t\t\t\tif (prefix !== lang && localeSet.has(prefix)) return prefix\n\t\t\t}\n\t\t\treturn null\n\t\t},\n\t}\n}\n\n/** URL query strategy: reads a query parameter and validates against known locales */\nexport function fromUrlQuery(param = 'lang'): ResolveStrategy {\n\treturn {\n\t\tkind: 'url_query',\n\t\tresolve(data) {\n\t\t\tif (!data.url) return null\n\t\t\ttry {\n\t\t\t\tconst url = new URL(data.url, 'http://localhost')\n\t\t\t\tconst value = url.searchParams.get(param)\n\t\t\t\tif (value && data.locales.includes(value)) return value\n\t\t\t} catch {\n\t\t\t\t// Invalid URL — skip\n\t\t\t}\n\t\t\treturn null\n\t\t},\n\t}\n}\n\n/** Run strategies in order; first non-null wins, otherwise defaultLocale */\nexport function resolveChain(strategies: ResolveStrategy[], data: ResolveData): string {\n\tfor (const s of strategies) {\n\t\tconst result = s.resolve(data)\n\t\tif (result !== null) return result\n\t}\n\treturn data.defaultLocale\n}\n\n/** Default strategy chain: url_prefix -> cookie -> accept_language */\nexport function defaultStrategies(): ResolveStrategy[] {\n\treturn [fromUrlPrefix(), fromCookie(), fromAcceptLanguage()]\n}\n","/* src/server/core/typescript/src/router/helpers.ts */\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { HandleResult, InternalProcedure } from './handler.js'\nimport type { HandlePageResult } from '../page/handler.js'\nimport type { PageDef, I18nConfig } from '../page/index.js'\nimport type { ChannelResult, ChannelMeta } from '../channel.js'\nimport type { ContextConfig, RawContextMap } from '../context.js'\nimport { resolveContext } from '../context.js'\nimport { SeamError } from '../errors.js'\nimport { handlePageRequest } from '../page/handler.js'\nimport { defaultStrategies, resolveChain } from '../resolve.js'\nimport type { ResolveStrategy } from '../resolve.js'\nimport type { ValidationMode, RouterOptions, PageRequestHeaders } from './index.js'\n\n/** Resolve a ValidationMode to a boolean flag */\nexport function resolveValidationMode(mode: ValidationMode | undefined): boolean {\n\tconst m = mode ?? 'dev'\n\tif (m === 'always') return true\n\tif (m === 'never') return false\n\treturn typeof process !== 'undefined' && process.env.NODE_ENV !== 'production'\n}\n\n/** Build the resolve strategy list from options */\nexport function buildStrategies<TState = undefined>(\n\topts?: RouterOptions<TState>,\n): {\n\tstrategies: ResolveStrategy[]\n\thasUrlPrefix: boolean\n} {\n\tconst strategies = opts?.resolve ?? defaultStrategies()\n\treturn {\n\t\tstrategies,\n\t\thasUrlPrefix: strategies.some((s) => s.kind === 'url_prefix'),\n\t}\n}\n\n/** Register built-in seam.i18n.query procedure (route-hash-based lookup) */\nexport function registerI18nQuery(\n\tprocedureMap: Map<string, InternalProcedure>,\n\tconfig: I18nConfig,\n): void {\n\tconst localeSet = new Set(config.locales)\n\tprocedureMap.set('seam.i18n.query', {\n\t\tinputSchema: {},\n\t\toutputSchema: {},\n\t\tcontextKeys: [],\n\t\thandler: ({ input }) => {\n\t\t\tconst { route, locale: rawLocale } = input as { route: string; locale: string }\n\t\t\tconst locale = localeSet.has(rawLocale) ? rawLocale : config.default\n\t\t\tconst messages = lookupI18nMessages(config, route, locale)\n\t\t\tconst hash = config.contentHashes[route]?.[locale] ?? ''\n\t\t\treturn { hash, messages }\n\t\t},\n\t})\n}\n\n/** Look up messages by route hash + locale for RPC query */\nfunction lookupI18nMessages(\n\tconfig: I18nConfig,\n\trouteHash: string,\n\tlocale: string,\n): Record<string, string> {\n\tif (config.mode === 'paged' && config.distDir) {\n\t\tconst filePath = join(config.distDir, 'i18n', routeHash, `${locale}.json`)\n\t\tif (existsSync(filePath)) {\n\t\t\treturn JSON.parse(readFileSync(filePath, 'utf-8')) as Record<string, string>\n\t\t}\n\t\treturn {}\n\t}\n\treturn config.messages[locale]?.[routeHash] ?? {}\n}\n\n/** Collect channel metadata from channel results for manifest */\nexport function collectChannelMeta(\n\tchannels: ChannelResult[] | undefined,\n): Record<string, ChannelMeta> | undefined {\n\tif (!channels || channels.length === 0) return undefined\n\treturn Object.fromEntries(\n\t\tchannels.map((ch) => {\n\t\t\tconst firstKey = Object.keys(ch.procedures)[0] ?? ''\n\t\t\tconst name = firstKey.includes('.') ? firstKey.slice(0, firstKey.indexOf('.')) : firstKey\n\t\t\treturn [name, ch.channelMeta]\n\t\t}),\n\t)\n}\n\n/** Resolve context for a procedure, returning undefined if no context needed */\nexport function resolveCtxFor(\n\tmap: Map<string, { contextKeys: string[] }>,\n\tname: string,\n\trawCtx: RawContextMap | undefined,\n\tctxConfig: ContextConfig,\n): Record<string, unknown> | undefined {\n\tif (!rawCtx) return undefined\n\tconst proc = map.get(name)\n\tif (!proc || proc.contextKeys.length === 0) return undefined\n\treturn resolveContext(ctxConfig, rawCtx, proc.contextKeys)\n}\n\n/** Resolve locale and match page route */\nexport async function matchAndHandlePage(\n\tpageMatcher: {\n\t\tmatch(path: string): { value: PageDef; params: Record<string, string>; pattern: string } | null\n\t},\n\tprocedureMap: Map<string, InternalProcedure>,\n\ti18nConfig: I18nConfig | null,\n\tstrategies: ResolveStrategy[],\n\thasUrlPrefix: boolean,\n\tpath: string,\n\theaders?: PageRequestHeaders,\n\trawCtx?: RawContextMap,\n\tctxConfig?: ContextConfig,\n\tappState?: unknown,\n\tshouldValidateInput?: boolean,\n): Promise<HandlePageResult | null> {\n\tlet pathLocale: string | null = null\n\tlet routePath = path\n\n\tif (hasUrlPrefix && i18nConfig) {\n\t\tconst segments = path.split('/').filter(Boolean)\n\t\tconst localeSet = new Set(i18nConfig.locales)\n\t\tconst first = segments[0]\n\t\tif (first && localeSet.has(first)) {\n\t\t\tpathLocale = first\n\t\t\troutePath = '/' + segments.slice(1).join('/') || '/'\n\t\t}\n\t}\n\n\tlet locale: string | undefined\n\tif (i18nConfig) {\n\t\tlocale = resolveChain(strategies, {\n\t\t\turl: headers?.url ?? '',\n\t\t\tpathLocale,\n\t\t\tcookie: headers?.cookie,\n\t\t\tacceptLanguage: headers?.acceptLanguage,\n\t\t\tlocales: i18nConfig.locales,\n\t\t\tdefaultLocale: i18nConfig.default,\n\t\t})\n\t}\n\n\tconst match = pageMatcher.match(routePath)\n\tif (!match) return null\n\n\t// SSG short-circuit: serve pre-rendered HTML without loader execution\n\tif (match.value.prerender && match.value.staticDir) {\n\t\tconst htmlPath = join(match.value.staticDir, routePath === '/' ? '' : routePath, 'index.html')\n\t\ttry {\n\t\t\tconst html = readFileSync(htmlPath, 'utf-8')\n\t\t\treturn { status: 200, html }\n\t\t} catch {\n\t\t\t// Fall through to dynamic rendering (graceful degradation)\n\t\t}\n\t}\n\n\tlet searchParams: URLSearchParams | undefined\n\tif (headers?.url) {\n\t\ttry {\n\t\t\tconst url = new URL(headers.url, 'http://localhost')\n\t\t\tif (url.search) searchParams = url.searchParams\n\t\t} catch {\n\t\t\t// Malformed URL — ignore\n\t\t}\n\t}\n\n\tconst i18nOpts =\n\t\tlocale && i18nConfig ? { locale, config: i18nConfig, routePattern: match.pattern } : undefined\n\n\tconst ctxResolver = rawCtx\n\t\t? (proc: { contextKeys: string[] }) => {\n\t\t\t\tif (proc.contextKeys.length === 0) return {}\n\t\t\t\treturn resolveContext(ctxConfig ?? {}, rawCtx, proc.contextKeys)\n\t\t\t}\n\t\t: undefined\n\n\treturn handlePageRequest(\n\t\tmatch.value,\n\t\tmatch.params,\n\t\tprocedureMap,\n\t\ti18nOpts,\n\t\tsearchParams,\n\t\tctxResolver,\n\t\tappState,\n\t\tshouldValidateInput,\n\t)\n}\n\n/** Catch context resolution errors and return them as HandleResult */\nexport function resolveCtxSafe(\n\tmap: Map<string, { contextKeys: string[] }>,\n\tname: string,\n\trawCtx: RawContextMap | undefined,\n\tctxConfig: ContextConfig,\n): { ctx?: Record<string, unknown>; error?: HandleResult } {\n\ttry {\n\t\treturn { ctx: resolveCtxFor(map, name, rawCtx, ctxConfig) }\n\t} catch (err) {\n\t\tif (err instanceof SeamError) {\n\t\t\treturn { error: { status: err.status, body: err.toJSON() } }\n\t\t}\n\t\tthrow err\n\t}\n}\n","/* src/server/core/typescript/src/router/state.ts */\n\nimport { readFileSync, existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { contextHasExtracts } from '../context.js'\nimport { buildManifest } from '../manifest/index.js'\nimport type { PageDef } from '../page/index.js'\nimport { RouteMatcher } from '../page/route-matcher.js'\nimport {\n\thandleRequest,\n\thandleSubscription,\n\thandleStream,\n\thandleBatchRequest,\n\thandleUploadRequest,\n} from './handler.js'\nimport { categorizeProcedures } from './categorize.js'\nimport {\n\tresolveValidationMode,\n\tbuildStrategies,\n\tregisterI18nQuery,\n\tcollectChannelMeta,\n\tresolveCtxFor,\n\tresolveCtxSafe,\n\tmatchAndHandlePage,\n} from './helpers.js'\nimport type { BuildOutput } from '../page/build-loader.js'\nimport type { DefinitionMap, RouterOptions, Router } from './index.js'\n\n/** Build all shared state that createRouter methods close over */\nexport function initRouterState<TState = undefined>(\n\tprocedures: DefinitionMap,\n\topts?: RouterOptions<TState>,\n) {\n\tconst ctxConfig = opts?.context ?? {}\n\tconst { procedureMap, subscriptionMap, streamMap, uploadMap, kindMap } = categorizeProcedures(\n\t\tprocedures,\n\t\tObject.keys(ctxConfig).length > 0 ? ctxConfig : undefined,\n\t)\n\tconst shouldValidateInput = resolveValidationMode(opts?.validation?.input)\n\tconst shouldValidateOutput =\n\t\topts?.validateOutput ??\n\t\t(typeof process !== 'undefined' && process.env.NODE_ENV !== 'production')\n\tconst pageMatcher = new RouteMatcher<PageDef>()\n\tconst pages = opts?.pages\n\tif (pages) {\n\t\tfor (const [pattern, page] of Object.entries(pages)) {\n\t\t\tpageMatcher.add(pattern, page)\n\t\t}\n\t}\n\tconst i18nConfig = opts?.i18n ?? null\n\tconst { strategies, hasUrlPrefix } = buildStrategies(opts)\n\tif (i18nConfig) registerI18nQuery(procedureMap, i18nConfig)\n\tconst channelsMeta = collectChannelMeta(opts?.channels)\n\tconst hasCtx = contextHasExtracts(ctxConfig)\n\treturn {\n\t\tctxConfig,\n\t\tprocedureMap,\n\t\tsubscriptionMap,\n\t\tstreamMap,\n\t\tuploadMap,\n\t\tkindMap,\n\t\tshouldValidateInput,\n\t\tshouldValidateOutput,\n\t\tpageMatcher,\n\t\tpages,\n\t\ti18nConfig,\n\t\tstrategies,\n\t\thasUrlPrefix,\n\t\tchannelsMeta,\n\t\thasCtx,\n\t\tappState: opts?.state,\n\t\trpcHashMap: opts?.rpcHashMap,\n\t\tpublicDir: opts?.publicDir,\n\t}\n}\n\n/** Build request-response methods: handle, handleBatch, handleUpload */\nfunction buildRpcMethods<TState = undefined>(\n\tstate: ReturnType<typeof initRouterState<TState>>,\n): Pick<Router<DefinitionMap>, 'handle' | 'handleBatch' | 'handleUpload'> {\n\treturn {\n\t\tasync handle(procedureName, body, rawCtx) {\n\t\t\tconst { ctx, error } = resolveCtxSafe(\n\t\t\t\tstate.procedureMap,\n\t\t\t\tprocedureName,\n\t\t\t\trawCtx,\n\t\t\t\tstate.ctxConfig,\n\t\t\t)\n\t\t\tif (error) return error\n\t\t\treturn handleRequest(\n\t\t\t\tstate.procedureMap,\n\t\t\t\tprocedureName,\n\t\t\t\tbody,\n\t\t\t\tstate.shouldValidateInput,\n\t\t\t\tstate.shouldValidateOutput,\n\t\t\t\tctx,\n\t\t\t\tstate.appState,\n\t\t\t)\n\t\t},\n\t\thandleBatch(calls, rawCtx) {\n\t\t\tconst ctxResolver = rawCtx\n\t\t\t\t? (name: string) => resolveCtxFor(state.procedureMap, name, rawCtx, state.ctxConfig) ?? {}\n\t\t\t\t: undefined\n\t\t\treturn handleBatchRequest(\n\t\t\t\tstate.procedureMap,\n\t\t\t\tcalls,\n\t\t\t\tstate.shouldValidateInput,\n\t\t\t\tstate.shouldValidateOutput,\n\t\t\t\tctxResolver,\n\t\t\t\tstate.appState,\n\t\t\t)\n\t\t},\n\t\tasync handleUpload(name, body, file, rawCtx) {\n\t\t\tconst { ctx, error } = resolveCtxSafe(state.uploadMap, name, rawCtx, state.ctxConfig)\n\t\t\tif (error) return error\n\t\t\treturn handleUploadRequest(\n\t\t\t\tstate.uploadMap,\n\t\t\t\tname,\n\t\t\t\tbody,\n\t\t\t\tfile,\n\t\t\t\tstate.shouldValidateInput,\n\t\t\t\tstate.shouldValidateOutput,\n\t\t\t\tctx,\n\t\t\t\tstate.appState,\n\t\t\t)\n\t\t},\n\t}\n}\n\n/** Build all Router method implementations from shared state */\nexport function buildRouterMethods<TState = undefined>(\n\tstate: ReturnType<typeof initRouterState<TState>>,\n\tprocedures: DefinitionMap,\n\topts?: RouterOptions<TState>,\n): Omit<Router<DefinitionMap>, 'procedures' | 'rpcHashMap' | 'publicDir' | 'hasPages'> {\n\treturn {\n\t\tctxConfig: state.ctxConfig,\n\t\thasContext() {\n\t\t\treturn state.hasCtx\n\t\t},\n\t\tmanifest() {\n\t\t\treturn buildManifest(procedures, state.channelsMeta, state.ctxConfig, opts?.transportDefaults)\n\t\t},\n\t\t...buildRpcMethods(state),\n\t\thandleSubscription(name, input, rawCtx, lastEventId) {\n\t\t\tconst ctx = resolveCtxFor(state.subscriptionMap, name, rawCtx, state.ctxConfig)\n\t\t\treturn handleSubscription(\n\t\t\t\tstate.subscriptionMap,\n\t\t\t\tname,\n\t\t\t\tinput,\n\t\t\t\tstate.shouldValidateInput,\n\t\t\t\tstate.shouldValidateOutput,\n\t\t\t\tctx,\n\t\t\t\tstate.appState,\n\t\t\t\tlastEventId,\n\t\t\t)\n\t\t},\n\t\thandleStream(name, input, rawCtx) {\n\t\t\tconst ctx = resolveCtxFor(state.streamMap, name, rawCtx, state.ctxConfig)\n\t\t\treturn handleStream(\n\t\t\t\tstate.streamMap,\n\t\t\t\tname,\n\t\t\t\tinput,\n\t\t\t\tstate.shouldValidateInput,\n\t\t\t\tstate.shouldValidateOutput,\n\t\t\t\tctx,\n\t\t\t\tstate.appState,\n\t\t\t)\n\t\t},\n\t\tgetKind(name) {\n\t\t\treturn state.kindMap.get(name) ?? null\n\t\t},\n\t\thandlePage(path, headers, rawCtx) {\n\t\t\treturn matchAndHandlePage(\n\t\t\t\tstate.pageMatcher,\n\t\t\t\tstate.procedureMap,\n\t\t\t\tstate.i18nConfig,\n\t\t\t\tstate.strategies,\n\t\t\t\tstate.hasUrlPrefix,\n\t\t\t\tpath,\n\t\t\t\theaders,\n\t\t\t\trawCtx,\n\t\t\t\tstate.ctxConfig,\n\t\t\t\tstate.appState,\n\t\t\t\tstate.shouldValidateInput,\n\t\t\t)\n\t\t},\n\t\treload(build: BuildOutput) {\n\t\t\tstate.pageMatcher.clear()\n\t\t\tfor (const [pattern, page] of Object.entries(build.pages)) {\n\t\t\t\tstate.pageMatcher.add(pattern, page)\n\t\t\t}\n\t\t\tstate.pages = build.pages\n\t\t\tstate.i18nConfig = build.i18n ?? null\n\t\t\tif (state.i18nConfig) registerI18nQuery(state.procedureMap, state.i18nConfig)\n\t\t\tstate.rpcHashMap = build.rpcHashMap\n\t\t\tstate.publicDir = build.publicDir\n\t\t},\n\t\thandlePageData(path) {\n\t\t\tconst match = state.pageMatcher?.match(path)\n\t\t\tif (!match) return Promise.resolve(null)\n\t\t\tconst page = match.value\n\t\t\tif (!page.prerender || !page.staticDir) return Promise.resolve(null)\n\t\t\tconst dataPath = join(page.staticDir, path === '/' ? '' : path, '__data.json')\n\t\t\ttry {\n\t\t\t\tif (!existsSync(dataPath)) return Promise.resolve(null)\n\t\t\t\treturn Promise.resolve(JSON.parse(readFileSync(dataPath, 'utf-8')) as unknown)\n\t\t\t} catch {\n\t\t\t\treturn Promise.resolve(null)\n\t\t\t}\n\t\t},\n\t}\n}\n","/* src/server/core/typescript/src/router/index.ts */\n\nimport type { RpcHashMap } from '../http.js'\nimport type { SchemaNode } from '../types/schema.js'\nimport type { ProcedureManifest } from '../manifest/index.js'\nimport type { HandleResult } from './handler.js'\nimport type { SeamFileHandle } from '../procedure.js'\nimport type { HandlePageResult } from '../page/handler.js'\nimport type { PageDef, I18nConfig } from '../page/index.js'\nimport type { ChannelResult } from '../channel.js'\nimport type { ContextConfig, RawContextMap } from '../context.js'\nimport type { ResolveStrategy } from '../resolve.js'\nimport type { BatchCall, BatchResultItem } from './handler.js'\nimport type { BuildOutput } from '../page/build-loader.js'\nimport { initRouterState, buildRouterMethods } from './state.js'\n\nexport type ProcedureKind = 'query' | 'command' | 'subscription' | 'stream' | 'upload'\n\nexport type ValidationMode = 'dev' | 'always' | 'never'\n\nexport interface ValidationConfig {\n\tinput?: ValidationMode\n}\n\nexport type MappingValue = string | { from: string; each?: boolean }\n\nexport type InvalidateTarget =\n\t| string\n\t| {\n\t\t\tquery: string\n\t\t\tmapping?: Record<string, MappingValue>\n\t }\n\nexport type TransportPreference = 'http' | 'sse' | 'ws' | 'ipc'\n\nexport interface TransportConfig {\n\tprefer: TransportPreference\n\tfallback?: TransportPreference[]\n}\n\nexport type CacheConfig = false | { ttl: number }\n\n/** @deprecated Use QueryDef instead */\nexport interface ProcedureDef<TIn = unknown, TOut = unknown, TState = undefined> {\n\tkind?: 'query'\n\t/** @deprecated Use `kind` instead */\n\ttype?: 'query'\n\tinput: SchemaNode<TIn>\n\toutput: SchemaNode<TOut>\n\terror?: SchemaNode\n\tcontext?: string[]\n\ttransport?: TransportConfig\n\tsuppress?: string[]\n\tcache?: CacheConfig\n\thandler: (params: {\n\t\tinput: TIn\n\t\tctx: Record<string, unknown>\n\t\tstate: TState\n\t}) => TOut | Promise<TOut>\n}\n\nexport type QueryDef<TIn = unknown, TOut = unknown, TState = undefined> = ProcedureDef<\n\tTIn,\n\tTOut,\n\tTState\n>\n\nexport interface CommandDef<TIn = unknown, TOut = unknown, TState = undefined> {\n\tkind?: 'command'\n\t/** @deprecated Use `kind` instead */\n\ttype?: 'command'\n\tinput: SchemaNode<TIn>\n\toutput: SchemaNode<TOut>\n\terror?: SchemaNode\n\tcontext?: string[]\n\tinvalidates?: InvalidateTarget[]\n\ttransport?: TransportConfig\n\tsuppress?: string[]\n\thandler: (params: {\n\t\tinput: TIn\n\t\tctx: Record<string, unknown>\n\t\tstate: TState\n\t}) => TOut | Promise<TOut>\n}\n\nexport interface SubscriptionDef<TIn = unknown, TOut = unknown, TState = undefined> {\n\tkind?: 'subscription'\n\t/** @deprecated Use `kind` instead */\n\ttype?: 'subscription'\n\tinput: SchemaNode<TIn>\n\toutput: SchemaNode<TOut>\n\terror?: SchemaNode\n\tcontext?: string[]\n\ttransport?: TransportConfig\n\tsuppress?: string[]\n\thandler: (params: {\n\t\tinput: TIn\n\t\tctx: Record<string, unknown>\n\t\tstate: TState\n\t\tlastEventId?: string\n\t}) => AsyncIterable<TOut>\n}\n\nexport interface StreamDef<TIn = unknown, TChunk = unknown, TState = undefined> {\n\tkind: 'stream'\n\tinput: SchemaNode<TIn>\n\toutput: SchemaNode<TChunk>\n\terror?: SchemaNode\n\tcontext?: string[]\n\ttransport?: TransportConfig\n\tsuppress?: string[]\n\thandler: (params: {\n\t\tinput: TIn\n\t\tctx: Record<string, unknown>\n\t\tstate: TState\n\t}) => AsyncGenerator<TChunk>\n}\n\nexport interface UploadDef<TIn = unknown, TOut = unknown, TState = undefined> {\n\tkind: 'upload'\n\tinput: SchemaNode<TIn>\n\toutput: SchemaNode<TOut>\n\terror?: SchemaNode\n\tcontext?: string[]\n\ttransport?: TransportConfig\n\tsuppress?: string[]\n\thandler: (params: {\n\t\tinput: TIn\n\t\tfile: SeamFileHandle\n\t\tctx: Record<string, unknown>\n\t\tstate: TState\n\t}) => TOut | Promise<TOut>\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport type DefinitionMap = Record<\n\tstring,\n\t| QueryDef<any, any, any>\n\t| CommandDef<any, any, any>\n\t| SubscriptionDef<any, any, any>\n\t| StreamDef<any, any, any>\n\t| UploadDef<any, any, any>\n>\n\ntype NestedDefinitionValue =\n\t| QueryDef<any, any, any>\n\t| CommandDef<any, any, any>\n\t| SubscriptionDef<any, any, any>\n\t| StreamDef<any, any, any>\n\t| UploadDef<any, any, any>\n\t| { [key: string]: NestedDefinitionValue }\n\nexport type NestedDefinitionMap = Record<string, NestedDefinitionValue>\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\nfunction isProcedureDef(value: unknown): value is DefinitionMap[string] {\n\treturn typeof value === 'object' && value !== null && 'input' in value && 'handler' in value\n}\n\nfunction flattenDefinitions(nested: NestedDefinitionMap, prefix = ''): DefinitionMap {\n\tconst flat: DefinitionMap = {}\n\tfor (const [key, value] of Object.entries(nested)) {\n\t\tconst fullKey = prefix ? `${prefix}.${key}` : key\n\t\tif (isProcedureDef(value)) {\n\t\t\tflat[fullKey] = value\n\t\t} else {\n\t\t\tObject.assign(flat, flattenDefinitions(value as NestedDefinitionMap, fullKey))\n\t\t}\n\t}\n\treturn flat\n}\n\nexport interface RouterOptions<TState = undefined> {\n\tpages?: Record<string, PageDef>\n\trpcHashMap?: RpcHashMap\n\ti18n?: I18nConfig | null\n\tpublicDir?: string\n\tvalidateOutput?: boolean\n\tvalidation?: ValidationConfig\n\tresolve?: ResolveStrategy[]\n\tchannels?: ChannelResult[]\n\tcontext?: ContextConfig\n\tstate?: TState\n\ttransportDefaults?: Partial<Record<ProcedureKind, TransportConfig>>\n}\n\nexport interface PageRequestHeaders {\n\turl?: string\n\tcookie?: string\n\tacceptLanguage?: string\n}\n\nexport interface Router<T extends DefinitionMap> {\n\tmanifest(): ProcedureManifest\n\thandle(procedureName: string, body: unknown, rawCtx?: RawContextMap): Promise<HandleResult>\n\thandleBatch(calls: BatchCall[], rawCtx?: RawContextMap): Promise<{ results: BatchResultItem[] }>\n\thandleSubscription(\n\t\tname: string,\n\t\tinput: unknown,\n\t\trawCtx?: RawContextMap,\n\t\tlastEventId?: string,\n\t): AsyncIterable<unknown>\n\thandleStream(name: string, input: unknown, rawCtx?: RawContextMap): AsyncGenerator<unknown>\n\thandleUpload(\n\t\tname: string,\n\t\tbody: unknown,\n\t\tfile: SeamFileHandle,\n\t\trawCtx?: RawContextMap,\n\t): Promise<HandleResult>\n\tgetKind(name: string): ProcedureKind | null\n\thandlePage(\n\t\tpath: string,\n\t\theaders?: PageRequestHeaders,\n\t\trawCtx?: RawContextMap,\n\t): Promise<HandlePageResult | null>\n\t/** Serve __data.json for a prerendered page (SPA navigation) */\n\thandlePageData(path: string): Promise<unknown>\n\thasContext(): boolean\n\treadonly ctxConfig: ContextConfig\n\treadonly hasPages: boolean\n\treadonly rpcHashMap: RpcHashMap | undefined\n\treadonly publicDir: string | undefined\n\t/** Atomically replace pages, i18n, and rpcHashMap from a fresh build (dev-mode hot-reload) */\n\treload(build: BuildOutput): void\n\t/** Exposed for adapter access to the definitions */\n\treadonly procedures: T\n}\n\nexport function createRouter<TState = undefined, T extends DefinitionMap = DefinitionMap>(\n\tprocedures: T | NestedDefinitionMap,\n\topts?: RouterOptions<TState>,\n): Router<T> {\n\tconst flat = flattenDefinitions(procedures as NestedDefinitionMap) as T\n\tconst state = initRouterState(flat, opts)\n\tconst methods = buildRouterMethods(state, flat, opts)\n\tconst router = { procedures: flat, ...methods } as Router<T>\n\tObject.defineProperty(router, 'hasPages', {\n\t\tget: () => state.pageMatcher.size > 0,\n\t\tenumerable: true,\n\t\tconfigurable: true,\n\t})\n\tObject.defineProperty(router, 'rpcHashMap', {\n\t\tget: () => state.rpcHashMap,\n\t\tenumerable: true,\n\t\tconfigurable: true,\n\t})\n\tObject.defineProperty(router, 'publicDir', {\n\t\tget: () => state.publicDir,\n\t\tenumerable: true,\n\t\tconfigurable: true,\n\t})\n\treturn router\n}\n","/* src/server/core/typescript/src/factory.ts */\n\nimport type { QueryDef, CommandDef, SubscriptionDef, StreamDef, UploadDef } from './router/index.js'\n\nexport function query<TIn, TOut, TState = undefined>(\n\tdef: Omit<QueryDef<TIn, TOut, TState>, 'kind' | 'type'>,\n): QueryDef<TIn, TOut, TState> {\n\treturn { ...def, kind: 'query' } as QueryDef<TIn, TOut, TState>\n}\n\nexport function command<TIn, TOut, TState = undefined>(\n\tdef: Omit<CommandDef<TIn, TOut, TState>, 'kind' | 'type'>,\n): CommandDef<TIn, TOut, TState> {\n\treturn { ...def, kind: 'command' } as CommandDef<TIn, TOut, TState>\n}\n\nexport function subscription<TIn, TOut, TState = undefined>(\n\tdef: Omit<SubscriptionDef<TIn, TOut, TState>, 'kind' | 'type'>,\n): SubscriptionDef<TIn, TOut, TState> {\n\treturn { ...def, kind: 'subscription' } as SubscriptionDef<TIn, TOut, TState>\n}\n\nexport function stream<TIn, TChunk, TState = undefined>(\n\tdef: Omit<StreamDef<TIn, TChunk, TState>, 'kind'>,\n): StreamDef<TIn, TChunk, TState> {\n\treturn { ...def, kind: 'stream' } as StreamDef<TIn, TChunk, TState>\n}\n\nexport function upload<TIn, TOut, TState = undefined>(\n\tdef: Omit<UploadDef<TIn, TOut, TState>, 'kind'>,\n): UploadDef<TIn, TOut, TState> {\n\treturn { ...def, kind: 'upload' } as UploadDef<TIn, TOut, TState>\n}\n","/* src/server/core/typescript/src/seam-router.ts */\n\nimport type { SchemaNode } from './types/schema.js'\nimport type {\n\tQueryDef,\n\tCommandDef,\n\tSubscriptionDef,\n\tStreamDef,\n\tUploadDef,\n\tDefinitionMap,\n\tRouter,\n\tRouterOptions,\n\tInvalidateTarget,\n\tTransportConfig,\n\tCacheConfig,\n} from './router/index.js'\nimport type { SeamFileHandle } from './procedure.js'\nimport { createRouter } from './router/index.js'\n\n// -- Type-level context inference --\n\nexport interface TypedContextFieldDef<T = unknown> {\n\textract: string\n\tschema: SchemaNode<T>\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\ntype InferContextMap<T extends Record<string, TypedContextFieldDef<any>>> = {\n\t[K in keyof T]: T[K] extends TypedContextFieldDef<infer U> ? U : never\n}\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\ntype PickContext<TMap, TKeys extends readonly string[]> = Pick<TMap, TKeys[number] & keyof TMap>\n\n// -- Per-kind def types with typed ctx --\n\ntype QueryDefWithCtx<TIn, TOut, TCtx, TState> = {\n\tinput: SchemaNode<TIn>\n\toutput: SchemaNode<TOut>\n\terror?: SchemaNode\n\tcontext?: readonly string[]\n\ttransport?: TransportConfig\n\tsuppress?: string[]\n\tcache?: CacheConfig\n\thandler: (params: { input: TIn; ctx: TCtx; state: TState }) => TOut | Promise<TOut>\n}\n\ntype CommandDefWithCtx<TIn, TOut, TCtx, TState> = {\n\tinput: SchemaNode<TIn>\n\toutput: SchemaNode<TOut>\n\terror?: SchemaNode\n\tcontext?: readonly string[]\n\tinvalidates?: InvalidateTarget[]\n\ttransport?: TransportConfig\n\tsuppress?: string[]\n\thandler: (params: { input: TIn; ctx: TCtx; state: TState }) => TOut | Promise<TOut>\n}\n\ntype SubscriptionDefWithCtx<TIn, TOut, TCtx, TState> = {\n\tinput: SchemaNode<TIn>\n\toutput: SchemaNode<TOut>\n\terror?: SchemaNode\n\tcontext?: readonly string[]\n\ttransport?: TransportConfig\n\tsuppress?: string[]\n\thandler: (params: { input: TIn; ctx: TCtx; state: TState }) => AsyncIterable<TOut>\n}\n\ntype StreamDefWithCtx<TIn, TChunk, TCtx, TState> = {\n\tinput: SchemaNode<TIn>\n\toutput: SchemaNode<TChunk>\n\terror?: SchemaNode\n\tcontext?: readonly string[]\n\ttransport?: TransportConfig\n\tsuppress?: string[]\n\thandler: (params: { input: TIn; ctx: TCtx; state: TState }) => AsyncGenerator<TChunk>\n}\n\ntype UploadDefWithCtx<TIn, TOut, TCtx, TState> = {\n\tinput: SchemaNode<TIn>\n\toutput: SchemaNode<TOut>\n\terror?: SchemaNode\n\tcontext?: readonly string[]\n\ttransport?: TransportConfig\n\tsuppress?: string[]\n\thandler: (params: {\n\t\tinput: TIn\n\t\tfile: SeamFileHandle\n\t\tctx: TCtx\n\t\tstate: TState\n\t}) => TOut | Promise<TOut>\n}\n\n// -- SeamDefine interface --\n\nexport interface SeamDefine<TCtxMap extends Record<string, unknown>, TState> {\n\tquery<TIn, TOut, const TKeys extends readonly (keyof TCtxMap & string)[] = []>(\n\t\tdef: QueryDefWithCtx<TIn, TOut, PickContext<TCtxMap, TKeys>, TState> & { context?: TKeys },\n\t): QueryDef<TIn, TOut, TState>\n\n\tcommand<TIn, TOut, const TKeys extends readonly (keyof TCtxMap & string)[] = []>(\n\t\tdef: CommandDefWithCtx<TIn, TOut, PickContext<TCtxMap, TKeys>, TState> & { context?: TKeys },\n\t): CommandDef<TIn, TOut, TState>\n\n\tsubscription<TIn, TOut, const TKeys extends readonly (keyof TCtxMap & string)[] = []>(\n\t\tdef: SubscriptionDefWithCtx<TIn, TOut, PickContext<TCtxMap, TKeys>, TState> & {\n\t\t\tcontext?: TKeys\n\t\t},\n\t): SubscriptionDef<TIn, TOut, TState>\n\n\tstream<TIn, TChunk, const TKeys extends readonly (keyof TCtxMap & string)[] = []>(\n\t\tdef: StreamDefWithCtx<TIn, TChunk, PickContext<TCtxMap, TKeys>, TState> & {\n\t\t\tcontext?: TKeys\n\t\t},\n\t): StreamDef<TIn, TChunk, TState>\n\n\tupload<TIn, TOut, const TKeys extends readonly (keyof TCtxMap & string)[] = []>(\n\t\tdef: UploadDefWithCtx<TIn, TOut, PickContext<TCtxMap, TKeys>, TState> & { context?: TKeys },\n\t): UploadDef<TIn, TOut, TState>\n}\n\n// -- createSeamRouter --\n\n/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return */\nexport function createSeamRouter<\n\tconst T extends Record<string, TypedContextFieldDef<any>>,\n\tTState = undefined,\n>(\n\tconfig: { context: T; state?: TState } & Omit<RouterOptions<TState>, 'context' | 'state'>,\n): {\n\trouter: <P extends DefinitionMap>(\n\t\tprocedures: P,\n\t\textraOpts?: Omit<RouterOptions<TState>, 'context' | 'state'>,\n\t) => Router<P>\n\tdefine: SeamDefine<InferContextMap<T>, TState>\n} {\n\tconst { context, state, ...restConfig } = config\n\n\tconst define: SeamDefine<InferContextMap<T>, TState> = {\n\t\tquery(def) {\n\t\t\treturn { ...def, kind: 'query' } as any\n\t\t},\n\t\tcommand(def) {\n\t\t\treturn { ...def, kind: 'command' } as any\n\t\t},\n\t\tsubscription(def) {\n\t\t\treturn { ...def, kind: 'subscription' } as any\n\t\t},\n\t\tstream(def) {\n\t\t\treturn { ...def, kind: 'stream' } as any\n\t\t},\n\t\tupload(def) {\n\t\t\treturn { ...def, kind: 'upload' } as any\n\t\t},\n\t}\n\n\tfunction router<P extends DefinitionMap>(\n\t\tprocedures: P,\n\t\textraOpts?: Omit<RouterOptions<TState>, 'context' | 'state'>,\n\t): Router<P> {\n\t\treturn createRouter(procedures, { ...restConfig, context, state, ...extraOpts })\n\t}\n\n\treturn { router, define }\n}\n/* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return */\n","/* src/server/core/typescript/src/channel.ts */\n\nimport type { Schema } from 'jtd'\nimport type { SchemaNode, Infer, JTDSchema } from './types/schema.js'\nimport type { CommandDef, SubscriptionDef, DefinitionMap, TransportConfig } from './router/index.js'\n\n// -- Public types --\n\nexport interface IncomingDef<TIn = unknown, TOut = unknown> {\n\tinput: SchemaNode<TIn>\n\toutput: SchemaNode<TOut>\n\terror?: SchemaNode\n\thandler: (params: { input: TIn }) => TOut | Promise<TOut>\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport interface ChannelDef<\n\tTChannelIn = unknown,\n\tTIncoming extends Record<string, IncomingDef<any, any>> = Record<string, IncomingDef<any, any>>,\n\tTOutgoing extends Record<string, SchemaNode<Record<string, unknown>>> = Record<\n\t\tstring,\n\t\tSchemaNode<Record<string, unknown>>\n\t>,\n> {\n\tinput: SchemaNode<TChannelIn>\n\tincoming: TIncoming\n\toutgoing: TOutgoing\n\tsubscribe: (params: { input: TChannelIn }) => AsyncIterable<ChannelEvent<TOutgoing>>\n\ttransport?: TransportConfig\n}\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\ntype ChannelEvent<TOutgoing extends Record<string, SchemaNode<Record<string, unknown>>>> = {\n\t[K in keyof TOutgoing & string]: { type: K; payload: Infer<TOutgoing[K]> }\n}[keyof TOutgoing & string]\n\n/** IR hint stored in the manifest `channels` field */\nexport interface ChannelMeta {\n\tinput: Schema\n\tincoming: Record<string, { input: Schema; output: Schema; error?: Schema }>\n\toutgoing: Record<string, Schema>\n\ttransport?: { prefer: string; fallback?: string[] }\n}\n\nexport interface ChannelResult {\n\t/** Expanded Level 0 procedure definitions — spread into createRouter */\n\tprocedures: DefinitionMap\n\t/** IR hint for codegen */\n\tchannelMeta: ChannelMeta\n}\n\n// -- Helpers --\n\n/** Merge channel-level and message-level JTD properties schemas */\nfunction mergeObjectSchemas(channel: JTDSchema, message: JTDSchema): JTDSchema {\n\tconst channelProps = (channel as Record<string, unknown>).properties as\n\t\t| Record<string, JTDSchema>\n\t\t| undefined\n\tconst channelOptional = (channel as Record<string, unknown>).optionalProperties as\n\t\t| Record<string, JTDSchema>\n\t\t| undefined\n\tconst msgProps = (message as Record<string, unknown>).properties as\n\t\t| Record<string, JTDSchema>\n\t\t| undefined\n\tconst msgOptional = (message as Record<string, unknown>).optionalProperties as\n\t\t| Record<string, JTDSchema>\n\t\t| undefined\n\n\tconst merged: Record<string, unknown> = {}\n\n\tconst props = { ...channelProps, ...msgProps }\n\tif (Object.keys(props).length > 0) {\n\t\tmerged.properties = props\n\t}\n\n\tconst optProps = { ...channelOptional, ...msgOptional }\n\tif (Object.keys(optProps).length > 0) {\n\t\tmerged.optionalProperties = optProps\n\t}\n\n\t// Empty object schema needs at least empty properties\n\tif (!merged.properties && !merged.optionalProperties) {\n\t\tmerged.properties = {}\n\t}\n\n\treturn merged as JTDSchema\n}\n\n/** Build a tagged union schema from outgoing event definitions */\nfunction buildOutgoingUnionSchema(\n\toutgoing: Record<string, SchemaNode<Record<string, unknown>>>,\n): JTDSchema {\n\tconst mapping: Record<string, JTDSchema> = {}\n\tfor (const [eventName, node] of Object.entries(outgoing)) {\n\t\t// Wrap each outgoing payload as a \"payload\" property\n\t\tmapping[eventName] = {\n\t\t\tproperties: { payload: node._schema },\n\t\t} as JTDSchema\n\t}\n\treturn { discriminator: 'type', mapping } as JTDSchema\n}\n\n// -- Main API --\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport function createChannel<\n\tTChannelIn,\n\tTIncoming extends Record<string, IncomingDef<any, any>>,\n\tTOutgoing extends Record<string, SchemaNode<Record<string, unknown>>>,\n>(name: string, def: ChannelDef<TChannelIn, TIncoming, TOutgoing>): ChannelResult {\n\tconst procedures: DefinitionMap = {}\n\tconst channelInputSchema = def.input._schema\n\n\t// Expand incoming messages to command procedures\n\tfor (const [msgName, msgDef] of Object.entries(def.incoming)) {\n\t\tconst mergedInputSchema = mergeObjectSchemas(channelInputSchema, msgDef.input._schema)\n\n\t\tconst command: CommandDef<any, any> = {\n\t\t\tkind: 'command',\n\t\t\tinput: { _schema: mergedInputSchema } as SchemaNode<any>,\n\t\t\toutput: msgDef.output,\n\t\t\thandler: msgDef.handler as CommandDef<any, any>['handler'],\n\t\t}\n\t\tif (msgDef.error) {\n\t\t\tcommand.error = msgDef.error\n\t\t}\n\t\tprocedures[`${name}.${msgName}`] = command\n\t}\n\n\t// Expand subscribe to a subscription with tagged union output\n\tconst unionSchema = buildOutgoingUnionSchema(def.outgoing)\n\tconst subscription: SubscriptionDef<any, any> = {\n\t\tkind: 'subscription',\n\t\tinput: def.input as SchemaNode<any>,\n\t\toutput: { _schema: unionSchema } as SchemaNode<any>,\n\t\thandler: def.subscribe as SubscriptionDef<any, any>['handler'],\n\t}\n\tprocedures[`${name}.events`] = subscription\n\n\t// Build channel metadata for manifest IR hint\n\tconst incomingMeta: ChannelMeta['incoming'] = {}\n\tfor (const [msgName, msgDef] of Object.entries(def.incoming)) {\n\t\tconst entry: { input: Schema; output: Schema; error?: Schema } = {\n\t\t\tinput: msgDef.input._schema,\n\t\t\toutput: msgDef.output._schema,\n\t\t}\n\t\tif (msgDef.error) {\n\t\t\tentry.error = msgDef.error._schema\n\t\t}\n\t\tincomingMeta[msgName] = entry\n\t}\n\n\tconst outgoingMeta: ChannelMeta['outgoing'] = {}\n\tfor (const [eventName, node] of Object.entries(def.outgoing)) {\n\t\toutgoingMeta[eventName] = node._schema\n\t}\n\n\tconst channelMeta: ChannelMeta = {\n\t\tinput: channelInputSchema,\n\t\tincoming: incomingMeta,\n\t\toutgoing: outgoingMeta,\n\t}\n\tif (def.transport) {\n\t\tchannelMeta.transport = def.transport\n\t}\n\n\treturn { procedures, channelMeta }\n}\n/* eslint-enable @typescript-eslint/no-explicit-any */\n","/* src/server/core/typescript/src/page/index.ts */\n\nexport interface LoaderResult {\n\tprocedure: string\n\tinput: unknown\n}\n\nexport type LoaderFn = (\n\tparams: Record<string, string>,\n\tsearchParams?: URLSearchParams,\n) => LoaderResult\n\nexport interface LayoutDef {\n\tid: string\n\ttemplate: string\n\tlocaleTemplates?: Record<string, string>\n\tloaders: Record<string, LoaderFn>\n\ti18nKeys?: string[]\n}\n\nexport interface PageAssets {\n\tstyles: string[]\n\tscripts: string[]\n\tpreload: string[]\n\tprefetch: string[]\n}\n\nexport type HeadFn = (data: Record<string, unknown>) => {\n\ttitle?: string\n\tmeta?: Record<string, string | undefined>[]\n\tlink?: Record<string, string | undefined>[]\n}\n\nexport interface PageDef {\n\ttemplate: string\n\tlocaleTemplates?: Record<string, string>\n\tloaders: Record<string, LoaderFn>\n\tlayoutChain?: LayoutDef[]\n\theadMeta?: string\n\theadFn?: HeadFn\n\tdataId?: string\n\ti18nKeys?: string[]\n\tpageAssets?: PageAssets\n\tprojections?: Record<string, string[]>\n\t/** SSG: page was pre-rendered at build time */\n\tprerender?: boolean\n\t/** SSG: directory containing pre-rendered HTML and __data.json */\n\tstaticDir?: string\n}\n\nexport interface I18nConfig {\n\tlocales: string[]\n\tdefault: string\n\tmode: 'memory' | 'paged'\n\tcache: boolean\n\trouteHashes: Record<string, string>\n\tcontentHashes: Record<string, Record<string, string>>\n\t/** Memory mode: locale → routeHash → messages */\n\tmessages: Record<string, Record<string, Record<string, string>>>\n\t/** Paged mode: base directory for on-demand reads */\n\tdistDir?: string\n}\n\nexport function definePage(config: PageDef): PageDef {\n\treturn { ...config, layoutChain: config.layoutChain ?? [] }\n}\n","/* src/server/core/typescript/src/dev/reload-watcher.ts */\n\nimport { existsSync, watch } from 'node:fs'\nimport { join } from 'node:path'\n\nexport interface ReloadWatcher {\n\tclose(): void\n\t/** Resolves on the next reload event. Rejects if the watcher is already closed. */\n\tnextReload(): Promise<void>\n}\n\ninterface Closable {\n\tclose(): void\n}\n\nexport interface ReloadWatcherBackend {\n\twatchFile(path: string, onChange: () => void, onError: (error: unknown) => void): Closable\n\tfileExists(path: string): boolean\n\tsetPoll(callback: () => void, intervalMs: number): Closable\n}\n\nconst nodeReloadWatcherBackend: ReloadWatcherBackend = {\n\twatchFile(path, onChange, onError) {\n\t\tconst watcher = watch(path, () => onChange())\n\t\twatcher.on('error', onError)\n\t\treturn watcher\n\t},\n\tfileExists(path) {\n\t\treturn existsSync(path)\n\t},\n\tsetPoll(callback, intervalMs) {\n\t\tconst timer = setInterval(callback, intervalMs)\n\t\treturn {\n\t\t\tclose() {\n\t\t\t\tclearInterval(timer)\n\t\t\t},\n\t\t}\n\t},\n}\n\nfunction isMissingFileError(error: unknown): boolean {\n\treturn typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT'\n}\n\nexport function createReloadWatcher(\n\tdistDir: string,\n\tonReload: () => void,\n\tbackend: ReloadWatcherBackend,\n): ReloadWatcher {\n\tconst triggerPath = join(distDir, '.reload-trigger')\n\tlet watcher: Closable | null = null\n\tlet poller: Closable | null = null\n\tlet closed = false\n\tlet pending: Array<{ resolve: () => void; reject: (e: Error) => void }> = []\n\n\tconst notify = () => {\n\t\tonReload()\n\t\tconst batch = pending\n\t\tpending = []\n\t\tfor (const p of batch) p.resolve()\n\t}\n\n\tconst nextReload = (): Promise<void> => {\n\t\tif (closed) return Promise.reject(new Error('watcher closed'))\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tpending.push({ resolve, reject })\n\t\t})\n\t}\n\n\tconst closeAll = () => {\n\t\tclosed = true\n\t\tconst batch = pending\n\t\tpending = []\n\t\tconst err = new Error('watcher closed')\n\t\tfor (const p of batch) p.reject(err)\n\t}\n\n\tconst stopWatcher = () => {\n\t\twatcher?.close()\n\t\twatcher = null\n\t}\n\n\tconst stopPoller = () => {\n\t\tpoller?.close()\n\t\tpoller = null\n\t}\n\n\tconst startPolling = () => {\n\t\tif (closed || poller) return\n\t\tpoller = backend.setPoll(() => {\n\t\t\tif (!backend.fileExists(triggerPath)) return\n\t\t\tstopPoller()\n\t\t\t// First appearance counts as a reload signal.\n\t\t\tnotify()\n\t\t\tstartWatchingFile()\n\t\t}, 50)\n\t}\n\n\tconst startWatchingFile = () => {\n\t\tif (closed) return\n\t\ttry {\n\t\t\twatcher = backend.watchFile(\n\t\t\t\ttriggerPath,\n\t\t\t\t() => notify(),\n\t\t\t\t(error) => {\n\t\t\t\t\tstopWatcher()\n\t\t\t\t\tif (!closed && isMissingFileError(error)) {\n\t\t\t\t\t\tstartPolling()\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t)\n\t\t} catch (error) {\n\t\t\tstopWatcher()\n\t\t\tif (isMissingFileError(error)) {\n\t\t\t\tstartPolling()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthrow error\n\t\t}\n\t}\n\n\tstartWatchingFile()\n\treturn {\n\t\tclose() {\n\t\t\tstopWatcher()\n\t\t\tstopPoller()\n\t\t\tcloseAll()\n\t\t},\n\t\tnextReload,\n\t}\n}\n\nexport function watchReloadTrigger(distDir: string, onReload: () => void): ReloadWatcher {\n\treturn createReloadWatcher(distDir, onReload, nodeReloadWatcherBackend)\n}\n","/* src/server/core/typescript/src/page/build-loader.ts */\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { PageDef, PageAssets, LayoutDef, LoaderFn, LoaderResult, I18nConfig } from './index.js'\nimport type { RpcHashMap } from '../http.js'\n\ninterface RouteManifest {\n\tlayouts?: Record<string, LayoutManifestEntry>\n\troutes: Record<string, RouteManifestEntry>\n\tdata_id?: string\n\ti18n?: {\n\t\tlocales: string[]\n\t\tdefault: string\n\t\tmode?: string\n\t\tcache?: boolean\n\t\troute_hashes?: Record<string, string>\n\t\tcontent_hashes?: Record<string, Record<string, string>>\n\t}\n}\n\ninterface LayoutManifestEntry {\n\ttemplate?: string\n\ttemplates?: Record<string, string>\n\tloaders?: Record<string, LoaderConfig>\n\tparent?: string\n\ti18n_keys?: string[]\n}\n\ninterface RouteManifestEntry {\n\ttemplate?: string\n\ttemplates?: Record<string, string>\n\tlayout?: string\n\tloaders: Record<string, LoaderConfig>\n\thead_meta?: string\n\ti18n_keys?: string[]\n\tassets?: PageAssets\n\tprojections?: Record<string, string[]>\n\tprerender?: boolean\n}\n\ninterface LoaderConfig {\n\tprocedure: string\n\tparams?: Record<string, string | ParamConfig>\n\thandoff?: 'client'\n}\n\ninterface ParamConfig {\n\tfrom: 'route' | 'query'\n\ttype?: 'string' | 'int'\n}\n\nfunction normalizeParamConfig(value: string | ParamConfig): ParamConfig {\n\treturn typeof value === 'string' ? { from: value as ParamConfig['from'] } : value\n}\n\nfunction buildLoaderFn(config: LoaderConfig): LoaderFn {\n\treturn (params, searchParams): LoaderResult => {\n\t\tconst input: Record<string, unknown> = {}\n\t\tif (config.params) {\n\t\t\tfor (const [key, raw_mapping] of Object.entries(config.params)) {\n\t\t\t\tconst mapping = normalizeParamConfig(raw_mapping)\n\t\t\t\tconst raw = mapping.from === 'query' ? (searchParams?.get(key) ?? undefined) : params[key]\n\t\t\t\tif (raw !== undefined) {\n\t\t\t\t\tinput[key] = mapping.type === 'int' ? Number(raw) : raw\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn { procedure: config.procedure, input }\n\t}\n}\n\nfunction buildLoaderFns(configs: Record<string, LoaderConfig>): Record<string, LoaderFn> {\n\tconst fns: Record<string, LoaderFn> = {}\n\tfor (const [key, config] of Object.entries(configs)) {\n\t\tfns[key] = buildLoaderFn(config)\n\t}\n\treturn fns\n}\n\nfunction resolveTemplatePath(\n\tentry: { template?: string; templates?: Record<string, string> },\n\tdefaultLocale: string | undefined,\n): string {\n\tif (entry.template) return entry.template\n\tif (entry.templates) {\n\t\tconst locale = defaultLocale ?? (Object.keys(entry.templates)[0] as string)\n\t\tconst path = entry.templates[locale]\n\t\tif (!path) throw new Error(`No template for locale \"${locale}\"`)\n\t\treturn path\n\t}\n\tthrow new Error(\"Manifest entry has neither 'template' nor 'templates'\")\n}\n\n/** Load all locale templates for a manifest entry, keyed by locale */\nfunction loadLocaleTemplates(\n\tentry: { templates?: Record<string, string> },\n\tdistDir: string,\n): Record<string, string> | undefined {\n\tif (!entry.templates) return undefined\n\tconst result: Record<string, string> = {}\n\tfor (const [locale, relPath] of Object.entries(entry.templates)) {\n\t\tresult[locale] = readFileSync(join(distDir, relPath), 'utf-8')\n\t}\n\treturn result\n}\n\n/** Callback that returns template + localeTemplates for a layout entry */\ntype TemplateGetter = (\n\tid: string,\n\tentry: LayoutManifestEntry,\n) => { template: string; localeTemplates?: Record<string, string> }\n\n/** Resolve parent chain for a layout, returning outer-to-inner order */\nfunction resolveLayoutChain(\n\tlayoutId: string,\n\tlayoutEntries: Record<string, LayoutManifestEntry>,\n\tgetTemplates: TemplateGetter,\n): LayoutDef[] {\n\tconst chain: LayoutDef[] = []\n\tlet currentId: string | undefined = layoutId\n\n\twhile (currentId) {\n\t\tconst entry: LayoutManifestEntry | undefined = layoutEntries[currentId]\n\t\tif (!entry) break\n\t\tconst { template, localeTemplates } = getTemplates(currentId, entry)\n\t\tchain.push({\n\t\t\tid: currentId,\n\t\t\ttemplate,\n\t\t\tlocaleTemplates,\n\t\t\tloaders: buildLoaderFns(entry.loaders ?? {}),\n\t\t})\n\t\tcurrentId = entry.parent\n\t}\n\n\t// Reverse: we walked inner->outer, but want outer->inner\n\tchain.reverse()\n\treturn chain\n}\n\n/** Create a proxy object that lazily reads locale templates from disk */\nfunction makeLocaleTemplateGetters(\n\ttemplates: Record<string, string>,\n\tdistDir: string,\n): Record<string, string> {\n\tconst obj: Record<string, string> = {}\n\tfor (const [locale, relPath] of Object.entries(templates)) {\n\t\tconst fullPath = join(distDir, relPath)\n\t\tObject.defineProperty(obj, locale, {\n\t\t\tget: () => readFileSync(fullPath, 'utf-8'),\n\t\t\tenumerable: true,\n\t\t})\n\t}\n\treturn obj\n}\n\n/** Merge i18n_keys from route + layout chain into a single list */\nfunction mergeI18nKeys(\n\troute: RouteManifestEntry,\n\tlayoutEntries: Record<string, LayoutManifestEntry>,\n): string[] | undefined {\n\tconst keys: string[] = []\n\tif (route.layout) {\n\t\tlet currentId: string | undefined = route.layout\n\t\twhile (currentId) {\n\t\t\tconst entry: LayoutManifestEntry | undefined = layoutEntries[currentId]\n\t\t\tif (!entry) break\n\t\t\tif (entry.i18n_keys) keys.push(...entry.i18n_keys)\n\t\t\tcurrentId = entry.parent\n\t\t}\n\t}\n\tif (route.i18n_keys) keys.push(...route.i18n_keys)\n\treturn keys.length > 0 ? keys : undefined\n}\n\nexport interface BuildOutput {\n\tpages: Record<string, PageDef>\n\trpcHashMap: RpcHashMap | undefined\n\ti18n: I18nConfig | null\n\tpublicDir: string | undefined\n}\n\n/** Detect public-root directory from production build output */\nfunction detectBuiltPublicDir(distDir: string): string | undefined {\n\tconst publicRootDir = join(distDir, 'public-root')\n\treturn existsSync(publicRootDir) ? publicRootDir : undefined\n}\n\n/** Detect source public/ directory for dev mode. */\nfunction detectDevPublicDir(distDir: string): string | undefined {\n\tconst explicitDir = process.env.SEAM_PUBLIC_DIR\n\tif (explicitDir && existsSync(explicitDir)) return explicitDir\n\n\tconst sourcePublicDir = join(distDir, '..', '..', 'public')\n\treturn existsSync(sourcePublicDir) ? sourcePublicDir : undefined\n}\n\n/** Load all build artifacts (pages, rpcHashMap, i18n) in one call */\nexport function loadBuild(distDir: string): BuildOutput {\n\treturn {\n\t\tpages: loadBuildOutput(distDir),\n\t\trpcHashMap: loadRpcHashMap(distDir),\n\t\ti18n: loadI18nMessages(distDir),\n\t\tpublicDir: detectBuiltPublicDir(distDir),\n\t}\n}\n\n/** Load all build artifacts with lazy template getters (for dev mode) */\nexport function loadBuildDev(distDir: string): BuildOutput {\n\treturn {\n\t\tpages: loadBuildOutputDev(distDir),\n\t\trpcHashMap: loadRpcHashMap(distDir),\n\t\ti18n: loadI18nMessages(distDir),\n\t\tpublicDir: detectDevPublicDir(distDir) ?? detectBuiltPublicDir(distDir),\n\t}\n}\n\n/** Load the RPC hash map from build output (returns undefined when obfuscation is off) */\nexport function loadRpcHashMap(distDir: string): RpcHashMap | undefined {\n\tconst hashMapPath = join(distDir, 'rpc-hash-map.json')\n\ttry {\n\t\treturn JSON.parse(readFileSync(hashMapPath, 'utf-8')) as RpcHashMap\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\n/** Load i18n config and messages from build output */\nexport function loadI18nMessages(distDir: string): I18nConfig | null {\n\tconst manifestPath = join(distDir, 'route-manifest.json')\n\ttry {\n\t\tconst manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as RouteManifest\n\t\tif (!manifest.i18n) return null\n\n\t\tconst mode = (manifest.i18n.mode ?? 'memory') as 'memory' | 'paged'\n\t\tconst cache = manifest.i18n.cache ?? false\n\t\tconst routeHashes = manifest.i18n.route_hashes ?? {}\n\t\tconst contentHashes = manifest.i18n.content_hashes ?? {}\n\n\t\t// Memory mode: preload all route messages per locale\n\t\t// Paged mode: store distDir for on-demand reads\n\t\tconst messages: Record<string, Record<string, Record<string, string>>> = {}\n\t\tif (mode === 'memory') {\n\t\t\tconst i18nDir = join(distDir, 'i18n')\n\t\t\tfor (const locale of manifest.i18n.locales) {\n\t\t\t\tconst localePath = join(i18nDir, `${locale}.json`)\n\t\t\t\tif (existsSync(localePath)) {\n\t\t\t\t\tmessages[locale] = JSON.parse(readFileSync(localePath, 'utf-8')) as Record<\n\t\t\t\t\t\tstring,\n\t\t\t\t\t\tRecord<string, string>\n\t\t\t\t\t>\n\t\t\t\t} else {\n\t\t\t\t\tmessages[locale] = {}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tlocales: manifest.i18n.locales,\n\t\t\tdefault: manifest.i18n.default,\n\t\t\tmode,\n\t\t\tcache,\n\t\t\trouteHashes,\n\t\t\tcontentHashes,\n\t\t\tmessages,\n\t\t\tdistDir: mode === 'paged' ? distDir : undefined,\n\t\t}\n\t} catch {\n\t\treturn null\n\t}\n}\n\nexport function loadBuildOutput(distDir: string): Record<string, PageDef> {\n\tconst manifestPath = join(distDir, 'route-manifest.json')\n\tconst raw = readFileSync(manifestPath, 'utf-8')\n\tconst manifest = JSON.parse(raw) as RouteManifest\n\tconst defaultLocale = manifest.i18n?.default\n\n\t// Load layout templates (default + all locales)\n\tconst layoutTemplates: Record<string, string> = {}\n\tconst layoutLocaleTemplates: Record<string, Record<string, string>> = {}\n\tconst layoutEntries = manifest.layouts ?? {}\n\tfor (const [id, entry] of Object.entries(layoutEntries)) {\n\t\tlayoutTemplates[id] = readFileSync(\n\t\t\tjoin(distDir, resolveTemplatePath(entry, defaultLocale)),\n\t\t\t'utf-8',\n\t\t)\n\t\tconst lt = loadLocaleTemplates(entry, distDir)\n\t\tif (lt) layoutLocaleTemplates[id] = lt\n\t}\n\n\t// Static dir for prerendered pages (adjacent to output dir)\n\tconst staticDir = join(distDir, '..', 'static')\n\tconst hasStaticDir = existsSync(staticDir)\n\n\tconst pages: Record<string, PageDef> = {}\n\tfor (const [path, entry] of Object.entries(manifest.routes)) {\n\t\tconst templatePath = join(distDir, resolveTemplatePath(entry, defaultLocale))\n\t\tconst template = readFileSync(templatePath, 'utf-8')\n\n\t\tconst loaders = buildLoaderFns(entry.loaders)\n\t\tconst layoutChain = entry.layout\n\t\t\t? resolveLayoutChain(entry.layout, layoutEntries, (id) => ({\n\t\t\t\t\ttemplate: layoutTemplates[id] ?? '',\n\t\t\t\t\tlocaleTemplates: layoutLocaleTemplates[id],\n\t\t\t\t}))\n\t\t\t: []\n\n\t\t// Merge i18n_keys from layout chain + route\n\t\tconst i18nKeys = mergeI18nKeys(entry, layoutEntries)\n\n\t\tconst page: PageDef = {\n\t\t\ttemplate,\n\t\t\tlocaleTemplates: loadLocaleTemplates(entry, distDir),\n\t\t\tloaders,\n\t\t\tlayoutChain,\n\t\t\theadMeta: entry.head_meta,\n\t\t\tdataId: manifest.data_id,\n\t\t\ti18nKeys,\n\t\t\tpageAssets: entry.assets,\n\t\t\tprojections: entry.projections,\n\t\t}\n\n\t\tif (entry.prerender && hasStaticDir) {\n\t\t\tpage.prerender = true\n\t\t\tpage.staticDir = staticDir\n\t\t}\n\n\t\tpages[path] = page\n\t}\n\treturn pages\n}\n\n/** Load build output with lazy template getters -- templates re-read from disk on each access */\nexport function loadBuildOutputDev(distDir: string): Record<string, PageDef> {\n\tconst manifestPath = join(distDir, 'route-manifest.json')\n\tconst raw = readFileSync(manifestPath, 'utf-8')\n\tconst manifest = JSON.parse(raw) as RouteManifest\n\tconst defaultLocale = manifest.i18n?.default\n\n\tconst layoutEntries = manifest.layouts ?? {}\n\n\tconst pages: Record<string, PageDef> = {}\n\tfor (const [path, entry] of Object.entries(manifest.routes)) {\n\t\tconst templatePath = join(distDir, resolveTemplatePath(entry, defaultLocale))\n\t\tconst loaders = buildLoaderFns(entry.loaders)\n\t\tconst layoutChain = entry.layout\n\t\t\t? resolveLayoutChain(entry.layout, layoutEntries, (id, layoutEntry) => {\n\t\t\t\t\tconst tmplPath = join(distDir, resolveTemplatePath(layoutEntry, defaultLocale))\n\t\t\t\t\tconst def = {\n\t\t\t\t\t\ttemplate: '',\n\t\t\t\t\t\tlocaleTemplates: layoutEntry.templates\n\t\t\t\t\t\t\t? makeLocaleTemplateGetters(layoutEntry.templates, distDir)\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t}\n\t\t\t\t\tObject.defineProperty(def, 'template', {\n\t\t\t\t\t\tget: () => readFileSync(tmplPath, 'utf-8'),\n\t\t\t\t\t\tenumerable: true,\n\t\t\t\t\t})\n\t\t\t\t\treturn def\n\t\t\t\t})\n\t\t\t: []\n\n\t\tconst localeTemplates = entry.templates\n\t\t\t? makeLocaleTemplateGetters(entry.templates, distDir)\n\t\t\t: undefined\n\n\t\t// Merge i18n_keys from layout chain + route\n\t\tconst i18nKeys = mergeI18nKeys(entry, layoutEntries)\n\n\t\tconst page: PageDef = {\n\t\t\ttemplate: '', // placeholder, overridden by getter\n\t\t\tlocaleTemplates,\n\t\t\tloaders,\n\t\t\tlayoutChain,\n\t\t\theadMeta: entry.head_meta,\n\t\t\tdataId: manifest.data_id,\n\t\t\ti18nKeys,\n\t\t\tpageAssets: entry.assets,\n\t\t\tprojections: entry.projections,\n\t\t}\n\t\tObject.defineProperty(page, 'template', {\n\t\t\tget: () => readFileSync(templatePath, 'utf-8'),\n\t\t\tenumerable: true,\n\t\t})\n\t\tpages[path] = page\n\t}\n\treturn pages\n}\n","/* src/server/core/typescript/src/http-sse.ts */\n\nimport { SeamError } from './errors.js'\nimport type { RawContextMap } from './context.js'\nimport type { HttpStreamResponse, RpcHashMap, SseOptions } from './http.js'\nimport type { DefinitionMap, Router } from './router/index.js'\n\nconst SSE_HEADER = {\n\t'Content-Type': 'text/event-stream',\n\t'Cache-Control': 'no-cache',\n\tConnection: 'keep-alive',\n}\n\nconst DEFAULT_HEARTBEAT_MS = 8_000\nconst DEFAULT_SSE_IDLE_MS = 12_000\n\nexport function getSseHeaders(): Record<string, string> {\n\treturn SSE_HEADER\n}\n\nexport function sseDataEvent(data: unknown): string {\n\treturn `event: data\\ndata: ${JSON.stringify(data)}\\n\\n`\n}\n\nexport function sseDataEventWithId(data: unknown, id: number): string {\n\treturn `event: data\\nid: ${id}\\ndata: ${JSON.stringify(data)}\\n\\n`\n}\n\nexport function sseErrorEvent(code: string, message: string, transient = false): string {\n\treturn `event: error\\ndata: ${JSON.stringify({ code, message, transient })}\\n\\n`\n}\n\nexport function sseCompleteEvent(): string {\n\treturn 'event: complete\\ndata: {}\\n\\n'\n}\n\nfunction formatSseError(error: unknown): string {\n\tif (error instanceof SeamError) {\n\t\treturn sseErrorEvent(error.code, error.message)\n\t}\n\tconst message = error instanceof Error ? error.message : 'Unknown error'\n\treturn sseErrorEvent('INTERNAL_ERROR', message)\n}\n\nexport async function* withSseLifecycle(\n\tinner: AsyncIterable<string>,\n\topts?: SseOptions,\n): AsyncGenerator<string> {\n\tconst heartbeatMs = opts?.heartbeatInterval ?? DEFAULT_HEARTBEAT_MS\n\tconst idleMs = opts?.sseIdleTimeout ?? DEFAULT_SSE_IDLE_MS\n\tconst idleEnabled = idleMs > 0\n\n\tconst queue: Array<\n\t\t{ type: 'data'; value: string } | { type: 'done' } | { type: 'heartbeat' } | { type: 'idle' }\n\t> = []\n\tlet resolve: (() => void) | null = null\n\tconst signal = () => {\n\t\tif (resolve) {\n\t\t\tresolve()\n\t\t\tresolve = null\n\t\t}\n\t}\n\n\tlet idleTimer: ReturnType<typeof setTimeout> | null = null\n\tconst resetIdle = () => {\n\t\tif (!idleEnabled) return\n\t\tif (idleTimer) clearTimeout(idleTimer)\n\t\tidleTimer = setTimeout(() => {\n\t\t\tqueue.push({ type: 'idle' })\n\t\t\tsignal()\n\t\t}, idleMs)\n\t}\n\n\tconst heartbeatTimer = setInterval(() => {\n\t\tqueue.push({ type: 'heartbeat' })\n\t\tsignal()\n\t}, heartbeatMs)\n\n\tqueue.push({ type: 'heartbeat' })\n\tresetIdle()\n\n\tvoid (async () => {\n\t\ttry {\n\t\t\tfor await (const chunk of inner) {\n\t\t\t\tqueue.push({ type: 'data', value: chunk })\n\t\t\t\tresetIdle()\n\t\t\t\tsignal()\n\t\t\t}\n\t\t} catch {\n\t\t\t// Inner generator error\n\t\t}\n\t\tqueue.push({ type: 'done' })\n\t\tsignal()\n\t})()\n\n\ttry {\n\t\tfor (;;) {\n\t\t\twhile (queue.length === 0) {\n\t\t\t\tawait new Promise<void>((r) => {\n\t\t\t\t\tresolve = r\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst item = queue.shift()\n\t\t\tif (!item) continue\n\t\t\tif (item.type === 'data') {\n\t\t\t\tyield item.value\n\t\t\t} else if (item.type === 'heartbeat') {\n\t\t\t\tyield ': heartbeat\\n\\n'\n\t\t\t} else if (item.type === 'idle') {\n\t\t\t\tyield sseCompleteEvent()\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tclearInterval(heartbeatTimer)\n\t\tif (idleTimer) clearTimeout(idleTimer)\n\t}\n}\n\nexport async function* sseStream<T extends DefinitionMap>(\n\trouter: Router<T>,\n\tname: string,\n\tinput: unknown,\n\trawCtx?: RawContextMap,\n\tlastEventId?: string,\n): AsyncIterable<string> {\n\ttry {\n\t\tlet seq = 0\n\t\tfor await (const value of router.handleSubscription(name, input, rawCtx, lastEventId)) {\n\t\t\tyield sseDataEventWithId(value, seq++)\n\t\t}\n\t\tyield sseCompleteEvent()\n\t} catch (error) {\n\t\tyield formatSseError(error)\n\t}\n}\n\nexport async function* sseStreamForStream<T extends DefinitionMap>(\n\trouter: Router<T>,\n\tname: string,\n\tinput: unknown,\n\tsignal?: AbortSignal,\n\trawCtx?: RawContextMap,\n): AsyncGenerator<string> {\n\tconst gen = router.handleStream(name, input, rawCtx)\n\tif (signal) {\n\t\tsignal.addEventListener(\n\t\t\t'abort',\n\t\t\t() => {\n\t\t\t\tvoid gen.return(undefined)\n\t\t\t},\n\t\t\t{ once: true },\n\t\t)\n\t}\n\ttry {\n\t\tlet seq = 0\n\t\tfor await (const value of gen) {\n\t\t\tyield sseDataEventWithId(value, seq++)\n\t\t}\n\t\tyield sseCompleteEvent()\n\t} catch (error) {\n\t\tyield formatSseError(error)\n\t}\n}\n\nexport function buildHashLookup(hashMap: RpcHashMap | undefined): Map<string, string> | null {\n\tif (!hashMap) return null\n\tconst map = new Map(Object.entries(hashMap.procedures).map(([n, h]) => [h, n]))\n\tmap.set('seam.i18n.query', 'seam.i18n.query')\n\treturn map\n}\n\nexport function createDevReloadResponse(\n\tdevState: { resolvers: Set<() => void> },\n\tsseOptions?: SseOptions,\n): HttpStreamResponse {\n\tconst controller = new AbortController()\n\tasync function* devStream(): AsyncGenerator<string> {\n\t\tyield ': connected\\n\\n'\n\t\tconst aborted = new Promise<never>((_, reject) => {\n\t\t\tcontroller.signal.addEventListener('abort', () => reject(new Error('aborted')), {\n\t\t\t\tonce: true,\n\t\t\t})\n\t\t})\n\t\ttry {\n\t\t\twhile (!controller.signal.aborted) {\n\t\t\t\tawait Promise.race([\n\t\t\t\t\tnew Promise<void>((r) => {\n\t\t\t\t\t\tdevState.resolvers.add(r)\n\t\t\t\t\t}),\n\t\t\t\t\taborted,\n\t\t\t\t])\n\t\t\t\tyield 'data: reload\\n\\n'\n\t\t\t}\n\t\t} catch {\n\t\t\t/* aborted */\n\t\t}\n\t}\n\treturn {\n\t\tstatus: 200,\n\t\theaders: { ...SSE_HEADER, 'X-Accel-Buffering': 'no' },\n\t\tstream: withSseLifecycle(devStream(), { ...sseOptions, sseIdleTimeout: 0 }),\n\t\tonCancel: () => controller.abort(),\n\t}\n}\n","/* src/server/core/typescript/src/mime.ts */\n\nexport const MIME_TYPES: Record<string, string> = {\n\t'.js': 'application/javascript',\n\t'.mjs': 'application/javascript',\n\t'.css': 'text/css',\n\t'.html': 'text/html',\n\t'.json': 'application/json',\n\t'.svg': 'image/svg+xml',\n\t'.png': 'image/png',\n\t'.jpg': 'image/jpeg',\n\t'.jpeg': 'image/jpeg',\n\t'.gif': 'image/gif',\n\t'.woff': 'font/woff',\n\t'.woff2': 'font/woff2',\n\t'.ttf': 'font/ttf',\n\t'.ico': 'image/x-icon',\n\t'.webp': 'image/webp',\n\t'.txt': 'text/plain',\n\t'.xml': 'application/xml',\n\t'.webmanifest': 'application/manifest+json',\n\t'.map': 'application/json',\n\t'.ts': 'application/javascript',\n\t'.tsx': 'application/javascript',\n}\n","/* src/server/core/typescript/src/http-response.ts */\n\nimport { readFile } from 'node:fs/promises'\nimport { extname, join } from 'node:path'\nimport { SeamError } from './errors.js'\nimport { MIME_TYPES } from './mime.js'\nimport type { HttpBodyResponse, HttpResponse } from './http.js'\n\nconst JSON_HEADER = { 'Content-Type': 'application/json' }\nconst PUBLIC_CACHE = 'public, max-age=3600'\nconst IMMUTABLE_CACHE = 'public, max-age=31536000, immutable'\nconst TEXT_ENCODINGS = new Set([\n\t'application/javascript',\n\t'application/json',\n\t'application/manifest+json',\n\t'application/xml',\n\t'image/svg+xml',\n])\n\nfunction normalizeBinaryBody(body: ArrayBufferView | ArrayBuffer): Uint8Array {\n\tif (body instanceof Uint8Array) return body\n\tif (body instanceof ArrayBuffer) return new Uint8Array(body)\n\treturn new Uint8Array(body.buffer, body.byteOffset, body.byteLength)\n}\n\nfunction isTextContentType(contentType: string): boolean {\n\tconst mime = contentType.split(';', 1)[0]?.trim().toLowerCase() ?? ''\n\treturn mime.startsWith('text/') || TEXT_ENCODINGS.has(mime)\n}\n\nasync function readResponseBody(\n\tfilePath: string,\n\tcontentType: string,\n): Promise<string | Uint8Array> {\n\tconst content = await readFile(filePath)\n\treturn isTextContentType(contentType) ? content.toString('utf-8') : content\n}\n\nexport function jsonResponse(status: number, body: unknown): HttpBodyResponse {\n\treturn { status, headers: JSON_HEADER, body }\n}\n\nexport function errorResponse(status: number, code: string, message: string): HttpBodyResponse {\n\treturn jsonResponse(status, new SeamError(code, message).toJSON())\n}\n\nexport async function handleStaticAsset(\n\tassetPath: string,\n\tstaticDir: string,\n): Promise<HttpBodyResponse> {\n\tif (assetPath.includes('..')) {\n\t\treturn errorResponse(403, 'VALIDATION_ERROR', 'Forbidden')\n\t}\n\n\tconst filePath = join(staticDir, assetPath)\n\ttry {\n\t\tconst ext = extname(filePath)\n\t\tconst contentType = MIME_TYPES[ext] || 'application/octet-stream'\n\t\tconst content = await readResponseBody(filePath, contentType)\n\t\treturn {\n\t\t\tstatus: 200,\n\t\t\theaders: {\n\t\t\t\t'Content-Type': contentType,\n\t\t\t\t'Cache-Control': IMMUTABLE_CACHE,\n\t\t\t},\n\t\t\tbody: content,\n\t\t}\n\t} catch {\n\t\treturn errorResponse(404, 'NOT_FOUND', 'Asset not found')\n\t}\n}\n\nexport async function handlePublicFile(\n\tpathname: string,\n\tpublicDir: string,\n): Promise<HttpBodyResponse | null> {\n\tif (pathname.includes('..')) return null\n\tconst filePath = join(publicDir, pathname)\n\ttry {\n\t\tconst ext = extname(filePath)\n\t\tconst contentType = MIME_TYPES[ext] || 'application/octet-stream'\n\t\tconst content = await readResponseBody(filePath, contentType)\n\t\treturn {\n\t\t\tstatus: 200,\n\t\t\theaders: { 'Content-Type': contentType, 'Cache-Control': PUBLIC_CACHE },\n\t\t\tbody: content,\n\t\t}\n\t} catch {\n\t\treturn null\n\t}\n}\n\nexport function serialize(body: unknown): string | Uint8Array {\n\tif (typeof body === 'string') return body\n\tif (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) {\n\t\treturn normalizeBinaryBody(body)\n\t}\n\treturn JSON.stringify(body)\n}\n\nexport async function drainStream(\n\tstream: AsyncIterable<string>,\n\twrite: (chunk: string) => boolean | void,\n): Promise<void> {\n\ttry {\n\t\tfor await (const chunk of stream) {\n\t\t\tif (write(chunk) === false) break\n\t\t}\n\t} catch {\n\t\t// Client disconnected\n\t}\n}\n\nexport function toWebResponse(result: HttpResponse): Response {\n\tif ('stream' in result) {\n\t\tconst stream = result.stream\n\t\tconst onCancel = result.onCancel\n\t\tconst encoder = new TextEncoder()\n\t\tconst readable = new ReadableStream({\n\t\t\tasync start(controller) {\n\t\t\t\tawait drainStream(stream, (chunk) => {\n\t\t\t\t\tcontroller.enqueue(encoder.encode(chunk))\n\t\t\t\t})\n\t\t\t\tcontroller.close()\n\t\t\t},\n\t\t\tcancel() {\n\t\t\t\tonCancel?.()\n\t\t\t},\n\t\t})\n\t\treturn new Response(readable, { status: result.status, headers: result.headers })\n\t}\n\treturn new Response(serialize(result.body) as BodyInit, {\n\t\tstatus: result.status,\n\t\theaders: result.headers,\n\t})\n}\n","/* src/server/core/typescript/src/http.ts */\n\nimport type { RawContextMap } from './context.js'\nimport { buildRawContext } from './context.js'\nimport { watchReloadTrigger } from './dev/index.js'\nimport { loadBuildDev } from './page/build-loader.js'\nimport type { SeamFileHandle } from './procedure.js'\nimport type { DefinitionMap, Router } from './router/index.js'\nimport {\n\tbuildHashLookup,\n\tcreateDevReloadResponse,\n\tgetSseHeaders,\n\tsseCompleteEvent,\n\tsseDataEvent,\n\tsseDataEventWithId,\n\tsseErrorEvent,\n\tsseStream,\n\tsseStreamForStream,\n\twithSseLifecycle,\n} from './http-sse.js'\nimport {\n\tdrainStream,\n\terrorResponse,\n\thandlePublicFile,\n\thandleStaticAsset,\n\tjsonResponse,\n\tserialize,\n\ttoWebResponse,\n} from './http-response.js'\n\nexport interface HttpRequest {\n\tmethod: string\n\turl: string\n\tbody: () => Promise<unknown>\n\theader?: (name: string) => string | null\n\tfile?: () => Promise<SeamFileHandle | null>\n}\n\nexport interface HttpBodyResponse {\n\tstatus: number\n\theaders: Record<string, string>\n\tbody: unknown\n}\n\nexport interface HttpStreamResponse {\n\tstatus: number\n\theaders: Record<string, string>\n\tstream: AsyncIterable<string>\n\tonCancel?: () => void\n}\n\nexport type HttpResponse = HttpBodyResponse | HttpStreamResponse\n\nexport type HttpHandler = (req: HttpRequest) => Promise<HttpResponse>\n\nexport interface RpcHashMap {\n\tprocedures: Record<string, string>\n\tbatch: string\n}\n\nexport interface SseOptions {\n\theartbeatInterval?: number\n\tsseIdleTimeout?: number\n}\n\nexport interface HttpHandlerOptions {\n\tstaticDir?: string\n\tpublicDir?: string\n\tfallback?: HttpHandler\n\trpcHashMap?: RpcHashMap\n\tsseOptions?: SseOptions\n\tdevBuildDir?: string\n}\n\nconst PROCEDURE_PREFIX = '/_seam/procedure/'\nconst PAGE_PREFIX = '/_seam/page/'\nconst DATA_PREFIX = '/_seam/data/'\nconst STATIC_PREFIX = '/_seam/static/'\nconst MANIFEST_PATH = '/_seam/manifest.json'\nconst DEV_RELOAD_PATH = '/_seam/dev/reload'\n\nconst HTML_HEADER = { 'Content-Type': 'text/html; charset=utf-8' }\n\nfunction getPageRequestHeaders(req: HttpRequest):\n\t| {\n\t\t\turl: string\n\t\t\tcookie?: string\n\t\t\tacceptLanguage?: string\n\t }\n\t| undefined {\n\tif (!req.header) return undefined\n\treturn {\n\t\turl: req.url,\n\t\tcookie: req.header('cookie') ?? undefined,\n\t\tacceptLanguage: req.header('accept-language') ?? undefined,\n\t}\n}\n\nasync function handleBatchHttp<T extends DefinitionMap>(\n\treq: HttpRequest,\n\trouter: Router<T>,\n\thashToName: Map<string, string> | null,\n\trawCtx?: RawContextMap,\n): Promise<HttpBodyResponse> {\n\tlet body: unknown\n\ttry {\n\t\tbody = await req.body()\n\t} catch {\n\t\treturn errorResponse(400, 'VALIDATION_ERROR', 'Invalid JSON body')\n\t}\n\tif (!body || typeof body !== 'object' || !Array.isArray((body as { calls?: unknown }).calls)) {\n\t\treturn errorResponse(400, 'VALIDATION_ERROR', \"Batch request must have a 'calls' array\")\n\t}\n\tconst calls = (body as { calls: Array<{ procedure?: unknown; input?: unknown }> }).calls.map(\n\t\t(c) => ({\n\t\t\tprocedure:\n\t\t\t\ttypeof c.procedure === 'string' ? (hashToName?.get(c.procedure) ?? c.procedure) : '',\n\t\t\tinput: c.input ?? {},\n\t\t}),\n\t)\n\tconst result = await router.handleBatch(calls, rawCtx)\n\treturn jsonResponse(200, { ok: true, data: result })\n}\n\nfunction resolveHashName(hashToName: Map<string, string> | null, name: string): string {\n\tif (!hashToName) return name\n\treturn hashToName.get(name) ?? name\n}\n\nasync function handleProcedurePost<T extends DefinitionMap>(\n\treq: HttpRequest,\n\trouter: Router<T>,\n\tname: string,\n\trawCtx?: RawContextMap,\n\tsseOptions?: SseOptions,\n): Promise<HttpResponse> {\n\tlet body: unknown\n\ttry {\n\t\tbody = await req.body()\n\t} catch {\n\t\treturn errorResponse(400, 'VALIDATION_ERROR', 'Invalid JSON body')\n\t}\n\n\tif (router.getKind(name) === 'stream') {\n\t\tconst controller = new AbortController()\n\t\treturn {\n\t\t\tstatus: 200,\n\t\t\theaders: getSseHeaders(),\n\t\t\tstream: withSseLifecycle(\n\t\t\t\tsseStreamForStream(router, name, body, controller.signal, rawCtx),\n\t\t\t\tsseOptions,\n\t\t\t),\n\t\t\tonCancel: () => controller.abort(),\n\t\t}\n\t}\n\n\tif (router.getKind(name) === 'upload') {\n\t\tif (!req.file) {\n\t\t\treturn errorResponse(400, 'VALIDATION_ERROR', 'Upload requires multipart/form-data')\n\t\t}\n\t\tconst file = await req.file()\n\t\tif (!file) {\n\t\t\treturn errorResponse(400, 'VALIDATION_ERROR', 'Upload requires file in multipart body')\n\t\t}\n\t\tconst result = await router.handleUpload(name, body, file, rawCtx)\n\t\treturn jsonResponse(result.status, result.body)\n\t}\n\n\tconst result = await router.handle(name, body, rawCtx)\n\treturn jsonResponse(result.status, result.body)\n}\n\nexport function createHttpHandler<T extends DefinitionMap>(\n\trouter: Router<T>,\n\topts?: HttpHandlerOptions,\n): HttpHandler {\n\tconst effectiveHashMap = opts?.rpcHashMap ?? router.rpcHashMap\n\tconst hashToName = buildHashLookup(effectiveHashMap)\n\tconst batchHash = effectiveHashMap?.batch ?? null\n\tconst hasCtx = router.hasContext()\n\n\tconst devDir =\n\t\topts?.devBuildDir ??\n\t\t(process.env.SEAM_DEV === '1' && process.env.SEAM_VITE !== '1'\n\t\t\t? process.env.SEAM_OUTPUT_DIR\n\t\t\t: undefined)\n\tconst devState: { resolvers: Set<() => void> } | null = devDir ? { resolvers: new Set() } : null\n\tif (devState && devDir) {\n\t\twatchReloadTrigger(devDir, () => {\n\t\t\ttry {\n\t\t\t\trouter.reload(loadBuildDev(devDir))\n\t\t\t} catch {\n\t\t\t\t// Manifest might be mid-write; skip this reload cycle\n\t\t\t}\n\t\t\tconst batch = devState.resolvers\n\t\t\tdevState.resolvers = new Set()\n\t\t\tfor (const r of batch) r()\n\t\t})\n\t}\n\n\treturn async (req) => {\n\t\tconst url = new URL(req.url, 'http://localhost')\n\t\tconst { pathname } = url\n\n\t\tconst rawCtx: RawContextMap | undefined = hasCtx\n\t\t\t? buildRawContext(router.ctxConfig, req.header, url)\n\t\t\t: undefined\n\n\t\tif (req.method === 'GET' && pathname === MANIFEST_PATH) {\n\t\t\tif (effectiveHashMap) return errorResponse(403, 'FORBIDDEN', 'Manifest disabled')\n\t\t\treturn jsonResponse(200, router.manifest())\n\t\t}\n\n\t\tif (pathname.startsWith(PROCEDURE_PREFIX)) {\n\t\t\tconst rawName = pathname.slice(PROCEDURE_PREFIX.length)\n\t\t\tif (!rawName) {\n\t\t\t\treturn errorResponse(404, 'NOT_FOUND', 'Empty procedure name')\n\t\t\t}\n\n\t\t\tif (req.method === 'POST') {\n\t\t\t\tif (rawName === '_batch' || (batchHash && rawName === batchHash)) {\n\t\t\t\t\treturn handleBatchHttp(req, router, hashToName, rawCtx)\n\t\t\t\t}\n\t\t\t\tconst name = resolveHashName(hashToName, rawName)\n\t\t\t\treturn handleProcedurePost(req, router, name, rawCtx, opts?.sseOptions)\n\t\t\t}\n\n\t\t\tif (req.method === 'GET') {\n\t\t\t\tconst name = resolveHashName(hashToName, rawName)\n\t\t\t\tconst rawInput = url.searchParams.get('input')\n\t\t\t\tlet input: unknown\n\t\t\t\ttry {\n\t\t\t\t\tinput = rawInput ? JSON.parse(rawInput) : {}\n\t\t\t\t} catch {\n\t\t\t\t\treturn errorResponse(400, 'VALIDATION_ERROR', 'Invalid input query parameter')\n\t\t\t\t}\n\n\t\t\t\tconst lastEventId = req.header?.('last-event-id') ?? undefined\n\t\t\t\treturn {\n\t\t\t\t\tstatus: 200,\n\t\t\t\t\theaders: getSseHeaders(),\n\t\t\t\t\tstream: withSseLifecycle(\n\t\t\t\t\t\tsseStream(router, name, input, rawCtx, lastEventId),\n\t\t\t\t\t\topts?.sseOptions,\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (req.method === 'GET' && pathname.startsWith(PAGE_PREFIX) && router.hasPages) {\n\t\t\tconst pagePath = '/' + pathname.slice(PAGE_PREFIX.length)\n\t\t\tconst headers = getPageRequestHeaders(req)\n\t\t\tconst result = await router.handlePage(pagePath, headers, rawCtx)\n\t\t\tif (result) {\n\t\t\t\treturn { status: result.status, headers: HTML_HEADER, body: result.html }\n\t\t\t}\n\t\t}\n\n\t\tif (req.method === 'GET' && pathname.startsWith(DATA_PREFIX) && router.hasPages) {\n\t\t\tconst pagePath = '/' + pathname.slice(DATA_PREFIX.length).replace(/\\/$/, '')\n\t\t\tconst dataResult = await router.handlePageData(pagePath)\n\t\t\tif (dataResult !== null) {\n\t\t\t\treturn jsonResponse(200, dataResult)\n\t\t\t}\n\t\t}\n\n\t\tif (req.method === 'GET' && pathname.startsWith(STATIC_PREFIX) && opts?.staticDir) {\n\t\t\tconst assetPath = pathname.slice(STATIC_PREFIX.length)\n\t\t\treturn handleStaticAsset(assetPath, opts.staticDir)\n\t\t}\n\n\t\tif (req.method === 'GET' && pathname === DEV_RELOAD_PATH && devState) {\n\t\t\treturn createDevReloadResponse(devState, opts?.sseOptions)\n\t\t}\n\n\t\tconst publicDir = opts?.publicDir ?? router.publicDir\n\t\tif (req.method === 'GET' && publicDir) {\n\t\t\tconst publicResult = await handlePublicFile(pathname, publicDir)\n\t\t\tif (publicResult) return publicResult\n\t\t}\n\n\t\tif (opts?.fallback) return opts.fallback(req)\n\t\treturn errorResponse(404, 'NOT_FOUND', 'Not found')\n\t}\n}\n\nexport {\n\tdrainStream,\n\tserialize,\n\tsseCompleteEvent,\n\tsseDataEvent,\n\tsseDataEventWithId,\n\tsseErrorEvent,\n\ttoWebResponse,\n}\n","/* src/server/core/typescript/src/subscription.ts */\n\n/**\n * Bridge callback-style event sources to an AsyncGenerator.\n *\n * Usage:\n * const stream = fromCallback<string>(({ emit, end, error }) => {\n * emitter.on(\"data\", emit);\n * emitter.on(\"end\", end);\n * emitter.on(\"error\", error);\n * return () => emitter.removeAllListeners();\n * });\n */\nexport interface CallbackSink<T> {\n\temit: (value: T) => void\n\tend: () => void\n\terror: (err: Error) => void\n}\n\ntype QueueItem<T> = { type: 'value'; value: T } | { type: 'end' } | { type: 'error'; error: Error }\n\nexport function fromCallback<T>(\n\tsetup: (sink: CallbackSink<T>) => (() => void) | void,\n): AsyncGenerator<T, void, undefined> {\n\tconst queue: QueueItem<T>[] = []\n\tlet resolve: (() => void) | null = null\n\tlet done = false\n\tfunction notify() {\n\t\tif (resolve) {\n\t\t\tconst r = resolve\n\t\t\tresolve = null\n\t\t\tr()\n\t\t}\n\t}\n\n\tconst sink: CallbackSink<T> = {\n\t\temit(value) {\n\t\t\tif (done) return\n\t\t\tqueue.push({ type: 'value', value })\n\t\t\tnotify()\n\t\t},\n\t\tend() {\n\t\t\tif (done) return\n\t\t\tdone = true\n\t\t\tqueue.push({ type: 'end' })\n\t\t\tnotify()\n\t\t},\n\t\terror(err) {\n\t\t\tif (done) return\n\t\t\tdone = true\n\t\t\tqueue.push({ type: 'error', error: err })\n\t\t\tnotify()\n\t\t},\n\t}\n\n\tconst cleanup = setup(sink)\n\n\tasync function* generate(): AsyncGenerator<T, void, undefined> {\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tif (queue.length === 0) {\n\t\t\t\t\tawait new Promise<void>((r) => {\n\t\t\t\t\t\tresolve = r\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t\twhile (queue.length > 0) {\n\t\t\t\t\tconst item = queue.shift() as QueueItem<T>\n\t\t\t\t\tif (item.type === 'value') {\n\t\t\t\t\t\tyield item.value\n\t\t\t\t\t} else if (item.type === 'error') {\n\t\t\t\t\t\tthrow item.error\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tdone = true\n\t\t\tif (cleanup) cleanup()\n\t\t}\n\t}\n\n\treturn generate()\n}\n","/* src/server/core/typescript/src/ws.ts */\n\nimport type { Router, DefinitionMap } from './router/index.js'\nimport { SeamError } from './errors.js'\n\nexport interface WsSink {\n\tsend(data: string): void\n\tping?: () => void\n\tclose?: () => void\n}\n\nexport interface ChannelWsSession {\n\tonMessage(data: string): void\n\tonPong(): void\n\tclose(): void\n}\n\nexport interface ChannelWsOptions {\n\theartbeatInterval?: number\n\tpongTimeout?: number\n}\n\ninterface UplinkMessage {\n\tid: string\n\tprocedure: string\n\tinput?: unknown\n}\n\nconst DEFAULT_HEARTBEAT_MS = 15_000\nconst DEFAULT_PONG_TIMEOUT_MS = 5_000\n\nfunction sendError(ws: WsSink, id: string | null, code: string, message: string): void {\n\tws.send(JSON.stringify({ id, ok: false, error: { code, message, transient: false } }))\n}\n\n/** Validate uplink message fields and channel scope */\nfunction parseUplink(ws: WsSink, data: string, channelName: string): UplinkMessage | null {\n\tlet msg: UplinkMessage\n\ttry {\n\t\tmsg = JSON.parse(data) as UplinkMessage\n\t} catch {\n\t\tsendError(ws, null, 'VALIDATION_ERROR', 'Invalid JSON')\n\t\treturn null\n\t}\n\tif (!msg.id || typeof msg.id !== 'string') {\n\t\tsendError(ws, null, 'VALIDATION_ERROR', \"Missing 'id' field\")\n\t\treturn null\n\t}\n\tif (!msg.procedure || typeof msg.procedure !== 'string') {\n\t\tsendError(ws, msg.id, 'VALIDATION_ERROR', \"Missing 'procedure' field\")\n\t\treturn null\n\t}\n\tconst prefix = channelName + '.'\n\tif (!msg.procedure.startsWith(prefix) || msg.procedure === `${channelName}.events`) {\n\t\tsendError(\n\t\t\tws,\n\t\t\tmsg.id,\n\t\t\t'VALIDATION_ERROR',\n\t\t\t`Procedure '${msg.procedure}' is not a command of channel '${channelName}'`,\n\t\t)\n\t\treturn null\n\t}\n\treturn msg\n}\n\n/** Dispatch validated uplink command through the router */\nfunction dispatchUplink<T extends DefinitionMap>(\n\trouter: Router<T>,\n\tws: WsSink,\n\tmsg: UplinkMessage,\n\tchannelInput: unknown,\n): void {\n\tconst mergedInput = {\n\t\t...(channelInput as Record<string, unknown>),\n\t\t...((msg.input ?? {}) as Record<string, unknown>),\n\t}\n\tvoid (async () => {\n\t\ttry {\n\t\t\tconst result = await router.handle(msg.procedure, mergedInput)\n\t\t\tif (result.status === 200) {\n\t\t\t\tconst envelope = result.body as { ok: true; data: unknown }\n\t\t\t\tws.send(JSON.stringify({ id: msg.id, ok: true, data: envelope.data }))\n\t\t\t} else {\n\t\t\t\tconst envelope = result.body as {\n\t\t\t\t\tok: false\n\t\t\t\t\terror: { code: string; message: string; transient: boolean }\n\t\t\t\t}\n\t\t\t\tws.send(JSON.stringify({ id: msg.id, ok: false, error: envelope.error }))\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tconst message = err instanceof Error ? err.message : 'Unknown error'\n\t\t\tsendError(ws, msg.id, 'INTERNAL_ERROR', message)\n\t\t}\n\t})()\n}\n\n/**\n * Start a WebSocket session for a channel.\n *\n * Reuses `router.handleSubscription` for the event stream and\n * `router.handle` for uplink command dispatch — no Router changes needed.\n */\nexport function startChannelWs<T extends DefinitionMap>(\n\trouter: Router<T>,\n\tchannelName: string,\n\tchannelInput: unknown,\n\tws: WsSink,\n\topts?: ChannelWsOptions,\n): ChannelWsSession {\n\tconst heartbeatMs = opts?.heartbeatInterval ?? DEFAULT_HEARTBEAT_MS\n\tconst pongTimeoutMs = opts?.pongTimeout ?? DEFAULT_PONG_TIMEOUT_MS\n\tlet closed = false\n\tlet pongTimer: ReturnType<typeof setTimeout> | null = null\n\n\t// Heartbeat timer — also sends ping frame when sink supports it\n\tconst heartbeatTimer = setInterval(() => {\n\t\tif (closed) return\n\t\tws.send(JSON.stringify({ heartbeat: true }))\n\t\tif (ws.ping) {\n\t\t\tws.ping()\n\t\t\tif (pongTimer) clearTimeout(pongTimer)\n\t\t\tpongTimer = setTimeout(() => {\n\t\t\t\tif (!closed) {\n\t\t\t\t\tclosed = true\n\t\t\t\t\tclearInterval(heartbeatTimer)\n\t\t\t\t\tvoid iter.return?.(undefined)\n\t\t\t\t\tws.close?.()\n\t\t\t\t}\n\t\t\t}, pongTimeoutMs)\n\t\t}\n\t}, heartbeatMs)\n\n\t// Start subscription and forward events as { event, payload }\n\tconst subIterable = router.handleSubscription(`${channelName}.events`, channelInput)\n\tconst iter = subIterable[Symbol.asyncIterator]()\n\n\tvoid (async () => {\n\t\ttry {\n\t\t\tfor (;;) {\n\t\t\t\tconst result: IteratorResult<unknown> = await iter.next()\n\t\t\t\tif (result.done || closed) break\n\t\t\t\tconst ev = result.value as { type: string; payload: unknown }\n\t\t\t\tws.send(JSON.stringify({ event: ev.type, payload: ev.payload }))\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tif (!closed) {\n\t\t\t\tconst code = err instanceof SeamError ? err.code : 'INTERNAL_ERROR'\n\t\t\t\tconst message = err instanceof Error ? err.message : 'Subscription error'\n\t\t\t\tws.send(JSON.stringify({ event: '__error', payload: { code, message } }))\n\t\t\t}\n\t\t}\n\t})()\n\n\treturn {\n\t\tonMessage(data: string) {\n\t\t\tif (closed) return\n\t\t\tconst msg = parseUplink(ws, data, channelName)\n\t\t\tif (msg) dispatchUplink(router, ws, msg, channelInput)\n\t\t},\n\n\t\tonPong() {\n\t\t\tif (pongTimer) {\n\t\t\t\tclearTimeout(pongTimer)\n\t\t\t\tpongTimer = null\n\t\t\t}\n\t\t},\n\n\t\tclose() {\n\t\t\tif (closed) return\n\t\t\tclosed = true\n\t\t\tclearInterval(heartbeatTimer)\n\t\t\tif (pongTimer) clearTimeout(pongTimer)\n\t\t\tvoid iter.return?.(undefined)\n\t\t},\n\t}\n}\n","/* src/server/core/typescript/src/proxy.ts */\n\nimport { readFile } from 'node:fs/promises'\nimport { join, extname } from 'node:path'\nimport type { HttpHandler, HttpBodyResponse } from './http.js'\nimport { MIME_TYPES } from './mime.js'\n\nexport interface DevProxyOptions {\n\t/** Target URL to forward requests to (e.g. \"http://localhost:5173\") */\n\ttarget: string\n}\n\nexport interface StaticHandlerOptions {\n\t/** Directory to serve static files from */\n\tdir: string\n}\n\n/** Forward non-seam requests to a dev server (e.g. Vite) */\nexport function createDevProxy(opts: DevProxyOptions): HttpHandler {\n\tconst target = opts.target.replace(/\\/$/, '')\n\n\treturn async (req) => {\n\t\tconst url = new URL(req.url, 'http://localhost')\n\t\tconst proxyUrl = `${target}${url.pathname}${url.search}`\n\n\t\ttry {\n\t\t\tconst resp = await fetch(proxyUrl, {\n\t\t\t\tmethod: req.method,\n\t\t\t\theaders: { Accept: '*/*' },\n\t\t\t})\n\n\t\t\tconst body = await resp.text()\n\t\t\tconst headers: Record<string, string> = {}\n\t\t\tresp.headers.forEach((value, key) => {\n\t\t\t\theaders[key] = value\n\t\t\t})\n\n\t\t\treturn { status: resp.status, headers, body }\n\t\t} catch {\n\t\t\treturn {\n\t\t\t\tstatus: 502,\n\t\t\t\theaders: { 'Content-Type': 'text/plain' },\n\t\t\t\tbody: `Bad Gateway: failed to connect to ${target}`,\n\t\t\t}\n\t\t}\n\t}\n}\n\n/** Serve static files from a directory, with index.html fallback for directories */\nexport function createStaticHandler(opts: StaticHandlerOptions): HttpHandler {\n\tconst dir = opts.dir\n\n\treturn async (req): Promise<HttpBodyResponse> => {\n\t\tconst url = new URL(req.url, 'http://localhost')\n\t\tlet filePath = url.pathname\n\n\t\tif (filePath.includes('..')) {\n\t\t\treturn {\n\t\t\t\tstatus: 403,\n\t\t\t\theaders: { 'Content-Type': 'text/plain' },\n\t\t\t\tbody: 'Forbidden',\n\t\t\t}\n\t\t}\n\n\t\t// Serve index.html for directory paths\n\t\tif (filePath.endsWith('/')) {\n\t\t\tfilePath += 'index.html'\n\t\t}\n\n\t\tconst fullPath = join(dir, filePath)\n\t\ttry {\n\t\t\tconst content = await readFile(fullPath)\n\t\t\tconst ext = extname(fullPath)\n\t\t\tconst contentType = MIME_TYPES[ext] || 'application/octet-stream'\n\t\t\treturn {\n\t\t\t\tstatus: 200,\n\t\t\t\theaders: { 'Content-Type': contentType },\n\t\t\t\tbody: content.toString(),\n\t\t\t}\n\t\t} catch {\n\t\t\treturn {\n\t\t\t\tstatus: 404,\n\t\t\t\theaders: { 'Content-Type': 'text/plain' },\n\t\t\t\tbody: 'Not found',\n\t\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