@microverse.ts/host-surface 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +53 -22
- package/dist/application/ports/ScriptReferenceResolverPort.d.ts +13 -0
- package/dist/application/ports/ScriptReferenceResolverPort.d.ts.map +1 -0
- package/dist/application/useCases/compileBridgeDeclarationsFromHostSurfaceSpec.d.ts +4 -4
- package/dist/application/useCases/compileBridgeDeclarationsFromHostSurfaceSpec.d.ts.map +1 -1
- package/dist/application/useCases/compileHostSurface.d.ts +7 -6
- package/dist/application/useCases/compileHostSurface.d.ts.map +1 -1
- package/dist/domain/componentSlotPrelude.d.ts +11 -0
- package/dist/domain/componentSlotPrelude.d.ts.map +1 -0
- package/dist/domain/componentTypeSpec.d.ts +12 -0
- package/dist/domain/componentTypeSpec.d.ts.map +1 -0
- package/dist/domain/hostSurfaceManifest.d.ts +3 -2
- package/dist/domain/hostSurfaceManifest.d.ts.map +1 -1
- package/dist/domain/hostSurfaceSpecTypes.d.ts +89 -0
- package/dist/domain/hostSurfaceSpecTypes.d.ts.map +1 -0
- package/dist/domain/hostSurfaceTypes.d.ts +16 -92
- package/dist/domain/hostSurfaceTypes.d.ts.map +1 -1
- package/dist/domain/luaGlobalHook.d.ts +1 -1
- package/dist/domain/safeObjectKey.d.ts +1 -1
- package/dist/domain/safeObjectKey.d.ts.map +1 -1
- package/dist/domain/scriptCatalogManifest.d.ts +14 -0
- package/dist/domain/scriptCatalogManifest.d.ts.map +1 -0
- package/dist/domain/scriptContextSymbol.d.ts +6 -0
- package/dist/domain/scriptContextSymbol.d.ts.map +1 -0
- package/dist/domain/scriptProfileSpec.d.ts +31 -0
- package/dist/domain/scriptProfileSpec.d.ts.map +1 -0
- package/dist/domain/scriptPropertyMergeEnv.d.ts +6 -0
- package/dist/domain/scriptPropertyMergeEnv.d.ts.map +1 -0
- package/dist/domain/surfaceCapabilities.d.ts +1 -1
- package/dist/domain/surfaceCapabilities.d.ts.map +1 -1
- package/dist/domain/surfaceMethodDef.d.ts +1 -1
- package/dist/domain/surfaceMethodDef.d.ts.map +1 -1
- package/dist/index.d.ts +30 -14
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +846 -258
- package/dist/index.js.map +1 -1
- package/dist/infrastructure/adapters/augmentHostWithCapabilityRegistry.d.ts +1 -1
- package/dist/infrastructure/adapters/augmentHostWithCapabilityRegistry.d.ts.map +1 -1
- package/dist/infrastructure/adapters/augmentHostWithScriptContext.d.ts +4 -0
- package/dist/infrastructure/adapters/augmentHostWithScriptContext.d.ts.map +1 -0
- package/dist/infrastructure/adapters/zodSchemaValidationAdapter.d.ts +1 -1
- package/dist/infrastructure/adapters/zodSchemaValidationAdapter.d.ts.map +1 -1
- package/dist/infrastructure/builders/bridgeMergeEnv.d.ts +6 -8
- package/dist/infrastructure/builders/bridgeMergeEnv.d.ts.map +1 -1
- package/dist/infrastructure/builders/defineHostSurfaceFacade.d.ts +5 -5
- package/dist/infrastructure/builders/defineHostSurfaceFacade.d.ts.map +1 -1
- package/dist/infrastructure/builders/filterBridgeDeclarations.d.ts +11 -0
- package/dist/infrastructure/builders/filterBridgeDeclarations.d.ts.map +1 -0
- package/dist/infrastructure/builders/surfaceBuilder.d.ts +16 -11
- package/dist/infrastructure/builders/surfaceBuilder.d.ts.map +1 -1
- package/dist/infrastructure/components/hostScriptSession.d.ts +42 -72
- package/dist/infrastructure/components/hostScriptSession.d.ts.map +1 -1
- 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 `{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,MAAM,0DAA0D,GAAG;CAGjF,OAAO,KAAK,MAAM,KAAK,IAAI,EAAE;AAC/B"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/domain/scriptContextSymbol.ts","../src/application/useCases/compileBridgeDeclarationsFromHostSurfaceSpec.ts","../src/infrastructure/builders/filterBridgeDeclarations.ts","../src/infrastructure/builders/bridgeMergeEnv.ts","../src/domain/safeObjectKey.ts","../src/domain/surfaceCapabilities.ts","../src/domain/scriptProfileSpec.ts","../src/domain/scriptCatalogManifest.ts","../src/domain/componentSlotPrelude.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/application/useCases/compileHostSurface.ts","../src/domain/inferMethodAsync.ts","../src/domain/surfaceMethodDef.ts","../src/infrastructure/builders/surfaceBuilder.ts","../src/infrastructure/builders/defineHostSurfaceFacade.ts","../src/domain/scriptPropertyMergeEnv.ts","../src/infrastructure/adapters/augmentHostWithScriptContext.ts","../src/infrastructure/components/hostScriptSession.ts","../src/domain/capabilityRegistrySymbol.ts","../src/infrastructure/adapters/augmentHostWithCapabilityRegistry.ts"],"sourcesContent":["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 { createScriptInstanceContext } from '@microverse.ts/runtime-core';\n\nimport { MICROVERSE_SCRIPT_CONTEXT, type WithMicroverseScriptContext } from '../../domain/scriptContextSymbol';\n\nimport type { AnyHostSurfaceMethod, HostSurfaceSpec } from '../../domain/hostSurfaceSpecTypes';\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<WithMicroverseScriptContext, string>> {\n const out: DeclarativeBridgeDeclaration<WithMicroverseScriptContext, 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 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 host[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: host 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 type { DeclarativeBridgeDeclaration } from '@microverse.ts/runtime-bridge';\nimport type { CapabilityId } from '@microverse.ts/runtime-capabilities';\n\nimport type { HostSurfaceSpec } from '../../domain/hostSurfaceSpecTypes';\nimport type { SchemaValidationPort } from '../../application/ports/SchemaValidationPort';\nimport { createBridgeDeclarationsFromHostSurfaceSpec } from '../../application/useCases/compileBridgeDeclarationsFromHostSurfaceSpec';\n\n/**\n * Keeps bridge declarations (and methods) whose capability is in the allow set.\n */\nexport function filterBridgeDeclarationsByCapabilities<\n THost,\n TSlotKey extends string,\n>(\n declarations: readonly DeclarativeBridgeDeclaration<THost, TSlotKey>[],\n spec: HostSurfaceSpec,\n capabilities: readonly CapabilityId[],\n): DeclarativeBridgeDeclaration<THost, TSlotKey>[] {\n const allowed = new Set(capabilities.map((c) => String(c)));\n const bridgeNames = 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]!;\n if (allowed.has(String(entry.capability))) {\n bridgeNames.add(bridgeName);\n break;\n }\n }\n }\n\n return declarations\n .filter((d) => bridgeNames.has(d.name))\n .map((d) => ({\n ...d,\n createApi: (host: THost, slotKey: TSlotKey) => {\n const api = d.createApi(host, slotKey) as Record<string, unknown>;\n const methods = spec[d.name]!;\n const filtered: Record<string, unknown> = {};\n for (const methodName of Object.keys(api)) {\n const entry = methods[methodName];\n if (entry !== undefined && allowed.has(String(entry.capability))) {\n filtered[methodName] = api[methodName];\n }\n }\n return Object.freeze(filtered);\n },\n }));\n}\n\nexport function createFilteredBridgeDeclarations(\n schemaValidation: SchemaValidationPort,\n spec: HostSurfaceSpec,\n capabilities: readonly CapabilityId[],\n): ReturnType<typeof createBridgeDeclarationsFromHostSurfaceSpec> {\n const all = createBridgeDeclarationsFromHostSurfaceSpec(schemaValidation, spec);\n return filterBridgeDeclarationsByCapabilities(all, spec, capabilities);\n}\n","import { buildDeclarativeBridgeTable } from '@microverse.ts/runtime-bridge';\nimport type { CapabilityId } from '@microverse.ts/runtime-capabilities';\n\nimport type { WithMicroverseScriptContext } from '../../domain/scriptContextSymbol';\nimport type { HostSurfaceSpec } from '../../domain/hostSurfaceSpecTypes';\nimport type { SchemaValidationPort } from '../../application/ports/SchemaValidationPort';\nimport { createFilteredBridgeDeclarations } from './filterBridgeDeclarations';\n\n/**\n * Builds a frozen bridge table for a component profile capability set.\n */\nexport function buildBridgeMergeEnvForProfile<THost>(\n schemaValidation: SchemaValidationPort,\n host: THost & WithMicroverseScriptContext,\n slotKey: string,\n spec: HostSurfaceSpec,\n capabilities: readonly CapabilityId[],\n): Readonly<Record<string, unknown>> {\n const filtered = createFilteredBridgeDeclarations(schemaValidation, spec, capabilities);\n return buildDeclarativeBridgeTable(host, slotKey, [...filtered]);\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' | 'componentType', 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 type { CapabilityId } from '@microverse.ts/runtime-capabilities';\n\nimport type { AnyHostSurfaceMethod, HostSurfaceMethodEntry, HostSurfaceSpec } from './hostSurfaceSpecTypes';\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 { createCapabilityId, type CapabilityId } from '@microverse.ts/runtime-capabilities';\nimport type { ScriptProfileDefInput } from '@microverse.ts/runtime-core';\nimport { z } from 'zod';\n\nimport type { HostComponentHooksSpec, HostSurfaceSpec } from './hostSurfaceSpecTypes';\nimport { assertSafeObjectKey } from './safeObjectKey';\nimport { collectCapabilitiesFromHostSurfaceSpec } from './surfaceCapabilities';\n\nexport type ScriptProfileDefRegistry = Readonly<Record<string, ScriptProfileDefInput>>;\n\nexport type ResolvedScriptProfile = {\n readonly name: string;\n readonly extends?: string | undefined;\n readonly capabilities: readonly CapabilityId[];\n readonly props: z.ZodObject<z.ZodRawShape>;\n readonly state: z.ZodObject<z.ZodRawShape>;\n readonly hooks: readonly string[];\n readonly bridgeNames: readonly string[];\n readonly references?: ScriptProfileDefInput['references'];\n};\n\nexport type ResolvedScriptProfileRegistry = Readonly<Record<string, ResolvedScriptProfile>>;\n\nconst EMPTY_PROPS = z.object({}) as z.ZodObject<z.ZodRawShape>;\nconst EMPTY_STATE = z.object({}) as z.ZodObject<z.ZodRawShape>;\n\nexport function scriptProfileComponentClassName(profileName: string): string {\n return `${profileName}Component`;\n}\n\nexport function scriptProfilePropsAlias(profileName: string): string {\n return `${profileName}Props`;\n}\n\nexport function scriptProfileStateAlias(profileName: string): string {\n return `${profileName}State`;\n}\n\nexport function scriptProfileBridgesClassName(profileName: string): string {\n return `${profileName}Bridges`;\n}\n\n/** Bridge table names whose methods include at least one capability from the profile. */\nexport function bridgeNamesForCapabilities(\n spec: HostSurfaceSpec,\n capabilities: readonly CapabilityId[],\n): readonly string[] {\n const allowed = new Set(capabilities.map((c) => String(c)));\n const names: 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]!;\n if (allowed.has(String(entry.capability))) {\n names.push(bridgeName);\n break;\n }\n }\n }\n return names.sort((a, b) => a.localeCompare(b));\n}\n\nexport function resolveScriptProfile(\n registry: ScriptProfileDefRegistry,\n name: string,\n spec: HostSurfaceSpec,\n): ResolvedScriptProfile {\n const def = registry[name];\n if (def === undefined) {\n throw new Error(`unknown script profile: ${name}`);\n }\n\n const capabilities: CapabilityId[] = def.capabilities.map((c) => createCapabilityId(c));\n let props = def.props;\n let state = def.state ?? EMPTY_STATE;\n const hooks: string[] = [...(def.hooks ?? [])];\n let parentName = def.extends;\n\n const visited = new Set<string>([name]);\n while (parentName !== undefined) {\n if (visited.has(parentName)) {\n throw new Error(`script profile inheritance cycle: ${name}`);\n }\n visited.add(parentName);\n const parent = registry[parentName];\n if (parent === undefined) {\n throw new Error(`script profile \"${name}\" extends unknown profile \"${parentName}\"`);\n }\n const parentCaps = parent.capabilities.map((c) => createCapabilityId(c));\n for (const cap of parentCaps) {\n if (!capabilities.some((c) => String(c) === String(cap))) {\n capabilities.push(cap);\n }\n }\n props = parent.props.merge(props) as z.ZodObject<z.ZodRawShape>;\n const parentState = parent.state ?? EMPTY_STATE;\n state = parentState.merge(state) as z.ZodObject<z.ZodRawShape>;\n const parentHooks = parent.hooks ?? [];\n for (const h of parentHooks) {\n if (!hooks.includes(h)) {\n hooks.push(h);\n }\n }\n parentName = parent.extends;\n }\n\n hooks.sort((a, b) => a.localeCompare(b));\n const bridgeNames = bridgeNamesForCapabilities(spec, capabilities);\n\n return {\n name,\n extends: def.extends,\n capabilities,\n props,\n state,\n hooks,\n bridgeNames,\n references: def.references,\n };\n}\n\nexport function buildResolvedScriptProfileRegistry(\n registry: ScriptProfileDefRegistry,\n spec: HostSurfaceSpec,\n): ResolvedScriptProfileRegistry {\n const out: Record<string, ResolvedScriptProfile> = {};\n for (const name of Object.keys(registry)) {\n out[name] = resolveScriptProfile(registry, name, spec);\n }\n return out;\n}\n\nexport function validateScriptProfileRegistry(\n registry: ScriptProfileDefRegistry,\n spec: HostSurfaceSpec,\n componentHooks?: HostComponentHooksSpec,\n opts?: { readonly requireAtLeastOne?: boolean | undefined },\n): void {\n const requireAtLeastOne = opts?.requireAtLeastOne ?? false;\n if (requireAtLeastOne && Object.keys(registry).length === 0) {\n throw new Error('host surface: at least one script profile or .componentType() is required');\n }\n\n const surfaceCaps = new Set(\n collectCapabilitiesFromHostSurfaceSpec(spec).map((c) => String(c)),\n );\n const hookKinds =\n componentHooks !== undefined ? new Set(Object.keys(componentHooks)) : new Set<string>();\n\n for (const name of Object.keys(registry)) {\n assertSafeObjectKey('componentType', name);\n const def = registry[name]!;\n\n if (def.extends !== undefined) {\n assertSafeObjectKey('componentType', def.extends);\n }\n\n for (const cap of def.capabilities) {\n const id = createCapabilityId(cap);\n if (!surfaceCaps.has(String(id))) {\n throw new Error(\n `script profile \"${name}\": capability not declared on surface: ${String(cap)}`,\n );\n }\n }\n\n for (const hook of def.hooks ?? []) {\n if (!hookKinds.has(hook)) {\n throw new Error(\n `script profile \"${name}\": hook \"${hook}\" not declared in .componentHooks()`,\n );\n }\n }\n\n if (def.extends !== undefined && registry[def.extends] === undefined) {\n throw new Error(`script profile \"${name}\" extends unknown profile \"${def.extends}\"`);\n }\n }\n\n for (const name of Object.keys(registry)) {\n resolveScriptProfile(registry, name, spec);\n }\n}\n\nexport { EMPTY_PROPS, EMPTY_STATE };\n","import type { LuaDefManifest, ManifestAlias } from '@microverse.ts/lua-defs';\n\nimport { scriptProfileComponentClassName } from './scriptProfileSpec';\n\nexport type ScriptCatalogEntry = {\n readonly scriptId: string;\n readonly profileId: string;\n /**\n * When true, the script's `.lua` file defines `---@class …ScriptComponent` (e.g. script-local methods).\n * Omit the catalog `---@alias` so LuaLS does not report duplicate-doc-alias.\n */\n readonly localComponentClass?: boolean | undefined;\n};\n\n/** LuaCATS aliases per catalog scriptId → resolved component class (for `---@type` in `.lua` files). */\nexport function buildScriptCatalogLuaDefManifest(\n entries: readonly ScriptCatalogEntry[],\n): LuaDefManifest {\n const aliases: ManifestAlias[] = entries\n .filter((entry) => entry.localComponentClass !== true)\n .slice()\n .sort((a, b) => a.scriptId.localeCompare(b.scriptId))\n .map((entry) => {\n const componentClass = scriptProfileComponentClassName(entry.profileId);\n const aliasName = scriptCatalogComponentAlias(entry.scriptId);\n return {\n name: aliasName,\n definition: componentClass,\n };\n });\n\n return {\n schemaVersion: 1,\n output: 'generated/scriptCatalog.d.lua',\n classes: [],\n aliases,\n globals: [],\n luaHooks: [],\n };\n}\n\nexport function scriptCatalogComponentAlias(scriptId: string): string {\n const safe = scriptId.replace(/[^A-Za-z0-9_]/g, '_');\n return `${safe}ScriptComponent`;\n}\n","import type { ResolvedScriptProfileRegistry } from './scriptProfileSpec';\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\nlocal ReferencesMT = {\n __index = function(t, k)\n local wrap = rawget(_ENV, \"__microverse_reference_wrap\")\n local raw = rawget(t, \"__raw\")\n local val = raw[k]\n if type(wrap) == \"function\" then\n return wrap(k, val)\n end\n return val\n end,\n}\n\nfunction __microverse_lua_build_component_impl(bridges)\n local impl = { state = {}, bridges = type(bridges) == \"table\" and bridges or {} }\n local proxy = { __raw = rawProps() }\n setmetatable(proxy, PropertiesMT)\n impl.properties = proxy\n local refProxy = { __raw = rawProps() }\n setmetatable(refProxy, ReferencesMT)\n impl.references = refProxy\n local base = rawget(_ENV, \"__microverse_component_hook_base\")\n if type(base) == \"table\" then\n setmetatable(impl, { __index = base })\n end\n rawset(_ENV, \"__microverse_lua_ComponentImpl\", impl)\n return impl\nend\n\nrawset(_ENV, \"__microverse_lua_build_component_impl\", __microverse_lua_build_component_impl)\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\n/** Lua prelude that registers `TypeName:extend()` singletons for each component type. */\nexport function profileBridgeSlotKey(typeName: string, bridgeName: string): string {\n return `__mv_${typeName}_${bridgeName}`;\n}\n\nexport function profileBridgeNamesMergeEnvKey(typeName: string): string {\n return `__microverse_profile_bridge_names_${typeName}`;\n}\n\nexport function buildComponentTypeBridgeNamesPreludeLua(\n componentTypes: ResolvedScriptProfileRegistry,\n): string {\n const lines: string[] = [];\n for (const typeName of Object.keys(componentTypes).sort((a, b) => a.localeCompare(b))) {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(typeName)) {\n throw new Error(`unsafe component type name for bridge names prelude: ${typeName}`);\n }\n const names = componentTypes[typeName]!.bridgeNames;\n const entries = names.map((n) => JSON.stringify(n)).join(', ');\n lines.push(\n `rawset(_ENV, ${JSON.stringify(profileBridgeNamesMergeEnvKey(typeName))}, { ${entries} })`,\n );\n }\n return lines.join('\\n');\n}\n\nexport function buildComponentTypeSingletonsPreludeLua(typeNames: readonly string[]): string {\n const lines: string[] = [\n 'local function __microverse_collect_profile_bridges(typeName)',\n ' local names = rawget(_ENV, \"__microverse_profile_bridge_names_\" .. typeName)',\n ' local bridges = {}',\n ' if type(names) ~= \"table\" then',\n ' return bridges',\n ' end',\n ' for _, name in ipairs(names) do',\n ' if type(name) == \"string\" then',\n ' local b = rawget(_ENV, \"__mv_\" .. typeName .. \"_\" .. name)',\n ' if type(b) == \"table\" then',\n ' bridges[name] = b',\n ' end',\n ' end',\n ' end',\n ' return bridges',\n 'end',\n 'local function __microverse_make_type_extend(typeName)',\n ' return function(self)',\n ' local ext = rawget(_ENV, \"__microverse_lua_extend_component\")',\n ' if type(ext) == \"function\" then',\n ' ext(typeName)',\n ' end',\n ' local build = rawget(_ENV, \"__microverse_lua_build_component_impl\")',\n ' if type(build) ~= \"function\" then',\n ' error(\"component type extend: build impl missing\")',\n ' end',\n ' return build(__microverse_collect_profile_bridges(typeName))',\n ' end',\n 'end',\n ];\n for (const name of typeNames) {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {\n throw new Error(`unsafe component type name for Lua singleton: ${name}`);\n }\n lines.push(`rawset(_ENV, ${JSON.stringify(name)}, { extend = __microverse_make_type_extend(${JSON.stringify(name)}) })`);\n }\n return lines.join('\\n');\n}\n\n/** Applies host-selected profile (same as `Type:extend()` without requiring Lua to call it). */\nexport function buildApplyHostScriptProfileChunkLua(profileName: string): string {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(profileName)) {\n throw new Error(`unsafe script profile name: ${profileName}`);\n }\n return [\n `local T = ${profileName}`,\n 'if type(T) == \"table\" and type(T.extend) == \"function\" then',\n ' T:extend()',\n 'end',\n ].join('\\n');\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 {\n scriptProfileBridgesClassName,\n scriptProfileComponentClassName,\n scriptProfilePropsAlias,\n scriptProfileStateAlias,\n type ResolvedScriptProfile,\n type ResolvedScriptProfileRegistry,\n} from './scriptProfileSpec';\nimport type { HostComponentHooksSpec, HostSurfaceSpec } from './hostSurfaceSpecTypes';\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 buildComponentEventManifestFields(\n kinds: readonly string[],\n componentClassName: 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: ${componentClassName}, 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 pushBaseComponentClass(classes: ManifestClass[]): void {\n classes.push({\n name: 'Component',\n description: 'Base component lifecycle (extended by typed component profiles).',\n fields: [\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 emitSingleton: false,\n });\n}\n\nfunction pushProfileBridgesClass(typeName: string, bridgeNames: readonly string[], classes: ManifestClass[]): void {\n if (bridgeNames.length === 0) {\n return;\n }\n const bridgesName = scriptProfileBridgesClassName(typeName);\n classes.push({\n name: bridgesName,\n description: `Host bridges for \\`${typeName}\\` components (\\`self.bridges\\` after \\`${typeName}:extend()\\`).`,\n fields: bridgeNames.map((name) => ({\n name,\n luaType: bridgeLuaClassName(name),\n })),\n emitSingleton: false,\n });\n}\n\nfunction pushComponentTypeManifest(\n classes: ManifestClass[],\n aliases: Map<string, string>,\n typeName: string,\n profile: ResolvedScriptProfile,\n componentHooks: HostComponentHooksSpec | undefined,\n): void {\n const propsAlias = scriptProfilePropsAlias(typeName);\n const stateAlias = scriptProfileStateAlias(typeName);\n aliases.set(propsAlias, zodToLuaTypeRef(profile.props));\n aliases.set(stateAlias, zodToLuaTypeRef(profile.state));\n\n pushProfileBridgesClass(typeName, profile.bridgeNames, classes);\n\n const componentClass = scriptProfileComponentClassName(typeName);\n const bridgesClass = profile.bridgeNames.length > 0 ? scriptProfileBridgesClassName(typeName) : 'table';\n const extendsClass =\n profile.extends !== undefined ? scriptProfileComponentClassName(profile.extends) : 'Component';\n\n const fields: ManifestClassField[] = [\n { name: 'properties', luaType: propsAlias, description: 'Host-synced props (proxy).' },\n { name: 'state', luaType: stateAlias, description: 'Lua-local state.' },\n {\n name: 'bridges',\n luaType: bridgesClass,\n description: 'Host bridges allowed for this component type.',\n },\n {\n name: 'init',\n luaType: `fun(self: ${componentClass})`,\n description: 'Called once after mount and initial props are applied.',\n },\n {\n name: 'onPropsChanged',\n luaType: `fun(self: ${componentClass}, key: string, newValue: any)`,\n description: 'Called when the host patches a property key.',\n },\n {\n name: 'onDestroy',\n luaType: `fun(self: ${componentClass})`,\n description: 'Called before the script instance slot is disposed.',\n },\n ];\n\n if (componentHooks !== undefined && profile.hooks.length > 0) {\n fields.push(...buildComponentEventManifestFields(profile.hooks, componentClass, componentHooks));\n }\n\n classes.push({\n name: componentClass,\n extendsClass,\n description: `Component instance from \\`local C = ${typeName}:extend()\\`.`,\n fields,\n emitSingleton: false,\n });\n\n classes.push({\n name: typeName,\n description: `Factory for \\`${componentClass}\\` in this slot.`,\n methods: [\n {\n name: 'extend',\n description: 'Creates the active component with profile-scoped bridges.',\n params: [],\n returns: componentClass,\n },\n ],\n emitSingleton: true,\n });\n}\n\nfunction pushComponentManifestClasses(\n classes: ManifestClass[],\n aliases: Map<string, string>,\n componentTypes: ResolvedScriptProfileRegistry,\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 pushBaseComponentClass(classes);\n const typeNames = Object.keys(componentTypes).sort((a, b) => a.localeCompare(b));\n for (const typeName of typeNames) {\n pushComponentTypeManifest(classes, aliases, typeName, componentTypes[typeName]!, componentHooks);\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 componentTypes?: ResolvedScriptProfileRegistry,\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 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 (componentTypes !== undefined) {\n pushComponentManifestClasses(classes, merged, componentTypes, componentHooks);\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 { buildLuaDefManifestFromHostSurfaceSpec } from '../../domain/hostSurfaceManifest';\nimport type { ComponentTypeDefRegistry } from '../../domain/componentTypeSpec';\nimport {\n buildResolvedScriptProfileRegistry,\n validateScriptProfileRegistry,\n} from '../../domain/scriptProfileSpec';\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 componentTypeRegistry: ComponentTypeDefRegistry,\n componentHooks?: HostComponentHooksSpec,\n): HostSurfaceCore<InferSurfaceCapabilities<TSpec>> {\n validateScriptProfileRegistry(componentTypeRegistry, spec, componentHooks, {\n requireAtLeastOne: false,\n });\n const componentTypes = buildResolvedScriptProfileRegistry(componentTypeRegistry, spec);\n const capabilities = collectCapabilitiesFromHostSurfaceSpec(spec);\n\n return {\n getHostSurfaceSpec: () => spec,\n toBridgeDeclarations: () => createBridgeDeclarationsFromHostSurfaceSpec(schemaValidation, spec),\n toLuaDefManifest: (opts) =>\n buildLuaDefManifestFromHostSurfaceSpec(spec, opts, componentHooks, componentTypes),\n capabilities,\n componentTypes,\n getComponentType: (name: string) => {\n const profile = componentTypes[name];\n if (profile === undefined) {\n throw new Error(`unknown component type: ${name}`);\n }\n return profile;\n },\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 componentTypeRegistry: ComponentTypeDefRegistry,\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 componentTypeRegistry: ComponentTypeDefRegistry,\n componentHooks: THooks,\n): HostSurface<THooks, InferSurfaceCapabilities<TSpec>>;\nexport function compileHostSurface<const TSpec extends HostSurfaceSpec>(\n ports: readonly [SchemaValidationPort],\n spec: TSpec,\n componentTypeRegistry: ComponentTypeDefRegistry,\n componentHooks?: HostComponentHooksSpec,\n): HostSurface<undefined, InferSurfaceCapabilities<TSpec>> | HostSurface<HostComponentHooksSpec, InferSurfaceCapabilities<TSpec>> {\n const [schemaValidation] = ports;\n const core = buildHostSurfaceCore(schemaValidation, spec, componentTypeRegistry, 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 componentTypeRegistry: ComponentTypeDefRegistry,\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, componentTypeRegistry)\n : compileHostSurface(ports, spec, componentTypeRegistry, 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 './hostSurfaceSpecTypes';\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","import { compileHostSurfaceFor } from '../../application/useCases/compileHostSurface';\nimport type { SchemaValidationPort } from '../../application/ports/SchemaValidationPort';\nimport type { ComponentTypeDefInput, ComponentTypeDefRegistry } from '../../domain/componentTypeSpec';\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>>;\ntype MutableComponentTypeRegistry = Record<string, ComponentTypeDefInput>;\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 readonly componentTypeRegistry: MutableComponentTypeRegistry = 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 initialComponentTypes?: MutableComponentTypeRegistry,\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 if (initialComponentTypes !== undefined) {\n for (const name of Object.keys(initialComponentTypes)) {\n this.componentTypeRegistry[name] = initialComponentTypes[name]!;\n }\n }\n }\n\n /** Declares a typed Lua component profile (props, state, capabilities, hooks). */\n componentType<const N extends string>(\n name: N,\n def: ComponentTypeDefInput<`${string}:${string}`, THooks>,\n ): SurfaceBuilder<THost, THooks> {\n assertSafeObjectKey('componentType', name);\n this.componentTypeRegistry[name] = def;\n return this;\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 types). */\n componentHooks<const H extends HostComponentHooksSpec>(hooks: H): SurfaceBuilder<THost, H> {\n return new SurfaceBuilder<THost, H>(\n this.ports,\n hooks,\n this.spec,\n this.componentTypeRegistry,\n );\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 const registry = this.componentTypeRegistry as ComponentTypeDefRegistry;\n return compileHostSurfaceFor(this.ports, spec, registry, 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","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 { 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 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 RunScriptResult,\n type MicroverseSlot,\n type MicroverseId,\n type MicroverseRuntime,\n type ScriptAuditEvent,\n type ScriptInstanceContext,\n type MutableScriptPropertyBag,\n type ScriptPropertyBag,\n type ScriptPropertyValue,\n type TimeoutPolicy,\n} from '@microverse.ts/runtime-core';\n\nimport type { SchemaValidationPort } from '../../application/ports/SchemaValidationPort';\nimport { createZodSchemaValidationPort } from '../adapters/zodSchemaValidationAdapter';\nimport type { ScriptReferenceFieldDef } from '@microverse.ts/runtime-core';\nimport type { ScriptReferenceResolverPort } from '../../application/ports/ScriptReferenceResolverPort';\nimport {\n MICROVERSE_LUA_COMPONENT_SLOT_PRELUDE,\n buildApplyHostScriptProfileChunkLua,\n buildComponentTypeBridgeNamesPreludeLua,\n buildComponentTypeSingletonsPreludeLua,\n profileBridgeSlotKey,\n} from '../../domain/componentSlotPrelude';\nimport type { ResolvedScriptProfile } from '../../domain/scriptProfileSpec';\nimport {\n plainToScriptPropertyValue,\n scriptPropertyBagToMergeEnv,\n} from '../../domain/scriptPropertyMergeEnv';\nimport { augmentHostWithScriptContext } from '../adapters/augmentHostWithScriptContext';\nimport { buildBridgeMergeEnvForProfile } from '../builders/bridgeMergeEnv';\nimport type { HostSurface, HostComponentHooksSpec } from '../../domain/hostSurfaceTypes';\nimport type { LuaGlobalHookName } from '../../domain/luaGlobalHook';\nimport { luaGlobalHookName } from '../../domain/luaGlobalHook';\n\nconst defaultSchemaValidation: SchemaValidationPort = createZodSchemaValidationPort();\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 defaultTimeout?: TimeoutPolicy | undefined;\n readonly script: ScriptInstanceContext;\n /** Host-selected script profile (surface component type name). Applied at openSession before the main chunk. */\n readonly profileId?: string | undefined;\n /** When set, used instead of {@link HostSurfaceCore.getComponentType} (inline catalog profiles). */\n readonly resolvedProfile?: ResolvedScriptProfile | undefined;\n /** Lua singleton global for `Type:extend()` (e.g. `SortingAlgorithm`). Defaults to `profileId`. */\n readonly profileSingleton?: string | undefined;\n readonly enableComponentRuntime?: boolean | undefined;\n readonly schemaValidation?: SchemaValidationPort | undefined;\n readonly referenceResolver?: ScriptReferenceResolverPort | 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 schemaValidation: SchemaValidationPort;\n\n private activeComponentType: string | undefined;\n\n private hostProfileApplied = false;\n\n readonly context: ScriptInstanceContext;\n\n constructor(private readonly opts: HostScriptSessionOptions<THost, THooks>) {\n this.schemaValidation = opts.schemaValidation ?? defaultSchemaValidation;\n this.context = opts.script;\n if (opts.resolvedProfile !== undefined) {\n this.activeComponentType = opts.resolvedProfile.name;\n } else if (opts.profileId !== undefined) {\n this.activeComponentType = opts.profileId;\n }\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 const activeProfile = this.tryGetActiveProfile();\n const singletonName = this.profileSingletonName();\n const typeNames = this.singletonTypeNames();\n if (typeNames.length > 0) {\n const bridgeRegistry =\n activeProfile !== undefined\n ? { [activeProfile.name]: activeProfile }\n : this.opts.surface.componentTypes;\n await sb.run({\n script: createMicroverseScript(\n [\n buildComponentTypeBridgeNamesPreludeLua(bridgeRegistry),\n buildComponentTypeSingletonsPreludeLua(typeNames),\n ].join('\\n'),\n ),\n mergeEnv: this.mergeEnv(),\n timeout: this.opts.defaultTimeout,\n });\n if (singletonName !== undefined) {\n await sb.run({\n script: createMicroverseScript(buildApplyHostScriptProfileChunkLua(singletonName)),\n mergeEnv: this.mergeEnv(),\n timeout: this.opts.defaultTimeout,\n });\n this.hostProfileApplied = true;\n }\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 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(): Record<string, unknown> {\n const host = augmentHostWithScriptContext(this.opts.host, this.opts.script);\n const spec = this.opts.surface.getHostSurfaceSpec();\n const env: Record<string, unknown> = {\n __microverse_lua_extend_component: (typeName: string): void => {\n if (this.opts.resolvedProfile !== undefined && typeName === this.profileSingletonName()) {\n this.activeComponentType = this.opts.resolvedProfile.name;\n return;\n }\n this.opts.surface.getComponentType(typeName);\n this.activeComponentType = typeName;\n },\n };\n const activeProfile = this.tryGetActiveProfile();\n const typeNames =\n activeProfile !== undefined\n ? [activeProfile.name]\n : Object.keys(this.opts.surface.componentTypes);\n for (const typeName of typeNames) {\n const profile =\n activeProfile !== undefined && typeName === activeProfile.name\n ? activeProfile\n : this.opts.surface.getComponentType(typeName);\n const bridgeTable = buildBridgeMergeEnvForProfile(\n this.schemaValidation,\n host,\n String(this.opts.slotKey),\n spec,\n profile.capabilities,\n );\n for (const bridgeName of profile.bridgeNames) {\n env[profileBridgeSlotKey(typeName, bridgeName)] = bridgeTable[bridgeName];\n }\n }\n\n const profileForRefs = this.tryGetActiveProfile();\n if (profileForRefs?.references !== undefined && this.opts.referenceResolver !== undefined) {\n const profile = profileForRefs;\n env.__microverse_reference_wrap = (field: string, raw: unknown) =>\n this.wrapReference(field, raw, profile);\n }\n\n return env;\n }\n\n private wrapReference(\n field: string,\n raw: unknown,\n profile: ResolvedScriptProfile,\n ): unknown {\n const resolver = this.opts.referenceResolver;\n const refs = profile.references;\n if (resolver === undefined || refs === undefined) {\n return raw;\n }\n const def = refs[field];\n if (def === undefined) {\n return raw;\n }\n const rawId =\n raw === null || raw === undefined\n ? null\n : typeof raw === 'string'\n ? raw\n : typeof raw === 'number' || typeof raw === 'boolean'\n ? String(raw)\n : null;\n return resolver.wrap({\n slotKey: String(this.opts.slotKey),\n field,\n raw: rawId,\n kind: def.kind,\n componentType: referenceComponentType(def),\n });\n }\n\n private emitAudit(event: ScriptAuditEvent): void {\n this.opts.onScriptAudit?.(event);\n }\n\n private getActiveProfileName(): string | undefined {\n return this.activeComponentType ?? this.opts.profileId;\n }\n\n private profileSingletonName(): string | undefined {\n return this.opts.profileSingleton ?? this.opts.profileId ?? this.opts.resolvedProfile?.name;\n }\n\n private singletonTypeNames(): string[] {\n const singleton = this.profileSingletonName();\n const fromSurface = Object.keys(this.opts.surface.componentTypes);\n const names = new Set<string>(fromSurface);\n if (singleton !== undefined) {\n names.add(singleton);\n }\n return [...names].sort((a, b) => a.localeCompare(b));\n }\n\n private tryGetActiveProfile(): ResolvedScriptProfile | undefined {\n if (this.opts.resolvedProfile !== undefined) {\n return this.opts.resolvedProfile;\n }\n const name = this.getActiveProfileName();\n if (name === undefined) {\n return undefined;\n }\n try {\n return this.opts.surface.getComponentType(name);\n } catch {\n return undefined;\n }\n }\n\n private validatePropsBag(bag: ScriptPropertyBag): ScriptPropertyBag {\n const profile = this.tryGetActiveProfile();\n if (profile === undefined) {\n throw new Error(\n 'HostScriptSession: set profileId or resolvedProfile before props or host sync',\n );\n }\n const parsed = profile.props.parse(bag);\n assertValidScriptPropertyBag(parsed);\n return parsed;\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 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 readonly getHostProfileApplied = (): boolean => this.hostProfileApplied;\n}\n\nfunction referenceComponentType(def: ScriptReferenceFieldDef): string | undefined {\n if (def.kind === 'entityComponentRef' || def.kind === 'entityComponentRefArray') {\n return def.componentType;\n }\n return undefined;\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 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","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 { 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"],"mappings":";;;;;;AAEA,IAAa,4BAA4B,OAAO,0BAA0B;;;ACQ1E,SAAS,WAAW,OAA2C;CAC7D,IAAI,UAAU,QAAQ,UAAU,KAAA,GAC9B,OAAO;CAET,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,YACh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C,MAAM,IAAI,MAAM,0DAA0D,GAAG;CAGjF,OAAO,KAAK,MAAM,KAAK,IAAI,EAAE;AAC/B;;;;;;;;AChhBA,IAAa,iCAAiC,OAAO,IAAI,+BAA+B;;;;;;;;;;ACIxF,SAAgB,kCACd,MACA,UAC0C;CAC1C,OAAO,OAAO,OAAO,MAAgB,GAClC,iCAAiC,SACpC,CAAC;AACH"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { CapabilityRegistryPort } from '@microverse.ts/runtime-capabilities';
|
|
2
|
-
import { WithMicroverseCapabilityRegistry } from '../../domain/capabilityRegistrySymbol
|
|
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,
|
|
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
|
|
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,
|
|
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,11 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { CapabilityId } from '@microverse.ts/runtime-capabilities';
|
|
2
|
+
import { WithMicroverseScriptContext } from '../../domain/scriptContextSymbol';
|
|
3
|
+
import { HostSurfaceSpec } from '../../domain/hostSurfaceSpecTypes';
|
|
4
|
+
import { SchemaValidationPort } from '../../application/ports/SchemaValidationPort';
|
|
3
5
|
/**
|
|
4
|
-
* Builds a frozen
|
|
5
|
-
*
|
|
6
|
-
* @param host - Your host context, already extended with the capability registry symbol from `@microverse.ts/host-surface`.
|
|
7
|
-
* @param slotKey - Same slot key passed to `buildDeclarativeBridgeTable` (string form of `MicroverseId` is fine).
|
|
8
|
-
* @param surface - Result of {@link defineHostSurface} (implements {@link HostSurfaceCore}).
|
|
6
|
+
* Builds a frozen bridge table for a component profile capability set.
|
|
9
7
|
*/
|
|
10
|
-
export declare function
|
|
8
|
+
export declare function buildBridgeMergeEnvForProfile<THost>(schemaValidation: SchemaValidationPort, host: THost & WithMicroverseScriptContext, slotKey: string, spec: HostSurfaceSpec, capabilities: readonly CapabilityId[]): Readonly<Record<string, unknown>>;
|
|
11
9
|
//# sourceMappingURL=bridgeMergeEnv.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bridgeMergeEnv.d.ts","sourceRoot":"","sources":["../../../src/infrastructure/builders/bridgeMergeEnv.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"bridgeMergeEnv.d.ts","sourceRoot":"","sources":["../../../src/infrastructure/builders/bridgeMergeEnv.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qCAAqC,CAAC;AAExE,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,kCAAkC,CAAC;AACpF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AACzE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,8CAA8C,CAAC;AAGzF;;GAEG;AACH,wBAAgB,6BAA6B,CAAC,KAAK,EACjD,gBAAgB,EAAE,oBAAoB,EACtC,IAAI,EAAE,KAAK,GAAG,2BAA2B,EACzC,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,eAAe,EACrB,YAAY,EAAE,SAAS,YAAY,EAAE,GACpC,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAGnC"}
|
|
@@ -1,8 +1,8 @@
|
|
|
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,
|
|
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,
|
|
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"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { DeclarativeBridgeDeclaration } from '@microverse.ts/runtime-bridge';
|
|
2
|
+
import { CapabilityId } from '@microverse.ts/runtime-capabilities';
|
|
3
|
+
import { HostSurfaceSpec } from '../../domain/hostSurfaceSpecTypes';
|
|
4
|
+
import { SchemaValidationPort } from '../../application/ports/SchemaValidationPort';
|
|
5
|
+
import { createBridgeDeclarationsFromHostSurfaceSpec } from '../../application/useCases/compileBridgeDeclarationsFromHostSurfaceSpec';
|
|
6
|
+
/**
|
|
7
|
+
* Keeps bridge declarations (and methods) whose capability is in the allow set.
|
|
8
|
+
*/
|
|
9
|
+
export declare function filterBridgeDeclarationsByCapabilities<THost, TSlotKey extends string>(declarations: readonly DeclarativeBridgeDeclaration<THost, TSlotKey>[], spec: HostSurfaceSpec, capabilities: readonly CapabilityId[]): DeclarativeBridgeDeclaration<THost, TSlotKey>[];
|
|
10
|
+
export declare function createFilteredBridgeDeclarations(schemaValidation: SchemaValidationPort, spec: HostSurfaceSpec, capabilities: readonly CapabilityId[]): ReturnType<typeof createBridgeDeclarationsFromHostSurfaceSpec>;
|
|
11
|
+
//# sourceMappingURL=filterBridgeDeclarations.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"filterBridgeDeclarations.d.ts","sourceRoot":"","sources":["../../../src/infrastructure/builders/filterBridgeDeclarations.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,+BAA+B,CAAC;AAClF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qCAAqC,CAAC;AAExE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AACzE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,8CAA8C,CAAC;AACzF,OAAO,EAAE,2CAA2C,EAAE,MAAM,yEAAyE,CAAC;AAEtI;;GAEG;AACH,wBAAgB,sCAAsC,CACpD,KAAK,EACL,QAAQ,SAAS,MAAM,EAEvB,YAAY,EAAE,SAAS,4BAA4B,CAAC,KAAK,EAAE,QAAQ,CAAC,EAAE,EACtE,IAAI,EAAE,eAAe,EACrB,YAAY,EAAE,SAAS,YAAY,EAAE,GACpC,4BAA4B,CAAC,KAAK,EAAE,QAAQ,CAAC,EAAE,CA+BjD;AAED,wBAAgB,gCAAgC,CAC9C,gBAAgB,EAAE,oBAAoB,EACtC,IAAI,EAAE,eAAe,EACrB,YAAY,EAAE,SAAS,YAAY,EAAE,GACpC,UAAU,CAAC,OAAO,2CAA2C,CAAC,CAGhE"}
|