@microverse.ts/host-surface 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +14 -13
  2. package/dist/application/useCases/compileBridgeDeclarationsFromHostSurfaceSpec.d.ts +3 -3
  3. package/dist/application/useCases/compileBridgeDeclarationsFromHostSurfaceSpec.d.ts.map +1 -1
  4. package/dist/application/useCases/compileHostSurface.d.ts +5 -5
  5. package/dist/application/useCases/compileHostSurface.d.ts.map +1 -1
  6. package/dist/domain/componentSlotPrelude.d.ts +3 -0
  7. package/dist/domain/componentSlotPrelude.d.ts.map +1 -0
  8. package/dist/domain/hostSurfaceManifest.d.ts +2 -2
  9. package/dist/domain/hostSurfaceManifest.d.ts.map +1 -1
  10. package/dist/domain/hostSurfaceTypes.d.ts +12 -9
  11. package/dist/domain/hostSurfaceTypes.d.ts.map +1 -1
  12. package/dist/domain/luaGlobalHook.d.ts +1 -1
  13. package/dist/domain/scriptContextSymbol.d.ts +6 -0
  14. package/dist/domain/scriptContextSymbol.d.ts.map +1 -0
  15. package/dist/domain/scriptPropertyMergeEnv.d.ts +6 -0
  16. package/dist/domain/scriptPropertyMergeEnv.d.ts.map +1 -0
  17. package/dist/domain/surfaceCapabilities.d.ts +1 -1
  18. package/dist/domain/surfaceCapabilities.d.ts.map +1 -1
  19. package/dist/domain/surfaceMethodDef.d.ts +1 -1
  20. package/dist/domain/surfaceMethodDef.d.ts.map +1 -1
  21. package/dist/index.d.ts +18 -14
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +407 -139
  24. package/dist/index.js.map +1 -1
  25. package/dist/infrastructure/adapters/augmentHostWithCapabilityRegistry.d.ts +1 -1
  26. package/dist/infrastructure/adapters/augmentHostWithCapabilityRegistry.d.ts.map +1 -1
  27. package/dist/infrastructure/adapters/augmentHostWithScriptContext.d.ts +4 -0
  28. package/dist/infrastructure/adapters/augmentHostWithScriptContext.d.ts.map +1 -0
  29. package/dist/infrastructure/adapters/zodSchemaValidationAdapter.d.ts +1 -1
  30. package/dist/infrastructure/adapters/zodSchemaValidationAdapter.d.ts.map +1 -1
  31. package/dist/infrastructure/builders/bridgeMergeEnv.d.ts +6 -3
  32. package/dist/infrastructure/builders/bridgeMergeEnv.d.ts.map +1 -1
  33. package/dist/infrastructure/builders/defineHostSurfaceFacade.d.ts +5 -5
  34. package/dist/infrastructure/builders/defineHostSurfaceFacade.d.ts.map +1 -1
  35. package/dist/infrastructure/builders/surfaceBuilder.d.ts +11 -11
  36. package/dist/infrastructure/builders/surfaceBuilder.d.ts.map +1 -1
  37. package/dist/infrastructure/components/hostScriptSession.d.ts +23 -68
  38. package/dist/infrastructure/components/hostScriptSession.d.ts.map +1 -1
  39. package/package.json +10 -9
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/infrastructure/builders/bridgeMergeEnv.ts","../src/infrastructure/adapters/zodSchemaValidationAdapter.ts","../src/domain/luaGlobalHook.ts","../src/domain/luaTypeAtoms.ts","../src/domain/zodLuaType.ts","../src/domain/zodToLuaTypeRef.ts","../src/domain/hostSurfaceManifest.ts","../src/domain/surfaceCapabilities.ts","../src/domain/capabilityRegistrySymbol.ts","../src/application/useCases/compileBridgeDeclarationsFromHostSurfaceSpec.ts","../src/application/useCases/compileHostSurface.ts","../src/domain/inferMethodAsync.ts","../src/domain/surfaceMethodDef.ts","../src/domain/safeObjectKey.ts","../src/infrastructure/builders/surfaceBuilder.ts","../src/infrastructure/builders/defineHostSurfaceFacade.ts","../src/infrastructure/adapters/augmentHostWithCapabilityRegistry.ts","../src/infrastructure/components/hostScriptSession.ts"],"sourcesContent":["import { buildDeclarativeBridgeTable } from '@microverse.ts/runtime-bridge';\n\nimport type { WithMicroverseCapabilityRegistry } from '../../domain/capabilityRegistrySymbol.js';\nimport type { HostSurfaceCore } from '../../domain/hostSurfaceTypes.js';\n\n/**\n * Builds a frozen `mergeEnv` table: bridge name → API object, ready for `MicroverseSlot.run({ mergeEnv })`.\n *\n * @param host - Your host context, already extended with the capability registry symbol from `@microverse.ts/host-surface`.\n * @param slotKey - Same slot key passed to `buildDeclarativeBridgeTable` (string form of `MicroverseId` is fine).\n * @param surface - Result of {@link defineHostSurface} (implements {@link HostSurfaceCore}).\n */\nexport function buildBridgeMergeEnvForHost<THost>(\n host: THost & WithMicroverseCapabilityRegistry,\n slotKey: string,\n surface: HostSurfaceCore,\n): Readonly<Record<string, unknown>> {\n return buildDeclarativeBridgeTable(host, slotKey, [...surface.toBridgeDeclarations()]);\n}\n","import { validateWithZodSchema } from '@microverse.ts/runtime-zod';\n\nimport type { SchemaValidationPort } from '../../application/ports/SchemaValidationPort.js';\n\nexport function createZodSchemaValidationPort(): SchemaValidationPort {\n return { validateWithZodSchema };\n}\n","/**\n * Lua convention for domain hooks: PascalCase event kind → method name `on{Kind}` on the workflow\n * handler table from `workflow:extend()` in each Lua slot (e.g. `OrderPlaced` → `onOrderPlaced`).\n */\nexport type LuaGlobalHookName<Kind extends string> = `on${Kind}`;\n\n/**\n * Builds the `on{Kind}` method name dispatched on the slot’s workflow handler for a PascalCase event `kind`\n * (e.g. `InventoryLow` → `onInventoryLow`).\n * Throws if `kind` is not a safe Lua identifier fragment.\n */\nexport function luaGlobalHookName<const Kind extends string>(kind: Kind): LuaGlobalHookName<Kind> {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(kind)) {\n throw new Error(`unsafe Lua identifier for event kind: ${kind}`);\n }\n const name = `on${kind}`;\n return name as LuaGlobalHookName<Kind>;\n}\n","/** Lua / LuaCATS type atoms: never emit `---@alias` for these names from `lua.paramTypes` / `lua.returns` tokens. */\nexport const LUA_TYPE_ATOMS = new Set([\n 'any',\n 'boolean',\n 'false',\n 'integer',\n 'nil',\n 'never',\n 'number',\n 'self',\n 'string',\n 'table',\n 'true',\n 'unknown',\n]);\n\nexport function isLuaTypeAtom(name: string): boolean {\n return LUA_TYPE_ATOMS.has(name);\n}\n","import { z } from 'zod';\n\nconst aliasBySchema = new WeakMap<z.ZodTypeAny, string>();\n\n/**\n * Registers a nominal LuaCATS name for a Zod schema. {@link zodToLuaTypeRef} emits the name;\n * `.d.lua` generation adds a matching `---@alias` with the structural shape.\n *\n * @example\n * ```ts\n * export const orderDto = luaType('OrderDto', z.object({ id: z.string() }));\n * // bridge: output: orderDto.optional() → returns `OrderDto|nil` in manifest\n * ```\n */\nexport function luaType<T extends z.ZodTypeAny>(name: string, schema: T): T {\n if (!/^[A-Za-z_]\\w*$/.test(name)) {\n throw new Error(`luaType: invalid alias name: ${name}`);\n }\n aliasBySchema.set(schema, name);\n return schema;\n}\n\n/** @internal Root schema that carries a {@link luaType} registration (after unwrapping optional/nullable/…). */\nexport function getLuaTypeRegistrationRoot(schema: z.ZodTypeAny): z.ZodTypeAny | undefined {\n let cur: z.ZodTypeAny = schema;\n for (;;) {\n const name = aliasBySchema.get(cur);\n if (name !== undefined) {\n return cur;\n }\n const next = unwrapOneLayer(cur);\n if (next === undefined) {\n return undefined;\n }\n cur = next;\n }\n}\n\n/** @internal Nominal LuaCATS name for this schema, if registered via {@link luaType}. */\nexport function resolveZodLuaTypeAlias(schema: z.ZodTypeAny): string | undefined {\n const root = getLuaTypeRegistrationRoot(schema);\n return root === undefined ? undefined : aliasBySchema.get(root);\n}\n\nexport function getRegisteredLuaTypeName(root: z.ZodTypeAny): string | undefined {\n return aliasBySchema.get(root);\n}\n\nfunction unwrapOneLayer(schema: z.ZodTypeAny): z.ZodTypeAny | undefined {\n if (schema instanceof z.ZodOptional || schema instanceof z.ZodNullable) {\n return schema.unwrap() as z.ZodTypeAny;\n }\n if (schema instanceof z.ZodDefault) {\n return schema.removeDefault() as z.ZodTypeAny;\n }\n if (schema instanceof z.ZodReadonly) {\n return schema.unwrap() as z.ZodTypeAny;\n }\n if (schema instanceof z.ZodEffects) {\n return schema.innerType() as z.ZodTypeAny;\n }\n if (schema instanceof z.ZodPipeline) {\n return schema._def.in as z.ZodTypeAny;\n }\n if (schema instanceof z.ZodLazy) {\n return schema.schema as z.ZodTypeAny;\n }\n if (schema instanceof z.ZodBranded) {\n return schema.unwrap() as z.ZodTypeAny;\n }\n return undefined;\n}\n","import { z } from 'zod';\n\nimport { resolveZodLuaTypeAlias } from './zodLuaType.js';\n\n/* Zod's internal `_def` / `options` are intentionally untyped for this best-effort emitter. */\n/* eslint-disable @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-return */\n\nexport type ZodToLuaTypeRefOptions = {\n /**\n * When `false`, expands {@link luaType} registrations to structural shapes (for `---@alias` bodies).\n * Default `true` emits registered nominal names at use sites.\n */\n readonly emitAliasNames?: boolean | undefined;\n};\n\n/**\n * Maps a Zod schema to a LuaCATS type reference string for manifest emission.\n *\n * @remarks\n * Register nominal types with {@link luaType} on shared Zod schemas (e.g. `orderDto`, `orderId`).\n * Prefer that over per-method `lua.paramTypes` / `lua.returns` escape hatches on bridge methods.\n */\nexport function zodToLuaTypeRef(schema: z.ZodTypeAny, options?: ZodToLuaTypeRefOptions): string {\n const emitAliasNames = options?.emitAliasNames !== false;\n\n if (schema instanceof z.ZodOptional) {\n return `${zodToLuaTypeRef(schema.unwrap(), options)}|nil`;\n }\n if (schema instanceof z.ZodNullable) {\n return `${zodToLuaTypeRef(schema.unwrap(), options)}|nil`;\n }\n if (schema instanceof z.ZodDefault) {\n return zodToLuaTypeRef(schema.removeDefault(), options);\n }\n if (schema instanceof z.ZodReadonly) {\n return zodToLuaTypeRef(schema.unwrap(), options);\n }\n if (schema instanceof z.ZodCatch) {\n return zodToLuaTypeRef(schema._def.innerType as z.ZodTypeAny, options);\n }\n if (schema instanceof z.ZodPipeline) {\n return zodToLuaTypeRef(schema._def.out as z.ZodTypeAny, options);\n }\n if (schema instanceof z.ZodEffects) {\n return zodToLuaTypeRef(schema.innerType(), options);\n }\n if (schema instanceof z.ZodLazy) {\n return zodToLuaTypeRef(schema.schema, options);\n }\n if (schema instanceof z.ZodBranded) {\n return zodToLuaTypeRef(schema.unwrap(), options);\n }\n\n if (emitAliasNames) {\n const alias = resolveZodLuaTypeAlias(schema);\n if (alias !== undefined) {\n return alias;\n }\n }\n\n if (schema instanceof z.ZodString) {\n return 'string';\n }\n if (schema instanceof z.ZodNumber) {\n return zodNumberToLua(schema);\n }\n if (schema instanceof z.ZodBoolean) {\n return 'boolean';\n }\n if (schema instanceof z.ZodBigInt) {\n return 'integer';\n }\n if (schema instanceof z.ZodUndefined) {\n return 'nil';\n }\n if (schema instanceof z.ZodNull) {\n return 'nil';\n }\n if (schema instanceof z.ZodVoid) {\n return 'nil';\n }\n if (schema instanceof z.ZodUnknown || schema instanceof z.ZodAny) {\n return 'unknown';\n }\n if (schema instanceof z.ZodLiteral) {\n const v = schema.value;\n if (typeof v === 'string') {\n return `\"${v}\"`;\n }\n if (typeof v === 'number' || typeof v === 'boolean') {\n return String(v);\n }\n return 'unknown';\n }\n if (schema instanceof z.ZodEnum) {\n return schema.options.map((o: string) => `\"${String(o)}\"`).join('|');\n }\n if (schema instanceof z.ZodNativeEnum) {\n return 'string|number';\n }\n if (schema instanceof z.ZodArray) {\n return 'table';\n }\n if (schema instanceof z.ZodRecord) {\n return 'table';\n }\n if (schema instanceof z.ZodObject) {\n const shape = schema.shape as Record<string, z.ZodTypeAny>;\n const keys = Object.keys(shape);\n if (keys.length === 0) {\n return '{}';\n }\n const parts = keys.map((k) => `${k}: ${zodToLuaTypeRef(shape[k]!, options)}`);\n return `{ ${parts.join('; ')} }`;\n }\n if (schema instanceof z.ZodUnion) {\n return schema.options.map((o: z.ZodTypeAny) => zodToLuaTypeRef(o, options)).join('|');\n }\n if (schema instanceof z.ZodDiscriminatedUnion) {\n return schema.options.map((o: z.ZodTypeAny) => zodToLuaTypeRef(o, options)).join('|');\n }\n if (schema instanceof z.ZodIntersection) {\n return 'table';\n }\n if (schema instanceof z.ZodTuple) {\n return 'table';\n }\n return 'unknown';\n}\n\nfunction zodNumberToLua(schema: z.ZodNumber): string {\n const checks = schema._def.checks as readonly { readonly kind: string }[];\n if (checks.some((c) => c.kind === 'int')) {\n return 'integer';\n }\n return 'number';\n}\n","import type {\n LuaDefManifest,\n ManifestAlias,\n ManifestClass,\n ManifestClassField,\n ManifestMethod,\n ManifestParam,\n} from '@microverse.ts/lua-defs';\nimport { z } from 'zod';\n\nimport type { HostSurfaceSpec, HostWorkflowHooksSpec } from './hostSurfaceTypes.js';\nimport { luaGlobalHookName } from './luaGlobalHook.js';\nimport { isLuaTypeAtom } from './luaTypeAtoms.js';\nimport { getLuaTypeRegistrationRoot, getRegisteredLuaTypeName } from './zodLuaType.js';\nimport { zodToLuaTypeRef } from './zodToLuaTypeRef.js';\n\nfunction asyncHandleClassName(bridgeName: string, methodName: string): string {\n const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);\n return `${cap(bridgeName)}${cap(methodName)}Handle`;\n}\n\nfunction buildWorkflowHookManifestFields(\n kinds: readonly string[],\n workflowHooks: HostWorkflowHooksSpec,\n selfType: string,\n fieldDescriptionSuffix: string,\n): ManifestClassField[] {\n const out: ManifestClassField[] = [];\n for (const kind of kinds) {\n const schema = workflowHooks[kind];\n if (!(schema instanceof z.ZodObject)) {\n throw new Error(`defineHostSurface workflowHooks: \"${kind}\" must be a z.object(...)`);\n }\n const payloadName = `MicroverseWorkflowEvt_${kind}`;\n const hookName = luaGlobalHookName(kind);\n out.push({\n name: hookName,\n description: `${fieldDescriptionSuffix} Payload: \\`${payloadName}\\`.`,\n luaType: `fun(self: ${selfType}, evt: ${payloadName})`,\n });\n }\n return out;\n}\n\nfunction pushWorkflowPayloadManifestClasses(\n kinds: readonly string[],\n workflowHooks: HostWorkflowHooksSpec,\n classes: ManifestClass[],\n): void {\n for (const kind of kinds) {\n const schema = workflowHooks[kind];\n if (!(schema instanceof z.ZodObject)) {\n throw new Error(`defineHostSurface workflowHooks: \"${kind}\" must be a z.object(...)`);\n }\n const name = `MicroverseWorkflowEvt_${kind}`;\n const shape = schema.shape as Record<string, z.ZodTypeAny>;\n classes.push({\n name,\n description: `Workflow hook payload for \\`${luaGlobalHookName(kind)}\\` (Zod → LuaCATS fields).`,\n fields: Object.keys(shape).map((k) => ({\n name: k,\n luaType: zodToLuaTypeRef(shape[k]!),\n })),\n emitSingleton: false,\n });\n }\n}\n\nexport function buildLuaDefManifestFromHostSurfaceSpec(\n spec: HostSurfaceSpec,\n opts: {\n readonly output: string;\n readonly headerNote?: string | undefined;\n readonly luaTypeAliases?: Readonly<Record<string, string>> | undefined;\n },\n workflowHooks?: HostWorkflowHooksSpec,\n): LuaDefManifest {\n const classes: ManifestClass[] = [];\n for (const bridgeName of Object.keys(spec)) {\n const methods = spec[bridgeName]!;\n const manifestMethods: ManifestMethod[] = [];\n for (const methodName of Object.keys(methods)) {\n const entry = methods[methodName]!;\n const resultLua = entry.lua?.returns ?? zodToLuaTypeRef(entry.output);\n if (entry.async === true) {\n const handleName = asyncHandleClassName(bridgeName, methodName);\n const payloadParams = zodInputToManifestParams(entry.input, entry.lua?.paramTypes) ?? [];\n manifestMethods.push({\n name: methodName,\n description: entry.description,\n callStyle: 'asyncBridge',\n params: [\n ...payloadParams,\n { name: 'onComplete', luaType: `fun(result: ${resultLua})|nil` },\n ],\n returns: handleName,\n });\n classes.push({\n name: handleName,\n description: `Async handle for \\`${bridgeName}:${methodName}\\`. Call \\`:await()\\` for the resolved value.`,\n fields: [{ name: 'await', luaType: `fun(self: ${handleName}): ${resultLua}` }],\n emitSingleton: false,\n });\n } else {\n manifestMethods.push({\n name: methodName,\n description: entry.description,\n params: zodInputToManifestParams(entry.input, entry.lua?.paramTypes),\n returns: resultLua,\n });\n }\n }\n classes.push({\n name: bridgeName,\n methods: manifestMethods,\n });\n }\n const fromLuaType = collectLuaTypeAliasesFromHostSpec(spec);\n const fromOverrides = inferLuaTypeAliasesFromHostSpec(spec);\n const merged = new Map<string, string>([\n ...fromLuaType.map((a) => [a.name, a.definition] as const),\n ...fromOverrides.map((a) => [a.name, a.definition] as const),\n ]);\n if (opts.luaTypeAliases !== undefined) {\n for (const [k, v] of Object.entries(opts.luaTypeAliases)) {\n merged.set(k, v);\n }\n }\n\n if (workflowHooks !== undefined) {\n const kinds = Object.keys(workflowHooks).sort((a, b) => a.localeCompare(b));\n pushWorkflowPayloadManifestClasses(kinds, workflowHooks, classes);\n const abstractFields = buildWorkflowHookManifestFields(\n kinds,\n workflowHooks,\n 'Workflow',\n 'Host invokes this method on your table (from `workflow:extend()`) when the matching domain event fires.',\n );\n classes.push({\n name: 'Workflow',\n description:\n 'Abstract workflow handler type. Call `local w = workflow:extend()` then define `function w:onOrderPlaced(evt) … end` (etc.). Each Lua slot has its own `workflow` helper and handler table.',\n fields: abstractFields,\n emitSingleton: false,\n });\n classes.push({\n name: 'workflow',\n description:\n 'Per-slot helper injected by the host (not a TS bridge). Creates the active handler table for this sandbox slot.',\n methods: [\n {\n name: 'extend',\n description:\n 'Returns a new handler table with default no-op hooks; registers it for host → Lua dispatch in this slot.',\n params: [],\n returns: 'Workflow',\n },\n ],\n });\n }\n\n const aliases =\n merged.size === 0\n ? undefined\n : [...merged.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([name, definition]) => ({ name, definition }));\n\n return {\n schemaVersion: 1,\n output: opts.output,\n headerNote: opts.headerNote,\n aliases,\n classes,\n };\n}\n\nfunction nominalTokensFromLuaReturnString(retLua: string): readonly string[] {\n const out: string[] = [];\n const seen = new Set<string>();\n for (const segment of retLua.split('|')) {\n const s = segment.trim();\n if (!/^[A-Za-z_]\\w*$/.test(s)) {\n continue;\n }\n if (isLuaTypeAtom(s)) {\n continue;\n }\n if (seen.has(s)) {\n continue;\n }\n seen.add(s);\n out.push(s);\n }\n return out;\n}\n\nfunction unwrapOutputBaseForAlias(schema: z.ZodTypeAny): z.ZodTypeAny {\n /* eslint-disable @typescript-eslint/no-unsafe-assignment -- Zod internal unwrap chain */\n let cur: z.ZodTypeAny = schema;\n for (;;) {\n if (cur instanceof z.ZodOptional || cur instanceof z.ZodNullable) {\n cur = cur.unwrap();\n continue;\n }\n if (cur instanceof z.ZodDefault) {\n cur = cur.removeDefault();\n continue;\n }\n if (cur instanceof z.ZodReadonly) {\n cur = cur.unwrap();\n continue;\n }\n if (cur instanceof z.ZodEffects) {\n cur = cur.innerType();\n continue;\n }\n if (cur instanceof z.ZodPipeline) {\n cur = cur._def.out as z.ZodTypeAny;\n continue;\n }\n break;\n }\n /* eslint-enable @typescript-eslint/no-unsafe-assignment */\n return cur;\n}\n\nfunction collectLuaTypeAliasesFromHostSpec(spec: HostSurfaceSpec): readonly ManifestAlias[] {\n const byName = new Map<string, string>();\n const seenRoots = new Set<z.ZodTypeAny>();\n\n const consider = (schema: z.ZodTypeAny): void => {\n const root = getLuaTypeRegistrationRoot(schema);\n if (root === undefined || seenRoots.has(root)) {\n return;\n }\n const name = getRegisteredLuaTypeName(root);\n if (name === undefined) {\n return;\n }\n seenRoots.add(root);\n const definition = zodToLuaTypeRef(root, { emitAliasNames: false });\n if (definition !== name) {\n byName.set(name, definition);\n }\n };\n\n const walk = (schema: z.ZodTypeAny): void => {\n consider(schema);\n const base = unwrapInputSchema(schema);\n if (base instanceof z.ZodObject) {\n const shape = base.shape as Record<string, z.ZodTypeAny>;\n for (const field of Object.values(shape)) {\n consider(field);\n }\n }\n };\n\n for (const bridgeName of Object.keys(spec)) {\n const methods = spec[bridgeName]!;\n for (const methodName of Object.keys(methods)) {\n const entry = methods[methodName]!;\n walk(entry.input);\n walk(entry.output);\n }\n }\n\n return [...byName.entries()]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([name, definition]) => ({ name, definition }));\n}\n\nfunction inferLuaTypeAliasesFromHostSpec(spec: HostSurfaceSpec): readonly ManifestAlias[] {\n const byName = new Map<string, string>();\n\n for (const bridgeName of Object.keys(spec)) {\n const methods = spec[bridgeName]!;\n for (const methodName of Object.keys(methods)) {\n const entry = methods[methodName]!;\n\n const luaParams = entry.lua?.paramTypes;\n if (luaParams !== undefined) {\n const baseInput = unwrapInputSchema(entry.input);\n if (baseInput instanceof z.ZodObject) {\n const shape = baseInput.shape as Record<string, z.ZodTypeAny>;\n for (const [key, L] of Object.entries(luaParams)) {\n if (typeof L !== 'string') {\n continue;\n }\n if (!/^[A-Za-z_]\\w*$/.test(L) || isLuaTypeAtom(L)) {\n continue;\n }\n const field = shape[key];\n if (field === undefined) {\n continue;\n }\n const def = zodToLuaTypeRef(field);\n if (L !== def) {\n byName.set(L, def);\n }\n }\n }\n }\n\n const retLua = entry.lua?.returns;\n if (typeof retLua === 'string' && retLua.length > 0) {\n for (const T of nominalTokensFromLuaReturnString(retLua)) {\n const baseOut = unwrapOutputBaseForAlias(entry.output);\n const def = zodToLuaTypeRef(baseOut);\n if (T !== def) {\n byName.set(T, def);\n }\n }\n }\n }\n }\n\n return [...byName.entries()]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([name, definition]) => ({ name, definition }));\n}\n\nfunction zodInputToManifestParams(\n input: z.ZodTypeAny,\n luaParamTypes: Partial<Record<string, string>> | undefined,\n): ManifestParam[] | undefined {\n const base = unwrapInputSchema(input);\n if (base instanceof z.ZodObject) {\n const shape = base.shape as Record<string, z.ZodTypeAny>;\n return Object.keys(shape).map((name) => ({\n name,\n luaType: luaParamTypes?.[name] ?? zodToLuaTypeRef(shape[name]!),\n }));\n }\n return [{ name: 'value', luaType: luaParamTypes?.value ?? zodToLuaTypeRef(base) }];\n}\n\nfunction unwrapInputSchema(schema: z.ZodTypeAny): z.ZodTypeAny {\n let cur: z.ZodTypeAny = schema;\n if (cur instanceof z.ZodEffects) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- ZodEffects.innerType()\n cur = cur.innerType();\n }\n if (cur instanceof z.ZodPipeline) {\n cur = cur._def.in as z.ZodTypeAny;\n }\n return cur;\n}\n","import type { CapabilityId } from '@microverse.ts/runtime-capabilities';\n\nimport type { AnyHostSurfaceMethod, HostSurfaceMethodEntry, HostSurfaceSpec } from './hostSurfaceTypes.js';\n\ntype InferMethodCapability<M> = M extends { readonly capability: infer C extends CapabilityId }\n ? C\n : never;\n\ntype InferBridgeCapabilities<B> = B extends Readonly<Record<string, unknown>>\n ? InferMethodCapability<B[keyof B]>\n : never;\n\n/**\n * Union of every {@link CapabilityId} declared on methods in a {@link HostSurfaceSpec}\n * (via `requires: 'domain:action'` on each fluent `.method(…)` entry).\n */\nexport type InferSurfaceCapabilities<TSpec extends HostSurfaceSpec> = InferBridgeCapabilities<\n TSpec[keyof TSpec]\n>;\n\n/** Runtime list of capability ids declared on a compiled surface spec. */\nexport function collectCapabilitiesFromHostSurfaceSpec<const TSpec extends HostSurfaceSpec>(\n spec: TSpec,\n): readonly InferSurfaceCapabilities<TSpec>[] {\n const out: CapabilityId[] = [];\n const seen = new Set<string>();\n for (const bridgeName of Object.keys(spec)) {\n const methods = spec[bridgeName]!;\n for (const methodName of Object.keys(methods)) {\n const entry = methods[methodName]! as AnyHostSurfaceMethod;\n const id: CapabilityId = entry.capability;\n const key = String(id);\n if (!seen.has(key)) {\n seen.add(key);\n out.push(id);\n }\n }\n }\n return out as unknown as readonly InferSurfaceCapabilities<TSpec>[];\n}\n\n/** Narrows `capabilities` to those declared on the surface (runtime check). */\nexport function pickSurfaceCapabilities<\n const TSurface extends readonly CapabilityId[],\n const T extends readonly `${string}:${string}`[],\n>(\n surfaceCapabilities: TSurface,\n ...capabilities: T\n): ReadonlyArray<Extract<TSurface[number], CapabilityId>> {\n const allowed = new Set(surfaceCapabilities.map((c) => String(c)));\n for (const id of capabilities) {\n if (!allowed.has(String(id))) {\n throw new Error(\n `capability not declared on host surface: ${String(id)} (surface has: ${[...allowed].join(', ')})`,\n );\n }\n }\n return capabilities as unknown as ReadonlyArray<Extract<TSurface[number], CapabilityId>>;\n}\n\n/** Helper type for method entries that preserve a specific capability literal. */\nexport type SurfaceCapabilityEntry<TCap extends CapabilityId> = HostSurfaceMethodEntry<\n unknown,\n unknown,\n unknown\n> & { readonly capability: TCap };\n","import type { CapabilityRegistryPort } from '@microverse.ts/runtime-capabilities';\n\n/**\n * Well-known symbol key used to attach a {@link CapabilityRegistryPort} on the host object\n * while surface bridge methods run. Populated by {@link augmentHostWithCapabilityRegistry} or\n * internally by {@link HostScriptSession}.\n */\nexport const MICROVERSE_CAPABILITY_REGISTRY = Symbol.for('microverse:capabilityRegistry');\n\n/**\n * Host object extended with the capability registry required by host-surface bridge wrappers.\n */\nexport type WithMicroverseCapabilityRegistry = {\n readonly [MICROVERSE_CAPABILITY_REGISTRY]: CapabilityRegistryPort;\n};\n","import { type DeclarativeBridgeDeclaration } from '@microverse.ts/runtime-bridge';\nimport type { z } from 'zod';\n\nimport { MICROVERSE_CAPABILITY_REGISTRY, type WithMicroverseCapabilityRegistry } from '../../domain/capabilityRegistrySymbol.js';\nimport type { CapabilityId } from '@microverse.ts/runtime-capabilities';\n\nimport type { AnyHostSurfaceMethod, HostSurfaceSpec } from '../../domain/hostSurfaceTypes.js';\nimport type { SchemaValidationPort } from '../ports/SchemaValidationPort.js';\n\nfunction isThenable(value: unknown): value is Promise<unknown> {\n if (value === null || value === undefined) {\n return false;\n }\n if (typeof value !== 'object' && typeof value !== 'function') {\n return false;\n }\n const then = (value as { then?: unknown }).then;\n return typeof then === 'function';\n}\n\n/**\n * Builds declarative bridge declarations from a host surface spec, using the schema validation port for Lua ↔ host payloads.\n */\nexport function createBridgeDeclarationsFromHostSurfaceSpec<TSpec extends HostSurfaceSpec>(\n schemaValidation: SchemaValidationPort,\n spec: TSpec,\n): ReadonlyArray<DeclarativeBridgeDeclaration<WithMicroverseCapabilityRegistry, string>> {\n const out: DeclarativeBridgeDeclaration<WithMicroverseCapabilityRegistry, string>[] = [];\n for (const bridgeName of Object.keys(spec)) {\n const methods = spec[bridgeName]!;\n out.push({\n name: bridgeName,\n perEntity: true,\n createApi: (host, slotKey) => {\n const api: Record<string, (payload: unknown) => unknown> = {};\n for (const methodName of Object.keys(methods)) {\n const entry = methods[methodName]! as AnyHostSurfaceMethod;\n api[methodName] = (...args: unknown[]) => {\n const payload = args.length >= 2 ? args[1] : args[0];\n const registry = host[MICROVERSE_CAPABILITY_REGISTRY];\n const capability: CapabilityId = entry.capability;\n if (!registry.isAllowed(capability)) {\n throw new Error(`capability denied: ${String(capability)}`);\n }\n const parsedIn = schemaValidation.validateWithZodSchema(entry.input as z.ZodType<unknown>, payload);\n if (parsedIn._tag === 'err') {\n throw new Error(parsedIn.error);\n }\n const raw: unknown = entry.handler({ host, slotKey: String(slotKey) }, parsedIn.value);\n if (isThenable(raw)) {\n return raw.then((resolved) => {\n const parsedOut = schemaValidation.validateWithZodSchema(\n entry.output as z.ZodType<unknown>,\n resolved,\n );\n if (parsedOut._tag === 'err') {\n throw new Error(parsedOut.error);\n }\n return parsedOut.value;\n });\n }\n const parsedOut = schemaValidation.validateWithZodSchema(entry.output as z.ZodType<unknown>, raw);\n if (parsedOut._tag === 'err') {\n throw new Error(parsedOut.error);\n }\n return parsedOut.value;\n };\n }\n return Object.freeze(api);\n },\n });\n }\n return out;\n}\n","import { buildLuaDefManifestFromHostSurfaceSpec } from '../../domain/hostSurfaceManifest.js';\nimport {\n collectCapabilitiesFromHostSurfaceSpec,\n pickSurfaceCapabilities,\n type InferSurfaceCapabilities,\n} from '../../domain/surfaceCapabilities.js';\nimport type {\n HostSurface,\n HostSurfaceCore,\n HostSurfaceSpec,\n HostWorkflowHooksSpec,\n} from '../../domain/hostSurfaceTypes.js';\nimport type { SchemaValidationPort } from '../ports/SchemaValidationPort.js';\nimport { createBridgeDeclarationsFromHostSurfaceSpec } from './compileBridgeDeclarationsFromHostSurfaceSpec.js';\n\nfunction buildHostSurfaceCore<const TSpec extends HostSurfaceSpec>(\n schemaValidation: SchemaValidationPort,\n spec: TSpec,\n workflowHooks?: HostWorkflowHooksSpec,\n): HostSurfaceCore<InferSurfaceCapabilities<TSpec>> {\n const capabilities = collectCapabilitiesFromHostSurfaceSpec(spec);\n return {\n toBridgeDeclarations: () => createBridgeDeclarationsFromHostSurfaceSpec(schemaValidation, spec),\n toLuaDefManifest: (opts) => buildLuaDefManifestFromHostSurfaceSpec(spec, opts, workflowHooks),\n capabilities,\n pickCapabilities: (...picked) =>\n pickSurfaceCapabilities(capabilities, ...picked) as ReadonlyArray<\n Extract<(typeof picked)[number], InferSurfaceCapabilities<TSpec>>\n >,\n };\n}\n\n/**\n * Compiles a host surface using the injected schema validation port (tuple matches `UseCase` conventions in `@microverse.ts/shared`).\n */\nexport function compileHostSurface<const TSpec extends HostSurfaceSpec>(\n ports: readonly [SchemaValidationPort],\n spec: TSpec,\n): HostSurface<undefined, InferSurfaceCapabilities<TSpec>>;\nexport function compileHostSurface<\n const TSpec extends HostSurfaceSpec,\n const THooks extends HostWorkflowHooksSpec,\n>(\n ports: readonly [SchemaValidationPort],\n spec: TSpec,\n workflowHooks: THooks,\n): HostSurface<THooks, InferSurfaceCapabilities<TSpec>>;\nexport function compileHostSurface<const TSpec extends HostSurfaceSpec>(\n ports: readonly [SchemaValidationPort],\n spec: TSpec,\n workflowHooks?: HostWorkflowHooksSpec,\n): HostSurface<undefined, InferSurfaceCapabilities<TSpec>> | HostSurface<HostWorkflowHooksSpec, InferSurfaceCapabilities<TSpec>> {\n const [schemaValidation] = ports;\n const core = buildHostSurfaceCore(schemaValidation, spec, workflowHooks);\n if (workflowHooks === undefined) {\n return core;\n }\n return { ...core, workflowHooks };\n}\n\n/**\n * Same as {@link compileHostSurface}, but requires every bridge method to be typed with the same `THost`.\n */\nexport function compileHostSurfaceFor<\n const TSpec extends HostSurfaceSpec,\n const THooks extends HostWorkflowHooksSpec | undefined = undefined,\n>(\n ports: readonly [SchemaValidationPort],\n spec: TSpec,\n workflowHooks?: THooks,\n): THooks extends HostWorkflowHooksSpec\n ? HostSurface<THooks, InferSurfaceCapabilities<TSpec>>\n : HostSurface<undefined, InferSurfaceCapabilities<TSpec>> {\n return (\n workflowHooks === undefined\n ? compileHostSurface(ports, spec)\n : compileHostSurface(ports, spec, workflowHooks)\n ) as THooks extends HostWorkflowHooksSpec\n ? HostSurface<THooks, InferSurfaceCapabilities<TSpec>>\n : HostSurface<undefined, InferSurfaceCapabilities<TSpec>>;\n}\n","/** Infers {@link HostSurfaceMethodEntry.async} from handler shape unless overridden explicitly. */\nexport function inferMethodAsync(def: {\n readonly handler: { constructor: { readonly name: string } };\n readonly async?: boolean | undefined;\n}): boolean {\n if (def.async === true) {\n return true;\n }\n if (def.async === false) {\n return false;\n }\n return def.handler.constructor.name === 'AsyncFunction';\n}\n","import { createCapabilityId, type CapabilityId } from '@microverse.ts/runtime-capabilities';\nimport type { z } from 'zod';\n\nimport { inferMethodAsync } from './inferMethodAsync.js';\nimport type { HostFnContext, HostSurfaceMethodEntry } from './hostSurfaceTypes.js';\n\n/**\n * Consumer-facing method definition for the fluent {@link SurfaceBuilder} API.\n * Use `requires: 'domain:action'` for the capability id.\n */\nexport type SurfaceMethodDef<\n THost,\n TIn,\n TOut,\n TCap extends `${string}:${string}` = `${string}:${string}`,\n> = {\n /** Capability id required to invoke this method (`domain:action`). */\n readonly requires: TCap;\n readonly input: z.ZodType<TIn>;\n readonly output: z.ZodType<TOut>;\n readonly handler: (ctx: HostFnContext<THost>, input: TIn) => TOut | Promise<TOut>;\n readonly async?: boolean | undefined;\n readonly description?: string | undefined;\n readonly lua?: {\n readonly paramTypes?: Partial<Record<string, string>> | undefined;\n readonly returns?: string | undefined;\n };\n};\n\n/**\n * Converts a {@link SurfaceMethodDef} into a compiled {@link HostSurfaceMethodEntry}.\n */\nexport function normalizeMethodDef<\n THost,\n TIn,\n TOut,\n const TCap extends `${string}:${string}`,\n>(\n def: SurfaceMethodDef<THost, TIn, TOut, TCap>,\n): HostSurfaceMethodEntry<THost, TIn, TOut, CapabilityId & TCap> {\n const entry = {\n capability: createCapabilityId(def.requires) as CapabilityId & TCap,\n input: def.input,\n output: def.output,\n handler: def.handler,\n async: inferMethodAsync(def),\n ...(def.description !== undefined ? { description: def.description } : {}),\n ...(def.lua !== undefined ? { lua: def.lua } : {}),\n } satisfies HostSurfaceMethodEntry<THost, TIn, TOut, CapabilityId & TCap>;\n return entry;\n}\n","/** Keys that must not be used as dynamic property names on ordinary objects. */\nconst FORBIDDEN_OBJECT_KEYS = new Set(['__proto__', 'constructor', 'prototype']);\n\n/**\n * Rejects bridge/method names that could trigger prototype pollution when used as object keys.\n */\nexport function assertSafeObjectKey(kind: 'bridge' | 'method', name: string): void {\n if (FORBIDDEN_OBJECT_KEYS.has(name)) {\n throw new Error(`Invalid surface ${kind} name \"${name}\": reserved key`);\n }\n}\n\n/** Record with no inherited prototype — safe for dynamic string keys at runtime. */\nexport function createNullPrototypeRecord<T extends object>(): T {\n return Object.create(null) as T;\n}\n","import { compileHostSurfaceFor } from '../../application/useCases/compileHostSurface.js';\nimport type { SchemaValidationPort } from '../../application/ports/SchemaValidationPort.js';\nimport type { InferSurfaceCapabilities } from '../../domain/surfaceCapabilities.js';\nimport { normalizeMethodDef, type SurfaceMethodDef } from '../../domain/surfaceMethodDef.js';\nimport { assertSafeObjectKey, createNullPrototypeRecord } from '../../domain/safeObjectKey.js';\nimport type {\n AnyHostSurfaceMethod,\n HostSurface,\n HostSurfaceSpec,\n HostWorkflowHooksSpec,\n} from '../../domain/hostSurfaceTypes.js';\n\ntype MutableHostSurfaceSpec = Record<string, Record<string, AnyHostSurfaceMethod>>;\n\n/**\n * Fluent builder for a host surface. Created via {@link defineHostSurfaceFor} / {@link defineHostSurface} factory overloads.\n */\nexport class SurfaceBuilder<\n THost,\n const THooks extends HostWorkflowHooksSpec | undefined = undefined,\n> {\n private readonly spec: MutableHostSurfaceSpec = createNullPrototypeRecord();\n\n private workflowHooksSpec: THooks;\n\n private readonly ports: readonly [SchemaValidationPort];\n\n constructor(\n ports: readonly [SchemaValidationPort],\n workflowHooks?: THooks,\n initialSpec?: MutableHostSurfaceSpec,\n ) {\n this.ports = ports;\n this.workflowHooksSpec = workflowHooks as THooks;\n if (initialSpec !== undefined) {\n for (const bridgeName of Object.keys(initialSpec)) {\n assertSafeObjectKey('bridge', bridgeName);\n const srcBridge = initialSpec[bridgeName]!;\n const bridge = createNullPrototypeRecord<Record<string, AnyHostSurfaceMethod>>();\n for (const methodName of Object.keys(srcBridge)) {\n assertSafeObjectKey('method', methodName);\n bridge[methodName] = srcBridge[methodName]!;\n }\n this.spec[bridgeName] = bridge;\n }\n }\n }\n\n /** Opens a Lua bridge table (e.g. `orders`, `greet`). */\n bridge<const B extends string>(name: B): BridgeBuilder<THost, B, THooks> {\n return new BridgeBuilder(this, name);\n }\n\n /** Attaches workflow hook Zod schemas (emitted into `.d.lua` as `on*` methods). */\n workflowHooks<const H extends HostWorkflowHooksSpec>(hooks: H): SurfaceBuilder<THost, H> {\n return new SurfaceBuilder<THost, H>(this.ports, hooks, this.spec);\n }\n\n /** Compiles the accumulated spec into a {@link HostSurface}. */\n build(): THooks extends HostWorkflowHooksSpec\n ? HostSurface<THooks, InferSurfaceCapabilities<HostSurfaceSpec>>\n : HostSurface<undefined, InferSurfaceCapabilities<HostSurfaceSpec>> {\n const spec = this.spec as HostSurfaceSpec;\n return compileHostSurfaceFor(this.ports, spec, this.workflowHooksSpec);\n }\n\n /** @internal */\n addMethod<const B extends string, const M extends string>(\n bridgeName: B,\n methodName: M,\n entry: AnyHostSurfaceMethod,\n ): SurfaceBuilder<THost, THooks> {\n assertSafeObjectKey('bridge', bridgeName);\n assertSafeObjectKey('method', methodName);\n let bridge = this.spec[bridgeName];\n if (bridge === undefined) {\n bridge = createNullPrototypeRecord<Record<string, AnyHostSurfaceMethod>>();\n this.spec[bridgeName] = bridge;\n }\n bridge[methodName] = entry;\n return this;\n }\n}\n\n/**\n * Per-bridge step in the fluent surface DSL. Return to {@link SurfaceBuilder} via `.method(…)`.\n */\nexport class BridgeBuilder<\n THost,\n const B extends string,\n THooks extends HostWorkflowHooksSpec | undefined,\n> {\n constructor(\n private readonly parent: SurfaceBuilder<THost, THooks>,\n private readonly bridgeName: B,\n ) {}\n\n /** Registers one method on the current bridge and returns the root builder for chaining. */\n method<const M extends string, TIn, TOut, TCap extends `${string}:${string}`>(\n name: M,\n def: SurfaceMethodDef<THost, TIn, TOut, TCap>,\n ): SurfaceBuilder<THost, THooks> {\n return this.parent.addMethod(this.bridgeName, name, normalizeMethodDef(def));\n }\n}\n","import type { SchemaValidationPort } from '../../application/ports/SchemaValidationPort.js';\n\nimport { createZodSchemaValidationPort } from '../adapters/zodSchemaValidationAdapter.js';\nimport { SurfaceBuilder } from './surfaceBuilder.js';\n\nconst defaultPorts: readonly [SchemaValidationPort] = [createZodSchemaValidationPort()];\n\nexport type { InferSurfaceCapabilities } from '../../domain/surfaceCapabilities.js';\nexport type { SurfaceMethodDef } from '../../domain/surfaceMethodDef.js';\nexport { BridgeBuilder, SurfaceBuilder } from './surfaceBuilder.js';\n\nexport type {\n AnyHostSurfaceMethod,\n HostFnContext,\n HostSurface,\n HostSurfaceCore,\n HostSurfaceMethodEntry,\n HostSurfaceSpec,\n HostSurfaceSpecForHost,\n HostWorkflowHooksSpec,\n LuaDefManifestGeneratorOpts,\n} from '../../domain/hostSurfaceTypes.js';\n\nfunction createSurfaceBuilder<THost>(): SurfaceBuilder<THost> {\n return new SurfaceBuilder<THost>(defaultPorts);\n}\n\n/**\n * Declares a **host surface** via the fluent builder (`bridge` → `method` → `build`).\n *\n * @example\n * ```ts\n * const surface = defineHostSurface()\n * .bridge('time')\n * .method('delta', {\n * requires: 'engine:time',\n * input: z.object({}),\n * output: z.number(),\n * handler: ({ host }) => host.clock.dt,\n * })\n * .build();\n * ```\n */\nexport function defineHostSurface(): SurfaceBuilder<unknown> {\n return createSurfaceBuilder();\n}\n\n/**\n * Same as {@link defineHostSurface}, but every `handler` is typed against a single `THost`\n * (the engine context passed to {@link HostScriptSession} / {@link MicroverseLua.create}).\n *\n * @example\n * ```ts\n * const surface = defineHostSurfaceFor<MyHost>()\n * .bridge('greet')\n * .method('hello', {\n * requires: 'demo:greet',\n * input: z.object({ name: z.string() }),\n * output: z.string(),\n * handler: ({ host }, { name }) => `Hello, ${name}`,\n * })\n * .build();\n * ```\n */\nexport function defineHostSurfaceFor<THost>(): SurfaceBuilder<THost> {\n return createSurfaceBuilder<THost>();\n}\n","import type { CapabilityRegistryPort } from '@microverse.ts/runtime-capabilities';\n\nimport { MICROVERSE_CAPABILITY_REGISTRY, type WithMicroverseCapabilityRegistry } from '../../domain/capabilityRegistrySymbol.js';\n\n/**\n * Returns a shallow copy of `host` with {@link MICROVERSE_CAPABILITY_REGISTRY} set to `registry`.\n * Bridge handlers read the registry to enforce per-session capability allowlists.\n *\n * @param host - Your engine / service context passed into `buildDeclarativeBridgeTable`.\n * @param registry - Typically an {@link InMemoryCapabilityRegistry} from `@microverse.ts/runtime-capabilities`.\n */\nexport function augmentHostWithCapabilityRegistry<THost>(\n host: THost,\n registry: CapabilityRegistryPort,\n): THost & WithMicroverseCapabilityRegistry {\n return Object.assign(host as object, {\n [MICROVERSE_CAPABILITY_REGISTRY]: registry,\n }) as THost & WithMicroverseCapabilityRegistry;\n}\n","import {\n createAllowlist,\n type CapabilityId,\n InMemoryCapabilityRegistry,\n} from '@microverse.ts/runtime-capabilities';\nimport type { Result } from '@microverse.ts/shared';\nimport type { z } from 'zod';\nimport {\n createMicroverseScript,\n type ExecutionFailure,\n type RunScriptResult,\n type MicroverseSlot,\n type MicroverseId,\n type MicroverseRuntime,\n type TimeoutPolicy,\n} from '@microverse.ts/runtime-core';\n\nimport { augmentHostWithCapabilityRegistry } from '../adapters/augmentHostWithCapabilityRegistry.js';\nimport { buildBridgeMergeEnvForHost } from '../builders/bridgeMergeEnv.js';\nimport type { HostSurface, HostWorkflowHooksSpec } from '../../domain/hostSurfaceTypes.js';\nimport type { LuaGlobalHookName } from '../../domain/luaGlobalHook.js';\nimport { luaGlobalHookName } from '../../domain/luaGlobalHook.js';\n\n/**\n * Tuple accepted by {@link HostScriptSession.invokeGlobalHookIfPresent} when the session is specialised with\n * the same Zod map as {@link HostSurface} `workflowHooks` on the surface you pass in.\n */\nexport type WorkflowHookInvokeArgs<TH extends HostWorkflowHooksSpec> = {\n [K in keyof TH & string]: readonly [hook: LuaGlobalHookName<K>, payload: Readonly<z.infer<TH[K]>>];\n}[keyof TH & string];\n\ntype InvokeGlobalHookIfPresentFn<THooks extends HostWorkflowHooksSpec | undefined> = THooks extends HostWorkflowHooksSpec\n ? (...args: WorkflowHookInvokeArgs<THooks>) => Promise<Result<RunScriptResult, ExecutionFailure>>\n : (\n globalName: string,\n payload: Readonly<Record<string, string | number | boolean>>,\n ) => Promise<Result<RunScriptResult, ExecutionFailure>>;\n\n/**\n * Options for {@link HostScriptSession}: one Wasm (or other) slot, a surface, host services, and a capability allowlist.\n *\n * @typeParam THost - Your engine context; must match the `THost` used in {@link defineHostSurfaceFor} (or {@link defineHostSurface}).\n * @typeParam THooks - When the surface was built with workflow hooks, pass the same `THooks` so {@link HostScriptSession.invokeGlobalHookIfPresent} narrows to those payloads (match `surface`’s `workflowHooks` typing).\n */\nexport type HostScriptSessionOptions<\n THost,\n THooks extends HostWorkflowHooksSpec | undefined = undefined,\n> = {\n /** Shared runtime (typically one Wasmoon VM for many slots). */\n readonly runtime: MicroverseRuntime;\n /** Surface produced by {@link defineHostSurface}. */\n readonly surface: HostSurface<THooks>;\n /** Host services passed into bridge handlers (orders, clock, …). */\n readonly host: THost;\n /** Stable sandbox id for this script / workflow / entity. */\n readonly slotKey: MicroverseId;\n /** Exact capability ids this session may invoke on any bridge method. */\n readonly allowedCapabilities: readonly CapabilityId[];\n /** Optional default timeout forwarded to {@link MicroverseSlot.run}. */\n readonly defaultTimeout?: TimeoutPolicy | undefined;\n};\n\n/**\n * Binds one **Lua slot** to a {@link HostSurface}: capability allowlist, Zod validation, and `mergeEnv` wiring.\n *\n * @remarks\n * - **Lua → host (bridges):** tables/methods from {@link defineHostSurface} on `_ENV` call into TypeScript with Zod validation.\n * - **Host → Lua (hooks):** when the surface defines `workflowHooks`, {@link HostScriptSession.openSession} installs\n * a small `workflow` helper (`workflow:extend()` → handler table + slot registration) and\n * {@link HostScriptSession.invokeGlobalHookIfPresent} dispatches `on…` methods on that table. Each session has its own\n * slot env, so many workflows run concurrently without sharing Lua globals. Without `workflowHooks`, hooks are optional\n * globals (`onSmoke`, …) invoked as plain functions.\n * - Call {@link HostScriptSession.openSession} once before running chunks or invocations; {@link HostScriptSession.dispose} when the slot is torn down.\n *\n * @typeParam THost - Same host type as your surface handlers.\n * @typeParam THooks - Align with {@link HostSurface} `workflowHooks` on the surface you pass in (or `undefined` when the surface has no workflow hooks).\n */\nexport class HostScriptSession<\n THost,\n THooks extends HostWorkflowHooksSpec | undefined = undefined,\n> {\n private sandbox: MicroverseSlot | undefined;\n\n private readonly registry: InMemoryCapabilityRegistry;\n\n constructor(private readonly opts: HostScriptSessionOptions<THost, THooks>) {\n this.registry = new InMemoryCapabilityRegistry(createAllowlist([...opts.allowedCapabilities]));\n }\n\n /**\n * Allocates the underlying {@link MicroverseSlot} for this `slotKey` on the shared runtime.\n */\n readonly openSession = async (): Promise<void> => {\n this.sandbox = await this.opts.runtime.createMicroverse({ slotKey: this.opts.slotKey });\n const hooks = readWorkflowHooks(this.opts.surface);\n if (hooks !== undefined) {\n const prelude = buildWorkflowStubPreludeLua(hooks);\n const sb = this.requireMicroverseSlot();\n await sb.run({\n script: createMicroverseScript(prelude),\n mergeEnv: this.mergeEnv(),\n timeout: this.opts.defaultTimeout,\n });\n }\n };\n\n /**\n * Exposes the in-memory registry (e.g. to mutate allowlists in advanced tests).\n */\n readonly getCapabilityRegistry = (): InMemoryCapabilityRegistry => this.registry;\n\n private requireMicroverseSlot(): MicroverseSlot {\n if (this.sandbox === undefined) {\n throw new Error('HostScriptSession: openSession() was not called');\n }\n return this.sandbox;\n }\n\n private mergeEnv() {\n const host = augmentHostWithCapabilityRegistry(this.opts.host, this.registry);\n return buildBridgeMergeEnvForHost(host, String(this.opts.slotKey), this.opts.surface);\n }\n\n /**\n * Executes Lua source in the slot environment with surface bridges on `_ENV`.\n *\n * @param source - Full Lua chunk (compiled with `load(..., \"t\", env)` in the Wasm adapter).\n */\n readonly runChunk = async (source: string) => {\n const sb = this.requireMicroverseSlot();\n return sb.run({\n script: createMicroverseScript(source),\n mergeEnv: this.mergeEnv(),\n timeout: this.opts.defaultTimeout,\n });\n };\n\n /**\n * Host → Lua: when the surface has `workflowHooks`, invokes `impl:onHook(evt)` on the handler table registered by\n * `workflow:extend()` in this slot. Otherwise invokes `_ENV[globalName](evt)` when that entry is a function.\n *\n * @param globalName - Hook method name, e.g. `onOrderPlaced` (same as {@link luaGlobalHookName}).\n * @param payload - Table fields: only string, finite number, or boolean (Lua literals).\n */\n readonly invokeGlobalHookIfPresent = (async (\n globalName: string,\n payload: Readonly<Record<string, string | number | boolean>>,\n ) => {\n assertSafeLuaGlobalName(globalName);\n const sb = this.requireMicroverseSlot();\n const tbl = luaTableLiteralFromPlainRecord(payload);\n const hooks = readWorkflowHooks(this.opts.surface);\n const src =\n hooks !== undefined\n ? buildWorkflowHookInvokeLuaSource(globalName, tbl)\n : buildGlobalHookInvokeLuaSource(globalName, tbl);\n return sb.run({\n script: createMicroverseScript(src),\n mergeEnv: this.mergeEnv(),\n timeout: this.opts.defaultTimeout,\n });\n }) as InvokeGlobalHookIfPresentFn<THooks>;\n\n /**\n * Host → Lua: invokes `_ENV[tableName][methodName](literalTable)` where `literalTable` is built only from\n * string, finite number, or boolean fields in `payload`.\n *\n * @param tableName - Global table name in the slot env.\n * @param methodName - Function field on that table.\n * @param payload - Plain serializable fields for the Lua table literal.\n */\n readonly call = async (tableName: string, methodName: string, payload: Record<string, unknown>) => {\n const sb = this.requireMicroverseSlot();\n const tbl = luaTableLiteralFromUnknownRecord(payload);\n const src = [\n `local t = _ENV[${JSON.stringify(tableName)}]`,\n `local f = type(t) == \"table\" and t[${JSON.stringify(methodName)}] or nil`,\n `if type(f) == \"function\" then`,\n ` f(${tbl})`,\n `end`,\n ].join('\\n');\n return sb.run({\n script: createMicroverseScript(src),\n mergeEnv: this.mergeEnv(),\n timeout: this.opts.defaultTimeout,\n });\n };\n\n /**\n * Releases the slot in the runtime adapter and clears the session handle.\n */\n readonly dispose = async (): Promise<void> => {\n if (this.sandbox !== undefined) {\n await this.sandbox.dispose();\n this.sandbox = undefined;\n }\n };\n}\n\nfunction assertSafeLuaGlobalName(name: string): void {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {\n throw new Error(`unsafe Lua global name: ${name}`);\n }\n}\n\nfunction readWorkflowHooks(surface: HostSurface<HostWorkflowHooksSpec | undefined>): HostWorkflowHooksSpec | undefined {\n if (!('workflowHooks' in surface)) {\n return undefined;\n }\n const wh = (surface as HostSurface<HostWorkflowHooksSpec>).workflowHooks;\n return wh;\n}\n\nfunction buildWorkflowStubPreludeLua(hooks: HostWorkflowHooksSpec): string {\n const hookNames = Object.keys(hooks)\n .sort((a, b) => a.localeCompare(b))\n .map((kind) => {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(kind)) {\n throw new Error(`unsafe workflow hook kind: ${kind}`);\n }\n return JSON.stringify(luaGlobalHookName(kind));\n });\n const lines: string[] = [\n 'local Base = {}',\n 'for _, name in ipairs({',\n ...hookNames.map((h) => ` ${h},`),\n '}) do',\n ' rawset(Base, name, function() end)',\n 'end',\n 'rawset(_ENV, \"workflow\", {',\n ' extend = function(_)',\n ' local w = setmetatable({}, { __index = Base })',\n ' rawset(_ENV, \"__microverse_lua_WorkflowImpl\", w)',\n ' return w',\n ' end,',\n '})',\n ];\n return lines.join('\\n');\n}\n\nfunction buildWorkflowHookInvokeLuaSource(methodName: string, evtLiteral: string): string {\n return [\n `local impl = rawget(_ENV, \"__microverse_lua_WorkflowImpl\")`,\n `if type(impl) == \"table\" then`,\n ` local m = rawget(impl, ${JSON.stringify(methodName)})`,\n ` if type(m) == \"function\" then`,\n ` m(impl, ${evtLiteral})`,\n ` end`,\n `end`,\n ].join('\\n');\n}\n\nfunction buildGlobalHookInvokeLuaSource(globalName: string, evtLiteral: string): string {\n return [\n `local f = rawget(_ENV, ${JSON.stringify(globalName)})`,\n `if type(f) == \"function\" then`,\n ` f(${evtLiteral})`,\n `end`,\n ].join('\\n');\n}\n\nfunction luaTableLiteralFromPlainRecord(o: Readonly<Record<string, string | number | boolean>>): string {\n const parts: string[] = [];\n for (const [k, v] of Object.entries(o)) {\n if (typeof v === 'string') {\n parts.push(`${k} = ${JSON.stringify(v)}`);\n } else if (typeof v === 'number' && Number.isFinite(v)) {\n parts.push(`${k} = ${v}`);\n } else if (typeof v === 'boolean') {\n parts.push(`${k} = ${v ? 'true' : 'false'}`);\n } else {\n throw new Error(`HostScriptSession: unsupported value type for key ${k}`);\n }\n }\n return `{ ${parts.join(', ')} }`;\n}\n\nfunction luaTableLiteralFromUnknownRecord(o: Record<string, unknown>): string {\n const parts: string[] = [];\n for (const [k, v] of Object.entries(o)) {\n if (typeof v === 'string') {\n parts.push(`${k} = ${JSON.stringify(v)}`);\n } else if (typeof v === 'number' && Number.isFinite(v)) {\n parts.push(`${k} = ${v}`);\n } else if (typeof v === 'boolean') {\n parts.push(`${k} = ${v ? 'true' : 'false'}`);\n } else {\n throw new Error(`HostScriptSession.call: unsupported value type for key ${k}`);\n }\n }\n return `{ ${parts.join(', ')} }`;\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,SAAgB,2BACd,MACA,SACA,SACmC;CACnC,OAAO,4BAA4B,MAAM,SAAS,CAAC,GAAG,QAAQ,qBAAqB,CAAC,CAAC;AACvF;;;ACdA,SAAgB,gCAAsD;CACpE,OAAO,EAAE,sBAAsB;AACjC;;;;;;;;ACKA,SAAgB,kBAA6C,MAAqC;CAChG,IAAI,CAAC,2BAA2B,KAAK,IAAI,GACvC,MAAM,IAAI,MAAM,yCAAyC,MAAM;CAGjE,OAAO,KADW;AAEpB;;;;AChBA,IAAa,iBAAiB,IAAI,IAAI;CACpC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;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AAC;CACzB,KAAK,MAAM,CAAC,GAAG,MAAM,OAAO,QAAQ,CAAC,GACnC,IAAI,OAAO,MAAM,UACf,MAAM,KAAK,GAAG,EAAE,KAAK,KAAK,UAAU,CAAC,GAAG;MACnC,IAAI,OAAO,MAAM,YAAY,OAAO,SAAS,CAAC,GACnD,MAAM,KAAK,GAAG,EAAE,KAAK,GAAG;MACnB,IAAI,OAAO,MAAM,WACtB,MAAM,KAAK,GAAG,EAAE,KAAK,IAAI,SAAS,SAAS;MAE3C,MAAM,IAAI,MAAM,qDAAqD,GAAG;CAG5E,OAAO,KAAK,MAAM,KAAK,IAAI,EAAE;AAC/B;AAEA,SAAS,iCAAiC,GAAoC;CAC5E,MAAM,QAAkB,CAAC;CACzB,KAAK,MAAM,CAAC,GAAG,MAAM,OAAO,QAAQ,CAAC,GACnC,IAAI,OAAO,MAAM,UACf,MAAM,KAAK,GAAG,EAAE,KAAK,KAAK,UAAU,CAAC,GAAG;MACnC,IAAI,OAAO,MAAM,YAAY,OAAO,SAAS,CAAC,GACnD,MAAM,KAAK,GAAG,EAAE,KAAK,GAAG;MACnB,IAAI,OAAO,MAAM,WACtB,MAAM,KAAK,GAAG,EAAE,KAAK,IAAI,SAAS,SAAS;MAE3C,MAAM,IAAI,MAAM,0DAA0D,GAAG;CAGjF,OAAO,KAAK,MAAM,KAAK,IAAI,EAAE;AAC/B"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/infrastructure/builders/bridgeMergeEnv.ts","../src/infrastructure/adapters/zodSchemaValidationAdapter.ts","../src/domain/luaGlobalHook.ts","../src/domain/luaTypeAtoms.ts","../src/domain/zodLuaType.ts","../src/domain/zodToLuaTypeRef.ts","../src/domain/hostSurfaceManifest.ts","../src/domain/surfaceCapabilities.ts","../src/domain/capabilityRegistrySymbol.ts","../src/domain/scriptContextSymbol.ts","../src/application/useCases/compileBridgeDeclarationsFromHostSurfaceSpec.ts","../src/application/useCases/compileHostSurface.ts","../src/domain/inferMethodAsync.ts","../src/domain/surfaceMethodDef.ts","../src/domain/safeObjectKey.ts","../src/infrastructure/builders/surfaceBuilder.ts","../src/infrastructure/builders/defineHostSurfaceFacade.ts","../src/domain/componentSlotPrelude.ts","../src/domain/scriptPropertyMergeEnv.ts","../src/infrastructure/adapters/augmentHostWithCapabilityRegistry.ts","../src/infrastructure/adapters/augmentHostWithScriptContext.ts","../src/infrastructure/components/hostScriptSession.ts"],"sourcesContent":["import { buildDeclarativeBridgeTable } from '@microverse.ts/runtime-bridge';\n\nimport type { WithMicroverseCapabilityRegistry } from '../../domain/capabilityRegistrySymbol';\nimport type { WithMicroverseScriptContext } from '../../domain/scriptContextSymbol';\nimport type { HostSurfaceCore } from '../../domain/hostSurfaceTypes';\n\n/**\n * Builds a frozen `mergeEnv` table: bridge name → API object, ready for `MicroverseSlot.run({ mergeEnv })`.\n *\n * @param host - Your host context, already extended with the capability registry symbol from `@microverse.ts/host-surface`.\n * @param slotKey - Same slot key passed to `buildDeclarativeBridgeTable` (string form of `MicroverseId` is fine).\n * @param surface - Result of {@link defineHostSurface} (implements {@link HostSurfaceCore}).\n */\nexport function buildBridgeMergeEnvForHost<THost>(\n host: THost & WithMicroverseCapabilityRegistry & WithMicroverseScriptContext,\n slotKey: string,\n surface: HostSurfaceCore,\n): Readonly<Record<string, unknown>> {\n return buildDeclarativeBridgeTable(host, slotKey, [...surface.toBridgeDeclarations()]);\n}\n\n/** Bridge table names for `__microverse_bridge_names` in the slot env. */\nexport function bridgeNamesFromSurface(surface: HostSurfaceCore): readonly string[] {\n return surface.toBridgeDeclarations().map((d) => d.name);\n}\n","import { validateWithZodSchema } from '@microverse.ts/runtime-zod';\n\nimport type { SchemaValidationPort } from '../../application/ports/SchemaValidationPort';\n\nexport function createZodSchemaValidationPort(): SchemaValidationPort {\n return { validateWithZodSchema };\n}\n","/**\n * Lua convention for domain hooks: PascalCase event kind → method name `on{Kind}` on the workflow\n * component table from `component:extend()` in each Lua slot (e.g. `OrderPlaced` → `onOrderPlaced`).\n */\nexport type LuaGlobalHookName<Kind extends string> = `on${Kind}`;\n\n/**\n * Builds the `on{Kind}` method name dispatched on the slot’s workflow handler for a PascalCase event `kind`\n * (e.g. `InventoryLow` → `onInventoryLow`).\n * Throws if `kind` is not a safe Lua identifier fragment.\n */\nexport function luaGlobalHookName<const Kind extends string>(kind: Kind): LuaGlobalHookName<Kind> {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(kind)) {\n throw new Error(`unsafe Lua identifier for event kind: ${kind}`);\n }\n const name = `on${kind}`;\n return name as LuaGlobalHookName<Kind>;\n}\n","/** Lua / LuaCATS type atoms: never emit `---@alias` for these names from `lua.paramTypes` / `lua.returns` tokens. */\nexport const LUA_TYPE_ATOMS = new Set([\n 'any',\n 'boolean',\n 'false',\n 'integer',\n 'nil',\n 'never',\n 'number',\n 'self',\n 'string',\n 'table',\n 'true',\n 'unknown',\n]);\n\nexport function isLuaTypeAtom(name: string): boolean {\n return LUA_TYPE_ATOMS.has(name);\n}\n","import { z } from 'zod';\n\nconst aliasBySchema = new WeakMap<z.ZodTypeAny, string>();\n\n/**\n * Registers a nominal LuaCATS name for a Zod schema. {@link zodToLuaTypeRef} emits the name;\n * `.d.lua` generation adds a matching `---@alias` with the structural shape.\n *\n * @example\n * ```ts\n * export const orderDto = luaType('OrderDto', z.object({ id: z.string() }));\n * // bridge: output: orderDto.optional() → returns `OrderDto|nil` in manifest\n * ```\n */\nexport function luaType<T extends z.ZodTypeAny>(name: string, schema: T): T {\n if (!/^[A-Za-z_]\\w*$/.test(name)) {\n throw new Error(`luaType: invalid alias name: ${name}`);\n }\n aliasBySchema.set(schema, name);\n return schema;\n}\n\n/** @internal Root schema that carries a {@link luaType} registration (after unwrapping optional/nullable/…). */\nexport function getLuaTypeRegistrationRoot(schema: z.ZodTypeAny): z.ZodTypeAny | undefined {\n let cur: z.ZodTypeAny = schema;\n for (;;) {\n const name = aliasBySchema.get(cur);\n if (name !== undefined) {\n return cur;\n }\n const next = unwrapOneLayer(cur);\n if (next === undefined) {\n return undefined;\n }\n cur = next;\n }\n}\n\n/** @internal Nominal LuaCATS name for this schema, if registered via {@link luaType}. */\nexport function resolveZodLuaTypeAlias(schema: z.ZodTypeAny): string | undefined {\n const root = getLuaTypeRegistrationRoot(schema);\n return root === undefined ? undefined : aliasBySchema.get(root);\n}\n\nexport function getRegisteredLuaTypeName(root: z.ZodTypeAny): string | undefined {\n return aliasBySchema.get(root);\n}\n\nfunction unwrapOneLayer(schema: z.ZodTypeAny): z.ZodTypeAny | undefined {\n if (schema instanceof z.ZodOptional || schema instanceof z.ZodNullable) {\n return schema.unwrap() as z.ZodTypeAny;\n }\n if (schema instanceof z.ZodDefault) {\n return schema.removeDefault() as z.ZodTypeAny;\n }\n if (schema instanceof z.ZodReadonly) {\n return schema.unwrap() as z.ZodTypeAny;\n }\n if (schema instanceof z.ZodEffects) {\n return schema.innerType() as z.ZodTypeAny;\n }\n if (schema instanceof z.ZodPipeline) {\n return schema._def.in as z.ZodTypeAny;\n }\n if (schema instanceof z.ZodLazy) {\n return schema.schema as z.ZodTypeAny;\n }\n if (schema instanceof z.ZodBranded) {\n return schema.unwrap() as z.ZodTypeAny;\n }\n return undefined;\n}\n","import { z } from 'zod';\n\nimport { resolveZodLuaTypeAlias } from './zodLuaType';\n\n/* Zod's internal `_def` / `options` are intentionally untyped for this best-effort emitter. */\n/* eslint-disable @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-return */\n\nexport type ZodToLuaTypeRefOptions = {\n /**\n * When `false`, expands {@link luaType} registrations to structural shapes (for `---@alias` bodies).\n * Default `true` emits registered nominal names at use sites.\n */\n readonly emitAliasNames?: boolean | undefined;\n};\n\n/**\n * Maps a Zod schema to a LuaCATS type reference string for manifest emission.\n *\n * @remarks\n * Register nominal types with {@link luaType} on shared Zod schemas (e.g. `orderDto`, `orderId`).\n * Prefer that over per-method `lua.paramTypes` / `lua.returns` escape hatches on bridge methods.\n */\nexport function zodToLuaTypeRef(schema: z.ZodTypeAny, options?: ZodToLuaTypeRefOptions): string {\n const emitAliasNames = options?.emitAliasNames !== false;\n\n if (schema instanceof z.ZodOptional) {\n return `${zodToLuaTypeRef(schema.unwrap(), options)}|nil`;\n }\n if (schema instanceof z.ZodNullable) {\n return `${zodToLuaTypeRef(schema.unwrap(), options)}|nil`;\n }\n if (schema instanceof z.ZodDefault) {\n return zodToLuaTypeRef(schema.removeDefault(), options);\n }\n if (schema instanceof z.ZodReadonly) {\n return zodToLuaTypeRef(schema.unwrap(), options);\n }\n if (schema instanceof z.ZodCatch) {\n return zodToLuaTypeRef(schema._def.innerType as z.ZodTypeAny, options);\n }\n if (schema instanceof z.ZodPipeline) {\n return zodToLuaTypeRef(schema._def.out as z.ZodTypeAny, options);\n }\n if (schema instanceof z.ZodEffects) {\n return zodToLuaTypeRef(schema.innerType(), options);\n }\n if (schema instanceof z.ZodLazy) {\n return zodToLuaTypeRef(schema.schema, options);\n }\n if (schema instanceof z.ZodBranded) {\n return zodToLuaTypeRef(schema.unwrap(), options);\n }\n\n if (emitAliasNames) {\n const alias = resolveZodLuaTypeAlias(schema);\n if (alias !== undefined) {\n return alias;\n }\n }\n\n if (schema instanceof z.ZodString) {\n return 'string';\n }\n if (schema instanceof z.ZodNumber) {\n return zodNumberToLua(schema);\n }\n if (schema instanceof z.ZodBoolean) {\n return 'boolean';\n }\n if (schema instanceof z.ZodBigInt) {\n return 'integer';\n }\n if (schema instanceof z.ZodUndefined) {\n return 'nil';\n }\n if (schema instanceof z.ZodNull) {\n return 'nil';\n }\n if (schema instanceof z.ZodVoid) {\n return 'nil';\n }\n if (schema instanceof z.ZodUnknown || schema instanceof z.ZodAny) {\n return 'unknown';\n }\n if (schema instanceof z.ZodLiteral) {\n const v = schema.value;\n if (typeof v === 'string') {\n return `\"${v}\"`;\n }\n if (typeof v === 'number' || typeof v === 'boolean') {\n return String(v);\n }\n return 'unknown';\n }\n if (schema instanceof z.ZodEnum) {\n return schema.options.map((o: string) => `\"${String(o)}\"`).join('|');\n }\n if (schema instanceof z.ZodNativeEnum) {\n return 'string|number';\n }\n if (schema instanceof z.ZodArray) {\n return 'table';\n }\n if (schema instanceof z.ZodRecord) {\n return 'table';\n }\n if (schema instanceof z.ZodObject) {\n const shape = schema.shape as Record<string, z.ZodTypeAny>;\n const keys = Object.keys(shape);\n if (keys.length === 0) {\n return '{}';\n }\n const parts = keys.map((k) => `${k}: ${zodToLuaTypeRef(shape[k]!, options)}`);\n return `{ ${parts.join('; ')} }`;\n }\n if (schema instanceof z.ZodUnion) {\n return schema.options.map((o: z.ZodTypeAny) => zodToLuaTypeRef(o, options)).join('|');\n }\n if (schema instanceof z.ZodDiscriminatedUnion) {\n return schema.options.map((o: z.ZodTypeAny) => zodToLuaTypeRef(o, options)).join('|');\n }\n if (schema instanceof z.ZodIntersection) {\n return 'table';\n }\n if (schema instanceof z.ZodTuple) {\n return 'table';\n }\n return 'unknown';\n}\n\nfunction zodNumberToLua(schema: z.ZodNumber): string {\n const checks = schema._def.checks as readonly { readonly kind: string }[];\n if (checks.some((c) => c.kind === 'int')) {\n return 'integer';\n }\n return 'number';\n}\n","import type {\n LuaDefManifest,\n ManifestAlias,\n ManifestClass,\n ManifestClassField,\n ManifestMethod,\n ManifestParam,\n} from '@microverse.ts/lua-defs';\nimport { z } from 'zod';\n\nimport type { HostSurfaceSpec, HostComponentHooksSpec } from './hostSurfaceTypes';\nimport { luaGlobalHookName } from './luaGlobalHook';\nimport { isLuaTypeAtom } from './luaTypeAtoms';\nimport { getLuaTypeRegistrationRoot, getRegisteredLuaTypeName } from './zodLuaType';\nimport { zodToLuaTypeRef } from './zodToLuaTypeRef';\n\nfunction asyncHandleClassName(bridgeName: string, methodName: string): string {\n const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);\n return `${cap(bridgeName)}${cap(methodName)}Handle`;\n}\n\n/** LuaCATS class for runtime bridge key `audit` → `Audit` (distinct from field name for LuaLS). */\nfunction bridgeLuaClassName(bridgeTableName: string): string {\n return bridgeTableName.charAt(0).toUpperCase() + bridgeTableName.slice(1);\n}\n\nfunction pushMicroverseBridgesClass(bridgeNames: readonly string[], classes: ManifestClass[]): void {\n if (bridgeNames.length === 0) {\n return;\n }\n classes.push({\n name: 'MicroverseBridges',\n description: 'Capability-scoped host bridges for this component (`self.bridges` after `component:extend()`).',\n fields: bridgeNames.map((name) => ({\n name,\n luaType: bridgeLuaClassName(name),\n })),\n emitSingleton: false,\n });\n}\n\nfunction buildComponentEventManifestFields(\n kinds: readonly string[],\n componentHooks: HostComponentHooksSpec,\n): ManifestClassField[] {\n const out: ManifestClassField[] = [];\n for (const kind of kinds) {\n const schema = componentHooks[kind];\n if (!(schema instanceof z.ZodObject)) {\n throw new Error(`defineHostSurface componentHooks: \"${kind}\" must be a z.object(...)`);\n }\n const payloadName = `MicroverseEvt_${kind}`;\n const hookName = luaGlobalHookName(kind);\n out.push({\n name: hookName,\n description: `Host invokes when \\`${kind}\\` is emitted. Payload: \\`${payloadName}\\`.`,\n luaType: `fun(self: Component, evt: ${payloadName})`,\n });\n }\n return out;\n}\n\nfunction pushComponentEventPayloadClasses(\n kinds: readonly string[],\n componentHooks: HostComponentHooksSpec,\n classes: ManifestClass[],\n): void {\n for (const kind of kinds) {\n const schema = componentHooks[kind];\n if (!(schema instanceof z.ZodObject)) {\n throw new Error(`defineHostSurface componentHooks: \"${kind}\" must be a z.object(...)`);\n }\n const name = `MicroverseEvt_${kind}`;\n const shape = schema.shape as Record<string, z.ZodTypeAny>;\n classes.push({\n name,\n description: `Domain event payload for \\`${luaGlobalHookName(kind)}\\` (Zod → LuaCATS fields).`,\n fields: Object.keys(shape).map((k) => ({\n name: k,\n luaType: zodToLuaTypeRef(shape[k]!),\n })),\n emitSingleton: false,\n });\n }\n}\n\nfunction pushComponentManifestClasses(\n classes: ManifestClass[],\n bridgeNames: readonly string[],\n componentHooks?: HostComponentHooksSpec,\n): void {\n const eventKinds =\n componentHooks !== undefined\n ? Object.keys(componentHooks).sort((a, b) => a.localeCompare(b))\n : [];\n if (componentHooks !== undefined) {\n pushComponentEventPayloadClasses(eventKinds, componentHooks, classes);\n }\n const lifecycleFields: ManifestClassField[] = [\n { name: 'properties', luaType: 'table', description: 'Host-synced props (proxy).' },\n { name: 'state', luaType: 'table', description: 'Lua-local state.' },\n {\n name: 'bridges',\n luaType: bridgeNames.length > 0 ? 'MicroverseBridges' : 'table',\n description: 'Host bridges allowed for this instance (not global in the slot).',\n },\n {\n name: 'init',\n luaType: 'fun(self: Component)',\n description: 'Called once after mount and initial props are applied.',\n },\n {\n name: 'onPropsChanged',\n luaType: 'fun(self: Component, key: string, newValue: any)',\n description: 'Called when the host patches a property key.',\n },\n {\n name: 'onDestroy',\n luaType: 'fun(self: Component)',\n description: 'Called before the script instance slot is disposed.',\n },\n ];\n if (componentHooks !== undefined) {\n lifecycleFields.push(...buildComponentEventManifestFields(eventKinds, componentHooks));\n }\n classes.push({\n name: 'Component',\n description:\n 'Component instance from `local C = component:extend()`. Use `self.bridges` for host APIs; define `on*` methods for domain events.',\n fields: lifecycleFields,\n emitSingleton: false,\n });\n classes.push({\n name: 'component',\n description: 'Per-slot helper injected by the host. Use `component:extend()` to create the active component.',\n methods: [\n {\n name: 'extend',\n description: 'Returns the component table with `properties`, `state`, and `bridges` wired for this slot.',\n params: [],\n returns: 'Component',\n },\n ],\n });\n}\n\nexport function buildLuaDefManifestFromHostSurfaceSpec(\n spec: HostSurfaceSpec,\n opts: {\n readonly output: string;\n readonly headerNote?: string | undefined;\n readonly luaTypeAliases?: Readonly<Record<string, string>> | undefined;\n },\n componentHooks?: HostComponentHooksSpec,\n): LuaDefManifest {\n const classes: ManifestClass[] = [];\n const bridgeNames = Object.keys(spec).sort((a, b) => a.localeCompare(b));\n for (const bridgeName of bridgeNames) {\n const methods = spec[bridgeName]!;\n const manifestMethods: ManifestMethod[] = [];\n for (const methodName of Object.keys(methods)) {\n const entry = methods[methodName]!;\n const resultLua = entry.lua?.returns ?? zodToLuaTypeRef(entry.output);\n if (entry.async === true) {\n const handleName = asyncHandleClassName(bridgeName, methodName);\n const payloadParams = zodInputToManifestParams(entry.input, entry.lua?.paramTypes) ?? [];\n manifestMethods.push({\n name: methodName,\n description: entry.description,\n callStyle: 'asyncBridge',\n params: [\n ...payloadParams,\n { name: 'onComplete', luaType: `fun(result: ${resultLua})|nil` },\n ],\n returns: handleName,\n });\n classes.push({\n name: handleName,\n description: `Async handle for \\`${bridgeName}:${methodName}\\`. Call \\`:await()\\` for the resolved value.`,\n fields: [{ name: 'await', luaType: `fun(self: ${handleName}): ${resultLua}` }],\n emitSingleton: false,\n });\n } else {\n manifestMethods.push({\n name: methodName,\n description: entry.description,\n params: zodInputToManifestParams(entry.input, entry.lua?.paramTypes),\n returns: resultLua,\n });\n }\n }\n classes.push({\n name: bridgeLuaClassName(bridgeName),\n methods: manifestMethods,\n emitSingleton: false,\n });\n }\n pushMicroverseBridgesClass(bridgeNames, classes);\n const fromLuaType = collectLuaTypeAliasesFromHostSpec(spec);\n const fromOverrides = inferLuaTypeAliasesFromHostSpec(spec);\n const merged = new Map<string, string>([\n ...fromLuaType.map((a) => [a.name, a.definition] as const),\n ...fromOverrides.map((a) => [a.name, a.definition] as const),\n ]);\n if (opts.luaTypeAliases !== undefined) {\n for (const [k, v] of Object.entries(opts.luaTypeAliases)) {\n merged.set(k, v);\n }\n }\n\n pushComponentManifestClasses(classes, bridgeNames, componentHooks);\n\n const aliases =\n merged.size === 0\n ? undefined\n : [...merged.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([name, definition]) => ({ name, definition }));\n\n return {\n schemaVersion: 1,\n output: opts.output,\n headerNote: opts.headerNote,\n aliases,\n classes,\n };\n}\n\nfunction nominalTokensFromLuaReturnString(retLua: string): readonly string[] {\n const out: string[] = [];\n const seen = new Set<string>();\n for (const segment of retLua.split('|')) {\n const s = segment.trim();\n if (!/^[A-Za-z_]\\w*$/.test(s)) {\n continue;\n }\n if (isLuaTypeAtom(s)) {\n continue;\n }\n if (seen.has(s)) {\n continue;\n }\n seen.add(s);\n out.push(s);\n }\n return out;\n}\n\nfunction unwrapOutputBaseForAlias(schema: z.ZodTypeAny): z.ZodTypeAny {\n /* eslint-disable @typescript-eslint/no-unsafe-assignment -- Zod internal unwrap chain */\n let cur: z.ZodTypeAny = schema;\n for (;;) {\n if (cur instanceof z.ZodOptional || cur instanceof z.ZodNullable) {\n cur = cur.unwrap();\n continue;\n }\n if (cur instanceof z.ZodDefault) {\n cur = cur.removeDefault();\n continue;\n }\n if (cur instanceof z.ZodReadonly) {\n cur = cur.unwrap();\n continue;\n }\n if (cur instanceof z.ZodEffects) {\n cur = cur.innerType();\n continue;\n }\n if (cur instanceof z.ZodPipeline) {\n cur = cur._def.out as z.ZodTypeAny;\n continue;\n }\n break;\n }\n /* eslint-enable @typescript-eslint/no-unsafe-assignment */\n return cur;\n}\n\nfunction collectLuaTypeAliasesFromHostSpec(spec: HostSurfaceSpec): readonly ManifestAlias[] {\n const byName = new Map<string, string>();\n const seenRoots = new Set<z.ZodTypeAny>();\n\n const consider = (schema: z.ZodTypeAny): void => {\n const root = getLuaTypeRegistrationRoot(schema);\n if (root === undefined || seenRoots.has(root)) {\n return;\n }\n const name = getRegisteredLuaTypeName(root);\n if (name === undefined) {\n return;\n }\n seenRoots.add(root);\n const definition = zodToLuaTypeRef(root, { emitAliasNames: false });\n if (definition !== name) {\n byName.set(name, definition);\n }\n };\n\n const walk = (schema: z.ZodTypeAny): void => {\n consider(schema);\n const base = unwrapInputSchema(schema);\n if (base instanceof z.ZodObject) {\n const shape = base.shape as Record<string, z.ZodTypeAny>;\n for (const field of Object.values(shape)) {\n consider(field);\n }\n }\n };\n\n for (const bridgeName of Object.keys(spec)) {\n const methods = spec[bridgeName]!;\n for (const methodName of Object.keys(methods)) {\n const entry = methods[methodName]!;\n walk(entry.input);\n walk(entry.output);\n }\n }\n\n return [...byName.entries()]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([name, definition]) => ({ name, definition }));\n}\n\nfunction inferLuaTypeAliasesFromHostSpec(spec: HostSurfaceSpec): readonly ManifestAlias[] {\n const byName = new Map<string, string>();\n\n for (const bridgeName of Object.keys(spec)) {\n const methods = spec[bridgeName]!;\n for (const methodName of Object.keys(methods)) {\n const entry = methods[methodName]!;\n\n const luaParams = entry.lua?.paramTypes;\n if (luaParams !== undefined) {\n const baseInput = unwrapInputSchema(entry.input);\n if (baseInput instanceof z.ZodObject) {\n const shape = baseInput.shape as Record<string, z.ZodTypeAny>;\n for (const [key, L] of Object.entries(luaParams)) {\n if (typeof L !== 'string') {\n continue;\n }\n if (!/^[A-Za-z_]\\w*$/.test(L) || isLuaTypeAtom(L)) {\n continue;\n }\n const field = shape[key];\n if (field === undefined) {\n continue;\n }\n const def = zodToLuaTypeRef(field);\n if (L !== def) {\n byName.set(L, def);\n }\n }\n }\n }\n\n const retLua = entry.lua?.returns;\n if (typeof retLua === 'string' && retLua.length > 0) {\n for (const T of nominalTokensFromLuaReturnString(retLua)) {\n const baseOut = unwrapOutputBaseForAlias(entry.output);\n const def = zodToLuaTypeRef(baseOut);\n if (T !== def) {\n byName.set(T, def);\n }\n }\n }\n }\n }\n\n return [...byName.entries()]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([name, definition]) => ({ name, definition }));\n}\n\nfunction zodInputToManifestParams(\n input: z.ZodTypeAny,\n luaParamTypes: Partial<Record<string, string>> | undefined,\n): ManifestParam[] | undefined {\n const base = unwrapInputSchema(input);\n if (base instanceof z.ZodObject) {\n const shape = base.shape as Record<string, z.ZodTypeAny>;\n return Object.keys(shape).map((name) => ({\n name,\n luaType: luaParamTypes?.[name] ?? zodToLuaTypeRef(shape[name]!),\n }));\n }\n return [{ name: 'value', luaType: luaParamTypes?.value ?? zodToLuaTypeRef(base) }];\n}\n\nfunction unwrapInputSchema(schema: z.ZodTypeAny): z.ZodTypeAny {\n let cur: z.ZodTypeAny = schema;\n if (cur instanceof z.ZodEffects) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- ZodEffects.innerType()\n cur = cur.innerType();\n }\n if (cur instanceof z.ZodPipeline) {\n cur = cur._def.in as z.ZodTypeAny;\n }\n return cur;\n}\n","import type { CapabilityId } from '@microverse.ts/runtime-capabilities';\n\nimport type { AnyHostSurfaceMethod, HostSurfaceMethodEntry, HostSurfaceSpec } from './hostSurfaceTypes';\n\ntype InferMethodCapability<M> = M extends { readonly capability: infer C extends CapabilityId }\n ? C\n : never;\n\ntype InferBridgeCapabilities<B> = B extends Readonly<Record<string, unknown>>\n ? InferMethodCapability<B[keyof B]>\n : never;\n\n/**\n * Union of every {@link CapabilityId} declared on methods in a {@link HostSurfaceSpec}\n * (via `requires: 'domain:action'` on each fluent `.method(…)` entry).\n */\nexport type InferSurfaceCapabilities<TSpec extends HostSurfaceSpec> = InferBridgeCapabilities<\n TSpec[keyof TSpec]\n>;\n\n/** Runtime list of capability ids declared on a compiled surface spec. */\nexport function collectCapabilitiesFromHostSurfaceSpec<const TSpec extends HostSurfaceSpec>(\n spec: TSpec,\n): readonly InferSurfaceCapabilities<TSpec>[] {\n const out: CapabilityId[] = [];\n const seen = new Set<string>();\n for (const bridgeName of Object.keys(spec)) {\n const methods = spec[bridgeName]!;\n for (const methodName of Object.keys(methods)) {\n const entry = methods[methodName]! as AnyHostSurfaceMethod;\n const id: CapabilityId = entry.capability;\n const key = String(id);\n if (!seen.has(key)) {\n seen.add(key);\n out.push(id);\n }\n }\n }\n return out as unknown as readonly InferSurfaceCapabilities<TSpec>[];\n}\n\n/** Narrows `capabilities` to those declared on the surface (runtime check). */\nexport function pickSurfaceCapabilities<\n const TSurface extends readonly CapabilityId[],\n const T extends readonly `${string}:${string}`[],\n>(\n surfaceCapabilities: TSurface,\n ...capabilities: T\n): ReadonlyArray<Extract<TSurface[number], CapabilityId>> {\n const allowed = new Set(surfaceCapabilities.map((c) => String(c)));\n for (const id of capabilities) {\n if (!allowed.has(String(id))) {\n throw new Error(\n `capability not declared on host surface: ${String(id)} (surface has: ${[...allowed].join(', ')})`,\n );\n }\n }\n return capabilities as unknown as ReadonlyArray<Extract<TSurface[number], CapabilityId>>;\n}\n\n/** Helper type for method entries that preserve a specific capability literal. */\nexport type SurfaceCapabilityEntry<TCap extends CapabilityId> = HostSurfaceMethodEntry<\n unknown,\n unknown,\n unknown\n> & { readonly capability: TCap };\n","import type { CapabilityRegistryPort } from '@microverse.ts/runtime-capabilities';\n\n/**\n * Well-known symbol key used to attach a {@link CapabilityRegistryPort} on the host object\n * while surface bridge methods run. Populated by {@link augmentHostWithCapabilityRegistry} or\n * internally by {@link HostScriptSession}.\n */\nexport const MICROVERSE_CAPABILITY_REGISTRY = Symbol.for('microverse:capabilityRegistry');\n\n/**\n * Host object extended with the capability registry required by host-surface bridge wrappers.\n */\nexport type WithMicroverseCapabilityRegistry = {\n readonly [MICROVERSE_CAPABILITY_REGISTRY]: CapabilityRegistryPort;\n};\n","import type { ScriptInstanceContext } from '@microverse.ts/runtime-core';\n\nexport const MICROVERSE_SCRIPT_CONTEXT = Symbol('microverse.scriptContext');\n\nexport type WithMicroverseScriptContext = {\n readonly [MICROVERSE_SCRIPT_CONTEXT]?: ScriptInstanceContext | undefined;\n};\n","import { type DeclarativeBridgeDeclaration } from '@microverse.ts/runtime-bridge';\nimport type { z } from 'zod';\n\nimport { MICROVERSE_CAPABILITY_REGISTRY, type WithMicroverseCapabilityRegistry } from '../../domain/capabilityRegistrySymbol';\nimport { createScriptInstanceContext } from '@microverse.ts/runtime-core';\n\nimport { MICROVERSE_SCRIPT_CONTEXT, type WithMicroverseScriptContext } from '../../domain/scriptContextSymbol';\nimport type { CapabilityId } from '@microverse.ts/runtime-capabilities';\n\nimport type { AnyHostSurfaceMethod, HostSurfaceSpec } from '../../domain/hostSurfaceTypes';\nimport type { SchemaValidationPort } from '../ports/SchemaValidationPort';\n\nfunction isThenable(value: unknown): value is Promise<unknown> {\n if (value === null || value === undefined) {\n return false;\n }\n if (typeof value !== 'object' && typeof value !== 'function') {\n return false;\n }\n const then = (value as { then?: unknown }).then;\n return typeof then === 'function';\n}\n\n/**\n * Builds declarative bridge declarations from a host surface spec, using the schema validation port for Lua ↔ host payloads.\n */\nexport function createBridgeDeclarationsFromHostSurfaceSpec<TSpec extends HostSurfaceSpec>(\n schemaValidation: SchemaValidationPort,\n spec: TSpec,\n): ReadonlyArray<DeclarativeBridgeDeclaration<WithMicroverseCapabilityRegistry, string>> {\n const out: DeclarativeBridgeDeclaration<WithMicroverseCapabilityRegistry, string>[] = [];\n for (const bridgeName of Object.keys(spec)) {\n const methods = spec[bridgeName]!;\n out.push({\n name: bridgeName,\n perEntity: true,\n createApi: (host, slotKey) => {\n const hostWithScript = host as WithMicroverseCapabilityRegistry & WithMicroverseScriptContext;\n const api: Record<string, (payload: unknown) => unknown> = {};\n for (const methodName of Object.keys(methods)) {\n const entry = methods[methodName]! as AnyHostSurfaceMethod;\n api[methodName] = (...args: unknown[]) => {\n const payload = args.length >= 2 ? args[1] : args[0];\n const registry = hostWithScript[MICROVERSE_CAPABILITY_REGISTRY];\n const capability: CapabilityId = entry.capability;\n if (!registry.isAllowed(capability)) {\n throw new Error(`capability denied: ${String(capability)}`);\n }\n const parsedIn = schemaValidation.validateWithZodSchema(entry.input as z.ZodType<unknown>, payload);\n if (parsedIn._tag === 'err') {\n throw new Error(parsedIn.error);\n }\n const script =\n hostWithScript[MICROVERSE_SCRIPT_CONTEXT] ??\n createScriptInstanceContext({\n instanceId: String(slotKey),\n scriptId: 'unknown',\n slotKey: String(slotKey),\n });\n const raw: unknown = entry.handler(\n { host: hostWithScript as never, slotKey: String(slotKey), script },\n parsedIn.value,\n );\n if (isThenable(raw)) {\n return raw.then((resolved) => {\n const parsedOut = schemaValidation.validateWithZodSchema(\n entry.output as z.ZodType<unknown>,\n resolved,\n );\n if (parsedOut._tag === 'err') {\n throw new Error(parsedOut.error);\n }\n return parsedOut.value;\n });\n }\n const parsedOut = schemaValidation.validateWithZodSchema(entry.output as z.ZodType<unknown>, raw);\n if (parsedOut._tag === 'err') {\n throw new Error(parsedOut.error);\n }\n return parsedOut.value;\n };\n }\n return Object.freeze(api);\n },\n });\n }\n return out;\n}\n","import { buildLuaDefManifestFromHostSurfaceSpec } from '../../domain/hostSurfaceManifest';\nimport {\n collectCapabilitiesFromHostSurfaceSpec,\n pickSurfaceCapabilities,\n type InferSurfaceCapabilities,\n} from '../../domain/surfaceCapabilities';\nimport type {\n HostSurface,\n HostSurfaceCore,\n HostSurfaceSpec,\n HostComponentHooksSpec,\n} from '../../domain/hostSurfaceTypes';\nimport type { SchemaValidationPort } from '../ports/SchemaValidationPort';\nimport { createBridgeDeclarationsFromHostSurfaceSpec } from './compileBridgeDeclarationsFromHostSurfaceSpec';\n\nfunction buildHostSurfaceCore<const TSpec extends HostSurfaceSpec>(\n schemaValidation: SchemaValidationPort,\n spec: TSpec,\n componentHooks?: HostComponentHooksSpec,\n): HostSurfaceCore<InferSurfaceCapabilities<TSpec>> {\n const capabilities = collectCapabilitiesFromHostSurfaceSpec(spec);\n return {\n toBridgeDeclarations: () => createBridgeDeclarationsFromHostSurfaceSpec(schemaValidation, spec),\n toLuaDefManifest: (opts) => buildLuaDefManifestFromHostSurfaceSpec(spec, opts, componentHooks),\n capabilities,\n pickCapabilities: (...picked) =>\n pickSurfaceCapabilities(capabilities, ...picked) as ReadonlyArray<\n Extract<(typeof picked)[number], InferSurfaceCapabilities<TSpec>>\n >,\n };\n}\n\n/**\n * Compiles a host surface using the injected schema validation port (tuple matches `UseCase` conventions in `@microverse.ts/shared`).\n */\nexport function compileHostSurface<const TSpec extends HostSurfaceSpec>(\n ports: readonly [SchemaValidationPort],\n spec: TSpec,\n): HostSurface<undefined, InferSurfaceCapabilities<TSpec>>;\nexport function compileHostSurface<\n const TSpec extends HostSurfaceSpec,\n const THooks extends HostComponentHooksSpec,\n>(\n ports: readonly [SchemaValidationPort],\n spec: TSpec,\n componentHooks: THooks,\n): HostSurface<THooks, InferSurfaceCapabilities<TSpec>>;\nexport function compileHostSurface<const TSpec extends HostSurfaceSpec>(\n ports: readonly [SchemaValidationPort],\n spec: TSpec,\n componentHooks?: HostComponentHooksSpec,\n): HostSurface<undefined, InferSurfaceCapabilities<TSpec>> | HostSurface<HostComponentHooksSpec, InferSurfaceCapabilities<TSpec>> {\n const [schemaValidation] = ports;\n const core = buildHostSurfaceCore(schemaValidation, spec, componentHooks);\n if (componentHooks === undefined) {\n return core;\n }\n return { ...core, componentHooks };\n}\n\n/**\n * Same as {@link compileHostSurface}, but requires every bridge method to be typed with the same `THost`.\n */\nexport function compileHostSurfaceFor<\n const TSpec extends HostSurfaceSpec,\n const THooks extends HostComponentHooksSpec | undefined = undefined,\n>(\n ports: readonly [SchemaValidationPort],\n spec: TSpec,\n componentHooks?: THooks,\n): THooks extends HostComponentHooksSpec\n ? HostSurface<THooks, InferSurfaceCapabilities<TSpec>>\n : HostSurface<undefined, InferSurfaceCapabilities<TSpec>> {\n return (\n componentHooks === undefined\n ? compileHostSurface(ports, spec)\n : compileHostSurface(ports, spec, componentHooks)\n ) as THooks extends HostComponentHooksSpec\n ? HostSurface<THooks, InferSurfaceCapabilities<TSpec>>\n : HostSurface<undefined, InferSurfaceCapabilities<TSpec>>;\n}\n","/** Infers {@link HostSurfaceMethodEntry.async} from handler shape unless overridden explicitly. */\nexport function inferMethodAsync(def: {\n readonly handler: { constructor: { readonly name: string } };\n readonly async?: boolean | undefined;\n}): boolean {\n if (def.async === true) {\n return true;\n }\n if (def.async === false) {\n return false;\n }\n return def.handler.constructor.name === 'AsyncFunction';\n}\n","import { createCapabilityId, type CapabilityId } from '@microverse.ts/runtime-capabilities';\nimport type { z } from 'zod';\n\nimport { inferMethodAsync } from './inferMethodAsync';\nimport type { HostFnContext, HostSurfaceMethodEntry } from './hostSurfaceTypes';\n\n/**\n * Consumer-facing method definition for the fluent {@link SurfaceBuilder} API.\n * Use `requires: 'domain:action'` for the capability id.\n */\nexport type SurfaceMethodDef<\n THost,\n TIn,\n TOut,\n TCap extends `${string}:${string}` = `${string}:${string}`,\n> = {\n /** Capability id required to invoke this method (`domain:action`). */\n readonly requires: TCap;\n readonly input: z.ZodType<TIn>;\n readonly output: z.ZodType<TOut>;\n readonly handler: (ctx: HostFnContext<THost>, input: TIn) => TOut | Promise<TOut>;\n readonly async?: boolean | undefined;\n readonly description?: string | undefined;\n readonly lua?: {\n readonly paramTypes?: Partial<Record<string, string>> | undefined;\n readonly returns?: string | undefined;\n };\n};\n\n/**\n * Converts a {@link SurfaceMethodDef} into a compiled {@link HostSurfaceMethodEntry}.\n */\nexport function normalizeMethodDef<\n THost,\n TIn,\n TOut,\n const TCap extends `${string}:${string}`,\n>(\n def: SurfaceMethodDef<THost, TIn, TOut, TCap>,\n): HostSurfaceMethodEntry<THost, TIn, TOut, CapabilityId & TCap> {\n const entry = {\n capability: createCapabilityId(def.requires) as CapabilityId & TCap,\n input: def.input,\n output: def.output,\n handler: def.handler,\n async: inferMethodAsync(def),\n ...(def.description !== undefined ? { description: def.description } : {}),\n ...(def.lua !== undefined ? { lua: def.lua } : {}),\n } satisfies HostSurfaceMethodEntry<THost, TIn, TOut, CapabilityId & TCap>;\n return entry;\n}\n","/** Keys that must not be used as dynamic property names on ordinary objects. */\nconst FORBIDDEN_OBJECT_KEYS = new Set(['__proto__', 'constructor', 'prototype']);\n\n/**\n * Rejects bridge/method names that could trigger prototype pollution when used as object keys.\n */\nexport function assertSafeObjectKey(kind: 'bridge' | 'method', name: string): void {\n if (FORBIDDEN_OBJECT_KEYS.has(name)) {\n throw new Error(`Invalid surface ${kind} name \"${name}\": reserved key`);\n }\n}\n\n/** Record with no inherited prototype — safe for dynamic string keys at runtime. */\nexport function createNullPrototypeRecord<T extends object>(): T {\n return Object.create(null) as T;\n}\n","import { compileHostSurfaceFor } from '../../application/useCases/compileHostSurface';\nimport type { SchemaValidationPort } from '../../application/ports/SchemaValidationPort';\nimport type { InferSurfaceCapabilities } from '../../domain/surfaceCapabilities';\nimport { normalizeMethodDef, type SurfaceMethodDef } from '../../domain/surfaceMethodDef';\nimport { assertSafeObjectKey, createNullPrototypeRecord } from '../../domain/safeObjectKey';\nimport type {\n AnyHostSurfaceMethod,\n HostSurface,\n HostSurfaceSpec,\n HostComponentHooksSpec,\n} from '../../domain/hostSurfaceTypes';\n\ntype MutableHostSurfaceSpec = Record<string, Record<string, AnyHostSurfaceMethod>>;\n\n/**\n * Fluent builder for a host surface. Created via {@link defineHostSurfaceFor} / {@link defineHostSurface} factory overloads.\n */\nexport class SurfaceBuilder<\n THost,\n const THooks extends HostComponentHooksSpec | undefined = undefined,\n> {\n private readonly spec: MutableHostSurfaceSpec = createNullPrototypeRecord();\n\n private componentHooksSpec: THooks;\n\n private readonly ports: readonly [SchemaValidationPort];\n\n constructor(\n ports: readonly [SchemaValidationPort],\n componentHooks?: THooks,\n initialSpec?: MutableHostSurfaceSpec,\n ) {\n this.ports = ports;\n this.componentHooksSpec = componentHooks as THooks;\n if (initialSpec !== undefined) {\n for (const bridgeName of Object.keys(initialSpec)) {\n assertSafeObjectKey('bridge', bridgeName);\n const srcBridge = initialSpec[bridgeName]!;\n const bridge = createNullPrototypeRecord<Record<string, AnyHostSurfaceMethod>>();\n for (const methodName of Object.keys(srcBridge)) {\n assertSafeObjectKey('method', methodName);\n bridge[methodName] = srcBridge[methodName]!;\n }\n this.spec[bridgeName] = bridge;\n }\n }\n }\n\n /** Opens a Lua bridge table (e.g. `orders`, `greet`). */\n bridge<const B extends string>(name: B): BridgeBuilder<THost, B, THooks> {\n return new BridgeBuilder(this, name);\n }\n\n /** Attaches component domain-event Zod schemas (emitted into `.d.lua` as `on*` methods on `Component`). */\n componentHooks<const H extends HostComponentHooksSpec>(hooks: H): SurfaceBuilder<THost, H> {\n return new SurfaceBuilder<THost, H>(this.ports, hooks, this.spec);\n }\n\n /** Compiles the accumulated spec into a {@link HostSurface}. */\n build(): THooks extends HostComponentHooksSpec\n ? HostSurface<THooks, InferSurfaceCapabilities<HostSurfaceSpec>>\n : HostSurface<undefined, InferSurfaceCapabilities<HostSurfaceSpec>> {\n const spec = this.spec as HostSurfaceSpec;\n return compileHostSurfaceFor(this.ports, spec, this.componentHooksSpec);\n }\n\n /** @internal */\n addMethod<const B extends string, const M extends string>(\n bridgeName: B,\n methodName: M,\n entry: AnyHostSurfaceMethod,\n ): SurfaceBuilder<THost, THooks> {\n assertSafeObjectKey('bridge', bridgeName);\n assertSafeObjectKey('method', methodName);\n let bridge = this.spec[bridgeName];\n if (bridge === undefined) {\n bridge = createNullPrototypeRecord<Record<string, AnyHostSurfaceMethod>>();\n this.spec[bridgeName] = bridge;\n }\n bridge[methodName] = entry;\n return this;\n }\n}\n\n/**\n * Per-bridge step in the fluent surface DSL. Return to {@link SurfaceBuilder} via `.method(…)`.\n */\nexport class BridgeBuilder<\n THost,\n const B extends string,\n THooks extends HostComponentHooksSpec | undefined,\n> {\n constructor(\n private readonly parent: SurfaceBuilder<THost, THooks>,\n private readonly bridgeName: B,\n ) {}\n\n /** Registers one method on the current bridge and returns the root builder for chaining. */\n method<const M extends string, TIn, TOut, TCap extends `${string}:${string}`>(\n name: M,\n def: SurfaceMethodDef<THost, TIn, TOut, TCap>,\n ): SurfaceBuilder<THost, THooks> {\n return this.parent.addMethod(this.bridgeName, name, normalizeMethodDef(def));\n }\n}\n","import type { SchemaValidationPort } from '../../application/ports/SchemaValidationPort';\n\nimport { createZodSchemaValidationPort } from '../adapters/zodSchemaValidationAdapter';\nimport { SurfaceBuilder } from './surfaceBuilder';\n\nconst defaultPorts: readonly [SchemaValidationPort] = [createZodSchemaValidationPort()];\n\nexport type { InferSurfaceCapabilities } from '../../domain/surfaceCapabilities';\nexport type { SurfaceMethodDef } from '../../domain/surfaceMethodDef';\nexport { BridgeBuilder, SurfaceBuilder } from './surfaceBuilder';\n\nexport type {\n AnyHostSurfaceMethod,\n HostFnContext,\n HostSurface,\n HostSurfaceCore,\n HostSurfaceMethodEntry,\n HostSurfaceSpec,\n HostSurfaceSpecForHost,\n HostComponentHooksSpec,\n LuaDefManifestGeneratorOpts,\n} from '../../domain/hostSurfaceTypes';\n\nfunction createSurfaceBuilder<THost>(): SurfaceBuilder<THost> {\n return new SurfaceBuilder<THost>(defaultPorts);\n}\n\n/**\n * Declares a **host surface** via the fluent builder (`bridge` → `method` → `build`).\n *\n * @example\n * ```ts\n * const surface = defineHostSurface()\n * .bridge('time')\n * .method('delta', {\n * requires: 'engine:time',\n * input: z.object({}),\n * output: z.number(),\n * handler: ({ host }) => host.clock.dt,\n * })\n * .build();\n * ```\n */\nexport function defineHostSurface(): SurfaceBuilder<unknown> {\n return createSurfaceBuilder();\n}\n\n/**\n * Same as {@link defineHostSurface}, but every `handler` is typed against a single `THost`\n * (the engine context passed to {@link HostScriptSession} / {@link MicroverseLua.create}).\n *\n * @example\n * ```ts\n * const surface = defineHostSurfaceFor<MyHost>()\n * .bridge('greet')\n * .method('hello', {\n * requires: 'demo:greet',\n * input: z.object({ name: z.string() }),\n * output: z.string(),\n * handler: ({ host }, { name }) => `Hello, ${name}`,\n * })\n * .build();\n * ```\n */\nexport function defineHostSurfaceFor<THost>(): SurfaceBuilder<THost> {\n return createSurfaceBuilder<THost>();\n}\n","/** @see MICROVERSE_LUA_COMPONENT_SLOT_PRELUDE */\nexport const MICROVERSE_LUA_COMPONENT_SLOT_PRELUDE = `\nrawset(_ENV, \"__microverse_component_rawProps\", {})\nrawset(_ENV, \"__microverse_component_dirty\", {})\n\nlocal function rawProps()\n return rawget(_ENV, \"__microverse_component_rawProps\")\nend\n\nlocal function dirty()\n return rawget(_ENV, \"__microverse_component_dirty\")\nend\n\nlocal PropertiesMT = {\n __index = function(t, k)\n return rawget(t, \"__raw\")[k]\n end,\n __newindex = function(t, k, v)\n rawget(t, \"__raw\")[k] = v\n local d = dirty()\n d[k] = v\n end,\n}\n\nfunction __microverse_lua_attach_bridges(impl)\n if type(impl) ~= \"table\" then\n return\n end\n impl.bridges = impl.bridges or {}\n local names = rawget(_ENV, \"__microverse_bridge_names\")\n if type(names) ~= \"table\" then\n return\n end\n for _, name in ipairs(names) do\n if type(name) == \"string\" then\n local g = rawget(_ENV, name)\n if type(g) == \"table\" then\n impl.bridges[name] = g\n rawset(_ENV, name, nil)\n end\n end\n end\nend\n\nrawset(_ENV, \"__microverse_lua_attach_bridges\", __microverse_lua_attach_bridges)\n\nrawset(_ENV, \"component\", {\n extend = function()\n local impl = { state = {}, bridges = {} }\n local proxy = { __raw = rawProps() }\n setmetatable(proxy, PropertiesMT)\n impl.properties = proxy\n local base = rawget(_ENV, \"__microverse_component_hook_base\")\n if type(base) == \"table\" then\n setmetatable(impl, { __index = base })\n end\n __microverse_lua_attach_bridges(impl)\n rawset(_ENV, \"__microverse_lua_ComponentImpl\", impl)\n return impl\n end,\n})\n\nrawset(_ENV, \"__microverse_lua_component_apply_incoming\", function()\n local incoming = rawget(_ENV, \"__microverseIncomingProps\")\n if type(incoming) ~= \"table\" then\n return\n end\n local rp = rawProps()\n local impl = rawget(_ENV, \"__microverse_lua_ComponentImpl\")\n if type(impl) ~= \"table\" or type(impl.properties) ~= \"table\" then\n for k, v in pairs(incoming) do\n rp[k] = v\n end\n return\n end\n for k, v in pairs(incoming) do\n impl.properties[k] = v\n end\nend)\n\nrawset(_ENV, \"__microverse_lua_component_flush_to_sink\", function()\n local push = rawget(_ENV, \"__microverseFlushPush\")\n local d = dirty()\n for k, v in pairs(d) do\n if type(push) == \"function\" then\n push(k, v)\n end\n d[k] = nil\n end\nend)\n`.trim();\n","import type { ScriptPropertyBag, ScriptPropertyValue } from '@microverse.ts/runtime-core';\n\nexport function scriptPropertyBagToMergeEnv(bag: ScriptPropertyBag): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(bag)) {\n out[k] = scriptPropertyValueToPlain(v);\n }\n return out;\n}\n\nexport function scriptPropertyValueToPlain(value: ScriptPropertyValue): unknown {\n if (value === null || typeof value !== 'object') {\n return value;\n }\n if (Array.isArray(value)) {\n const items = value as readonly ScriptPropertyValue[];\n return items.map((item) => scriptPropertyValueToPlain(item));\n }\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n out[k] = scriptPropertyValueToPlain(v);\n }\n return out;\n}\n\nexport function mergeEnvSinkToScriptPropertyBag(\n sink: Record<string, unknown>,\n): ScriptPropertyBag {\n const out: Record<string, ScriptPropertyValue> = {};\n for (const [k, v] of Object.entries(sink)) {\n const converted = plainToScriptPropertyValue(v);\n if (converted !== undefined) {\n out[k] = converted;\n }\n }\n return out;\n}\n\nexport function plainToScriptPropertyValue(value: unknown): ScriptPropertyValue | undefined {\n if (value === null) {\n return null;\n }\n const t = typeof value;\n if (t === 'string' || t === 'boolean') {\n return value as string | boolean;\n }\n if (typeof value === 'number' && Number.isFinite(value)) {\n return value;\n }\n if (Array.isArray(value)) {\n const arr: ScriptPropertyValue[] = [];\n for (const item of value) {\n const c = plainToScriptPropertyValue(item);\n if (c !== undefined) {\n arr.push(c);\n }\n }\n return arr;\n }\n if (t === 'object' && value !== null) {\n const obj: Record<string, ScriptPropertyValue> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n const c = plainToScriptPropertyValue(v);\n if (c !== undefined) {\n obj[k] = c;\n }\n }\n return obj;\n }\n return undefined;\n}\n","import type { CapabilityRegistryPort } from '@microverse.ts/runtime-capabilities';\n\nimport { MICROVERSE_CAPABILITY_REGISTRY, type WithMicroverseCapabilityRegistry } from '../../domain/capabilityRegistrySymbol';\n\n/**\n * Returns a shallow copy of `host` with {@link MICROVERSE_CAPABILITY_REGISTRY} set to `registry`.\n * Bridge handlers read the registry to enforce per-session capability allowlists.\n *\n * @param host - Your engine / service context passed into `buildDeclarativeBridgeTable`.\n * @param registry - Typically an {@link InMemoryCapabilityRegistry} from `@microverse.ts/runtime-capabilities`.\n */\nexport function augmentHostWithCapabilityRegistry<THost>(\n host: THost,\n registry: CapabilityRegistryPort,\n): THost & WithMicroverseCapabilityRegistry {\n return Object.assign(host as object, {\n [MICROVERSE_CAPABILITY_REGISTRY]: registry,\n }) as THost & WithMicroverseCapabilityRegistry;\n}\n","import type { ScriptInstanceContext } from '@microverse.ts/runtime-core';\n\nimport { MICROVERSE_SCRIPT_CONTEXT, type WithMicroverseScriptContext } from '../../domain/scriptContextSymbol';\n\nexport function augmentHostWithScriptContext<THost>(\n host: THost,\n script: ScriptInstanceContext,\n): THost & WithMicroverseScriptContext {\n return Object.assign(host as object, {\n [MICROVERSE_SCRIPT_CONTEXT]: script,\n }) as THost & WithMicroverseScriptContext;\n}\n","import {\n createAllowlist,\n type CapabilityId,\n InMemoryCapabilityRegistry,\n} from '@microverse.ts/runtime-capabilities';\nimport type { Result } from '@microverse.ts/shared';\nimport type { z } from 'zod';\nimport {\n applyScriptPropertyChanges,\n assertValidScriptPropertyBag,\n cloneScriptPropertyBag,\n createMicroverseScript,\n diffScriptProperties,\n type ExecutionFailure,\n type MutableScriptPropertyBag,\n type RunScriptResult,\n type MicroverseSlot,\n type MicroverseId,\n type MicroverseRuntime,\n type ScriptAuditEvent,\n type ScriptInstanceContext,\n type ScriptPropertyBag,\n type ScriptPropertyValue,\n type TimeoutPolicy,\n} from '@microverse.ts/runtime-core';\n\nimport { MICROVERSE_LUA_COMPONENT_SLOT_PRELUDE } from '../../domain/componentSlotPrelude';\nimport {\n plainToScriptPropertyValue,\n scriptPropertyBagToMergeEnv,\n} from '../../domain/scriptPropertyMergeEnv';\nimport { augmentHostWithCapabilityRegistry } from '../adapters/augmentHostWithCapabilityRegistry';\nimport { augmentHostWithScriptContext } from '../adapters/augmentHostWithScriptContext';\nimport { bridgeNamesFromSurface, buildBridgeMergeEnvForHost } from '../builders/bridgeMergeEnv';\nimport type { HostSurface, HostComponentHooksSpec } from '../../domain/hostSurfaceTypes';\nimport type { LuaGlobalHookName } from '../../domain/luaGlobalHook';\nimport { luaGlobalHookName } from '../../domain/luaGlobalHook';\n\nexport type ComponentEventHookInvokeArgs<TH extends HostComponentHooksSpec> = {\n [K in keyof TH & string]: readonly [hook: LuaGlobalHookName<K>, payload: Readonly<z.infer<TH[K]>>];\n}[keyof TH & string];\n\ntype InvokeComponentEventHookFn<THooks extends HostComponentHooksSpec | undefined> = THooks extends HostComponentHooksSpec\n ? (...args: ComponentEventHookInvokeArgs<THooks>) => Promise<Result<RunScriptResult, ExecutionFailure>>\n : (\n hookName: string,\n payload: Readonly<Record<string, string | number | boolean>>,\n ) => Promise<Result<RunScriptResult, ExecutionFailure>>;\n\nexport type HostScriptSessionOptions<\n THost,\n THooks extends HostComponentHooksSpec | undefined = undefined,\n> = {\n readonly runtime: MicroverseRuntime;\n readonly surface: HostSurface<THooks>;\n readonly host: THost;\n readonly slotKey: MicroverseId;\n readonly allowedCapabilities: readonly CapabilityId[];\n readonly defaultTimeout?: TimeoutPolicy | undefined;\n readonly script: ScriptInstanceContext;\n readonly enableComponentRuntime?: boolean | undefined;\n readonly propsSchema?: z.ZodObject<z.ZodRawShape> | undefined;\n readonly onScriptAudit?: ((event: ScriptAuditEvent) => void) | undefined;\n};\n\nexport class HostScriptSession<\n THost,\n THooks extends HostComponentHooksSpec | undefined = undefined,\n> {\n private sandbox: MicroverseSlot | undefined;\n\n private readonly hostProps: MutableScriptPropertyBag = {};\n\n private readonly registry: InMemoryCapabilityRegistry;\n\n readonly context: ScriptInstanceContext;\n\n constructor(private readonly opts: HostScriptSessionOptions<THost, THooks>) {\n this.registry = new InMemoryCapabilityRegistry(createAllowlist([...opts.allowedCapabilities]));\n this.context = opts.script;\n }\n\n readonly openSession = async (): Promise<void> => {\n this.sandbox = await this.opts.runtime.createMicroverse({ slotKey: this.opts.slotKey });\n const sb = this.requireMicroverseSlot();\n if (this.opts.enableComponentRuntime !== false) {\n await sb.run({\n script: createMicroverseScript(MICROVERSE_LUA_COMPONENT_SLOT_PRELUDE),\n mergeEnv: this.mergeEnv(),\n timeout: this.opts.defaultTimeout,\n });\n await sb.run({\n script: createMicroverseScript(buildBridgeNamesPreludeLua(bridgeNamesFromSurface(this.opts.surface))),\n mergeEnv: this.mergeEnv(),\n timeout: this.opts.defaultTimeout,\n });\n const hooks = readComponentHooks(this.opts.surface);\n if (hooks !== undefined) {\n const prelude = buildComponentEventStubPreludeLua(hooks);\n await sb.run({\n script: createMicroverseScript(prelude),\n mergeEnv: this.mergeEnv(),\n timeout: this.opts.defaultTimeout,\n });\n }\n }\n };\n\n readonly getCapabilityRegistry = (): InMemoryCapabilityRegistry => this.registry;\n\n private requireMicroverseSlot(): MicroverseSlot {\n if (this.sandbox === undefined) {\n throw new Error('HostScriptSession: openSession() was not called');\n }\n return this.sandbox;\n }\n\n private mergeEnv() {\n const withCaps = augmentHostWithCapabilityRegistry(this.opts.host, this.registry);\n const host = augmentHostWithScriptContext(withCaps, this.opts.script);\n return buildBridgeMergeEnvForHost(host, String(this.opts.slotKey), this.opts.surface);\n }\n\n private emitAudit(event: ScriptAuditEvent): void {\n this.opts.onScriptAudit?.(event);\n }\n\n private validatePropsBag(bag: ScriptPropertyBag): ScriptPropertyBag {\n if (this.opts.propsSchema !== undefined) {\n const parsed = this.opts.propsSchema.parse(bag);\n assertValidScriptPropertyBag(parsed);\n return parsed;\n }\n assertValidScriptPropertyBag(bag);\n return bag;\n }\n\n readonly getProps = (): Readonly<ScriptPropertyBag> => ({ ...this.hostProps });\n\n readonly setProps = async (bag: ScriptPropertyBag): Promise<void> => {\n const next = this.validatePropsBag(bag);\n const changed = diffScriptProperties(this.hostProps, next);\n applyScriptPropertyChanges(this.hostProps, next, changed);\n const sb = this.requireMicroverseSlot();\n await sb.run({\n script: createMicroverseScript(\n 'local f = rawget(_ENV, \"__microverse_lua_component_apply_incoming\")\\nif type(f) == \"function\" then f() end',\n ),\n mergeEnv: {\n ...this.mergeEnv(),\n __microverseIncomingProps: scriptPropertyBagToMergeEnv(this.hostProps),\n },\n timeout: this.opts.defaultTimeout,\n });\n if (changed.length > 0) {\n this.emitAudit({ kind: 'propsPatched', context: this.opts.script, changedKeys: changed });\n for (const key of changed) {\n const value = next[key];\n if (value !== undefined) {\n await this.invokeComponentHook('onPropsChanged', key, value);\n }\n }\n }\n };\n\n readonly patchProps = async (partial: ScriptPropertyBag): Promise<void> => {\n await this.setProps({ ...this.hostProps, ...partial });\n };\n\n readonly flushDirtyProps = async (): Promise<ScriptPropertyBag | null> => {\n if (this.opts.enableComponentRuntime === false) {\n return null;\n }\n const collected: Record<string, ScriptPropertyValue> = {};\n const sb = this.requireMicroverseSlot();\n await sb.run({\n script: createMicroverseScript(\n 'local f = rawget(_ENV, \"__microverse_lua_component_flush_to_sink\")\\nif type(f) == \"function\" then f() end',\n ),\n mergeEnv: {\n ...this.mergeEnv(),\n __microverseFlushPush: (key: string, value: unknown) => {\n const converted = plainToScriptPropertyValue(value);\n if (converted !== undefined) {\n collected[key] = converted;\n }\n },\n },\n timeout: this.opts.defaultTimeout,\n });\n const keys = Object.keys(collected);\n if (keys.length === 0) {\n return null;\n }\n const dirty = collected;\n for (const key of keys) {\n this.hostProps[key] = dirty[key]!;\n }\n this.emitAudit({ kind: 'propsFlushed', context: this.opts.script, dirtyKeys: keys });\n return dirty;\n };\n\n readonly runChunk = async (source: string) => {\n const sb = this.requireMicroverseSlot();\n return sb.run({\n script: createMicroverseScript(source),\n mergeEnv: this.mergeEnv(),\n timeout: this.opts.defaultTimeout,\n });\n };\n\n readonly invokeComponentHook = async (\n hookName: string,\n ...args: (string | ScriptPropertyValue | Readonly<Record<string, string | number | boolean>>)[]\n ): Promise<Result<RunScriptResult, ExecutionFailure>> => {\n assertSafeLuaGlobalName(hookName);\n this.emitAudit({ kind: 'hookInvoked', context: this.opts.script, hookName });\n const sb = this.requireMicroverseSlot();\n const argLiterals = args.map((a) => {\n if (typeof a === 'object' && a !== null && !Array.isArray(a)) {\n return luaTableLiteralFromPlainRecord(a as Readonly<Record<string, string | number | boolean>>);\n }\n return luaValueLiteral(a as string | ScriptPropertyValue);\n }).join(', ');\n const src = [\n `local impl = rawget(_ENV, \"__microverse_lua_ComponentImpl\")`,\n `if type(impl) == \"table\" then`,\n ` local attach = rawget(_ENV, \"__microverse_lua_attach_bridges\")`,\n ` if type(attach) == \"function\" then attach(impl) end`,\n ` local m = rawget(impl, ${JSON.stringify(hookName)})`,\n ` if type(m) == \"function\" then`,\n argLiterals.length > 0 ? ` m(impl, ${argLiterals})` : ` m(impl)`,\n ` end`,\n `end`,\n ].join('\\n');\n return sb.run({\n script: createMicroverseScript(src),\n mergeEnv: this.mergeEnv(),\n timeout: this.opts.defaultTimeout,\n });\n };\n\n readonly invokeComponentEventHook = (async (\n hookName: string,\n payload: Readonly<Record<string, string | number | boolean>>,\n ) => {\n assertSafeLuaGlobalName(hookName);\n return this.invokeComponentHook(hookName, payload);\n }) as InvokeComponentEventHookFn<THooks>;\n\n readonly call = async (tableName: string, methodName: string, payload: Record<string, unknown>) => {\n const sb = this.requireMicroverseSlot();\n const tbl = luaTableLiteralFromUnknownRecord(payload);\n const src = [\n `local impl = rawget(_ENV, \"__microverse_lua_ComponentImpl\")`,\n `local bridges = type(impl) == \"table\" and impl.bridges or nil`,\n `local t = type(bridges) == \"table\" and bridges[${JSON.stringify(tableName)}] or nil`,\n `local f = type(t) == \"table\" and t[${JSON.stringify(methodName)}] or nil`,\n `if type(f) == \"function\" then`,\n ` f(${tbl})`,\n `end`,\n ].join('\\n');\n return sb.run({\n script: createMicroverseScript(src),\n mergeEnv: this.mergeEnv(),\n timeout: this.opts.defaultTimeout,\n });\n };\n\n readonly dispose = async (): Promise<void> => {\n if (this.sandbox !== undefined) {\n if (this.opts.enableComponentRuntime !== false) {\n await this.invokeComponentHook('onDestroy');\n }\n await this.sandbox.dispose();\n this.sandbox = undefined;\n }\n };\n\n /** Seeds host props bag without Lua sync (call before setProps after mount). */\n readonly seedHostProps = (bag: ScriptPropertyBag): void => {\n const cloned = cloneScriptPropertyBag(bag);\n for (const k of Object.keys(this.hostProps)) {\n delete this.hostProps[k];\n }\n Object.assign(this.hostProps, cloned);\n };\n}\n\nfunction assertSafeLuaGlobalName(name: string): void {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {\n throw new Error(`unsafe Lua global name: ${name}`);\n }\n}\n\nfunction readComponentHooks(\n surface: HostSurface<HostComponentHooksSpec | undefined>,\n): HostComponentHooksSpec | undefined {\n if (!('componentHooks' in surface)) {\n return undefined;\n }\n return (surface as HostSurface<HostComponentHooksSpec>).componentHooks;\n}\n\nfunction buildBridgeNamesPreludeLua(bridgeNames: readonly string[]): string {\n const entries = bridgeNames.map((n) => JSON.stringify(n)).join(', ');\n return `rawset(_ENV, \"__microverse_bridge_names\", { ${entries} })`;\n}\n\nfunction buildComponentEventStubPreludeLua(hooks: HostComponentHooksSpec): string {\n const hookNames = Object.keys(hooks)\n .sort((a, b) => a.localeCompare(b))\n .map((kind) => {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(kind)) {\n throw new Error(`unsafe component hook kind: ${kind}`);\n }\n return JSON.stringify(luaGlobalHookName(kind));\n });\n const lines: string[] = [\n 'local Base = {}',\n 'for _, name in ipairs({',\n ...hookNames.map((h) => ` ${h},`),\n '}) do',\n ' rawset(Base, name, function() end)',\n 'end',\n 'rawset(_ENV, \"__microverse_component_hook_base\", Base)',\n ];\n return lines.join('\\n');\n}\n\nfunction luaValueLiteral(value: string | ScriptPropertyValue): string {\n if (typeof value === 'string') {\n return JSON.stringify(value);\n }\n if (typeof value === 'number' && Number.isFinite(value)) {\n return String(value);\n }\n if (typeof value === 'boolean') {\n return value ? 'true' : 'false';\n }\n if (value === null) {\n return 'nil';\n }\n if (Array.isArray(value)) {\n const items = value as readonly ScriptPropertyValue[];\n const luaItems = items.map((v) => luaValueLiteral(v)).join(', ');\n return `{ ${luaItems} }`;\n }\n const record = value as { readonly [key: string]: ScriptPropertyValue };\n const parts: string[] = [];\n for (const k of Object.keys(record)) {\n parts.push(`${k} = ${luaValueLiteral(record[k]!)}`);\n }\n return `{ ${parts.join(', ')} }`;\n}\n\nfunction luaTableLiteralFromPlainRecord(o: Readonly<Record<string, string | number | boolean>>): string {\n const parts: string[] = [];\n for (const [k, v] of Object.entries(o)) {\n if (typeof v === 'string') {\n parts.push(`${k} = ${JSON.stringify(v)}`);\n } else if (typeof v === 'number' && Number.isFinite(v)) {\n parts.push(`${k} = ${v}`);\n } else if (typeof v === 'boolean') {\n parts.push(`${k} = ${v ? 'true' : 'false'}`);\n } else {\n throw new Error(`HostScriptSession: unsupported value type for key ${k}`);\n }\n }\n return `{ ${parts.join(', ')} }`;\n}\n\nfunction luaTableLiteralFromUnknownRecord(o: Record<string, unknown>): string {\n const parts: string[] = [];\n for (const [k, v] of Object.entries(o)) {\n if (typeof v === 'string') {\n parts.push(`${k} = ${JSON.stringify(v)}`);\n } else if (typeof v === 'number' && Number.isFinite(v)) {\n parts.push(`${k} = ${v}`);\n } else if (typeof v === 'boolean') {\n parts.push(`${k} = ${v ? 'true' : 'false'}`);\n } else {\n throw new Error(`HostScriptSession.call: unsupported value type for key ${k}`);\n }\n }\n return `{ ${parts.join(', ')} }`;\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,SAAgB,2BACd,MACA,SACA,SACmC;CACnC,OAAO,4BAA4B,MAAM,SAAS,CAAC,GAAG,QAAQ,qBAAqB,CAAC,CAAC;AACvF;;AAGA,SAAgB,uBAAuB,SAA6C;CAClF,OAAO,QAAQ,qBAAqB,EAAE,KAAK,MAAM,EAAE,IAAI;AACzD;;;ACpBA,SAAgB,gCAAsD;CACpE,OAAO,EAAE,sBAAsB;AACjC;;;;;;;;ACKA,SAAgB,kBAA6C,MAAqC;CAChG,IAAI,CAAC,2BAA2B,KAAK,IAAI,GACvC,MAAM,IAAI,MAAM,yCAAyC,MAAM;CAGjE,OAAO,KADW;AAEpB;;;;AChBA,IAAa,iBAAiB,IAAI,IAAI;CACpC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,SAAgB,cAAc,MAAuB;CACnD,OAAO,eAAe,IAAI,IAAI;AAChC;;;AChBA,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AK,MAAM,KAAK,IAAI,EAAE;AAC/B"}
@@ -1,5 +1,5 @@
1
1
  import { CapabilityRegistryPort } from '@microverse.ts/runtime-capabilities';
