@lunora/codegen 1.0.0-alpha.32 → 1.0.0-alpha.321

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/index.d.mts +4230 -2183
  4. package/dist/index.d.ts +4230 -2183
  5. package/dist/index.mjs +1 -35
  6. package/dist/packem_shared/AGENTS_FILENAME-B6-kjzM3.mjs +1 -0
  7. package/dist/packem_shared/CAPABILITY_PROBES-brcmKenl.mjs +25 -0
  8. package/dist/packem_shared/CONTAINERS_FILENAME-dFRtAyIe.mjs +1 -0
  9. package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
  10. package/dist/packem_shared/DEFAULT_TARGET-B0FkdiZq.mjs +1 -0
  11. package/dist/packem_shared/FLAGS_FILENAME-Bf0MSlHH.mjs +1 -0
  12. package/dist/packem_shared/GENERATED_HEADER-Ck_WOHzE.mjs +1 -0
  13. package/dist/packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs +1 -0
  14. package/dist/packem_shared/MUTATORS_FILENAME-Jkk8Zgkb.mjs +1 -0
  15. package/dist/packem_shared/NOTIFY_FILENAME-bAt7J3cs.mjs +1 -0
  16. package/dist/packem_shared/OPENRPC_VERSION-CCY7xqSL.mjs +3 -0
  17. package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs +1 -0
  18. package/dist/packem_shared/QUEUES_FILENAME-CsRy4VTF.mjs +1 -0
  19. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-B6NxV9VM.mjs +11 -0
  20. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs +2 -0
  21. package/dist/packem_shared/SHAPES_FILENAME-DkBUN9dK.mjs +1 -0
  22. package/dist/packem_shared/SchemaSnapshotParseError-BRJT7c2k.mjs +18 -0
  23. package/dist/packem_shared/WORKFLOWS_FILENAME-CdeS224T.mjs +1 -0
  24. package/dist/packem_shared/attribution-hVBriwzy.mjs +1 -0
  25. package/dist/packem_shared/buildOpenApiDocument-DFv-RYZU.mjs +3 -0
  26. package/dist/packem_shared/capabilitiesUsedBy-QgSZyE0T.mjs +1 -0
  27. package/dist/packem_shared/chain-Cm6BMT8g.mjs +1 -0
  28. package/dist/packem_shared/classify-procedure-call-DVxdUhZt.mjs +1 -0
  29. package/dist/packem_shared/context-property-calls-Cn3upNgZ.mjs +1 -0
  30. package/dist/packem_shared/context-root-BdxINX-T.mjs +1 -0
  31. package/dist/packem_shared/createCodegenProject-V51_yBw3.mjs +1 -0
  32. package/dist/packem_shared/database-calls-BKozZUEW.mjs +1 -0
  33. package/dist/packem_shared/declared-output-Iaar469J.mjs +1 -0
  34. package/dist/packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs +1 -0
  35. package/dist/packem_shared/discoverAuthApiCalls-xs0ONfI-.mjs +1 -0
  36. package/dist/packem_shared/discoverCrons-DBnCama4.mjs +1 -0
  37. package/dist/packem_shared/discoverFunctions-CZgLhsMn.mjs +1 -0
  38. package/dist/packem_shared/discoverHttpRoutes-WBAqBcfK.mjs +1 -0
  39. package/dist/packem_shared/discoverHyperdriveCalls-DV4IglLE.mjs +1 -0
  40. package/dist/packem_shared/discoverInserts-BjxXCACZ.mjs +1 -0
  41. package/dist/packem_shared/discoverMaskProcedures-DE-8CDen.mjs +1 -0
  42. package/dist/packem_shared/discoverMigrations-C9mLIhGZ.mjs +1 -0
  43. package/dist/packem_shared/discoverNondeterministicCalls-DvhyKM-f.mjs +1 -0
  44. package/dist/packem_shared/discoverQueries-C8E7TeRT.mjs +1 -0
  45. package/dist/packem_shared/discoverR2sqlCalls-DVcfMO6-.mjs +1 -0
  46. package/dist/packem_shared/discoverRlsMetadata-QRsWRQbM.mjs +1 -0
  47. package/dist/packem_shared/discoverRlsProcedures-Du7ITNTQ.mjs +1 -0
  48. package/dist/packem_shared/discoverSandboxUsage-w6Q3RvxZ.mjs +1 -0
  49. package/dist/packem_shared/discoverSchema-BtsX-CN9.mjs +1 -0
  50. package/dist/packem_shared/discoverStorageRulesMetadata-ClzKLdCV.mjs +1 -0
  51. package/dist/packem_shared/dispatch-namespace-DwTjD7BU.mjs +1 -0
  52. package/dist/packem_shared/emitAgents-CR2_X_ov.mjs +1 -0
  53. package/dist/packem_shared/emitApi-CDgIPAG2.mjs +147 -0
  54. package/dist/packem_shared/emitApp-K6otnCNZ.mjs +986 -0
  55. package/dist/packem_shared/emitCrons-BQW2lviZ.mjs +96 -0
  56. package/dist/packem_shared/emitDataModel-BskFt9Wv.mjs +114 -0
  57. package/dist/packem_shared/emitDrizzleSchema-DitcRZ1a.mjs +15 -0
  58. package/dist/packem_shared/emitFunctions-CuZzKaU4.mjs +419 -0
  59. package/dist/packem_shared/emitServer-D1vA5_X1.mjs +1 -0
  60. package/dist/packem_shared/emitShard-C1aUZPCr.mjs +1 -0
  61. package/dist/packem_shared/exported-procedure-chains-BNBUkXui.mjs +1 -0
  62. package/dist/packem_shared/fingerprintSchemaSources-eVG9aVt0.mjs +1 -0
  63. package/dist/packem_shared/formatAdvisories-BCVASH7N.mjs +2 -0
  64. package/dist/packem_shared/handler-reference-vIeqkhV_.mjs +1 -0
  65. package/dist/packem_shared/index-JnqBWRYO.mjs +1 -0
  66. package/dist/packem_shared/isD1GlobalTable-udvHAAzD.mjs +1 -0
  67. package/dist/packem_shared/isTestPath-B81lOULB.mjs +1 -0
  68. package/dist/packem_shared/isTypedSchema-CKzc3ioR.mjs +4 -0
  69. package/dist/packem_shared/json-data-Chfs2Cz5.mjs +1 -0
  70. package/dist/packem_shared/loadProjectConfig-NO0dVJSl.mjs +1 -0
  71. package/dist/packem_shared/module-specifiers-WF8iAydP.mjs +1 -0
  72. package/dist/packem_shared/modules-CjOcuQnK.mjs +1 -0
  73. package/dist/packem_shared/parse-validator-IDBKIT7M.mjs +1 -0
  74. package/dist/packem_shared/platform-8oj7iXQy.mjs +1 -0
  75. package/dist/packem_shared/project-config-file-BV7RR-l6.mjs +1 -0
  76. package/dist/packem_shared/qualifiers-DEdXn5wP.mjs +1 -0
  77. package/dist/packem_shared/readPackageDependencies-RHhGiz0k.mjs +1 -0
  78. package/dist/packem_shared/readServiceBindings-DvqIThzd.mjs +1 -0
  79. package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
  80. package/dist/packem_shared/reserved-words-CW1QFbTd.mjs +1 -0
  81. package/dist/packem_shared/schema-BgM8A3XV.mjs +1 -0
  82. package/dist/packem_shared/schemaFromIr-BWFnvCVg.mjs +1 -0
  83. package/dist/packem_shared/server-DAvi_bv_.mjs +368 -0
  84. package/dist/packem_shared/shard-CtYnaXAX.mjs +1601 -0
  85. package/dist/packem_shared/shard-runtime-BpoCV-aM.mjs +331 -0
  86. package/dist/packem_shared/shared-DnCokNcE.mjs +13 -0
  87. package/dist/packem_shared/unwrap-handler-return-CeaOifqX.mjs +1 -0
  88. package/dist/sdk/index.d.mts +288 -0
  89. package/dist/sdk/index.d.ts +288 -0
  90. package/dist/sdk/index.mjs +372 -0
  91. package/package.json +21 -8
  92. package/dist/packem_shared/CONTAINERS_FILENAME-DjpXMqhp.mjs +0 -224
  93. package/dist/packem_shared/CodegenDiagnosticError-DyQ5FwkM.mjs +0 -24
  94. package/dist/packem_shared/FLAGS_FILENAME-BjpS5w08.mjs +0 -139
  95. package/dist/packem_shared/GENERATED_HEADER-CLwPlCQe.mjs +0 -3
  96. package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
  97. package/dist/packem_shared/MUTATORS_FILENAME-BZOfUhlY.mjs +0 -81
  98. package/dist/packem_shared/OPENRPC_VERSION-4YIeMkOI.mjs +0 -60
  99. package/dist/packem_shared/QUEUES_FILENAME-BF0iUmx7.mjs +0 -119
  100. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-OBXQBJV0.mjs +0 -3520
  101. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-D0ARY6rL.mjs +0 -249
  102. package/dist/packem_shared/SHAPES_FILENAME-DOhPGi-6.mjs +0 -94
  103. package/dist/packem_shared/WORKFLOWS_FILENAME-CCC_42o3.mjs +0 -124
  104. package/dist/packem_shared/buildOpenApiDocument-bp1pYSV6.mjs +0 -183
  105. package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
  106. package/dist/packem_shared/discoverAuthApiCalls-URDoTADN.mjs +0 -62
  107. package/dist/packem_shared/discoverCrons-DdZOeroL.mjs +0 -257
  108. package/dist/packem_shared/discoverFunctions-BJdF7lRs.mjs +0 -514
  109. package/dist/packem_shared/discoverHttpRoutes-CcwP-Rkr.mjs +0 -131
  110. package/dist/packem_shared/discoverInserts-BpFhM32L.mjs +0 -61
  111. package/dist/packem_shared/discoverMaskProcedures-DT-v8wvj.mjs +0 -273
  112. package/dist/packem_shared/discoverMigrations-cG1idBVM.mjs +0 -97
  113. package/dist/packem_shared/discoverNondeterministicCalls-CEOjmfk4.mjs +0 -122
  114. package/dist/packem_shared/discoverQueries-DeVBQVAG.mjs +0 -62
  115. package/dist/packem_shared/discoverR2sqlCalls-CWCAU-xJ.mjs +0 -80
  116. package/dist/packem_shared/discoverRlsMetadata-BL0oukaK.mjs +0 -280
  117. package/dist/packem_shared/discoverSchema-CeXJWVKV.mjs +0 -874
  118. package/dist/packem_shared/discoverStorageRulesMetadata-CFHByjIl.mjs +0 -97
  119. package/dist/packem_shared/emit-CBwEvCXQ.mjs +0 -3451
  120. package/dist/packem_shared/emitApp-nQ2oC-8G.mjs +0 -668
  121. package/dist/packem_shared/formatAdvisories-C9wNBNvL.mjs +0 -113
  122. package/dist/packem_shared/parse-validator-D6zI2i85.mjs +0 -134
  123. package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
  124. package/dist/packem_shared/redact-oTmsol5A.mjs +0 -33
  125. package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
