@canmi/seam-server 0.5.10 → 0.5.27
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 +2 -2
- package/dist/index.d.ts +215 -62
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +672 -290
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["primitives"],"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/router/handler.ts","../src/page/projection.ts","../src/page/handler.ts","../src/page/route-matcher.ts","../src/resolve.ts","../src/router/categorize.ts","../src/router/index.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 readonly _schema: JTDSchema\n /** Phantom type marker — never exists at runtime */\n readonly _output: TOutput\n}\n\nexport interface OptionalSchemaNode<TOutput = unknown> extends SchemaNode<TOutput> {\n readonly _optional: true\n}\n\nexport type Infer<T extends SchemaNode> = T['_output']\n\nexport function createSchemaNode<T>(schema: JTDSchema): SchemaNode<T> {\n return { _schema: schema } as SchemaNode<T>\n}\n\nexport function createOptionalSchemaNode<T>(schema: JTDSchema): OptionalSchemaNode<T> {\n return { _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 return createSchemaNode<string>({ type: 'string' })\n}\n\nexport function boolean(): SchemaNode<boolean> {\n return createSchemaNode<boolean>({ type: 'boolean' })\n}\n\nexport function int8(): SchemaNode<number> {\n return createSchemaNode<number>({ type: 'int8' })\n}\n\nexport function int16(): SchemaNode<number> {\n return createSchemaNode<number>({ type: 'int16' })\n}\n\nexport function int32(): SchemaNode<number> {\n return createSchemaNode<number>({ type: 'int32' })\n}\n\nexport function uint8(): SchemaNode<number> {\n return createSchemaNode<number>({ type: 'uint8' })\n}\n\nexport function uint16(): SchemaNode<number> {\n return createSchemaNode<number>({ type: 'uint16' })\n}\n\nexport function uint32(): SchemaNode<number> {\n return createSchemaNode<number>({ type: 'uint32' })\n}\n\nexport function float32(): SchemaNode<number> {\n return createSchemaNode<number>({ type: 'float32' })\n}\n\nexport function float64(): SchemaNode<number> {\n return createSchemaNode<number>({ type: 'float64' })\n}\n\nexport function timestamp(): SchemaNode<string> {\n return createSchemaNode<string>({ type: 'timestamp' })\n}\n\nexport function html(): SchemaNode<string> {\n return 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 [K in keyof T]: T[K] extends OptionalSchemaNode ? never : K\n}[keyof T]\n\ntype OptionalKeys<T extends Record<string, SchemaNode>> = {\n [K in keyof T]: T[K] extends OptionalSchemaNode ? K : never\n}[keyof T]\n\ntype InferObject<T extends Record<string, SchemaNode>> = Simplify<\n { [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 fields: T,\n): SchemaNode<InferObject<T>> {\n const properties: Record<string, JTDSchema> = {}\n const optionalProperties: Record<string, JTDSchema> = {}\n\n for (const [key, node] of Object.entries(fields)) {\n if ('_optional' in node && node._optional === true) {\n optionalProperties[key] = node._schema\n } else {\n properties[key] = node._schema\n }\n }\n\n const schema: Record<string, unknown> = {}\n if (Object.keys(properties).length > 0 || Object.keys(optionalProperties).length === 0) {\n schema.properties = properties\n }\n if (Object.keys(optionalProperties).length > 0) {\n schema.optionalProperties = optionalProperties\n }\n\n return createSchemaNode<InferObject<T>>(schema as JTDSchema)\n}\n\nexport function optional<T>(node: SchemaNode<T>): OptionalSchemaNode<T> {\n return createOptionalSchemaNode<T>(node._schema)\n}\n\nexport function array<T>(node: SchemaNode<T>): SchemaNode<T[]> {\n return createSchemaNode<T[]>({ elements: node._schema })\n}\n\nexport function nullable<T>(node: SchemaNode<T>): SchemaNode<T | null> {\n return 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 return createSchemaNode<T[number]>({ enum: [...values] } as JTDSchema)\n}\n\nexport function values<T>(node: SchemaNode<T>): SchemaNode<Record<string, T>> {\n return createSchemaNode<Record<string, T>>({ values: node._schema })\n}\n\ntype DiscriminatorUnion<TTag extends string, TMapping extends Record<string, SchemaNode>> = {\n [K in keyof TMapping & string]: Simplify<{ [P in TTag]: K } & Infer<TMapping[K]>>\n}[keyof TMapping & string]\n\nexport function discriminator<\n TTag extends string,\n TMapping extends Record<string, SchemaNode<Record<string, unknown>>>,\n>(tag: TTag, mapping: TMapping): SchemaNode<DiscriminatorUnion<TTag, TMapping>> {\n const jtdMapping: Record<string, JTDSchema> = {}\n for (const [key, node] of Object.entries(mapping)) {\n jtdMapping[key] = node._schema\n }\n return createSchemaNode<DiscriminatorUnion<TTag, TMapping>>({\n discriminator: tag,\n mapping: jtdMapping,\n } 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 ...primitives,\n object,\n optional,\n array,\n nullable,\n enum: enumType,\n values,\n discriminator,\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 valid: boolean\n errors: JTDValidationError[]\n}\n\nexport function validateInput(schema: Schema, data: unknown): ValidationResult {\n const errors = validate(schema, data, { maxDepth: 32, maxErrors: 10 })\n return {\n valid: errors.length === 0,\n errors,\n }\n}\n\nexport function formatValidationErrors(errors: JTDValidationError[]): string {\n return errors\n .map((e) => {\n const path = e.instancePath.length > 0 ? e.instancePath.join('/') : '(root)'\n const schema = e.schemaPath.join('/')\n return `${path} (schema: ${schema})`\n })\n .join('; ')\n}\n","/* src/server/core/typescript/src/errors.ts */\n\nexport type ErrorCode =\n | 'VALIDATION_ERROR'\n | 'NOT_FOUND'\n | 'UNAUTHORIZED'\n | 'FORBIDDEN'\n | 'RATE_LIMITED'\n | 'INTERNAL_ERROR'\n | (string & {})\n\nexport const DEFAULT_STATUS: Record<string, number> = {\n VALIDATION_ERROR: 400,\n UNAUTHORIZED: 401,\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n RATE_LIMITED: 429,\n INTERNAL_ERROR: 500,\n}\n\nexport class SeamError extends Error {\n readonly code: string\n readonly status: number\n\n constructor(code: string, message: string, status?: number) {\n super(message)\n this.code = code\n this.status = status ?? DEFAULT_STATUS[code] ?? 500\n this.name = 'SeamError'\n }\n\n toJSON() {\n return {\n ok: false,\n error: {\n code: this.code,\n message: this.message,\n transient: false,\n },\n }\n }\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 extract: string\n schema: 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 const idx = rule.indexOf(':')\n if (idx === -1) {\n throw new Error(`Invalid extract rule \"${rule}\": expected \"source:key\" format`)\n }\n const source = rule.slice(0, idx)\n const key = rule.slice(idx + 1)\n if (!source || !key) {\n throw new Error(`Invalid extract rule \"${rule}\": source and key must be non-empty`)\n }\n return { source, key }\n}\n\n/** Collect all header names needed by the context config */\nexport function contextExtractKeys(config: ContextConfig): string[] {\n const keys: string[] = []\n for (const field of Object.values(config)) {\n const { source, key } = parseExtractRule(field.extract)\n if (source === 'header') {\n keys.push(key)\n }\n }\n return [...new Set(keys)]\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 config: ContextConfig,\n raw: RawContextMap,\n requestedKeys: string[],\n): Record<string, unknown> {\n const result: Record<string, unknown> = {}\n\n for (const key of requestedKeys) {\n const field = config[key]\n if (!field) {\n throw new SeamError(\n 'CONTEXT_ERROR',\n `Context field \"${key}\" is not defined in router context config`,\n 400,\n )\n }\n\n const { source, key: extractKey } = parseExtractRule(field.extract)\n const rawKey = source === 'header' ? extractKey : extractKey\n const rawValue = raw[rawKey] ?? null\n\n let value: unknown\n if (rawValue === null) {\n value = null\n } else {\n const schema = field.schema._schema\n // If the root schema is { type: \"string\" } or nullable string, use raw value directly\n const isStringSchema =\n 'type' in schema && schema.type === 'string' && !('nullable' in schema && schema.nullable)\n const isNullableStringSchema =\n 'type' in schema && schema.type === 'string' && 'nullable' in schema && schema.nullable\n\n if (isStringSchema || isNullableStringSchema) {\n value = rawValue\n } else {\n // Attempt JSON parse for complex types\n try {\n value = JSON.parse(rawValue)\n } catch {\n throw new SeamError(\n 'CONTEXT_ERROR',\n `Context field \"${key}\": failed to parse value as JSON`,\n 400,\n )\n }\n }\n }\n\n const validation = validateInput(field.schema._schema, value)\n if (!validation.valid) {\n const details = formatValidationErrors(validation.errors)\n throw new SeamError(\n 'CONTEXT_ERROR',\n `Context field \"${key}\" validation failed: ${details}`,\n 400,\n )\n }\n\n result[key] = value\n }\n\n return result\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 from: string\n each?: boolean\n}\n\nexport interface NormalizedInvalidateTarget {\n query: string\n mapping?: Record<string, NormalizedMappingValue>\n}\n\nexport interface ContextManifestEntry {\n extract: string\n schema: Schema\n}\n\nexport interface ProcedureEntry {\n kind: ProcedureType\n input: Schema\n output?: Schema\n chunkOutput?: Schema\n error?: Schema\n invalidates?: NormalizedInvalidateTarget[]\n context?: string[]\n transport?: { prefer: string; fallback?: string[] }\n suppress?: string[]\n cache?: false | { ttl: number }\n}\n\nexport interface ProcedureManifest {\n version: number\n context: Record<string, ContextManifestEntry>\n procedures: Record<string, ProcedureEntry>\n channels?: Record<string, ChannelMeta>\n transportDefaults: Record<string, { prefer: string; fallback?: string[] }>\n}\n\ntype InvalidateInput = Array<\n | string\n | {\n query: string\n mapping?: Record<string, string | { from: string; each?: boolean }>\n }\n>\n\nfunction normalizeInvalidates(targets: InvalidateInput): NormalizedInvalidateTarget[] {\n return targets.map((t) => {\n if (typeof t === 'string') return { query: t }\n const normalized: NormalizedInvalidateTarget = { query: t.query }\n if (t.mapping) {\n normalized.mapping = Object.fromEntries(\n Object.entries(t.mapping).map(([k, v]) => [k, typeof v === 'string' ? { from: v } : v]),\n )\n }\n return normalized\n })\n}\n\nexport function buildManifest(\n definitions: Record<\n string,\n {\n input: SchemaNode\n output: SchemaNode\n kind?: string\n type?: string\n error?: SchemaNode\n context?: string[]\n invalidates?: InvalidateInput\n }\n >,\n channels?: Record<string, ChannelMeta>,\n contextConfig?: ContextConfig,\n transportDefaults?: Record<string, { prefer: string; fallback?: string[] }>,\n): ProcedureManifest {\n const mapped: ProcedureManifest['procedures'] = {}\n\n for (const [name, def] of Object.entries(definitions)) {\n const k = def.kind ?? def.type\n const kind: ProcedureType =\n k === 'upload'\n ? 'upload'\n : k === 'stream'\n ? 'stream'\n : k === 'subscription'\n ? 'subscription'\n : k === 'command'\n ? 'command'\n : 'query'\n const entry: ProcedureEntry = { kind, input: def.input._schema }\n if (kind === 'stream') {\n entry.chunkOutput = def.output._schema\n } else {\n entry.output = def.output._schema\n }\n if (def.error) {\n entry.error = def.error._schema\n }\n if (kind === 'command' && def.invalidates && def.invalidates.length > 0) {\n entry.invalidates = normalizeInvalidates(def.invalidates)\n }\n if (def.context && def.context.length > 0) {\n entry.context = def.context\n }\n const defAny = def as Record<string, unknown>\n if (defAny.transport) {\n entry.transport = defAny.transport as { prefer: string; fallback?: string[] }\n }\n if (defAny.suppress) {\n entry.suppress = defAny.suppress as string[]\n }\n if (defAny.cache !== undefined) {\n entry.cache = defAny.cache as false | { ttl: number }\n }\n mapped[name] = entry\n }\n\n const context: Record<string, ContextManifestEntry> = {}\n if (contextConfig) {\n for (const [key, field] of Object.entries(contextConfig)) {\n context[key] = { extract: field.extract, schema: field.schema._schema }\n }\n }\n\n const manifest: ProcedureManifest = {\n version: 2,\n context,\n procedures: mapped,\n transportDefaults: transportDefaults ?? {},\n }\n if (channels && Object.keys(channels).length > 0) {\n manifest.channels = channels\n }\n return manifest\n}\n","/* src/server/core/typescript/src/router/handler.ts */\n\nimport { SeamError } from '../errors.js'\nimport type {\n HandleResult,\n InternalProcedure,\n InternalSubscription,\n InternalStream,\n InternalUpload,\n SeamFileHandle,\n} from '../procedure.js'\nimport { validateInput, formatValidationErrors } from '../validation/index.js'\n\nexport type { HandleResult, InternalProcedure } from '../procedure.js'\n\nexport async function handleRequest(\n procedures: Map<string, InternalProcedure>,\n procedureName: string,\n rawBody: unknown,\n validateOutput?: boolean,\n ctx?: Record<string, unknown>,\n): Promise<HandleResult> {\n const procedure = procedures.get(procedureName)\n if (!procedure) {\n return {\n status: 404,\n body: new SeamError('NOT_FOUND', `Procedure '${procedureName}' not found`).toJSON(),\n }\n }\n\n const validation = validateInput(procedure.inputSchema, rawBody)\n if (!validation.valid) {\n const details = formatValidationErrors(validation.errors)\n return {\n status: 400,\n body: new SeamError('VALIDATION_ERROR', `Input validation failed: ${details}`).toJSON(),\n }\n }\n\n try {\n const result = await procedure.handler({ input: rawBody, ctx: ctx ?? {} })\n\n if (validateOutput) {\n const outValidation = validateInput(procedure.outputSchema, result)\n if (!outValidation.valid) {\n const details = formatValidationErrors(outValidation.errors)\n return {\n status: 500,\n body: new SeamError('INTERNAL_ERROR', `Output validation failed: ${details}`).toJSON(),\n }\n }\n }\n\n return { status: 200, body: { ok: true, data: result } }\n } catch (error) {\n if (error instanceof SeamError) {\n return { status: error.status, body: error.toJSON() }\n }\n const message = error instanceof Error ? error.message : 'Unknown error'\n return {\n status: 500,\n body: new SeamError('INTERNAL_ERROR', message).toJSON(),\n }\n }\n}\n\nexport interface BatchCall {\n procedure: string\n input: unknown\n}\n\nexport type BatchResultItem =\n | { ok: true; data: unknown }\n | { ok: false; error: { code: string; message: string; transient: boolean } }\n\nexport async function handleBatchRequest(\n procedures: Map<string, InternalProcedure>,\n calls: BatchCall[],\n validateOutput?: boolean,\n ctxResolver?: (procedureName: string) => Record<string, unknown>,\n): Promise<{ results: BatchResultItem[] }> {\n const results = await Promise.all(\n calls.map(async (call) => {\n const ctx = ctxResolver ? ctxResolver(call.procedure) : undefined\n const result = await handleRequest(\n procedures,\n call.procedure,\n call.input,\n validateOutput,\n ctx,\n )\n if (result.status === 200) {\n const envelope = result.body as { ok: true; data: unknown }\n return { ok: true as const, data: envelope.data }\n }\n const envelope = result.body as {\n ok: false\n error: { code: string; message: string; transient: boolean }\n }\n return { ok: false as const, error: envelope.error }\n }),\n )\n return { results }\n}\n\nexport async function* handleSubscription(\n subscriptions: Map<string, InternalSubscription>,\n name: string,\n rawInput: unknown,\n validateOutput?: boolean,\n ctx?: Record<string, unknown>,\n): AsyncIterable<unknown> {\n const sub = subscriptions.get(name)\n if (!sub) {\n throw new SeamError('NOT_FOUND', `Subscription '${name}' not found`)\n }\n\n const validation = validateInput(sub.inputSchema, rawInput)\n if (!validation.valid) {\n const details = formatValidationErrors(validation.errors)\n throw new SeamError('VALIDATION_ERROR', `Input validation failed: ${details}`)\n }\n\n for await (const value of sub.handler({ input: rawInput, ctx: ctx ?? {} })) {\n if (validateOutput) {\n const outValidation = validateInput(sub.outputSchema, value)\n if (!outValidation.valid) {\n const details = formatValidationErrors(outValidation.errors)\n throw new SeamError('INTERNAL_ERROR', `Output validation failed: ${details}`)\n }\n }\n yield value\n }\n}\n\nexport async function handleUploadRequest(\n uploads: Map<string, InternalUpload>,\n procedureName: string,\n rawBody: unknown,\n file: SeamFileHandle,\n validateOutput?: boolean,\n ctx?: Record<string, unknown>,\n): Promise<HandleResult> {\n const upload = uploads.get(procedureName)\n if (!upload) {\n return {\n status: 404,\n body: new SeamError('NOT_FOUND', `Procedure '${procedureName}' not found`).toJSON(),\n }\n }\n\n const validation = validateInput(upload.inputSchema, rawBody)\n if (!validation.valid) {\n const details = formatValidationErrors(validation.errors)\n return {\n status: 400,\n body: new SeamError('VALIDATION_ERROR', `Input validation failed: ${details}`).toJSON(),\n }\n }\n\n try {\n const result = await upload.handler({ input: rawBody, file, ctx: ctx ?? {} })\n\n if (validateOutput) {\n const outValidation = validateInput(upload.outputSchema, result)\n if (!outValidation.valid) {\n const details = formatValidationErrors(outValidation.errors)\n return {\n status: 500,\n body: new SeamError('INTERNAL_ERROR', `Output validation failed: ${details}`).toJSON(),\n }\n }\n }\n\n return { status: 200, body: { ok: true, data: result } }\n } catch (error) {\n if (error instanceof SeamError) {\n return { status: error.status, body: error.toJSON() }\n }\n const message = error instanceof Error ? error.message : 'Unknown error'\n return {\n status: 500,\n body: new SeamError('INTERNAL_ERROR', message).toJSON(),\n }\n }\n}\n\nexport async function* handleStream(\n streams: Map<string, InternalStream>,\n name: string,\n rawInput: unknown,\n validateOutput?: boolean,\n ctx?: Record<string, unknown>,\n): AsyncGenerator<unknown> {\n const stream = streams.get(name)\n if (!stream) {\n throw new SeamError('NOT_FOUND', `Stream '${name}' not found`)\n }\n\n const validation = validateInput(stream.inputSchema, rawInput)\n if (!validation.valid) {\n const details = formatValidationErrors(validation.errors)\n throw new SeamError('VALIDATION_ERROR', `Input validation failed: ${details}`)\n }\n\n for await (const value of stream.handler({ input: rawInput, ctx: ctx ?? {} })) {\n if (validateOutput) {\n const outValidation = validateInput(stream.chunkOutputSchema, value)\n if (!outValidation.valid) {\n const details = formatValidationErrors(outValidation.errors)\n throw new SeamError('INTERNAL_ERROR', `Output validation failed: ${details}`)\n }\n }\n yield value\n }\n}\n","/* src/server/core/typescript/src/page/projection.ts */\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 const parts = path.split('.')\n let current: Record<string, unknown> = target\n for (let i = 0; i < parts.length - 1; i++) {\n const key = parts[i] as string\n if (!(key in current) || typeof current[key] !== 'object' || current[key] === null) {\n current[key] = {}\n }\n current = current[key] as Record<string, unknown>\n }\n current[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 const parts = path.split('.')\n let current: unknown = source\n for (const part of parts) {\n if (current === null || current === undefined || typeof current !== 'object') {\n return undefined\n }\n current = (current as Record<string, unknown>)[part]\n }\n return current\n}\n\n/** Prune a single value according to its projected field paths. */\nfunction pruneValue(value: unknown, fields: string[]): unknown {\n // Separate $ paths (array element fields) from plain paths\n const arrayFields: string[] = []\n const plainFields: string[] = []\n\n for (const f of fields) {\n if (f === '$') {\n // Standalone $ means keep entire array elements — return value as-is\n return value\n } else if (f.startsWith('$.')) {\n arrayFields.push(f.slice(2))\n } else {\n plainFields.push(f)\n }\n }\n\n if (arrayFields.length > 0 && Array.isArray(value)) {\n return value.map((item: unknown) => {\n if (typeof item !== 'object' || item === null) return item\n const pruned: Record<string, unknown> = {}\n for (const field of arrayFields) {\n const val = getNestedField(item as Record<string, unknown>, field)\n if (val !== undefined) {\n setNestedField(pruned, field, val)\n }\n }\n return pruned\n })\n }\n\n if (plainFields.length > 0 && typeof value === 'object' && value !== null) {\n const source = value as Record<string, unknown>\n const pruned: Record<string, unknown> = {}\n for (const field of plainFields) {\n const val = getNestedField(source, field)\n if (val !== undefined) {\n setNestedField(pruned, field, val)\n }\n }\n return pruned\n }\n\n return value\n}\n\n/** Prune data to only include projected fields. Missing projection = keep all. */\nexport function applyProjection(\n data: Record<string, unknown>,\n projections: ProjectionMap | undefined,\n): Record<string, unknown> {\n if (!projections) return data\n\n const result: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(data)) {\n const fields = projections[key]\n if (!fields) {\n // No projection for this key — keep full value\n result[key] = value\n } else {\n result[key] = pruneValue(value, fields)\n }\n }\n return 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 { applyProjection } from './projection.js'\n\nexport interface PageTiming {\n /** Procedure execution time in milliseconds */\n dataFetch: number\n /** Template injection time in milliseconds */\n inject: number\n}\n\nexport interface HandlePageResult {\n status: number\n html: string\n timing?: PageTiming\n}\n\nexport interface I18nOpts {\n locale: string\n config: I18nConfig\n /** Route pattern for hash-based message lookup */\n routePattern: string\n}\n\n/** Execute loaders, returning keyed results */\nasync function executeLoaders(\n loaders: Record<string, LoaderFn>,\n params: Record<string, string>,\n procedures: Map<string, InternalProcedure>,\n searchParams?: URLSearchParams,\n): Promise<Record<string, unknown>> {\n const entries = Object.entries(loaders)\n const results = await Promise.all(\n entries.map(async ([key, loader]) => {\n const { procedure, input } = loader(params, searchParams)\n const proc = procedures.get(procedure)\n if (!proc) throw new SeamError('INTERNAL_ERROR', `Procedure '${procedure}' not found`)\n // Skip JTD validation -- loader input is trusted server-side code\n const result = await proc.handler({ input, ctx: {} })\n return [key, result] as const\n }),\n )\n return Object.fromEntries(results)\n}\n\n/** Select the template for a given locale, falling back to the default template */\nfunction selectTemplate(\n defaultTemplate: string,\n localeTemplates: Record<string, string> | undefined,\n locale: string | undefined,\n): string {\n if (locale && localeTemplates) {\n return localeTemplates[locale] ?? defaultTemplate\n }\n return defaultTemplate\n}\n\n/** Look up pre-resolved messages for a route + locale. Zero merge, zero filter. */\nfunction lookupMessages(\n config: I18nConfig,\n routePattern: string,\n locale: string,\n): Record<string, string> {\n const routeHash = config.routeHashes[routePattern]\n if (!routeHash) return {}\n\n if (config.mode === 'paged' && config.distDir) {\n const filePath = join(config.distDir, 'i18n', routeHash, `${locale}.json`)\n if (existsSync(filePath)) {\n return JSON.parse(readFileSync(filePath, 'utf-8')) as Record<string, string>\n }\n return {}\n }\n\n return config.messages[locale]?.[routeHash] ?? {}\n}\n\nexport async function handlePageRequest(\n page: PageDef,\n params: Record<string, string>,\n procedures: Map<string, InternalProcedure>,\n i18nOpts?: I18nOpts,\n searchParams?: URLSearchParams,\n): Promise<HandlePageResult> {\n try {\n const t0 = performance.now()\n const layoutChain = page.layoutChain ?? []\n const locale = i18nOpts?.locale\n\n // Execute all loaders (layout chain + page) in parallel\n const loaderResults = await Promise.all([\n ...layoutChain.map((layout) =>\n executeLoaders(layout.loaders, params, procedures, searchParams),\n ),\n executeLoaders(page.loaders, params, procedures, searchParams),\n ])\n\n const t1 = performance.now()\n\n // Merge all loader data into a single object\n const allData: Record<string, unknown> = {}\n for (const result of loaderResults) {\n Object.assign(allData, result)\n }\n\n // Prune to projected fields before template injection\n const prunedData = applyProjection(allData, page.projections)\n\n // Compose template: nest page inside layouts via outlet substitution\n const pageTemplate = selectTemplate(page.template, page.localeTemplates, locale)\n let composedTemplate = pageTemplate\n for (let i = layoutChain.length - 1; i >= 0; i--) {\n const layout = layoutChain[i] as LayoutDef\n const layoutTemplate = selectTemplate(layout.template, layout.localeTemplates, locale)\n composedTemplate = layoutTemplate.replace('<!--seam:outlet-->', composedTemplate)\n }\n\n // Build PageConfig for engine\n const config: Record<string, unknown> = {\n layout_chain: layoutChain.map((l) => ({\n id: l.id,\n loader_keys: Object.keys(l.loaders),\n })),\n data_id: page.dataId ?? '__data',\n head_meta: page.headMeta,\n }\n if (page.pageAssets) {\n config.page_assets = page.pageAssets\n }\n\n // Build I18nOpts for engine (hash-based lookup — zero merge, zero filter)\n let i18nOptsJson: string | undefined\n if (i18nOpts) {\n const { config: i18nConfig, routePattern } = i18nOpts\n const messages = lookupMessages(i18nConfig, routePattern, i18nOpts.locale)\n const routeHash = i18nConfig.routeHashes[routePattern]\n const i18nData: Record<string, unknown> = {\n locale: i18nOpts.locale,\n default_locale: i18nConfig.default,\n messages,\n }\n // Inject content hash and router table when cache is enabled\n if (i18nConfig.cache && routeHash) {\n i18nData.hash = i18nConfig.contentHashes[routeHash]?.[i18nOpts.locale]\n i18nData.router = i18nConfig.contentHashes\n }\n i18nOptsJson = JSON.stringify(i18nData)\n }\n\n // Single WASM call: inject slots, compose data script, apply locale/meta\n const html = renderPage(\n composedTemplate,\n JSON.stringify(prunedData),\n JSON.stringify(config),\n i18nOptsJson,\n )\n\n const t2 = performance.now()\n\n return {\n status: 200,\n html,\n timing: { dataFetch: t1 - t0, inject: t2 - t1 },\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error'\n return {\n status: 500,\n html: `<!DOCTYPE html><html><body><h1>500 Internal Server Error</h1><p>${escapeHtml(message)}</p></body></html>`,\n }\n }\n}\n","/* src/server/core/typescript/src/page/route-matcher.ts */\n\ninterface CompiledRoute {\n segments: RouteSegment[]\n}\n\ntype RouteSegment =\n | { kind: 'static'; value: string }\n | { kind: 'param'; name: string }\n | { kind: 'catch-all'; name: string; optional: boolean }\n\nfunction compileRoute(pattern: string): CompiledRoute {\n const segments: RouteSegment[] = pattern\n .split('/')\n .filter(Boolean)\n .map((seg) => {\n if (seg.startsWith('*')) {\n const optional = seg.endsWith('?')\n const name = optional ? seg.slice(1, -1) : seg.slice(1)\n return { kind: 'catch-all' as const, name, optional }\n }\n if (seg.startsWith(':')) {\n return { kind: 'param' as const, name: seg.slice(1) }\n }\n return { kind: 'static' as const, value: seg }\n })\n return { segments }\n}\n\nfunction matchRoute(segments: RouteSegment[], pathParts: string[]): Record<string, string> | null {\n const params: Record<string, string> = {}\n for (let i = 0; i < segments.length; i++) {\n const seg = segments[i] as RouteSegment\n if (seg.kind === 'catch-all') {\n // Catch-all must be the last segment\n const rest = pathParts.slice(i)\n if (rest.length === 0 && !seg.optional) return null\n params[seg.name] = rest.join('/')\n return params\n }\n if (i >= pathParts.length) return null\n if (seg.kind === 'static') {\n if (seg.value !== pathParts[i]) return null\n } else {\n params[seg.name] = pathParts[i] as string\n }\n }\n // All segments consumed — path must also be fully consumed\n if (segments.length !== pathParts.length) return null\n return params\n}\n\nexport class RouteMatcher<T> {\n private routes: { pattern: string; compiled: CompiledRoute; value: T }[] = []\n\n add(pattern: string, value: T): void {\n this.routes.push({ pattern, compiled: compileRoute(pattern), value })\n }\n\n match(path: string): { value: T; params: Record<string, string>; pattern: string } | null {\n const parts = path.split('/').filter(Boolean)\n for (const route of this.routes) {\n const params = matchRoute(route.compiled.segments, parts)\n if (params) return { value: route.value, params, pattern: route.pattern }\n }\n return null\n }\n}\n","/* src/server/core/typescript/src/resolve.ts */\n\n// -- New strategy-based API --\n\nexport interface ResolveStrategy {\n readonly kind: string\n resolve(data: ResolveData): string | null\n}\n\nexport interface ResolveData {\n readonly url: string\n readonly pathLocale: string | null\n readonly cookie: string | undefined\n readonly acceptLanguage: string | undefined\n readonly locales: string[]\n readonly defaultLocale: string\n}\n\n/** URL prefix strategy: trusts pathLocale if it is a known locale */\nexport function fromUrlPrefix(): ResolveStrategy {\n return {\n kind: 'url_prefix',\n resolve(data) {\n if (data.pathLocale && data.locales.includes(data.pathLocale)) {\n return data.pathLocale\n }\n return null\n },\n }\n}\n\n/** Cookie strategy: reads a named cookie and validates against known locales */\nexport function fromCookie(name = 'seam-locale'): ResolveStrategy {\n return {\n kind: 'cookie',\n resolve(data) {\n if (!data.cookie) return null\n for (const pair of data.cookie.split(';')) {\n const parts = pair.trim().split('=')\n const k = parts[0]\n const v = parts[1]\n if (k === name && v && data.locales.includes(v)) return v\n }\n return null\n },\n }\n}\n\n/** Accept-Language strategy: parses header with q-value sorting + prefix match */\nexport function fromAcceptLanguage(): ResolveStrategy {\n return {\n kind: 'accept_language',\n resolve(data) {\n if (!data.acceptLanguage) return null\n const entries: { lang: string; q: number }[] = []\n for (const part of data.acceptLanguage.split(',')) {\n const trimmed = part.trim()\n const parts = trimmed.split(';')\n const lang = parts[0] as string\n let q = 1\n for (let j = 1; j < parts.length; j++) {\n const match = (parts[j] as string).trim().match(/^q=(\\d+(?:\\.\\d+)?)$/)\n if (match) q = parseFloat(match[1] as string)\n }\n entries.push({ lang: lang.trim(), q })\n }\n entries.sort((a, b) => b.q - a.q)\n const localeSet = new Set(data.locales)\n for (const { lang } of entries) {\n if (localeSet.has(lang)) return lang\n // Prefix match: zh-CN -> zh\n const prefix = lang.split('-')[0] as string\n if (prefix !== lang && localeSet.has(prefix)) return prefix\n }\n return null\n },\n }\n}\n\n/** URL query strategy: reads a query parameter and validates against known locales */\nexport function fromUrlQuery(param = 'lang'): ResolveStrategy {\n return {\n kind: 'url_query',\n resolve(data) {\n if (!data.url) return null\n try {\n const url = new URL(data.url, 'http://localhost')\n const value = url.searchParams.get(param)\n if (value && data.locales.includes(value)) return value\n } catch {\n // Invalid URL — skip\n }\n return null\n },\n }\n}\n\n/** Run strategies in order; first non-null wins, otherwise defaultLocale */\nexport function resolveChain(strategies: ResolveStrategy[], data: ResolveData): string {\n for (const s of strategies) {\n const result = s.resolve(data)\n if (result !== null) return result\n }\n return data.defaultLocale\n}\n\n/** Default strategy chain: url_prefix -> cookie -> accept_language */\nexport function defaultStrategies(): ResolveStrategy[] {\n return [fromUrlPrefix(), fromCookie(), fromAcceptLanguage()]\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 if ('kind' in def && def.kind) return def.kind\n if ('type' in def && def.type) {\n console.warn(\n `[seam] \"${name}\": \"type\" field in procedure definition is deprecated, use \"kind\" instead`,\n )\n return def.type\n }\n return 'query'\n}\n\nexport interface CategorizedProcedures {\n procedureMap: Map<string, InternalProcedure>\n subscriptionMap: Map<string, InternalSubscription>\n streamMap: Map<string, InternalStream>\n uploadMap: Map<string, InternalUpload>\n kindMap: Map<string, ProcedureKind>\n}\n\n/** Split a flat definition map into typed procedure/subscription/stream maps */\nexport function categorizeProcedures(\n definitions: DefinitionMap,\n contextConfig?: ContextConfig,\n): CategorizedProcedures {\n const procedureMap = new Map<string, InternalProcedure>()\n const subscriptionMap = new Map<string, InternalSubscription>()\n const streamMap = new Map<string, InternalStream>()\n const uploadMap = new Map<string, InternalUpload>()\n const kindMap = new Map<string, ProcedureKind>()\n\n for (const [name, def] of Object.entries(definitions)) {\n const kind = resolveKind(name, def)\n kindMap.set(name, kind)\n const contextKeys = (def as { context?: string[] }).context ?? []\n\n // Validate context keys reference defined fields\n if (contextConfig && contextKeys.length > 0) {\n for (const key of contextKeys) {\n if (!(key in contextConfig)) {\n throw new Error(`Procedure \"${name}\" references undefined context field \"${key}\"`)\n }\n }\n }\n\n if (kind === 'upload') {\n uploadMap.set(name, {\n inputSchema: def.input._schema,\n outputSchema: def.output._schema,\n contextKeys,\n handler: def.handler as InternalUpload['handler'],\n })\n } else if (kind === 'stream') {\n streamMap.set(name, {\n inputSchema: def.input._schema,\n chunkOutputSchema: def.output._schema,\n contextKeys,\n handler: def.handler as InternalStream['handler'],\n })\n } else if (kind === 'subscription') {\n subscriptionMap.set(name, {\n inputSchema: def.input._schema,\n outputSchema: def.output._schema,\n contextKeys,\n handler: def.handler as InternalSubscription['handler'],\n })\n } else {\n procedureMap.set(name, {\n inputSchema: def.input._schema,\n outputSchema: def.output._schema,\n contextKeys,\n handler: def.handler as InternalProcedure['handler'],\n })\n }\n }\n\n return { procedureMap, subscriptionMap, streamMap, uploadMap, kindMap }\n}\n","/* src/server/core/typescript/src/router/index.ts */\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { SchemaNode } from '../types/schema.js'\nimport type { ProcedureManifest } from '../manifest/index.js'\nimport type { HandleResult, InternalProcedure } 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, ChannelMeta } from '../channel.js'\nimport type { ContextConfig, RawContextMap } from '../context.js'\nimport { contextExtractKeys, resolveContext } from '../context.js'\nimport { SeamError } from '../errors.js'\nimport { buildManifest } from '../manifest/index.js'\nimport {\n handleRequest,\n handleSubscription,\n handleStream,\n handleBatchRequest,\n handleUploadRequest,\n} from './handler.js'\nimport type { BatchCall, BatchResultItem } from './handler.js'\nimport { handlePageRequest } from '../page/handler.js'\nimport { RouteMatcher } from '../page/route-matcher.js'\nimport { defaultStrategies, resolveChain } from '../resolve.js'\nimport type { ResolveStrategy } from '../resolve.js'\nimport { categorizeProcedures } from './categorize.js'\n\nexport type ProcedureKind = 'query' | 'command' | 'subscription' | 'stream' | 'upload'\n\nexport type MappingValue = string | { from: string; each?: boolean }\n\nexport type InvalidateTarget =\n | string\n | {\n query: string\n mapping?: Record<string, MappingValue>\n }\n\nexport type TransportPreference = 'http' | 'sse' | 'ws' | 'ipc'\n\nexport interface TransportConfig {\n prefer: TransportPreference\n fallback?: TransportPreference[]\n}\n\nexport type CacheConfig = false | { ttl: number }\n\nexport interface ProcedureDef<TIn = unknown, TOut = unknown> {\n kind?: 'query'\n /** @deprecated Use `kind` instead */\n type?: 'query'\n input: SchemaNode<TIn>\n output: SchemaNode<TOut>\n error?: SchemaNode\n context?: string[]\n transport?: TransportConfig\n suppress?: string[]\n cache?: CacheConfig\n handler: (params: { input: TIn; ctx: Record<string, unknown> }) => TOut | Promise<TOut>\n}\n\nexport interface CommandDef<TIn = unknown, TOut = unknown> {\n kind?: 'command'\n /** @deprecated Use `kind` instead */\n type?: 'command'\n input: SchemaNode<TIn>\n output: SchemaNode<TOut>\n error?: SchemaNode\n context?: string[]\n invalidates?: InvalidateTarget[]\n transport?: TransportConfig\n suppress?: string[]\n handler: (params: { input: TIn; ctx: Record<string, unknown> }) => TOut | Promise<TOut>\n}\n\nexport interface SubscriptionDef<TIn = unknown, TOut = unknown> {\n kind?: 'subscription'\n /** @deprecated Use `kind` instead */\n type?: 'subscription'\n input: SchemaNode<TIn>\n output: SchemaNode<TOut>\n error?: SchemaNode\n context?: string[]\n transport?: TransportConfig\n suppress?: string[]\n handler: (params: { input: TIn; ctx: Record<string, unknown> }) => AsyncIterable<TOut>\n}\n\nexport interface StreamDef<TIn = unknown, TChunk = unknown> {\n kind: 'stream'\n input: SchemaNode<TIn>\n output: SchemaNode<TChunk>\n error?: SchemaNode\n context?: string[]\n transport?: TransportConfig\n suppress?: string[]\n handler: (params: { input: TIn; ctx: Record<string, unknown> }) => AsyncGenerator<TChunk>\n}\n\nexport interface UploadDef<TIn = unknown, TOut = unknown> {\n kind: 'upload'\n input: SchemaNode<TIn>\n output: SchemaNode<TOut>\n error?: SchemaNode\n context?: string[]\n transport?: TransportConfig\n suppress?: string[]\n handler: (params: {\n input: TIn\n file: SeamFileHandle\n ctx: Record<string, unknown>\n }) => TOut | Promise<TOut>\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport type DefinitionMap = Record<\n string,\n | ProcedureDef<any, any>\n | CommandDef<any, any>\n | SubscriptionDef<any, any>\n | StreamDef<any, any>\n | UploadDef<any, any>\n>\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\nexport interface RouterOptions {\n pages?: Record<string, PageDef>\n i18n?: I18nConfig | null\n validateOutput?: boolean\n resolve?: ResolveStrategy[]\n channels?: ChannelResult[]\n context?: ContextConfig\n transportDefaults?: Partial<Record<ProcedureKind, TransportConfig>>\n}\n\nexport interface PageRequestHeaders {\n url?: string\n cookie?: string\n acceptLanguage?: string\n}\n\nexport interface Router<T extends DefinitionMap> {\n manifest(): ProcedureManifest\n handle(procedureName: string, body: unknown, rawCtx?: RawContextMap): Promise<HandleResult>\n handleBatch(calls: BatchCall[], rawCtx?: RawContextMap): Promise<{ results: BatchResultItem[] }>\n handleSubscription(name: string, input: unknown, rawCtx?: RawContextMap): AsyncIterable<unknown>\n handleStream(name: string, input: unknown, rawCtx?: RawContextMap): AsyncGenerator<unknown>\n handleUpload(\n name: string,\n body: unknown,\n file: SeamFileHandle,\n rawCtx?: RawContextMap,\n ): Promise<HandleResult>\n getKind(name: string): ProcedureKind | null\n handlePage(path: string, headers?: PageRequestHeaders): Promise<HandlePageResult | null>\n contextExtractKeys(): string[]\n readonly hasPages: boolean\n /** Exposed for adapter access to the definitions */\n readonly procedures: T\n}\n\n/** Build the resolve strategy list from options */\nfunction buildStrategies(opts?: RouterOptions): {\n strategies: ResolveStrategy[]\n hasUrlPrefix: boolean\n} {\n const strategies = opts?.resolve ?? defaultStrategies()\n return {\n strategies,\n hasUrlPrefix: strategies.some((s) => s.kind === 'url_prefix'),\n }\n}\n\n/** Register built-in __seam_i18n_query procedure (route-hash-based lookup) */\nfunction registerI18nQuery(procedureMap: Map<string, InternalProcedure>, config: I18nConfig): void {\n procedureMap.set('__seam_i18n_query', {\n inputSchema: {},\n outputSchema: {},\n contextKeys: [],\n handler: ({ input }) => {\n const { route, locale } = input as { route: string; locale: string }\n const messages = lookupI18nMessages(config, route, locale)\n const hash = config.contentHashes[route]?.[locale] ?? ''\n return { hash, messages }\n },\n })\n}\n\n/** Look up messages by route hash + locale for RPC query */\nfunction lookupI18nMessages(\n config: I18nConfig,\n routeHash: string,\n locale: string,\n): Record<string, string> {\n if (config.mode === 'paged' && config.distDir) {\n const filePath = join(config.distDir, 'i18n', routeHash, `${locale}.json`)\n if (existsSync(filePath)) {\n return JSON.parse(readFileSync(filePath, 'utf-8')) as Record<string, string>\n }\n return {}\n }\n return config.messages[locale]?.[routeHash] ?? {}\n}\n\n/** Collect channel metadata from channel results for manifest */\nfunction collectChannelMeta(\n channels: ChannelResult[] | undefined,\n): Record<string, ChannelMeta> | undefined {\n if (!channels || channels.length === 0) return undefined\n return Object.fromEntries(\n channels.map((ch) => {\n const firstKey = Object.keys(ch.procedures)[0] ?? ''\n const name = firstKey.includes('.') ? firstKey.slice(0, firstKey.indexOf('.')) : firstKey\n return [name, ch.channelMeta]\n }),\n )\n}\n\n/** Resolve context for a procedure, returning undefined if no context needed */\nfunction resolveCtxFor(\n map: Map<string, { contextKeys: string[] }>,\n name: string,\n rawCtx: RawContextMap | undefined,\n extractKeys: string[],\n ctxConfig: ContextConfig,\n): Record<string, unknown> | undefined {\n if (!rawCtx || extractKeys.length === 0) return undefined\n const proc = map.get(name)\n if (!proc || proc.contextKeys.length === 0) return undefined\n return resolveContext(ctxConfig, rawCtx, proc.contextKeys)\n}\n\n/** Resolve locale and match page route */\nasync function matchAndHandlePage(\n pageMatcher: RouteMatcher<PageDef>,\n procedureMap: Map<string, InternalProcedure>,\n i18nConfig: I18nConfig | null,\n strategies: ResolveStrategy[],\n hasUrlPrefix: boolean,\n path: string,\n headers?: PageRequestHeaders,\n): Promise<HandlePageResult | null> {\n let pathLocale: string | null = null\n let routePath = path\n\n if (hasUrlPrefix && i18nConfig) {\n const segments = path.split('/').filter(Boolean)\n const localeSet = new Set(i18nConfig.locales)\n const first = segments[0]\n if (first && localeSet.has(first)) {\n pathLocale = first\n routePath = '/' + segments.slice(1).join('/') || '/'\n }\n }\n\n let locale: string | undefined\n if (i18nConfig) {\n locale = resolveChain(strategies, {\n url: headers?.url ?? '',\n pathLocale,\n cookie: headers?.cookie,\n acceptLanguage: headers?.acceptLanguage,\n locales: i18nConfig.locales,\n defaultLocale: i18nConfig.default,\n })\n }\n\n const match = pageMatcher.match(routePath)\n if (!match) return null\n\n let searchParams: URLSearchParams | undefined\n if (headers?.url) {\n try {\n const url = new URL(headers.url, 'http://localhost')\n if (url.search) searchParams = url.searchParams\n } catch {\n // Malformed URL — ignore\n }\n }\n\n const i18nOpts =\n locale && i18nConfig ? { locale, config: i18nConfig, routePattern: match.pattern } : undefined\n return handlePageRequest(match.value, match.params, procedureMap, i18nOpts, searchParams)\n}\n\n/** Catch context resolution errors and return them as HandleResult */\nfunction resolveCtxSafe(\n map: Map<string, { contextKeys: string[] }>,\n name: string,\n rawCtx: RawContextMap | undefined,\n extractKeys: string[],\n ctxConfig: ContextConfig,\n): { ctx?: Record<string, unknown>; error?: HandleResult } {\n try {\n return { ctx: resolveCtxFor(map, name, rawCtx, extractKeys, ctxConfig) }\n } catch (err) {\n if (err instanceof SeamError) {\n return { error: { status: err.status, body: err.toJSON() } }\n }\n throw err\n }\n}\n\nexport function createRouter<T extends DefinitionMap>(\n procedures: T,\n opts?: RouterOptions,\n): Router<T> {\n const ctxConfig = opts?.context ?? {}\n const { procedureMap, subscriptionMap, streamMap, uploadMap, kindMap } = categorizeProcedures(\n procedures,\n Object.keys(ctxConfig).length > 0 ? ctxConfig : undefined,\n )\n\n const shouldValidateOutput =\n opts?.validateOutput ??\n (typeof process !== 'undefined' && process.env.NODE_ENV !== 'production')\n\n const pageMatcher = new RouteMatcher<PageDef>()\n const pages = opts?.pages\n if (pages) {\n for (const [pattern, page] of Object.entries(pages)) {\n pageMatcher.add(pattern, page)\n }\n }\n\n const i18nConfig = opts?.i18n ?? null\n const { strategies, hasUrlPrefix } = buildStrategies(opts)\n if (i18nConfig) registerI18nQuery(procedureMap, i18nConfig)\n\n const channelsMeta = collectChannelMeta(opts?.channels)\n const extractKeys = contextExtractKeys(ctxConfig)\n\n return {\n procedures,\n hasPages: !!pages && Object.keys(pages).length > 0,\n contextExtractKeys() {\n return extractKeys\n },\n manifest() {\n return buildManifest(procedures, channelsMeta, ctxConfig, opts?.transportDefaults)\n },\n async handle(procedureName, body, rawCtx) {\n const { ctx, error } = resolveCtxSafe(\n procedureMap,\n procedureName,\n rawCtx,\n extractKeys,\n ctxConfig,\n )\n if (error) return error\n return handleRequest(procedureMap, procedureName, body, shouldValidateOutput, ctx)\n },\n handleBatch(calls, rawCtx) {\n const ctxResolver = rawCtx\n ? (name: string) => resolveCtxFor(procedureMap, name, rawCtx, extractKeys, ctxConfig) ?? {}\n : undefined\n return handleBatchRequest(procedureMap, calls, shouldValidateOutput, ctxResolver)\n },\n handleSubscription(name, input, rawCtx) {\n const ctx = resolveCtxFor(subscriptionMap, name, rawCtx, extractKeys, ctxConfig)\n return handleSubscription(subscriptionMap, name, input, shouldValidateOutput, ctx)\n },\n handleStream(name, input, rawCtx) {\n const ctx = resolveCtxFor(streamMap, name, rawCtx, extractKeys, ctxConfig)\n return handleStream(streamMap, name, input, shouldValidateOutput, ctx)\n },\n async handleUpload(name, body, file, rawCtx) {\n const { ctx, error } = resolveCtxSafe(uploadMap, name, rawCtx, extractKeys, ctxConfig)\n if (error) return error\n return handleUploadRequest(uploadMap, name, body, file, shouldValidateOutput, ctx)\n },\n getKind(name) {\n return kindMap.get(name) ?? null\n },\n handlePage(path, headers) {\n return matchAndHandlePage(\n pageMatcher,\n procedureMap,\n i18nConfig,\n strategies,\n hasUrlPrefix,\n path,\n headers,\n )\n },\n }\n}\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 input: SchemaNode<TIn>\n output: SchemaNode<TOut>\n error?: SchemaNode\n handler: (params: { input: TIn }) => TOut | Promise<TOut>\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport interface ChannelDef<\n TChannelIn = unknown,\n TIncoming extends Record<string, IncomingDef<any, any>> = Record<string, IncomingDef<any, any>>,\n TOutgoing extends Record<string, SchemaNode<Record<string, unknown>>> = Record<\n string,\n SchemaNode<Record<string, unknown>>\n >,\n> {\n input: SchemaNode<TChannelIn>\n incoming: TIncoming\n outgoing: TOutgoing\n subscribe: (params: { input: TChannelIn }) => AsyncIterable<ChannelEvent<TOutgoing>>\n transport?: TransportConfig\n}\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\ntype ChannelEvent<TOutgoing extends Record<string, SchemaNode<Record<string, unknown>>>> = {\n [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 input: Schema\n incoming: Record<string, { input: Schema; output: Schema; error?: Schema }>\n outgoing: Record<string, Schema>\n transport?: { prefer: string; fallback?: string[] }\n}\n\nexport interface ChannelResult {\n /** Expanded Level 0 procedure definitions — spread into createRouter */\n procedures: DefinitionMap\n /** IR hint for codegen */\n channelMeta: ChannelMeta\n}\n\n// -- Helpers --\n\n/** Merge channel-level and message-level JTD properties schemas */\nfunction mergeObjectSchemas(channel: JTDSchema, message: JTDSchema): JTDSchema {\n const channelProps = (channel as Record<string, unknown>).properties as\n | Record<string, JTDSchema>\n | undefined\n const channelOptional = (channel as Record<string, unknown>).optionalProperties as\n | Record<string, JTDSchema>\n | undefined\n const msgProps = (message as Record<string, unknown>).properties as\n | Record<string, JTDSchema>\n | undefined\n const msgOptional = (message as Record<string, unknown>).optionalProperties as\n | Record<string, JTDSchema>\n | undefined\n\n const merged: Record<string, unknown> = {}\n\n const props = { ...channelProps, ...msgProps }\n if (Object.keys(props).length > 0) {\n merged.properties = props\n }\n\n const optProps = { ...channelOptional, ...msgOptional }\n if (Object.keys(optProps).length > 0) {\n merged.optionalProperties = optProps\n }\n\n // Empty object schema needs at least empty properties\n if (!merged.properties && !merged.optionalProperties) {\n merged.properties = {}\n }\n\n return merged as JTDSchema\n}\n\n/** Build a tagged union schema from outgoing event definitions */\nfunction buildOutgoingUnionSchema(\n outgoing: Record<string, SchemaNode<Record<string, unknown>>>,\n): JTDSchema {\n const mapping: Record<string, JTDSchema> = {}\n for (const [eventName, node] of Object.entries(outgoing)) {\n // Wrap each outgoing payload as a \"payload\" property\n mapping[eventName] = {\n properties: { payload: node._schema },\n } as JTDSchema\n }\n return { discriminator: 'type', mapping } as JTDSchema\n}\n\n// -- Main API --\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport function createChannel<\n TChannelIn,\n TIncoming extends Record<string, IncomingDef<any, any>>,\n TOutgoing extends Record<string, SchemaNode<Record<string, unknown>>>,\n>(name: string, def: ChannelDef<TChannelIn, TIncoming, TOutgoing>): ChannelResult {\n const procedures: DefinitionMap = {}\n const channelInputSchema = def.input._schema\n\n // Expand incoming messages to command procedures\n for (const [msgName, msgDef] of Object.entries(def.incoming)) {\n const mergedInputSchema = mergeObjectSchemas(channelInputSchema, msgDef.input._schema)\n\n const command: CommandDef<any, any> = {\n kind: 'command',\n input: { _schema: mergedInputSchema } as SchemaNode<any>,\n output: msgDef.output,\n handler: msgDef.handler as CommandDef<any, any>['handler'],\n }\n if (msgDef.error) {\n command.error = msgDef.error\n }\n procedures[`${name}.${msgName}`] = command\n }\n\n // Expand subscribe to a subscription with tagged union output\n const unionSchema = buildOutgoingUnionSchema(def.outgoing)\n const subscription: SubscriptionDef<any, any> = {\n kind: 'subscription',\n input: def.input as SchemaNode<any>,\n output: { _schema: unionSchema } as SchemaNode<any>,\n handler: def.subscribe as SubscriptionDef<any, any>['handler'],\n }\n procedures[`${name}.events`] = subscription\n\n // Build channel metadata for manifest IR hint\n const incomingMeta: ChannelMeta['incoming'] = {}\n for (const [msgName, msgDef] of Object.entries(def.incoming)) {\n const entry: { input: Schema; output: Schema; error?: Schema } = {\n input: msgDef.input._schema,\n output: msgDef.output._schema,\n }\n if (msgDef.error) {\n entry.error = msgDef.error._schema\n }\n incomingMeta[msgName] = entry\n }\n\n const outgoingMeta: ChannelMeta['outgoing'] = {}\n for (const [eventName, node] of Object.entries(def.outgoing)) {\n outgoingMeta[eventName] = node._schema\n }\n\n const channelMeta: ChannelMeta = {\n input: channelInputSchema,\n incoming: incomingMeta,\n outgoing: outgoingMeta,\n }\n if (def.transport) {\n channelMeta.transport = def.transport\n }\n\n return { 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 procedure: string\n input: unknown\n}\n\nexport type LoaderFn = (\n params: Record<string, string>,\n searchParams?: URLSearchParams,\n) => LoaderResult\n\nexport interface LayoutDef {\n id: string\n template: string\n localeTemplates?: Record<string, string>\n loaders: Record<string, LoaderFn>\n i18nKeys?: string[]\n}\n\nexport interface PageAssets {\n styles: string[]\n scripts: string[]\n preload: string[]\n prefetch: string[]\n}\n\nexport interface PageDef {\n template: string\n localeTemplates?: Record<string, string>\n loaders: Record<string, LoaderFn>\n layoutChain?: LayoutDef[]\n headMeta?: string\n dataId?: string\n i18nKeys?: string[]\n pageAssets?: PageAssets\n projections?: Record<string, string[]>\n}\n\nexport interface I18nConfig {\n locales: string[]\n default: string\n mode: 'memory' | 'paged'\n cache: boolean\n routeHashes: Record<string, string>\n contentHashes: Record<string, Record<string, string>>\n /** Memory mode: locale → routeHash → messages */\n messages: Record<string, Record<string, Record<string, string>>>\n /** Paged mode: base directory for on-demand reads */\n distDir?: string\n}\n\nexport function definePage(config: PageDef): PageDef {\n return { ...config, layoutChain: config.layoutChain ?? [] }\n}\n","/* src/server/core/typescript/src/mime.ts */\n\nexport const MIME_TYPES: Record<string, string> = {\n '.js': 'application/javascript',\n '.mjs': 'application/javascript',\n '.css': 'text/css',\n '.html': 'text/html',\n '.json': 'application/json',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.ico': 'image/x-icon',\n '.map': 'application/json',\n '.ts': 'application/javascript',\n '.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 type { SeamFileHandle } from './procedure.js'\nimport { SeamError } from './errors.js'\nimport { MIME_TYPES } from './mime.js'\n\nexport interface HttpRequest {\n method: string\n url: string\n body: () => Promise<unknown>\n header?: (name: string) => string | null\n file?: () => Promise<SeamFileHandle | null>\n}\n\nexport interface HttpBodyResponse {\n status: number\n headers: Record<string, string>\n body: unknown\n}\n\nexport interface HttpStreamResponse {\n status: number\n headers: Record<string, string>\n stream: AsyncIterable<string>\n onCancel?: () => void\n}\n\nexport type HttpResponse = HttpBodyResponse | HttpStreamResponse\n\nexport type HttpHandler = (req: HttpRequest) => Promise<HttpResponse>\n\nexport interface RpcHashMap {\n procedures: Record<string, string>\n batch: string\n}\n\nexport interface HttpHandlerOptions {\n staticDir?: string\n fallback?: HttpHandler\n rpcHashMap?: RpcHashMap\n}\n\nconst PROCEDURE_PREFIX = '/_seam/procedure/'\nconst PAGE_PREFIX = '/_seam/page/'\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 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive',\n}\nconst IMMUTABLE_CACHE = 'public, max-age=31536000, immutable'\n\nfunction jsonResponse(status: number, body: unknown): HttpBodyResponse {\n return { status, headers: JSON_HEADER, body }\n}\n\nfunction errorResponse(status: number, code: string, message: string): HttpBodyResponse {\n return jsonResponse(status, new SeamError(code, message).toJSON())\n}\n\nasync function handleStaticAsset(assetPath: string, staticDir: string): Promise<HttpBodyResponse> {\n if (assetPath.includes('..')) {\n return errorResponse(403, 'VALIDATION_ERROR', 'Forbidden')\n }\n\n const filePath = join(staticDir, assetPath)\n try {\n const content = await readFile(filePath, 'utf-8')\n const ext = extname(filePath)\n const contentType = MIME_TYPES[ext] || 'application/octet-stream'\n return {\n status: 200,\n headers: {\n 'Content-Type': contentType,\n 'Cache-Control': IMMUTABLE_CACHE,\n },\n body: content,\n }\n } catch {\n return errorResponse(404, 'NOT_FOUND', 'Asset not found')\n }\n}\n\n/** Format a single SSE data event */\nexport function sseDataEvent(data: unknown): string {\n return `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 return `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 return `event: error\\ndata: ${JSON.stringify({ code, message, transient })}\\n\\n`\n}\n\n/** Format an SSE complete event */\nexport function sseCompleteEvent(): string {\n return 'event: complete\\ndata: {}\\n\\n'\n}\n\nasync function* sseStream<T extends DefinitionMap>(\n router: Router<T>,\n name: string,\n input: unknown,\n rawCtx?: RawContextMap,\n): AsyncIterable<string> {\n try {\n for await (const value of router.handleSubscription(name, input, rawCtx)) {\n yield sseDataEvent(value)\n }\n yield sseCompleteEvent()\n } catch (error) {\n if (error instanceof SeamError) {\n yield sseErrorEvent(error.code, error.message)\n } else {\n const message = error instanceof Error ? error.message : 'Unknown error'\n yield sseErrorEvent('INTERNAL_ERROR', message)\n }\n }\n}\n\nasync function* sseStreamForStream<T extends DefinitionMap>(\n router: Router<T>,\n name: string,\n input: unknown,\n signal?: AbortSignal,\n rawCtx?: RawContextMap,\n): AsyncGenerator<string> {\n const gen = router.handleStream(name, input, rawCtx)\n // Wire abort signal to terminate the generator\n if (signal) {\n signal.addEventListener(\n 'abort',\n () => {\n void gen.return(undefined)\n },\n { once: true },\n )\n }\n try {\n let seq = 0\n for await (const value of gen) {\n yield sseDataEventWithId(value, seq++)\n }\n yield sseCompleteEvent()\n } catch (error) {\n if (error instanceof SeamError) {\n yield sseErrorEvent(error.code, error.message)\n } else {\n const message = error instanceof Error ? error.message : 'Unknown error'\n yield sseErrorEvent('INTERNAL_ERROR', message)\n }\n }\n}\n\nasync function handleBatchHttp<T extends DefinitionMap>(\n req: HttpRequest,\n router: Router<T>,\n hashToName: Map<string, string> | null,\n rawCtx?: RawContextMap,\n): Promise<HttpBodyResponse> {\n let body: unknown\n try {\n body = await req.body()\n } catch {\n return errorResponse(400, 'VALIDATION_ERROR', 'Invalid JSON body')\n }\n if (!body || typeof body !== 'object' || !Array.isArray((body as { calls?: unknown }).calls)) {\n return errorResponse(400, 'VALIDATION_ERROR', \"Batch request must have a 'calls' array\")\n }\n const calls = (body as { calls: Array<{ procedure?: unknown; input?: unknown }> }).calls.map(\n (c) => ({\n procedure:\n typeof c.procedure === 'string' ? (hashToName?.get(c.procedure) ?? c.procedure) : '',\n input: c.input ?? {},\n }),\n )\n const result = await router.handleBatch(calls, rawCtx)\n return jsonResponse(200, { ok: true, data: result })\n}\n\n/** Resolve hash -> original name when obfuscation is active. Returns null on miss. */\nfunction resolveHashName(hashToName: Map<string, string> | null, name: string): string | null {\n if (!hashToName) return name\n return hashToName.get(name) ?? null\n}\n\nexport function createHttpHandler<T extends DefinitionMap>(\n router: Router<T>,\n opts?: HttpHandlerOptions,\n): HttpHandler {\n // Build reverse lookup (hash -> original name) when obfuscation is active\n const hashToName: Map<string, string> | null = opts?.rpcHashMap\n ? new Map(Object.entries(opts.rpcHashMap.procedures).map(([n, h]) => [h, n]))\n : null\n // Built-in procedures bypass hash obfuscation (identity mapping)\n if (hashToName) {\n hashToName.set('__seam_i18n_query', '__seam_i18n_query')\n }\n const batchHash = opts?.rpcHashMap?.batch ?? null\n const ctxExtractKeys = router.contextExtractKeys()\n\n return async (req) => {\n const url = new URL(req.url, 'http://localhost')\n const { pathname } = url\n\n // Build raw context map from request headers when context fields are defined\n const rawCtx: RawContextMap | undefined =\n ctxExtractKeys.length > 0 && req.header\n ? Object.fromEntries(ctxExtractKeys.map((k) => [k, req.header?.(k) ?? null]))\n : undefined\n\n if (req.method === 'GET' && pathname === MANIFEST_PATH) {\n if (opts?.rpcHashMap) return errorResponse(403, 'FORBIDDEN', 'Manifest disabled')\n return jsonResponse(200, router.manifest())\n }\n\n if (pathname.startsWith(PROCEDURE_PREFIX)) {\n const rawName = pathname.slice(PROCEDURE_PREFIX.length)\n if (!rawName) {\n return errorResponse(404, 'NOT_FOUND', 'Empty procedure name')\n }\n\n if (req.method === 'POST') {\n if (rawName === '_batch' || (batchHash && rawName === batchHash)) {\n return handleBatchHttp(req, router, hashToName, rawCtx)\n }\n\n const name = resolveHashName(hashToName, rawName)\n if (!name) return errorResponse(404, 'NOT_FOUND', 'Not found')\n\n let body: unknown\n try {\n body = await req.body()\n } catch {\n return errorResponse(400, 'VALIDATION_ERROR', 'Invalid JSON body')\n }\n\n if (router.getKind(name) === 'stream') {\n const controller = new AbortController()\n return {\n status: 200,\n headers: SSE_HEADER,\n stream: sseStreamForStream(router, name, body, controller.signal, rawCtx),\n onCancel: () => controller.abort(),\n }\n }\n\n if (router.getKind(name) === 'upload') {\n if (!req.file) {\n return errorResponse(400, 'VALIDATION_ERROR', 'Upload requires multipart/form-data')\n }\n const file = await req.file()\n if (!file) {\n return errorResponse(400, 'VALIDATION_ERROR', 'Upload requires file in multipart body')\n }\n const result = await router.handleUpload(name, body, file, rawCtx)\n return jsonResponse(result.status, result.body)\n }\n\n const result = await router.handle(name, body, rawCtx)\n return jsonResponse(result.status, result.body)\n }\n\n if (req.method === 'GET') {\n const name = resolveHashName(hashToName, rawName)\n if (!name) return errorResponse(404, 'NOT_FOUND', 'Not found')\n\n const rawInput = url.searchParams.get('input')\n let input: unknown\n try {\n input = rawInput ? JSON.parse(rawInput) : {}\n } catch {\n return errorResponse(400, 'VALIDATION_ERROR', 'Invalid input query parameter')\n }\n\n return { status: 200, headers: SSE_HEADER, stream: sseStream(router, name, input, rawCtx) }\n }\n }\n\n // Pages are served under /_seam/page/* prefix only.\n // Root-path serving is the application's responsibility — see the\n // github-dashboard ts-hono example for the fallback pattern.\n if (req.method === 'GET' && pathname.startsWith(PAGE_PREFIX) && router.hasPages) {\n const pagePath = '/' + pathname.slice(PAGE_PREFIX.length)\n const headers = req.header\n ? {\n url: req.url,\n cookie: req.header('cookie') ?? undefined,\n acceptLanguage: req.header('accept-language') ?? undefined,\n }\n : undefined\n const result = await router.handlePage(pagePath, headers)\n if (result) {\n return { status: result.status, headers: HTML_HEADER, body: result.html }\n }\n }\n\n if (req.method === 'GET' && pathname.startsWith(STATIC_PREFIX) && opts?.staticDir) {\n const assetPath = pathname.slice(STATIC_PREFIX.length)\n return handleStaticAsset(assetPath, opts.staticDir)\n }\n\n if (opts?.fallback) return opts.fallback(req)\n return errorResponse(404, 'NOT_FOUND', 'Not found')\n }\n}\n\nexport function serialize(body: unknown): string {\n return 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 stream: AsyncIterable<string>,\n write: (chunk: string) => boolean | void,\n): Promise<void> {\n try {\n for await (const chunk of stream) {\n if (write(chunk) === false) break\n }\n } catch {\n // Client disconnected\n }\n}\n\n/** Convert an HttpResponse to a Web API Response (for adapters using fetch-compatible runtimes) */\nexport function toWebResponse(result: HttpResponse): Response {\n if ('stream' in result) {\n const stream = result.stream\n const onCancel = result.onCancel\n const encoder = new TextEncoder()\n const readable = new ReadableStream({\n async start(controller) {\n await drainStream(stream, (chunk) => {\n controller.enqueue(encoder.encode(chunk))\n })\n controller.close()\n },\n cancel() {\n onCancel?.()\n },\n })\n return new Response(readable, { status: result.status, headers: result.headers })\n }\n return 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 layouts?: Record<string, LayoutManifestEntry>\n routes: Record<string, RouteManifestEntry>\n data_id?: string\n i18n?: {\n locales: string[]\n default: string\n mode?: string\n cache?: boolean\n route_hashes?: Record<string, string>\n content_hashes?: Record<string, Record<string, string>>\n }\n}\n\ninterface LayoutManifestEntry {\n template?: string\n templates?: Record<string, string>\n loaders?: Record<string, LoaderConfig>\n parent?: string\n i18n_keys?: string[]\n}\n\ninterface RouteManifestEntry {\n template?: string\n templates?: Record<string, string>\n layout?: string\n loaders: Record<string, LoaderConfig>\n head_meta?: string\n i18n_keys?: string[]\n assets?: PageAssets\n projections?: Record<string, string[]>\n}\n\ninterface LoaderConfig {\n procedure: string\n params?: Record<string, ParamConfig>\n handoff?: 'client'\n}\n\ninterface ParamConfig {\n from: 'route' | 'query'\n type?: 'string' | 'int'\n}\n\nfunction buildLoaderFn(config: LoaderConfig): LoaderFn {\n return (params, searchParams): LoaderResult => {\n const input: Record<string, unknown> = {}\n if (config.params) {\n for (const [key, mapping] of Object.entries(config.params)) {\n const raw = mapping.from === 'query' ? (searchParams?.get(key) ?? undefined) : params[key]\n if (raw !== undefined) {\n input[key] = mapping.type === 'int' ? Number(raw) : raw\n }\n }\n }\n return { procedure: config.procedure, input }\n }\n}\n\nfunction buildLoaderFns(configs: Record<string, LoaderConfig>): Record<string, LoaderFn> {\n const fns: Record<string, LoaderFn> = {}\n for (const [key, config] of Object.entries(configs)) {\n fns[key] = buildLoaderFn(config)\n }\n return fns\n}\n\nfunction resolveTemplatePath(\n entry: { template?: string; templates?: Record<string, string> },\n defaultLocale: string | undefined,\n): string {\n if (entry.template) return entry.template\n if (entry.templates) {\n const locale = defaultLocale ?? (Object.keys(entry.templates)[0] as string)\n const path = entry.templates[locale]\n if (!path) throw new Error(`No template for locale \"${locale}\"`)\n return path\n }\n throw 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 entry: { templates?: Record<string, string> },\n distDir: string,\n): Record<string, string> | undefined {\n if (!entry.templates) return undefined\n const result: Record<string, string> = {}\n for (const [locale, relPath] of Object.entries(entry.templates)) {\n result[locale] = readFileSync(join(distDir, relPath), 'utf-8')\n }\n return result\n}\n\n/** Callback that returns template + localeTemplates for a layout entry */\ntype TemplateGetter = (\n id: string,\n entry: LayoutManifestEntry,\n) => { template: string; localeTemplates?: Record<string, string> }\n\n/** Resolve parent chain for a layout, returning outer-to-inner order */\nfunction resolveLayoutChain(\n layoutId: string,\n layoutEntries: Record<string, LayoutManifestEntry>,\n getTemplates: TemplateGetter,\n): LayoutDef[] {\n const chain: LayoutDef[] = []\n let currentId: string | undefined = layoutId\n\n while (currentId) {\n const entry: LayoutManifestEntry | undefined = layoutEntries[currentId]\n if (!entry) break\n const { template, localeTemplates } = getTemplates(currentId, entry)\n chain.push({\n id: currentId,\n template,\n localeTemplates,\n loaders: buildLoaderFns(entry.loaders ?? {}),\n })\n currentId = entry.parent\n }\n\n // Reverse: we walked inner->outer, but want outer->inner\n chain.reverse()\n return chain\n}\n\n/** Create a proxy object that lazily reads locale templates from disk */\nfunction makeLocaleTemplateGetters(\n templates: Record<string, string>,\n distDir: string,\n): Record<string, string> {\n const obj: Record<string, string> = {}\n for (const [locale, relPath] of Object.entries(templates)) {\n const fullPath = join(distDir, relPath)\n Object.defineProperty(obj, locale, {\n get: () => readFileSync(fullPath, 'utf-8'),\n enumerable: true,\n })\n }\n return obj\n}\n\n/** Merge i18n_keys from route + layout chain into a single list */\nfunction mergeI18nKeys(\n route: RouteManifestEntry,\n layoutEntries: Record<string, LayoutManifestEntry>,\n): string[] | undefined {\n const keys: string[] = []\n if (route.layout) {\n let currentId: string | undefined = route.layout\n while (currentId) {\n const entry: LayoutManifestEntry | undefined = layoutEntries[currentId]\n if (!entry) break\n if (entry.i18n_keys) keys.push(...entry.i18n_keys)\n currentId = entry.parent\n }\n }\n if (route.i18n_keys) keys.push(...route.i18n_keys)\n return keys.length > 0 ? keys : undefined\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 const hashMapPath = join(distDir, 'rpc-hash-map.json')\n try {\n return JSON.parse(readFileSync(hashMapPath, 'utf-8')) as RpcHashMap\n } catch {\n return undefined\n }\n}\n\n/** Load i18n config and messages from build output */\nexport function loadI18nMessages(distDir: string): I18nConfig | null {\n const manifestPath = join(distDir, 'route-manifest.json')\n try {\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as RouteManifest\n if (!manifest.i18n) return null\n\n const mode = (manifest.i18n.mode ?? 'memory') as 'memory' | 'paged'\n const cache = manifest.i18n.cache ?? false\n const routeHashes = manifest.i18n.route_hashes ?? {}\n const contentHashes = manifest.i18n.content_hashes ?? {}\n\n // Memory mode: preload all route messages per locale\n // Paged mode: store distDir for on-demand reads\n const messages: Record<string, Record<string, Record<string, string>>> = {}\n if (mode === 'memory') {\n const i18nDir = join(distDir, 'i18n')\n for (const locale of manifest.i18n.locales) {\n const localePath = join(i18nDir, `${locale}.json`)\n if (existsSync(localePath)) {\n messages[locale] = JSON.parse(readFileSync(localePath, 'utf-8')) as Record<\n string,\n Record<string, string>\n >\n } else {\n messages[locale] = {}\n }\n }\n }\n\n return {\n locales: manifest.i18n.locales,\n default: manifest.i18n.default,\n mode,\n cache,\n routeHashes,\n contentHashes,\n messages,\n distDir: mode === 'paged' ? distDir : undefined,\n }\n } catch {\n return null\n }\n}\n\nexport function loadBuildOutput(distDir: string): Record<string, PageDef> {\n const manifestPath = join(distDir, 'route-manifest.json')\n const raw = readFileSync(manifestPath, 'utf-8')\n const manifest = JSON.parse(raw) as RouteManifest\n const defaultLocale = manifest.i18n?.default\n\n // Load layout templates (default + all locales)\n const layoutTemplates: Record<string, string> = {}\n const layoutLocaleTemplates: Record<string, Record<string, string>> = {}\n const layoutEntries = manifest.layouts ?? {}\n for (const [id, entry] of Object.entries(layoutEntries)) {\n layoutTemplates[id] = readFileSync(\n join(distDir, resolveTemplatePath(entry, defaultLocale)),\n 'utf-8',\n )\n const lt = loadLocaleTemplates(entry, distDir)\n if (lt) layoutLocaleTemplates[id] = lt\n }\n\n const pages: Record<string, PageDef> = {}\n for (const [path, entry] of Object.entries(manifest.routes)) {\n const templatePath = join(distDir, resolveTemplatePath(entry, defaultLocale))\n const template = readFileSync(templatePath, 'utf-8')\n\n const loaders = buildLoaderFns(entry.loaders)\n const layoutChain = entry.layout\n ? resolveLayoutChain(entry.layout, layoutEntries, (id) => ({\n template: layoutTemplates[id] ?? '',\n localeTemplates: layoutLocaleTemplates[id],\n }))\n : []\n\n // Merge i18n_keys from layout chain + route\n const i18nKeys = mergeI18nKeys(entry, layoutEntries)\n\n pages[path] = {\n template,\n localeTemplates: loadLocaleTemplates(entry, distDir),\n loaders,\n layoutChain,\n headMeta: entry.head_meta,\n dataId: manifest.data_id,\n i18nKeys,\n pageAssets: entry.assets,\n projections: entry.projections,\n }\n }\n return 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 const manifestPath = join(distDir, 'route-manifest.json')\n const raw = readFileSync(manifestPath, 'utf-8')\n const manifest = JSON.parse(raw) as RouteManifest\n const defaultLocale = manifest.i18n?.default\n\n const layoutEntries = manifest.layouts ?? {}\n\n const pages: Record<string, PageDef> = {}\n for (const [path, entry] of Object.entries(manifest.routes)) {\n const templatePath = join(distDir, resolveTemplatePath(entry, defaultLocale))\n const loaders = buildLoaderFns(entry.loaders)\n const layoutChain = entry.layout\n ? resolveLayoutChain(entry.layout, layoutEntries, (id, layoutEntry) => {\n const tmplPath = join(distDir, resolveTemplatePath(layoutEntry, defaultLocale))\n const def = {\n template: '',\n localeTemplates: layoutEntry.templates\n ? makeLocaleTemplateGetters(layoutEntry.templates, distDir)\n : undefined,\n }\n Object.defineProperty(def, 'template', {\n get: () => readFileSync(tmplPath, 'utf-8'),\n enumerable: true,\n })\n return def\n })\n : []\n\n const localeTemplates = entry.templates\n ? makeLocaleTemplateGetters(entry.templates, distDir)\n : undefined\n\n // Merge i18n_keys from layout chain + route\n const i18nKeys = mergeI18nKeys(entry, layoutEntries)\n\n const page: PageDef = {\n template: '', // placeholder, overridden by getter\n localeTemplates,\n loaders,\n layoutChain,\n dataId: manifest.data_id,\n i18nKeys,\n pageAssets: entry.assets,\n projections: entry.projections,\n }\n Object.defineProperty(page, 'template', {\n get: () => readFileSync(templatePath, 'utf-8'),\n enumerable: true,\n })\n pages[path] = page\n }\n return 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 emit: (value: T) => void\n end: () => void\n error: (err: Error) => void\n}\n\ntype QueueItem<T> = { type: 'value'; value: T } | { type: 'end' } | { type: 'error'; error: Error }\n\nexport function fromCallback<T>(\n setup: (sink: CallbackSink<T>) => (() => void) | void,\n): AsyncGenerator<T, void, undefined> {\n const queue: QueueItem<T>[] = []\n let resolve: (() => void) | null = null\n let done = false\n function notify() {\n if (resolve) {\n const r = resolve\n resolve = null\n r()\n }\n }\n\n const sink: CallbackSink<T> = {\n emit(value) {\n if (done) return\n queue.push({ type: 'value', value })\n notify()\n },\n end() {\n if (done) return\n done = true\n queue.push({ type: 'end' })\n notify()\n },\n error(err) {\n if (done) return\n done = true\n queue.push({ type: 'error', error: err })\n notify()\n },\n }\n\n const cleanup = setup(sink)\n\n async function* generate(): AsyncGenerator<T, void, undefined> {\n try {\n while (true) {\n if (queue.length === 0) {\n await new Promise<void>((r) => {\n resolve = r\n })\n }\n\n while (queue.length > 0) {\n const item = queue.shift() as QueueItem<T>\n if (item.type === 'value') {\n yield item.value\n } else if (item.type === 'error') {\n throw item.error\n } else {\n return\n }\n }\n }\n } finally {\n done = true\n if (cleanup) cleanup()\n }\n }\n\n return 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 send(data: string): void\n}\n\nexport interface ChannelWsSession {\n onMessage(data: string): void\n close(): void\n}\n\nexport interface ChannelWsOptions {\n heartbeatInterval?: number\n}\n\ninterface UplinkMessage {\n id: string\n procedure: string\n input?: unknown\n}\n\nconst DEFAULT_HEARTBEAT_MS = 30_000\n\nfunction sendError(ws: WsSink, id: string | null, code: string, message: string): void {\n ws.send(JSON.stringify({ id, ok: false, error: { code, message, transient: false } }))\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 router: Router<T>,\n channelName: string,\n channelInput: unknown,\n ws: WsSink,\n opts?: ChannelWsOptions,\n): ChannelWsSession {\n const heartbeatMs = opts?.heartbeatInterval ?? DEFAULT_HEARTBEAT_MS\n let closed = false\n\n // Heartbeat timer\n const heartbeatTimer = setInterval(() => {\n if (!closed) ws.send(JSON.stringify({ heartbeat: true }))\n }, heartbeatMs)\n\n // Start subscription and forward events as { event, payload }\n const subIterable = router.handleSubscription(`${channelName}.events`, channelInput)\n const iter = subIterable[Symbol.asyncIterator]()\n\n void (async () => {\n try {\n for (;;) {\n const result: IteratorResult<unknown> = await iter.next()\n if (result.done || closed) break\n // Channel subscription yields { type: string, payload: unknown }\n const ev = result.value as { type: string; payload: unknown }\n ws.send(JSON.stringify({ event: ev.type, payload: ev.payload }))\n }\n } catch (err) {\n if (!closed) {\n const code = err instanceof SeamError ? err.code : 'INTERNAL_ERROR'\n const message = err instanceof Error ? err.message : 'Subscription error'\n ws.send(JSON.stringify({ event: '__error', payload: { code, message } }))\n }\n }\n })()\n\n return {\n onMessage(data: string) {\n if (closed) return\n\n let msg: UplinkMessage\n try {\n msg = JSON.parse(data) as UplinkMessage\n } catch {\n sendError(ws, null, 'VALIDATION_ERROR', 'Invalid JSON')\n return\n }\n\n if (!msg.id || typeof msg.id !== 'string') {\n sendError(ws, null, 'VALIDATION_ERROR', \"Missing 'id' field\")\n return\n }\n\n if (!msg.procedure || typeof msg.procedure !== 'string') {\n sendError(ws, msg.id, 'VALIDATION_ERROR', \"Missing 'procedure' field\")\n return\n }\n\n // Only allow commands belonging to this channel (not .events)\n const prefix = channelName + '.'\n if (!msg.procedure.startsWith(prefix) || msg.procedure === `${channelName}.events`) {\n sendError(\n ws,\n msg.id,\n 'VALIDATION_ERROR',\n `Procedure '${msg.procedure}' is not a command of channel '${channelName}'`,\n )\n return\n }\n\n // Merge channel input + uplink input before dispatching\n const mergedInput = {\n ...(channelInput as Record<string, unknown>),\n ...((msg.input ?? {}) as Record<string, unknown>),\n }\n\n void (async () => {\n try {\n const result = await router.handle(msg.procedure, mergedInput)\n if (result.status === 200) {\n const envelope = result.body as { ok: true; data: unknown }\n ws.send(JSON.stringify({ id: msg.id, ok: true, data: envelope.data }))\n } else {\n const envelope = result.body as {\n ok: false\n error: { code: string; message: string; transient: boolean }\n }\n ws.send(JSON.stringify({ id: msg.id, ok: false, error: envelope.error }))\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Unknown error'\n sendError(ws, msg.id, 'INTERNAL_ERROR', message)\n }\n })()\n },\n\n close() {\n if (closed) return\n closed = true\n clearInterval(heartbeatTimer)\n void iter.return?.(undefined)\n },\n }\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 /** Target URL to forward requests to (e.g. \"http://localhost:5173\") */\n target: string\n}\n\nexport interface StaticHandlerOptions {\n /** Directory to serve static files from */\n dir: string\n}\n\n/** Forward non-seam requests to a dev server (e.g. Vite) */\nexport function createDevProxy(opts: DevProxyOptions): HttpHandler {\n const target = opts.target.replace(/\\/$/, '')\n\n return async (req) => {\n const url = new URL(req.url, 'http://localhost')\n const proxyUrl = `${target}${url.pathname}${url.search}`\n\n try {\n const resp = await fetch(proxyUrl, {\n method: req.method,\n headers: { Accept: '*/*' },\n })\n\n const body = await resp.text()\n const headers: Record<string, string> = {}\n resp.headers.forEach((value, key) => {\n headers[key] = value\n })\n\n return { status: resp.status, headers, body }\n } catch {\n return {\n status: 502,\n headers: { 'Content-Type': 'text/plain' },\n body: `Bad Gateway: failed to connect to ${target}`,\n }\n }\n }\n}\n\n/** Serve static files from a directory, with index.html fallback for directories */\nexport function createStaticHandler(opts: StaticHandlerOptions): HttpHandler {\n const dir = opts.dir\n\n return async (req): Promise<HttpBodyResponse> => {\n const url = new URL(req.url, 'http://localhost')\n let filePath = url.pathname\n\n if (filePath.includes('..')) {\n return {\n status: 403,\n headers: { 'Content-Type': 'text/plain' },\n body: 'Forbidden',\n }\n }\n\n // Serve index.html for directory paths\n if (filePath.endsWith('/')) {\n filePath += 'index.html'\n }\n\n const fullPath = join(dir, filePath)\n try {\n const content = await readFile(fullPath)\n const ext = extname(fullPath)\n const contentType = MIME_TYPES[ext] || 'application/octet-stream'\n return {\n status: 200,\n headers: { 'Content-Type': contentType },\n body: content.toString(),\n }\n } catch {\n return {\n status: 404,\n headers: { 'Content-Type': 'text/plain' },\n body: 'Not found',\n }\n }\n }\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 close(): void\n /** Resolves on the next reload event. Rejects if the watcher is already closed. */\n nextReload(): Promise<void>\n}\n\nexport function watchReloadTrigger(distDir: string, onReload: () => void): ReloadWatcher {\n const triggerPath = join(distDir, '.reload-trigger')\n let watcher: FSWatcher | null = null\n let closed = false\n let pending: Array<{ resolve: () => void; reject: (e: Error) => void }> = []\n\n const notify = () => {\n onReload()\n const batch = pending\n pending = []\n for (const p of batch) p.resolve()\n }\n\n const nextReload = (): Promise<void> => {\n if (closed) return Promise.reject(new Error('watcher closed'))\n return new Promise((resolve, reject) => {\n pending.push({ resolve, reject })\n })\n }\n\n const closeAll = () => {\n closed = true\n const batch = pending\n pending = []\n const err = new Error('watcher closed')\n for (const p of batch) p.reject(err)\n }\n\n try {\n watcher = watch(triggerPath, () => notify())\n } catch {\n // Trigger file may not exist yet; watch directory until it appears\n const dirWatcher = watch(distDir, (_event, filename) => {\n if (filename === '.reload-trigger') {\n dirWatcher.close()\n watcher = watch(triggerPath, () => notify())\n // First creation IS the reload signal -- fire immediately\n notify()\n }\n })\n return {\n close() {\n dirWatcher.close()\n watcher?.close()\n closeAll()\n },\n nextReload,\n }\n }\n return {\n close() {\n watcher?.close()\n closeAll()\n },\n nextReload,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAkBA,SAAgB,iBAAoB,QAAkC;AACpE,QAAO,EAAE,SAAS,QAAQ;;AAG5B,SAAgB,yBAA4B,QAA0C;AACpF,QAAO;EAAE,SAAS;EAAQ,WAAW;EAAM;;;;;;;;;;;;;;;;;;;AClB7C,SAAgB,SAA6B;AAC3C,QAAO,iBAAyB,EAAE,MAAM,UAAU,CAAC;;AAGrD,SAAgB,UAA+B;AAC7C,QAAO,iBAA0B,EA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FAULT_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/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): 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 ?? {} })) {\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\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/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 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\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// 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: page.headMeta,\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\t// Build I18nOpts for engine (hash-based lookup — zero merge, zero filter)\n\t\tlet i18nOptsJson: string | undefined\n\t\tif (i18nOpts) {\n\t\t\tconst { config: i18nConfig, routePattern } = i18nOpts\n\t\t\tconst messages = lookupMessages(i18nConfig, routePattern, i18nOpts.locale)\n\t\t\tconst routeHash = i18nConfig.routeHashes[routePattern]\n\t\t\tconst i18nData: Record<string, unknown> = {\n\t\t\t\tlocale: i18nOpts.locale,\n\t\t\t\tdefault_locale: i18nConfig.default,\n\t\t\t\tmessages,\n\t\t\t}\n\t\t\t// Inject content hash and router table when cache is enabled\n\t\t\tif (i18nConfig.cache && routeHash) {\n\t\t\t\ti18nData.hash = i18nConfig.contentHashes[routeHash]?.[i18nOpts.locale]\n\t\t\t\ti18nData.router = i18nConfig.contentHashes\n\t\t\t}\n\t\t\ti18nOptsJson = JSON.stringify(i18nData)\n\t\t}\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}\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\tprocedureMap.set('__seam_i18n_query', {\n\t\tinputSchema: {},\n\t\toutputSchema: {},\n\t\tcontextKeys: [],\n\t\thandler: ({ input }) => {\n\t\t\tconst { route, locale } = input as { route: string; locale: string }\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\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 { 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) {\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)\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}\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: { input: TIn; ctx: Record<string, unknown> }) => 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/* eslint-enable @typescript-eslint/no-explicit-any */\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(name: string, input: unknown, rawCtx?: RawContextMap): 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\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,\n\topts?: RouterOptions,\n): Router<T> {\n\tconst state = initRouterState(procedures, opts)\n\treturn {\n\t\tprocedures,\n\t\trpcHashMap: opts?.rpcHashMap,\n\t\t...buildRouterMethods(state, procedures, 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 interface PageDef {\n\ttemplate: string\n\tlocaleTemplates?: Record<string, string>\n\tloaders: Record<string, LoaderFn>\n\tlayoutChain?: LayoutDef[]\n\theadMeta?: string\n\tdataId?: string\n\ti18nKeys?: string[]\n\tpageAssets?: PageAssets\n\tprojections?: Record<string, 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 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): AsyncIterable<string> {\n\ttry {\n\t\tfor await (const value of router.handleSubscription(name, input, rawCtx)) {\n\t\t\tyield sseDataEvent(value)\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\treturn {\n\t\t\t\t\tstatus: 200,\n\t\t\t\t\theaders: SSE_HEADER,\n\t\t\t\t\tstream: withSseLifecycle(sseStream(router, name, input, rawCtx), opts?.sseOptions),\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\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}\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\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\tpages[path] = {\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\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,iBAAyB,EAAE,MAAM,aAAa,CAAC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