2
- import { WithMicroverseCapabilityRegistry } from '../../domain/capabilityRegistrySymbol.js';
2
+ import { WithMicroverseCapabilityRegistry } from '../../domain/capabilityRegistrySymbol';
3
3
  /**
4
4
  * Returns a shallow copy of `host` with {@link MICROVERSE_CAPABILITY_REGISTRY} set to `registry`.
5
5
  * Bridge handlers read the registry to enforce per-session capability allowlists.
@@ -1 +1 @@
1
- {"version":3,"file":"augmentHostWithCapabilityRegistry.d.ts","sourceRoot":"","sources":["../../../src/infrastructure/adapters/augmentHostWithCapabilityRegistry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AAElF,OAAO,EAAkC,KAAK,gCAAgC,EAAE,MAAM,0CAA0C,CAAC;AAEjI;;;;;;GAMG;AACH,wBAAgB,iCAAiC,CAAC,KAAK,EACrD,IAAI,EAAE,KAAK,EACX,QAAQ,EAAE,sBAAsB,GAC/B,KAAK,GAAG,gCAAgC,CAI1C"}
1
+ {"version":3,"file":"augmentHostWithCapabilityRegistry.d.ts","sourceRoot":"","sources":["../../../src/infrastructure/adapters/augmentHostWithCapabilityRegistry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AAElF,OAAO,EAAkC,KAAK,gCAAgC,EAAE,MAAM,uCAAuC,CAAC;AAE9H;;;;;;GAMG;AACH,wBAAgB,iCAAiC,CAAC,KAAK,EACrD,IAAI,EAAE,KAAK,EACX,QAAQ,EAAE,sBAAsB,GAC/B,KAAK,GAAG,gCAAgC,CAI1C"}
@@ -0,0 +1,4 @@
1
+ import { ScriptInstanceContext } from '@microverse.ts/runtime-core';
2
+ import { WithMicroverseScriptContext } from '../../domain/scriptContextSymbol';
3
+ export declare function augmentHostWithScriptContext<THost>(host: THost, script: ScriptInstanceContext): THost & WithMicroverseScriptContext;
4
+ //# sourceMappingURL=augmentHostWithScriptContext.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"augmentHostWithScriptContext.d.ts","sourceRoot":"","sources":["../../../src/infrastructure/adapters/augmentHostWithScriptContext.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AAEzE,OAAO,EAA6B,KAAK,2BAA2B,EAAE,MAAM,kCAAkC,CAAC;AAE/G,wBAAgB,4BAA4B,CAAC,KAAK,EAChD,IAAI,EAAE,KAAK,EACX,MAAM,EAAE,qBAAqB,GAC5B,KAAK,GAAG,2BAA2B,CAIrC"}
@@ -1,3 +1,3 @@
1
- import { SchemaValidationPort } from '../../application/ports/SchemaValidationPort.js';
1
+ import { SchemaValidationPort } from '../../application/ports/SchemaValidationPort';
2
2
  export declare function createZodSchemaValidationPort(): SchemaValidationPort;
3
3
  //# sourceMappingURL=zodSchemaValidationAdapter.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"zodSchemaValidationAdapter.d.ts","sourceRoot":"","sources":["../../../src/infrastructure/adapters/zodSchemaValidationAdapter.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,iDAAiD,CAAC;AAE5F,wBAAgB,6BAA6B,IAAI,oBAAoB,CAEpE"}
1
+ {"version":3,"file":"zodSchemaValidationAdapter.d.ts","sourceRoot":"","sources":["../../../src/infrastructure/adapters/zodSchemaValidationAdapter.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,8CAA8C,CAAC;AAEzF,wBAAgB,6BAA6B,IAAI,oBAAoB,CAEpE"}
@@ -1,5 +1,6 @@
1
- import { WithMicroverseCapabilityRegistry } from '../../domain/capabilityRegistrySymbol.js';
2
- import { HostSurfaceCore } from '../../domain/hostSurfaceTypes.js';
1
+ import { WithMicroverseCapabilityRegistry } from '../../domain/capabilityRegistrySymbol';
2
+ import { WithMicroverseScriptContext } from '../../domain/scriptContextSymbol';
3
+ import { HostSurfaceCore } from '../../domain/hostSurfaceTypes';
3
4
  /**
4
5
  * Builds a frozen `mergeEnv` table: bridge name → API object, ready for `MicroverseSlot.run({ mergeEnv })`.
5
6
  *
@@ -7,5 +8,7 @@ import { HostSurfaceCore } from '../../domain/hostSurfaceTypes.js';
7
8
  * @param slotKey - Same slot key passed to `buildDeclarativeBridgeTable` (string form of `MicroverseId` is fine).
8
9
  * @param surface - Result of {@link defineHostSurface} (implements {@link HostSurfaceCore}).
9
10
  */