@@ -0,0 +1,96 @@
1
+ import{G as i,d as c}from"./shared-DnCokNcE.mjs";import{i as m}from"./schema-BgM8A3XV.mjs";const u=r=>r?`${i}/**
2
+ * The \`SchedulerDO\` Durable Object class, re-exported so a worker entry can
3
+ * forward it — wrangler binds only what the entry exports:
4
+ *
5
+ * \`export * from "./lunora/_generated/scheduler.js";\`
6
+ *
7
+ * A Vite-first (class-A) app needs no such line: the generated worker entry
8
+ * forwards this module for you whenever it exists.
9
+ */
10
+ export { SchedulerDO } from "@lunora/scheduler";
11
+ `:"",y=(r,t)=>r.some(o=>m(o))?`${i}/**
12
+ * The \`ShardRegistryDO\` Durable Object class — the live set of shard keys per
13
+ * \`.shardBy()\` table, which cross-shard export, CDC sync and migrations fan out
14
+ * to. Re-exported so a worker entry can forward it (wrangler binds only what the
15
+ * entry exports), next to \`.shardRegistry((env) => env.SHARD_REGISTRY)\`:
16
+ *
17
+ * \`export { ShardRegistryDO } from "./lunora/_generated/shardRegistry.js";\`
18
+ *
19
+ * Name the class in a hand-written entry: binding inference provisions
20
+ * \`SHARD_REGISTRY\` off the entry's named exports, and cannot see through an
21
+ * \`export *\`. A Vite-first (class-A) app needs neither line — its generated
22
+ * worker entry does both whenever this module exists.
23
+ */
24
+ export { ShardRegistryDO } from "${c(t).do}";
25
+ `:"",w=r=>`${i}/**
26
+ * Host the shard, the scheduler and the shard registry in ONE Durable Object
27
+ * class, so the app spends one of the account's classes instead of three. A
28
+ * Vite-first (class-A) app needs nothing more: its generated worker entry builds
29
+ * \`LunoraDO\` from these. A hand-written entry does the same by hand:
30
+ *
31
+ * \`export const LunoraDO = mergeDurableObjects({ shard: app.ShardDO, scheduler: SchedulerDO, shardRegistry: ShardRegistryDO });\`
32
+ *
33
+ * and passes \`roleNamespace(env.SHARD, "scheduler")\` / \`roleNamespace(env.SHARD, "shardRegistry")\`
34
+ * to \`.scheduler()\` / \`.shardRegistry()\`. Merge before the first deploy only:
35
+ * data already in \`ShardDO\` does not move, and a deployed merge cannot be undone.
36
+ */
37
+ export { mergeDurableObjects, roleNamespace } from "${c(r).do}";
38
+ `,O=r=>{const t=new Map;for(const n of r){const d=t.get(n.cron);d?d.push(n):t.set(n.cron,[n])}const o=[...t.keys()].map(n=>` ${JSON.stringify(n)},`).join(`
39
+ `),e=o.length>0?`
40
+ ${o}
41
+ `:"",s=[...t.entries()].map(([n,d])=>{const l=d.map(a=>{const f=a.workflow?`workflow: ${JSON.stringify(a.workflow.className)}`:`functionPath: ${JSON.stringify(a.functionPath)}`;return` { name: ${JSON.stringify(a.name)}, ${f}, args: ${JSON.stringify(a.args)} },`}).join(`
42
+ `);return` ${JSON.stringify(n)}: [
43
+ ${l}
44
+ ],`}).join(`
45
+ `),h=s.length>0?`
46
+ ${s}
47
+ `:"";return`${i}/**
48
+ * One scheduled cron invocation. Exactly one target is set: \`functionPath\` is
49
+ * the \`namespace:fn\` dispatch ref (matches \`__lunoraRef\`), invoked on the
50
+ * shard; \`workflow\` is a workflow class name (its \`ctx.exports\` key) whose durable workflow is
51
+ * started fresh per fire. \`args\` are forwarded verbatim (a workflow's become
52
+ * its \`params\`).
53
+ */
54
+ export interface LunoraCronJob {
55
+ args: Record<string, unknown>;
56
+ functionPath?: string;
57
+ name: string;
58
+ workflow?: string;
59
+ }
60
+
61
+ /**
62
+ * Deduplicated cron schedules — mirror of wrangler's \`triggers.crons\`. The
63
+ * Lunora vite plugin keeps \`wrangler.jsonc\` in sync with this array.
64
+ */
65
+ export const LUNORA_CRON_TRIGGERS: ReadonlyArray<string> = [${e}];
66
+
67
+ /**
68
+ * Dispatcher map keyed by cron expression. The Worker's \`scheduled()\` handler
69
+ * looks up \`event.cron\` here and dispatches every job in the list.
70
+ */
71
+ export const LUNORA_CRONS: Record<string, ReadonlyArray<LunoraCronJob>> = {${h}};
72
+ `},S=r=>{const t=[...r].toSorted((e,s)=>e.name.localeCompare(s.name)).map(e=>{const s=[`name: ${JSON.stringify(e.name)}`,`table: ${JSON.stringify(e.table)}`];return e.field!==void 0&&s.push(`field: ${JSON.stringify(e.field)}`),e.dimensions!==void 0&&s.push(`dimensions: ${JSON.stringify(e.dimensions)}`),e.metric!==void 0&&s.push(`metric: ${JSON.stringify(e.metric)}`),e.metadata!==void 0&&s.push(`metadata: ${JSON.stringify(e.metadata)}`),` { ${s.join(", ")} },`}).join(`
73
+ `),o=t.length>0?`
74
+ ${t}
75
+ `:"";return`${i}/**
76
+ * One vector index declared in \`schema.ts\` — an inline \`.vectorize()\` column
77
+ * or a standalone \`defineVectorIndex()\`. \`field\` is the source column (absent
78
+ * for a \`select\`-derived Shape B index); \`metadata\` lists the row fields
79
+ * mirrored into Vectorize for filtering.
80
+ */
81
+ export interface LunoraVectorIndex {
82
+ dimensions?: number;
83
+ field?: string;
84
+ metadata?: ReadonlyArray<string>;
85
+ metric?: "cosine" | "dot-product" | "euclidean";
86
+ name: string;
87
+ table: string;
88
+ }
89
+
90
+ /**
91
+ * Static registry of every vector index in the schema, sorted by name.
92
+ * Vectorize cannot enumerate indexes at runtime, so the worker passes this to
93
+ * \`createWorker({ vectorIntrospector })\` to back the studio's vector browser.
94
+ */
95
+ export const LUNORA_VECTOR_INDEXES: ReadonlyArray<LunoraVectorIndex> = [${o}];
96
+ `},b=r=>[...new Set(r.map(t=>t.cron))];export{O as emitCrons,w as emitDurableObjects,u as emitScheduler,y as emitShardRegistry,S as emitVectors,b as emitWranglerCronTriggers};
@@ -0,0 +1,114 @@
1
+ import{r as k}from"./qualifiers-DEdXn5wP.mjs";import{a as i,e as o,v as d,f as v,G as M}from"./shared-DnCokNcE.mjs";const _="schema",w=a=>{for(const e of a.tables)i(e.name,"table name");const l=a.tables.map(e=>`"${e.name}"`).join(" | ")||"never",m=a.tables.filter(e=>e.extensionKey===void 0).map(e=>`"${e.name}"`).join(" | ")||"never",p=a.tables.map(e=>{const t=Object.entries(e.shape).map(([g,r])=>{const s=o(g);if(r.kind==="optional"){const h=r.inner?d(r.inner):"unknown";return` ${s}?: ${h};`}return` ${s}: ${d(r)};`}).join(`
2
+ `),n=t?`
3
+ ${t}
4
+ `:"",N=e.commitOrdered===!0?`
5
+ _commitSeq: number;`:"";return`export interface Doc_${e.name} {
6
+ _id: Id<"${e.name}">;
7
+ _creationTime: number;${N}${n}}`}).join(`
8
+
9
+ `),c=a.tables.map(e=>` ${e.name}: Doc_${e.name};`).join(`
10
+ `),y=a.tables.map(e=>{const t=e.indexes.map(n=>JSON.stringify(n.name)).join(" | ");return` ${e.name}: ${t||"never"};`}).join(`
11
+ `),x=a.tables.map(e=>{const t=e.searchIndexes.map(n=>JSON.stringify(n.name)).join(" | ");return` ${e.name}: ${t||"never"};`}).join(`
12
+ `),b=a.tables.map(e=>{const t=e.rankIndexes.map(n=>JSON.stringify(n.name)).join(" | ");return` ${e.name}: ${t||"never"};`}).join(`
13
+ `),f=a.tables.map(e=>{const t=e.shardMode==="global"?"":(e.geoIndexes??[]).map(n=>JSON.stringify(n.name)).join(" | ");return` ${e.name}: ${t||"never"};`}).join(`
14
+ `),T=a.vectorIndexes.map(e=>JSON.stringify(e.name)).join(" | ")||"never",$=a.tables.map(e=>v(e)).join(`
15
+
16
+ `),u=a.tables.map(e=>` ${e.name}: Insert_${e.name};`).join(`
17
+ `),I=a.tables.map(e=>{const t=e.relations.map(n=>(i(n.table,"relation target table"),n.kind==="one"?` ${o(n.name)}: OneRelation<"${n.table}", ${JSON.stringify(n.field)}>;`:` ${o(n.name)}: ManyRelation<"${n.table}">;`)).join(`
18
+ `);return t?` ${e.name}: {
19
+ ${t}
20
+ };`:` ${e.name}: {};`}).join(`
21
+ `);return k(`${M}export type TableName = ${l};
22
+
23
+ /**
24
+ * The tables **this app declared** — every {@link TableName} except those an add-on
25
+ * contributed through \`defineSchema(...).extend(...)\`.
26
+ *
27
+ * An add-on's tables are real tables and stay in \`TableName\` (they are queryable,
28
+ * they appear in \`DataModel\`), but an app enumerating "my tables" should not have to
29
+ * know they exist: an account-deletion sweep, an export, a migration allowlist, or a
30
+ * helper generic over a table union is about the app's own data, and every add-on
31
+ * added or removed would otherwise silently change the correct answer.
32
+ *
33
+ * \`\`\`ts
34
+ * // Doesn't need to mention \`ratelimit_buckets\`, and won't drift when an add-on lands.
35
+ * const EXPORTED: readonly AppTableName[] = ["nodes", "tagColors"];
36
+ * \`\`\`
37
+ */
38
+ export type AppTableName = ${m};
39
+
40
+ export type Id<TName extends string> = string & { readonly __table: TName };
41
+
42
+ ${p}
43
+
44
+ export interface DataModel {
45
+ ${c}
46
+ }
47
+
48
+ export type Doc<T extends keyof DataModel> = DataModel[T];
49
+
50
+ /**
51
+ * Per-table index name union. \`never\` for tables without secondary indexes.
52
+ * Used by \`TableReader.withIndex()\` to constrain callers to declared names.
53
+ */
54
+ export interface IndexNamesByTable {
55
+ ${y}
56
+ }
57
+
58
+ export type IndexName<T extends keyof DataModel> = IndexNamesByTable[T];
59
+
60
+ /** Per-table search-index name union. \`never\` for tables without searchIndex. */
61
+ export interface SearchIndexNamesByTable {
62
+ ${x}
63
+ }
64
+
65
+ export type SearchIndexName<T extends keyof DataModel> = SearchIndexNamesByTable[T];
66
+
67
+ /** Per-table rank-index name union. \`never\` for tables without a rankIndex. */
68
+ export interface RankIndexNamesByTable {
69
+ ${b}
70
+ }
71
+
72
+ export type RankIndexName<T extends keyof DataModel> = RankIndexNamesByTable[T];
73
+
74
+ /** Per-table geo-index name union. \`never\` for tables without a geoIndex. */
75
+ export interface GeoIndexNamesByTable {
76
+ ${f}
77
+ }
78
+
79
+ export type GeoIndexName<T extends keyof DataModel> = GeoIndexNamesByTable[T];
80
+
81
+ /** Union of declared vector index names. \`never\` when none are declared. */
82
+ export type VectorIndexName = ${T};
83
+
84
+ ${$}
85
+
86
+ /** Per-table insert shape, accepted by \`ctx.db.<table>.insert(...)\`. */
87
+ export interface InsertModel {
88
+ ${u}
89
+ }
90
+
91
+ export type Insert<T extends keyof DataModel> = InsertModel[T];
92
+
93
+ /**
94
+ * Phantom relation descriptors. They carry the relation kind and target table
95
+ * as type parameters only — there is no runtime value — so the \`with\` argument
96
+ * and its return type can be inferred from {@link Relations}.
97
+ */
98
+ export interface OneRelation<Target extends keyof DataModel, Field extends string> {
99
+ readonly __field: Field;
100
+ readonly __relationKind: "one";
101
+ readonly __target: Target;
102
+ }
103
+
104
+ export interface ManyRelation<Target extends keyof DataModel> {
105
+ readonly __relationKind: "many";
106
+ readonly __target: Target;
107
+ }
108
+
109
+ /** Per-table relation map keyed by accessor name. \`{}\` for tables with none. */
110
+ export interface Relations {
111
+ ${I}
112
+ }
113
+
114
+ `,_)};export{_ as SCHEMA_MODULE_PATH,w as emitDataModel};
@@ -0,0 +1,15 @@
1
+ import{SCHEMA_MODULE_PATH as c}from"./emitDataModel-BskFt9Wv.mjs";import{r as m}from"./qualifiers-DEdXn5wP.mjs";import{G as b,a as z,d as T,v as f,u as A,g as x,c as h}from"./shared-DnCokNcE.mjs";const d=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:f(e)};case"bigint":return{builder:"blob",mode:"bigint",notNull:!0};case"boolean":return{builder:"integer",mode:"boolean",notNull:!0};case"bytes":return{builder:"blob",mode:"buffer",notNull:!0};case"date":case"timestamp":return{builder:"integer",notNull:!0};case"from":return{builder:"text",notNull:!0,typeAnnotation:f(e)};case"id":return{builder:"text",notNull:!0};case"literal":{const t=e.literalValue??"";return t.startsWith('"')||t.startsWith("'")?{builder:"text",notNull:!0}:t==="true"||t==="false"?{builder:"integer",mode:"boolean",notNull:!0}:t==="null"?{builder:"text",notNull:!0}:{builder:"real",notNull:!0}}case"null":return{builder:"text",notNull:!0};case"number":return{builder:"real",notNull:!0};case"optional":return{...e.inner?d(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},N=(e,t)=>{const r=A(e);return r.kind==="id"&&r.tableName!==void 0&&t.has(r.tableName)?r.tableName:void 0},j=(e,t,r)=>{x(e,"drizzle column name");const n=d(t),o=n.mode?`, { mode: "${n.mode}" }`:"";let l=`${n.builder}("${e}"${o})`;n.typeAnnotation&&(l+=`.$type<${n.typeAnnotation}>()`);const s=N(t,r);return s!==void 0&&(l+=`.references((): AnySQLiteColumn => ${s}._id)`),n.notNull&&t.column?.notNull!==!1&&(l+=".notNull()"),l},I=e=>{const t=e.unique?"uniqueIndex":"index",r=e.fields.map(n=>(x(n,"drizzle index field"),`t.${n}`)).join(", ");return` ${h(e.name)}: ${t}(${JSON.stringify(e.name)}).on(${r}),`},S=(e,t)=>{z(e.name,"table name");const r=[' _id: text("_id").primaryKey(),',' _creationTime: integer("_creationTime").notNull(),',...Object.entries(e.shape).map(([o,l])=>` ${o}: ${j(o,l,t)},`)].join(`
2
+ `),n=e.indexes.length>0?`, (t) => ({
3
+ ${e.indexes.map(o=>I(o)).join(`
4
+ `)}
5
+ })`:"";return`export const ${e.name} = sqliteTable("${e.name}", {
6
+ ${r}
7
+ }${n});`},C=e=>e.typeAnnotation?.includes('Id<"')??!1,D=(e,t)=>{const r=new Set(["integer","sqliteTable","text"]),n=new Set;let o=!1,l=!1;for(const s of e){for(const i of Object.values(s.shape)){const a=d(i);r.add(a.builder),l=l||C(a),o=o||N(i,t)!==void 0}for(const i of s.indexes)n.add(i.unique?"uniqueIndex":"index")}return{columns:[...r].toSorted((s,i)=>s.localeCompare(i)),indexes:[...n].toSorted((s,i)=>s.localeCompare(i)),needsAnyColumn:o,needsId:l}},p=(e,t=!1)=>{if(e.length===0)return`${b}export {};
8
+ `;const r=T(t),n=new Set(e.map(u=>u.name)),{columns:o,indexes:l,needsAnyColumn:s,needsId:i}=D(e,n),a=[...l,...o].toSorted((u,g)=>u.localeCompare(g)),$=e.map(u=>S(u,n)).join(`
9
+
10
+ `),y=[s?`import type { AnySQLiteColumn } from "${r.serverDrizzle}";
11
+ `:"",i?`import type { Id } from "./dataModel.js";
12
+ `:""].join("");return`${b}import { ${a.join(", ")} } from "${r.serverDrizzle}";
13
+ ${y}
14
+ ${$}
15
+ `},v=(e,t=!1)=>{const r=e.tables.filter(o=>o.shardMode==="global"),n=e.tables.filter(o=>o.shardMode!=="global");return{global:m(p(r,t),c),shard:m(p(n,t),c)}};export{v as default};
@@ -0,0 +1,419 @@
1
+ import{LunoraError as P}from"@lunora/errors";import{L as oe,G as C,d as j,I as F,b as M,r as se,c as ae}from"./shared-DnCokNcE.mjs";import{renderAgentFunctionRegistry as ie,renderSandboxFunctionRegistry as ce}from"./emitApi-CDgIPAG2.mjs";import{b as le,a as de,r as _,c as ue}from"./qualifiers-DEdXn5wP.mjs";import{s as f}from"./dispatch-namespace-DwTjD7BU.mjs";const he=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),D=r=>r.column!==void 0,me=(r,t)=>{switch(r){case"bigint":return`if (typeof ${t} !== "bigint") return DEFER;
2
+ `;case"boolean":return`if (typeof ${t} !== "boolean") return DEFER;
3
+ `;case"date":case"number":case"timestamp":return`if (typeof ${t} !== "number" || !Number.isFinite(${t})) return DEFER;
4
+ `;case"null":return`if (${t} !== null) return DEFER;
5
+ `;default:return`if (typeof ${t} !== "string") return DEFER;
6
+ `}},pe=(r,t)=>r.stringMaxLength===void 0?"":`if (${t}.length > ${String(r.stringMaxLength)}) return DEFER;
7
+ `,ge=(r,t)=>{const n=r.literalValue?.trim();if(!(n===void 0||!oe.test(n)))return{out:t,pre:`if (${t} !== ${n}) return DEFER;
8
+ `}},T=(r,t,n)=>{if(!D(r)&&!(r.unmodelledRefinement||r.sourceText!==void 0)){if(he.has(r.kind))return r.kind==="any"?{out:t,pre:""}:{out:t,pre:me(r.kind,t)+pe(r,t)};switch(r.kind){case"array":return fe(r,t,n);case"literal":return ge(r,t);case"object":return we(r,t,n);default:return}}},fe=(r,t,n)=>{const{inner:o}=r;if(!o)return;const a=n.next(),i=`__arr${String(a)}`,s=`__i${String(a)}`,d=`__e${String(a)}`,u=T(o,d,n);if(!u)return;const c=`if (!Array.isArray(${t})) return DEFER;
9
+ const ${i} = new Array(${t}.length);
10
+ for (let ${s} = 0; ${s} < ${t}.length; ${s}++) {
11
+ const ${d} = ${t}[${s}];
12
+ ${u.pre}${i}[${s}] = ${u.out};
13
+ }
14
+ `;return{out:i,pre:c}},ye=(r,t,n,o)=>{const a=JSON.stringify(r);if(t.kind==="optional"){if(t.hasRefinement||t.sourceText!==void 0||D(t))return;const{inner:s}=t;if(!s)return;const d=T(s,n,o);if(!d)return;const u=o.next(),c=`__has${String(u)}`,l=`__val${String(u)}`,g=`let ${c} = false;
15
+ let ${l};
16
+ if (${n} !== undefined) {
17
+ ${d.pre}${l} = ${d.out};
18
+ ${c} = true;
19
+ }
20
+ `;return{entry:`...(${c} ? { ${a}: ${l} } : {})`,pre:g}}const i=T(t,n,o);if(i)return{entry:`${a}: ${i.out}`,pre:i.pre}},$e=new Set(Object.getOwnPropertyNames(Object.prototype)),U=(r,t,n)=>{let o="";const a=[];for(const i of Object.keys(r)){const s=r[i];if(!s)return;const d=JSON.stringify(i);let u=`${t}[${d}]`;if($e.has(i)){const l=`__f${String(n.next())}`;o+=`const ${l} = Object.hasOwn(${t}, ${d}) ? ${t}[${d}] : undefined;
21
+ `,u=l}const c=ye(i,s,u,n);if(!c)return;o+=c.pre,a.push(c.entry)}return{entries:a.join(", "),pre:o}},J=r=>{const t=`Object.getPrototypeOf(${r})`;return`if (${t} !== Object.prototype && ${t} !== null) return DEFER;
22
+ `},we=(r,t,n)=>{const o=r.shape??{},a=U(o,t,n);if(!a)return;const i=n.next(),s=`__obj${String(i)}`,d=`if (typeof ${t} !== "object" || ${t} === null || Array.isArray(${t})) return DEFER;
23
+ ${J(t)}${a.pre}const ${s} = { ${a.entries} };
24
+ `;return{out:s,pre:d}},B=r=>{let t=0;const o=U(r,"source",{next:()=>(t+=1,t)});if(o)return`(source) => {
25
+ if (typeof source !== "object" || source === null || Array.isArray(source)) return DEFER;
26
+ ${J("source")}${o.pre}return { ${o.entries} };
27
+ }`},Re=(r,t)=>`lunora_${f(r)}_${String(t)}`,I=r=>JSON.stringify(Object.entries(r).toSorted(([t],[n])=>t.localeCompare(n)).map(([t,n])=>{const o=n.kind==="optional",a=o?n.inner??{kind:"unknown"}:n,i=a.kind==="array"?a.inner?.kind:void 0,s=a.kind==="id"?a.tableName:void 0;return{kind:a.kind,name:t,optional:o,...s===void 0?{}:{table:s},...i===void 0||i==="unknown"?{}:{element:i}}})),H=(r,t,n,o)=>{const a=new Map,i=s=>{a.has(s)||a.set(s,Re(s,a.size))};for(const s of r)i(s.filePath);for(const s of t)i(s.filePath);for(const s of n)i(s.filePath);for(const s of o)i(s.filePath);return a},q=(r,t,n)=>new Set([...r.map(o=>o.filePath),...t.map(o=>o.filePath),...n.map(o=>o.filePath)]),k=r=>`${r}[functionPath]`,be=`const callRegistered = async <R>(context: CallerCtx, functionPath: string, args: Record<string, unknown> | undefined): Promise<R> => {
28
+ const registered = await loadFunction(functionPath);
29
+
30
+ if (!registered) {
31
+ throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
32
+ }
33
+
34
+ // A mutation is routed through the caller's own \`ctx.runMutation\` rather than
35
+ // invoked directly, so \`createCaller(ctx).ns.someMutation()\` gets exactly what
36
+ // \`ctx.runMutation(api.ns.someMutation)\` gets: the BEGIN/COMMIT span (or the
37
+ // enclosing one, when the caller is already inside a transaction), the jobs it
38
+ // schedules held until that span commits, and the deferred object deletes
39
+ // flushed only once it has. Called straight, a mutation composed from an action
40
+ // or a stream had none of the three — its writes autocommitted one row at a
41
+ // time and its \`ctx.scheduler\` calls dispatched immediately, so a mid-handler
42
+ // throw left the earlier writes durable and the job already enqueued.
43
+ //
44
+ // The fallback covers a context that is not a shard dispatch (\`runMutation\` is
45
+ // installed by \`buildCtx\` on every kind but a query's TYPE omits it); there is
46
+ // no transaction to join in that case, so a direct call is all there is.
47
+ //
48
+ // A query is routed through \`ctx.runQuery\` for the same reason: that is what
49
+ // hands it a query view of a mutation's or action's ctx (no request origin,
50
+ // query-guarded \`run*\`) instead of the caller's own.
51
+ if (registered.kind === "mutation" || registered.kind === "query") {
52
+ const run = (context as { runMutation?: unknown; runQuery?: unknown })[registered.kind === "mutation" ? "runMutation" : "runQuery"];
53
+
54
+ if (typeof run === "function") {
55
+ return (await run.call(context, { __lunoraRef: functionPath }, args ?? {})) as R;
56
+ }
57
+ }
58
+
59
+ return (await registered.handler(context, args ?? {})) as R;
60
+ };`,Ne=(r,t,n=[],o=[],a=!1)=>{const i=H(r,t,n,o),s=q(t,n,o),d=[...i.entries()].filter(([e])=>!a||s.has(e)?!0:r.some(m=>m.filePath===e&&m.channel?.kind==="room")).map(([e,m])=>{if(!F.test(e))throw new P("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(e)}`);return`import ${a&&!s.has(e)?"type ":""}* as ${m} from "../${e}.js";`}).join(`
61
+ `),u=r.map(e=>!a||s.has(e.filePath)?` "${f(e.filePath)}:${e.exportName}": ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredLunoraFunction,`:` "${f(e.filePath)}:${e.exportName}": { args: {}, handler: unloadedFunctionHandler, ...${JSON.stringify({argumentDescriptors:JSON.parse(I(e.args)),kind:e.kind,...e.channel?{channel:e.channel}:{},...e.expose?{expose:e.expose}:{},...e.lifecycle?{lifecycle:e.lifecycle}:{},...e.visibility?{visibility:e.visibility}:{},...e.x402?.price===void 0?{}:{x402:{price:e.x402.price}}})} } satisfies RegisteredLunoraFunction & Pick<FunctionManifestEntry, "argumentDescriptors" | "channel" | "expose">,`).join(`
62
+ `),c=t.map(e=>` ${JSON.stringify(e.id)}: ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredDataMigration,`).join(`
63
+ `),l=n.map(e=>` "${f(e.filePath)}:${e.exportName}": ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredLunoraFunction,`).join(`
64
+ `),g=o.map(e=>` "${e.exportName}": ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredShape,`).join(`
65
+ `),y=n.map(e=>`${f(e.filePath)}:${e.exportName}`),$=[u,l].filter(e=>e.length>0).join(`
66
+ `),v=r.filter(e=>!a||s.has(e.filePath)).map(e=>{if(e.lifecycle||Object.keys(e.args).length===0)return;const m=B(e.args);return m===void 0?void 0:`installCompiledValidatorMap(${i.get(e.filePath)??""}.${e.exportName}.args, ${m});`}).filter(e=>e!==void 0).join(`
67
+ `),O=r.filter(e=>e.channel?.kind==="room").map(e=>` ${JSON.stringify(e.channel?.name??"")}: RoomMessageOf<typeof ${i.get(e.filePath)??""}[${JSON.stringify(e.exportName)}]>;`).join(`
68
+ `),b=[...r.map(e=>({args:e.args,definition:e,path:`${f(e.filePath)}:${e.exportName}`})),...n.map(e=>({args:e.args,definition:{...e,expose:void 0,kind:"mutation",lifecycle:void 0,visibility:void 0,x402:void 0},path:`${f(e.filePath)}:${e.exportName}`}))],x=a?b.filter(({definition:e})=>!s.has(e.filePath)):[];for(const{definition:e}of b)if(a&&e.x402&&e.x402.price===void 0)throw new P("INTERNAL",`@lunora/codegen: lazy function registry needs a literal \`.x402({ price })\` value in ${e.filePath}:${e.exportName}`);const N=a?x.map(({definition:e,path:m})=>{const R=i.get(e.filePath)??"",S="channel"in e?e.channel:void 0,A={argumentDescriptors:JSON.parse(I(e.args)),exportName:e.exportName,kind:e.kind,moduleId:R,...S?{channel:S}:{},...e.expose?{expose:e.expose}:{},...e.lifecycle?{lifecycle:e.lifecycle}:{},...e.visibility?{visibility:e.visibility}:{},...e.x402?.price===void 0?{}:{x402:{price:e.x402.price}}};return` ${JSON.stringify(m)}: ${JSON.stringify(A)},`}).join(`
69
+ `):"",h=[...new Set(x.map(({definition:e})=>e.filePath))],w=a?h.map(e=>{if(!F.test(e))throw new P("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(e)}`);const m=i.get(e)??"";return` ${JSON.stringify(m)}: () => import(${JSON.stringify(`./fn/${m}.js`)}),`}).join(`
70
+ `):"";return{dispatchBody:$.length>0?`
71
+ ${$}
72
+ `:"",importBlock:d.length>0?`${d}
73
+
74
+ `:"",installBlock:v,manifestBody:N.length>0?`
75
+ ${N}
76
+ `:"",migrationBody:c.length>0?`
77
+ ${c}
78
+ `:"",moduleLoaders:w.length>0?`
79
+ ${w}
80
+ `:"",mutatorPaths:y,roomMessagesBody:O,shapeBody:g.length>0?`
81
+ ${g}
82
+ `:""}},ke=r=>{const t=M(r,o=>{const a=_(se(o.args),o.filePath),i=a==="{}"?"?":"",s=_(ue(o),o.filePath);return o.kind==="stream"?`${o.exportName}: (args${i}: ${a}) => Promise<AsyncIterable<${s}>>;`:`${o.exportName}: (args${i}: ${a}) => Promise<${s}>;`},"type");return{implementation:M(r,o=>`${ae(o.exportName)}: (args) => callRegistered(context, "${f(o.filePath)}:${o.exportName}", args),`,"value"),types:t}},ve=r=>{const t={connect:[],disconnect:[],init:[],reactor:[],whisper:[]};for(const n of r)n.lifecycle&&t[n.lifecycle].push(`${f(n.filePath)}:${n.exportName}`);return t},Oe=(r,t,n)=>r?{channelField:` /**
83
+ * Set on a \`defineRoom\` registration: the room's name (without the \`room:\`
84
+ * topic prefix). The generated \`LUNORA_ROOMS\` map keys it on the room's
85
+ * \`room:<name>\` whisper topic so the ShardDO resolves a room topic to this
86
+ * path.
87
+ */
88
+ channel?: { readonly kind: "room"; readonly name: string };
89
+ `,messagesBlock:`
90
+ /**
91
+ * The message type each \`defineRoom\` carries, read off the room's own registration. The generated \`rooms\` references type a client's \`connectRoom\` from it.
92
+ */
93
+ export type LunoraRoomMessages = {
94
+ ${n}
95
+ };
96
+ `,typeImport:`import type { RoomMessageOf } from "${t}";
97
+ `}:{channelField:"",messagesBlock:"",typeImport:""},xe=(r,t,n)=>r?t?`
98
+ /**
99
+ * Room routes are static metadata so building the worker never evaluates user handlers.
100
+ */
101
+ export const LUNORA_ROOMS: Readonly<Record<string, string>> = (() => {
102
+ const registry: Record<string, string> = {};
103
+ const owners = new Map<string, string>();
104
+
105
+ for (const { owner, path, topic } of [
106
+ ${n.filter(o=>o.channel?.kind==="room").map(o=>` { owner: ${JSON.stringify(o.filePath)}, path: ${JSON.stringify(`${f(o.filePath)}:${o.exportName}`)}, topic: ${JSON.stringify(`room:${o.channel?.name??""}`)} },`).join(`
107
+ `)}
108
+ ]) {
109
+ const prior = owners.get(topic);
110
+
111
+ if (prior !== undefined && prior !== owner) {
112
+ throw new Error(\`two defineRoom registrations are named "\${topic.slice("room:".length)}"; room names must be unique\`);
113
+ }
114
+
115
+ if (prior === undefined) {
116
+ owners.set(topic, owner);
117
+ registry[topic] = path;
118
+ }
119
+ }
120
+
121
+ return registry;
122
+ })();
123
+ `:`
124
+ /**
125
+ * Room registry: the whisper topic of each \`defineRoom\` registration → its
126
+ * function path. The generated ShardDO's \`roomHandlerPath\` override resolves a
127
+ * room topic through this map so a room's typed \`onJoin\`/\`onMessage\`/\`onLeave\`
128
+ * dispatch server-side, reusing the whisper channel for membership and fan-out.
129
+ * Two registrations under one name throw at module load: the map would otherwise
130
+ * silently keep whichever came last.
131
+ */
132
+ export const LUNORA_ROOMS: Readonly<Record<string, string>> = (() => {
133
+ const registry: Record<string, string> = {};
134
+ const owners = new Map<string, unknown>();
135
+
136
+ for (const [path, fn] of Object.entries(LUNORA_FUNCTIONS)) {
137
+ if (fn.channel?.kind !== "room") {
138
+ continue;
139
+ }
140
+
141
+ const topic = \`room:\${fn.channel.name}\`;
142
+ const owner = owners.get(topic);
143
+
144
+ // The same registration exported under two names (an alias) is one room.
145
+ if (owner !== undefined && owner !== fn) {
146
+ throw new Error(\`two defineRoom registrations are named "\${fn.channel.name}"; room names must be unique\`);
147
+ }
148
+
149
+ if (owner === undefined) {
150
+ owners.set(topic, fn);
151
+ registry[topic] = path;
152
+ }
153
+ }
154
+
155
+ return registry;
156
+ })();
157
+ `:"",Se=(r,t)=>{const n=ke(r),o=n.types?`
158
+ ${n.types}
159
+ `:"",a=n.implementation?`
160
+ ${n.implementation}
161
+ `:"",i=de(n.types),s=i.length>0?`import type { ${i.join(", ")} } from "./dataModel.js";
162
+ `:"",d=r.length>0?"context":"_context";let u="";if(r.length>0){let c=be;t||(c=c.replace("await loadFunction(functionPath)",k("LUNORA_FUNCTIONS"))),u=`${c}
163
+
164
+ `}return{callRegisteredHelper:u,dataModelImport:s,implementation:a,parameter:d,types:o}},Ee=r=>{const{agents:t=[],functions:n,lazyFunctions:o=!1,migrations:a=[],mutators:i=[],shapes:s=[],useUmbrella:d=!1,usesSandbox:u=!1}=r,c=j(d),{dispatchBody:l,importBlock:g,installBlock:y,manifestBody:$,migrationBody:v,moduleLoaders:O,mutatorPaths:b,roomMessagesBody:x,shapeBody:N}=Ne(n,a,i,s,o),h=ie(t,n),w=ce(u,n),e=[h.lines,w.lines].filter(p=>p.length>0).join(`
165
+ `);let m=l;e.length>0&&(m=l.length>0?`${l.trimEnd()}
166
+ ${e}
167
+ `:`
168
+ ${e}
169
+ `);const R=ve(n),S=o?"await loadFunction(functionPath)":k("LUNORA_FUNCTIONS"),A=o?` if (${k("LUNORA_FUNCTION_MANIFEST")}?.visibility === "internal") {
170
+ throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
171
+ }
172
+
173
+ `:"",z=s.length>0?`import type { RegisteredShape } from "${c.server}";
174
+ `:"",E=n.some(p=>p.channel?.kind==="room"),L=Oe(E,c.server,x),Q=s.length>0?`
175
+ /**
176
+ * Replication-shape registry — one entry per \`defineShape\` in \`lunora/shapes.ts\`.
177
+ * The generated ShardDO's \`resolveShape\` override looks a shape up by name and
178
+ * evaluates its trusted \`compileWhere(ctx, args)\` to authorize + scope a
179
+ * \`shape_subscribe\` (reads-as-permissions).
180
+ */
181
+ export const LUNORA_SHAPES: Record<string, RegisteredShape> = {${N}};
182
+ `:"",G=b.length>0?`
183
+ /**
184
+ * Custom-mutator function paths — the \`LUNORA_FUNCTIONS\` keys the generated
185
+ * ShardDO's \`isCustomMutator\` override routes through the client-watermark push
186
+ * protocol (\`x-lunora-client-id\`/\`x-lunora-client-seq\` ordering).
187
+ */
188
+ export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${b.map(p=>JSON.stringify(p)).join(", ")}]);
189
+ `:"",V=xe(E,o,n),W=y.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${c.values}";
190
+ `:"",Y=y.length>0?`
191
+ /**
192
+ * AOT-compiled argument validators (Worker-safe, no \`eval\`). Each is installed
193
+ * onto its function's live \`.args\` object and consulted by the interpreted
194
+ * parser as a zero-allocation fast path; anything it can't model is deferred.
195
+ */
196
+ ${y}
197
+ `:"",K=Se(n,o),{callRegisteredHelper:Z,dataModelImport:X,implementation:ee,parameter:te,types:re}=K,ne=o?`
198
+ export interface FunctionManifestEntry {
199
+ argumentDescriptors: ReadonlyArray<{ element?: string; kind: string; name: string; optional: boolean; table?: string }>;
200
+ channel?: { kind: "room"; name: string };
201
+ exportName: string;
202
+ expose?: { cache?: { credentialHeaders?: ReadonlyArray<string>; maxAge?: number; scope?: "private" | "public"; staleWhileRevalidate?: number; tag?: string; vary?: string }; rest?: boolean };
203
+ kind: "action" | "mutation" | "query" | "stream";
204
+ lifecycle?: "connect" | "disconnect" | "init" | "reactor" | "whisper";
205
+ moduleId: string;
206
+ visibility?: "internal" | "public";
207
+ x402?: { readonly price: number | string };
208
+ }
209
+
210
+ /** Static, codegen-derived facts. Request gates can inspect these without evaluating a user module. */
211
+ export const LUNORA_FUNCTION_MANIFEST: Readonly<Record<string, FunctionManifestEntry>> = {${$}};
212
+
213
+ const MODULE_LOADERS: Record<string, () => Promise<Record<string, unknown>>> = {${O}};
214
+ const loadedModules = new Map<string, Promise<Record<string, unknown>>>();
215
+ const resolvedModules = new Map<string, Record<string, unknown>>();
216
+ const boundFunctions = new Set<string>();
217
+ const unloadedFunctionHandler = (): never => {
218
+ throw new Error("a lazy function was invoked before it was prepared");
219
+ };
220
+
221
+ /** Reuse an evaluated module synchronously, so dispatch does not yield after restoring request scope. */
222
+ export const getLoadedFunction = (functionPath: string): RegisteredLunoraFunction | undefined => {
223
+ const registered = ${k("LUNORA_FUNCTIONS")};
224
+ const manifest = ${k("LUNORA_FUNCTION_MANIFEST")};
225
+
226
+ if (!registered || !manifest) {
227
+ return registered;
228
+ }
229
+
230
+ if (boundFunctions.has(functionPath)) {
231
+ return registered;
232
+ }
233
+
234
+ const module = resolvedModules.get(manifest.moduleId);
235
+
236
+ if (module === undefined) {
237
+ return undefined;
238
+ }
239
+
240
+ const loaded = module[manifest.exportName];
241
+
242
+ if (typeof loaded !== "object" || loaded === null) {
243
+ throw new Error(\`lazy module export for "\${functionPath}" is not a registered function\`);
244
+ }
245
+
246
+ Object.assign(registered, loaded);
247
+ boundFunctions.add(functionPath);
248
+
249
+ return registered;
250
+ };
251
+
252
+ /** Load one function's owning module once per isolate, then merge its live builder result into the registry entry. */
253
+ export const loadFunction = async (functionPath: string): Promise<RegisteredLunoraFunction | undefined> => {
254
+ const registered = getLoadedFunction(functionPath);
255
+ const manifest = ${k("LUNORA_FUNCTION_MANIFEST")};
256
+
257
+ if (registered || !manifest) {
258
+ return registered;
259
+ }
260
+
261
+ let pending = loadedModules.get(manifest.moduleId);
262
+
263
+ if (pending === undefined) {
264
+ const loader = MODULE_LOADERS[manifest.moduleId];
265
+
266
+ if (loader === undefined) {
267
+ throw new Error(\`no lazy module loader registered for "\${functionPath}"\`);
268
+ }
269
+
270
+ pending = loader();
271
+ loadedModules.set(manifest.moduleId, pending);
272
+ }
273
+
274
+ // A module that failed to evaluate stays failed for the isolate: the runtime has already cached
275
+ // the failed evaluation, and a bundler's lazy initializer can hand a retry a half-initialized
276
+ // namespace, so every later call rethrows the original error instead.
277
+ resolvedModules.set(manifest.moduleId, await pending);
278
+
279
+ return getLoadedFunction(functionPath);
280
+ };
281
+ `:"";return le(`${C}${g}${h.importLine}${w.importLine}${W}${z}${L.typeImport}import { LunoraError } from "${c.server}";
282
+ import type { ActionCtx, MutationCtx, QueryCtx } from "./server.js";
283
+ ${X}
284
+ /**
285
+ * Single registered function, narrowed to the shape \`handleRpc\` needs.
286
+ * The real argument validators / return types are checked elsewhere — at
287
+ * the dispatch site we erase to \`unknown\` so a single map can host every
288
+ * registered function.
289
+ */
290
+ export interface RegisteredLunoraFunction {
291
+ kind: "action" | "mutation" | "query" | "stream";
292
+ args: Record<string, unknown>;
293
+ /**
294
+ * Present on a \`"stream"\` declared \`durable\`: its run is persisted and
295
+ * survives the socket that opened it. Absent on every other kind, and on an
296
+ * ephemeral stream.
297
+ */
298
+ durable?: { ttlMs?: number };
299
+ /**
300
+ * For \`"action" | "mutation" | "query"\` the handler is awaited and its result returned.
301
+ * For \`"stream"\` the handler returns an \`AsyncIterable\` synchronously and takes an
302
+ * \`AbortSignal\` as a third argument — the runtime drives it frame-by-frame.
303
+ */
304
+ handler: ((context: unknown, args: Record<string, unknown>) => Promise<unknown> | unknown) | ((context: unknown, args: Record<string, unknown>, signal?: AbortSignal) => AsyncIterable<unknown>);
305
+ /**
306
+ * The lifecycle moment a hook fires on, when this registration came from
307
+ * \`onConnect\`/\`onDisconnect\`/\`onShardInit\`/\`onQueryChange\`/\`onWhisper\`.
308
+ * Read at dispatch to decide whether the function runs system-trusted:
309
+ * \`init\` and \`reactor\` have no caller identity, so RLS has no user to scope
310
+ * to. \`whisper\` does have one — it runs under the asking socket's identity.
311
+ */
312
+ lifecycle?: "connect" | "disconnect" | "init" | "reactor" | "whisper";
313
+ ${L.channelField} /**
314
+ * Hoisted by the builder when the \`.use()\` chain carries a step with a
315
+ * per-dispatch effect — \`rateLimit(...)\` consuming budget, a single-use
316
+ * captcha token being burned. Read by \`isCacheableQuery\`: the chain runs
317
+ * inside the dispatch callback, and a reactive-cache HIT skips that
318
+ * callback, so such a query must never be memoized.
319
+ */
320
+ perDispatch?: boolean;
321
+ /** \`"internal"\` functions are rejected on the external RPC path; absence === public. */
322
+ visibility?: "internal" | "public";
323
+ /**
324
+ * \`.x402({ price })\` tag on a paid public procedure. The origin worker
325
+ * paywalls it; the shard refuses to subscribe it (\`isPaidFunction\`).
326
+ */
327
+ x402?: { readonly price: number | string };
328
+ }
329
+ ${h.prelude}${w.prelude}${ne}
330
+ /**
331
+ * Static dispatch table. The key matches the \`__lunoraRef\` the client
332
+ * emits (\`api[namespace][fn].__lunoraRef === "namespace:fn"\`).
333
+ */
334
+ export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${m}};
335
+ ${Y}${Q}${G}${V}${L.messagesBlock}
336
+ /**
337
+ * Lifecycle manifest: the function paths the generated ShardDO dispatches when a
338
+ * client's WebSocket connects (\`connect\`) or disconnects (\`disconnect\`), once
339
+ * per Durable Object instance before any handler runs (\`init\`), after a
340
+ * write flush when a watched read's result changed (\`reactor\`), and before a
341
+ * socket joins or broadcasts to a whisper topic (\`whisper\`). Each path also
342
+ * resolves through {@link LUNORA_FUNCTIONS}. The socket-scoped moments run under
343
+ * the socket's verified identity; \`init\` and \`reactor\` have no caller, so they
344
+ * run anonymous — all via system dispatch.
345
+ */
346
+ export const LUNORA_LIFECYCLE_HOOKS: {
347
+ connect: readonly string[];
348
+ disconnect: readonly string[];
349
+ init: readonly string[];
350
+ reactor: readonly string[];
351
+ whisper: readonly string[];
352
+ } = {
353
+ connect: [${R.connect.map(p=>JSON.stringify(p)).join(", ")}],
354
+ disconnect: [${R.disconnect.map(p=>JSON.stringify(p)).join(", ")}],
355
+ init: [${R.init.map(p=>JSON.stringify(p)).join(", ")}],
356
+ reactor: [${R.reactor.map(p=>JSON.stringify(p)).join(", ")}],
357
+ whisper: [${R.whisper.map(p=>JSON.stringify(p)).join(", ")}],
358
+ };
359
+
360
+ /**
361
+ * Resolve and invoke a registered function from an external caller. Throws a
362
+ * LunoraError-shaped object (404) when the path is unknown — the runtime's
363
+ * structural error mapper turns that into the right HTTP status. Internal
364
+ * functions are treated as not-found so their existence never leaks to clients.
365
+ */
366
+ export const dispatchLunoraFunction = async (functionPath: string, context: unknown, args: Record<string, unknown>): Promise<unknown> => {
367
+ ${A} const registered = ${S};
368
+
369
+ if (!registered || registered.visibility === "internal") {
370
+ throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
371
+ }
372
+
373
+ return registered.handler(context, args);
374
+ };
375
+
376
+ /**
377
+ * A handler context accepted by {@link createCaller}. The runtime context the
378
+ * shard DO builds is uniform across kinds, so any handler's \`ctx\` works here.
379
+ */
380
+ export type CallerCtx = ActionCtx | MutationCtx | QueryCtx;
381
+
382
+ /**
383
+ * Typed, in-process server-to-server caller. Every registered function — public
384
+ * *and* internal — is reachable; each call dispatches against the same shard
385
+ * with the supplied \`context\`, exactly like \`ctx.runQuery\`/\`runMutation\`/
386
+ * \`runAction\` but without re-stating the function path.
387
+ */
388
+ export interface Caller {${re}}
389
+
390
+ ${Z}/** Build a {@link Caller} bound to \`context\` (typically a handler's \`ctx\`). */
391
+ export const createCaller = (${te}: CallerCtx): Caller => ({${ee}});
392
+
393
+ /**
394
+ * Single registered data migration, narrowed to the shape the per-shard runner
395
+ * consumes. \`up\`/\`down\` are erased to a structural transform; the authoring
396
+ * validation lives in \`defineMigration\`.
397
+ */
398
+ export interface RegisteredDataMigration {
399
+ batchSize?: number;
400
+ down?: (document: Record<string, unknown>) => Record<string, unknown> | undefined;
401
+ id: string;
402
+ table: string;
403
+ up: (document: Record<string, unknown>) => Record<string, unknown> | undefined;
404
+ }
405
+
406
+ /**
407
+ * Registry of online data migrations keyed by \`defineMigration\`'s \`id\`. The
408
+ * shard DO's admin RPC and the CLI resolve migrations to run through this map.
409
+ */
410
+ export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${v}};
411
+ `,d)},Me="fn",_e=r=>{if(r.lazyFunctions!==!0)return{};const{functions:t}=r,n=r.migrations??[],o=r.mutators??[],a=r.shapes??[],i=H(t,n,o,a),s=q(n,o,a),d=[...new Set(t.filter(l=>!s.has(l.filePath)).map(l=>l.filePath))],u=j(r.useUmbrella??!1),c={};for(const l of d){if(!F.test(l))throw new P("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(l)}`);const g=i.get(l)??"",y=`../../${l}.js`,$=t.filter(h=>h.filePath===l&&!h.lifecycle&&Object.keys(h.args).length>0).flatMap(h=>{const w=B(h.args);return w===void 0?[]:[`installCompiledValidatorMap(${g}.${h.exportName}.args, ${w});`]}),v=$.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${u.values}";
412
+ `:"",O=$.length>0?`import * as ${g} from "${y}";
413
+ `:"",b=$.length>0?`
414
+ /** Install the precompiled argument parsers before the module is dispatched. */
415
+ ${$.join(`
416
+ `)}
417
+ `:"",N=t.some(h=>h.filePath===l&&h.exportName==="default")||n.some(h=>h.filePath===l&&h.exportName==="default")?`export { default } from "${y}";
418
+ `:"";c[`${g}.ts`]=`${C}${v}${O}${b}export * from "${y}";
419
+ ${N}`}return c};export{Me as LAZY_FUNCTION_DIRECTORY,Ee as emitFunctions,_e as emitLazyFunctionModules};
@@ -0,0 +1 @@
1
+ import"./CAPABILITY_PROBES-brcmKenl.mjs";import{e}from"./server-DAvi_bv_.mjs";import"./shared-DnCokNcE.mjs";import"./platform-8oj7iXQy.mjs";export{e as default};