10
- export declare function buildBridgeMergeEnvForHost<THost>(host: THost & WithMicroverseCapabilityRegistry, slotKey: string, surface: HostSurfaceCore): Readonly<Record<string, unknown>>;
11
+ export declare function buildBridgeMergeEnvForHost<THost>(host: THost & WithMicroverseCapabilityRegistry & WithMicroverseScriptContext, slotKey: string, surface: HostSurfaceCore): Readonly<Record<string, unknown>>;
12
+ /** Bridge table names for `__microverse_bridge_names` in the slot env. */
13
+ export declare function bridgeNamesFromSurface(surface: HostSurfaceCore): readonly string[];
11
14
  //# sourceMappingURL=bridgeMergeEnv.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"bridgeMergeEnv.d.ts","sourceRoot":"","sources":["../../../src/infrastructure/builders/bridgeMergeEnv.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gCAAgC,EAAE,MAAM,0CAA0C,CAAC;AACjG,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAExE;;;;;;GAMG;AACH,wBAAgB,0BAA0B,CAAC,KAAK,EAC9C,IAAI,EAAE,KAAK,GAAG,gCAAgC,EAC9C,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,eAAe,GACvB,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAEnC"}
1
+ {"version":3,"file":"bridgeMergeEnv.d.ts","sourceRoot":"","sources":["../../../src/infrastructure/builders/bridgeMergeEnv.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gCAAgC,EAAE,MAAM,uCAAuC,CAAC;AAC9F,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,kCAAkC,CAAC;AACpF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAErE;;;;;;GAMG;AACH,wBAAgB,0BAA0B,CAAC,KAAK,EAC9C,IAAI,EAAE,KAAK,GAAG,gCAAgC,GAAG,2BAA2B,EAC5E,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,eAAe,GACvB,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAEnC;AAED,0EAA0E;AAC1E,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,eAAe,GAAG,SAAS,MAAM,EAAE,CAElF"}
@@ -1,8 +1,8 @@
1
- import { SurfaceBuilder } from './surfaceBuilder.js';
2
- export type { InferSurfaceCapabilities } from '../../domain/surfaceCapabilities.js';
3
- export type { SurfaceMethodDef } from '../../domain/surfaceMethodDef.js';
4
- export { BridgeBuilder, SurfaceBuilder } from './surfaceBuilder.js';
5
- export type { AnyHostSurfaceMethod, HostFnContext, HostSurface, HostSurfaceCore, HostSurfaceMethodEntry, HostSurfaceSpec, HostSurfaceSpecForHost, HostWorkflowHooksSpec, LuaDefManifestGeneratorOpts, } from '../../domain/hostSurfaceTypes.js';
1
+ import { SurfaceBuilder } from './surfaceBuilder';
2
+ export type { InferSurfaceCapabilities } from '../../domain/surfaceCapabilities';
3
+ export type { SurfaceMethodDef } from '../../domain/surfaceMethodDef';
4
+ export { BridgeBuilder, SurfaceBuilder } from './surfaceBuilder';
5
+ export type { AnyHostSurfaceMethod, HostFnContext, HostSurface, HostSurfaceCore, HostSurfaceMethodEntry, HostSurfaceSpec, HostSurfaceSpecForHost, HostComponentHooksSpec, LuaDefManifestGeneratorOpts, } from '../../domain/hostSurfaceTypes';
6
6
  /**
7
7
  * Declares a **host surface** via the fluent builder (`bridge` → `method` → `build`).
8
8
  *
@@ -1 +1 @@
1
- {"version":3,"file":"defineHostSurfaceFacade.d.ts","sourceRoot":"","sources":["../../../src/infrastructure/builders/defineHostSurfaceFacade.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAIrD,YAAY,EAAE,wBAAwB,EAAE,MAAM,qCAAqC,CAAC;AACpF,YAAY,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAC;AACzE,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAEpE,YAAY,EACV,oBAAoB,EACpB,aAAa,EACb,WAAW,EACX,eAAe,EACf,sBAAsB,EACtB,eAAe,EACf,sBAAsB,EACtB,qBAAqB,EACrB,2BAA2B,GAC5B,MAAM,kCAAkC,CAAC;AAM1C;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,iBAAiB,IAAI,cAAc,CAAC,OAAO,CAAC,CAE3D;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,KAAK,cAAc,CAAC,KAAK,CAAC,CAEnE"}
1
+ {"version":3,"file":"defineHostSurfaceFacade.d.ts","sourceRoot":"","sources":["../../../src/infrastructure/builders/defineHostSurfaceFacade.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAIlD,YAAY,EAAE,wBAAwB,EAAE,MAAM,kCAAkC,CAAC;AACjF,YAAY,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AACtE,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAEjE,YAAY,EACV,oBAAoB,EACpB,aAAa,EACb,WAAW,EACX,eAAe,EACf,sBAAsB,EACtB,eAAe,EACf,sBAAsB,EACtB,sBAAsB,EACtB,2BAA2B,GAC5B,MAAM,+BAA+B,CAAC;AAMvC;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,iBAAiB,IAAI,cAAc,CAAC,OAAO,CAAC,CAE3D;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,KAAK,cAAc,CAAC,KAAK,CAAC,CAEnE"}
@@ -1,29 +1,29 @@
1
- import { SchemaValidationPort } from '../../application/ports/SchemaValidationPort.js';
2
- import { InferSurfaceCapabilities } from '../../domain/surfaceCapabilities.js';
3
- import { SurfaceMethodDef } from '../../domain/surfaceMethodDef.js';
4
- import { AnyHostSurfaceMethod, HostSurface, HostSurfaceSpec, HostWorkflowHooksSpec } from '../../domain/hostSurfaceTypes.js';
1
+ import { SchemaValidationPort } from '../../application/ports/SchemaValidationPort';
2
+ import { InferSurfaceCapabilities } from '../../domain/surfaceCapabilities';
3
+ import { SurfaceMethodDef } from '../../domain/surfaceMethodDef';
4
+ import { AnyHostSurfaceMethod, HostSurface, HostSurfaceSpec, HostComponentHooksSpec } from '../../domain/hostSurfaceTypes';
5
5
  type MutableHostSurfaceSpec = Record<string, Record<string, AnyHostSurfaceMethod>>;
6
6
  /**
7
7
  * Fluent builder for a host surface. Created via {@link defineHostSurfaceFor} / {@link defineHostSurface} factory overloads.
8
8
  */
9
- export declare class SurfaceBuilder<THost, const THooks extends HostWorkflowHooksSpec | undefined = undefined> {
9
+ export declare class SurfaceBuilder<THost, const THooks extends HostComponentHooksSpec | undefined = undefined> {
10
10
  private readonly spec;
11
- private workflowHooksSpec;
11
+ private componentHooksSpec;
12
12
  private readonly ports;
13
- constructor(ports: readonly [SchemaValidationPort], workflowHooks?: THooks, initialSpec?: MutableHostSurfaceSpec);
13
+ constructor(ports: readonly [SchemaValidationPort], componentHooks?: THooks, initialSpec?: MutableHostSurfaceSpec);
14
14
  /** Opens a Lua bridge table (e.g. `orders`, `greet`). */
15
15
  bridge<const B extends string>(name: B): BridgeBuilder<THost, B, THooks>;
16
- /** Attaches workflow hook Zod schemas (emitted into `.d.lua` as `on*` methods). */
17
- workflowHooks<const H extends HostWorkflowHooksSpec>(hooks: H): SurfaceBuilder<THost, H>;
16
+ /** Attaches component domain-event Zod schemas (emitted into `.d.lua` as `on*` methods on `Component`). */
17
+ componentHooks<const H extends HostComponentHooksSpec>(hooks: H): SurfaceBuilder<THost, H>;
18
18
  /** Compiles the accumulated spec into a {@link HostSurface}. */
19
- build(): THooks extends HostWorkflowHooksSpec ? HostSurface<THooks, InferSurfaceCapabilities<HostSurfaceSpec>> : HostSurface<undefined, InferSurfaceCapabilities<HostSurfaceSpec>>;
19
+ build(): THooks extends HostComponentHooksSpec ? HostSurface<THooks, InferSurfaceCapabilities<HostSurfaceSpec>> : HostSurface<undefined, InferSurfaceCapabilities<HostSurfaceSpec>>;
20
20
  /** @internal */
21
21
  addMethod<const B extends string, const M extends string>(bridgeName: B, methodName: M, entry: AnyHostSurfaceMethod): SurfaceBuilder<THost, THooks>;
22
22
  }
23
23
  /**
24
24
  * Per-bridge step in the fluent surface DSL. Return to {@link SurfaceBuilder} via `.method(…)`.
25
25
  */
26
- export declare class BridgeBuilder<THost, const B extends string, THooks extends HostWorkflowHooksSpec | undefined> {
26
+ export declare class BridgeBuilder<THost, const B extends string, THooks extends HostComponentHooksSpec | undefined> {
27
27
  private readonly parent;
28
28
  private readonly bridgeName;
29
29
  constructor(parent: SurfaceBuilder<THost, THooks>, bridgeName: B);
@@ -1 +1 @@
1
- {"version":3,"file":"surfaceBuilder.d.ts","sourceRoot":"","sources":["../../../src/infrastructure/builders/surfaceBuilder.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,iDAAiD,CAAC;AAC5F,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,qCAAqC,CAAC;AACpF,OAAO,EAAsB,KAAK,gBAAgB,EAAE,MAAM,kCAAkC,CAAC;AAE7F,OAAO,KAAK,EACV,oBAAoB,EACpB,WAAW,EACX,eAAe,EACf,qBAAqB,EACtB,MAAM,kCAAkC,CAAC;AAE1C,KAAK,sBA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