@lunora/codegen 1.0.0-alpha.33 → 1.0.0-alpha.331

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 (124) hide show
  1. package/README.md +1 -1
  2. package/dist/index.d.mts +4298 -2183
  3. package/dist/index.d.ts +4298 -2183
  4. package/dist/index.mjs +1 -35
  5. package/dist/packem_shared/AGENTS_FILENAME-B6-kjzM3.mjs +1 -0
  6. package/dist/packem_shared/CAPABILITY_PROBES-brcmKenl.mjs +25 -0
  7. package/dist/packem_shared/CONTAINERS_FILENAME-dFRtAyIe.mjs +1 -0
  8. package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
  9. package/dist/packem_shared/DEFAULT_TARGET-BbWiB-rs.mjs +1 -0
  10. package/dist/packem_shared/FLAGS_FILENAME-Bf0MSlHH.mjs +1 -0
  11. package/dist/packem_shared/GENERATED_HEADER-Ck_WOHzE.mjs +1 -0
  12. package/dist/packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs +1 -0
  13. package/dist/packem_shared/MUTATORS_FILENAME-B_I0kkvJ.mjs +1 -0
  14. package/dist/packem_shared/NOTIFY_FILENAME-DOIxn0Qb.mjs +1 -0
  15. package/dist/packem_shared/OPENRPC_VERSION-CCY7xqSL.mjs +3 -0
  16. package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs +1 -0
  17. package/dist/packem_shared/QUEUES_FILENAME-CsRy4VTF.mjs +1 -0
  18. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DdPW4JCi.mjs +31 -0
  19. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs +2 -0
  20. package/dist/packem_shared/SHAPES_FILENAME-D7Ifi5Ce.mjs +1 -0
  21. package/dist/packem_shared/SchemaSnapshotParseError-BRJT7c2k.mjs +18 -0
  22. package/dist/packem_shared/WORKFLOWS_FILENAME-CdeS224T.mjs +1 -0
  23. package/dist/packem_shared/attribution-hVBriwzy.mjs +1 -0
  24. package/dist/packem_shared/buildOpenApiDocument-DFv-RYZU.mjs +3 -0
  25. package/dist/packem_shared/capabilitiesUsedBy-CF7sUwa8.mjs +1 -0
  26. package/dist/packem_shared/chain-ZlTHdRo2.mjs +1 -0
  27. package/dist/packem_shared/classify-procedure-call-Bw5sia-K.mjs +1 -0
  28. package/dist/packem_shared/context-property-calls-Co_G3ENU.mjs +1 -0
  29. package/dist/packem_shared/context-root-BTW5XwVq.mjs +1 -0
  30. package/dist/packem_shared/createCodegenProject-V51_yBw3.mjs +1 -0
  31. package/dist/packem_shared/database-calls-D-GwIhWO.mjs +1 -0
  32. package/dist/packem_shared/declared-output-Iaar469J.mjs +1 -0
  33. package/dist/packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs +1 -0
  34. package/dist/packem_shared/discoverAuthApiCalls-xs0ONfI-.mjs +1 -0
  35. package/dist/packem_shared/discoverCrons-B2SdRjRO.mjs +1 -0
  36. package/dist/packem_shared/discoverFunctions-C9Ra5XXH.mjs +1 -0
  37. package/dist/packem_shared/discoverHttpRoutes-WBAqBcfK.mjs +1 -0
  38. package/dist/packem_shared/discoverHyperdriveCalls-DfCAjBgd.mjs +1 -0
  39. package/dist/packem_shared/discoverInserts-T5ojinqL.mjs +1 -0
  40. package/dist/packem_shared/discoverMaskProcedures-DKd9fVDa.mjs +1 -0
  41. package/dist/packem_shared/discoverMigrations-ClgjUkaG.mjs +1 -0
  42. package/dist/packem_shared/discoverNondeterministicCalls-UCUCyCox.mjs +1 -0
  43. package/dist/packem_shared/discoverQueries-u2XNpxsn.mjs +1 -0
  44. package/dist/packem_shared/discoverR2sqlCalls-jz5KouxF.mjs +1 -0
  45. package/dist/packem_shared/discoverRlsMetadata-D2G3YAoe.mjs +1 -0
  46. package/dist/packem_shared/discoverRlsProcedures-BD8aG1BU.mjs +1 -0
  47. package/dist/packem_shared/discoverSandboxUsage-w6Q3RvxZ.mjs +1 -0
  48. package/dist/packem_shared/discoverSchema-BtsX-CN9.mjs +1 -0
  49. package/dist/packem_shared/discoverStorageRulesMetadata-C2ceH0ZO.mjs +1 -0
  50. package/dist/packem_shared/dispatch-namespace-DwTjD7BU.mjs +1 -0
  51. package/dist/packem_shared/emitAgents-CR2_X_ov.mjs +1 -0
  52. package/dist/packem_shared/emitApi-CDgIPAG2.mjs +147 -0
  53. package/dist/packem_shared/emitApp-DuJW6LKD.mjs +986 -0
  54. package/dist/packem_shared/emitCrons-BQW2lviZ.mjs +96 -0
  55. package/dist/packem_shared/emitDataModel-BskFt9Wv.mjs +114 -0
  56. package/dist/packem_shared/emitDrizzleSchema-DitcRZ1a.mjs +15 -0
  57. package/dist/packem_shared/emitFunctions-Cd0Tuw73.mjs +500 -0
  58. package/dist/packem_shared/emitServer-D1vA5_X1.mjs +1 -0
  59. package/dist/packem_shared/emitShard-DtfjUgjj.mjs +1 -0
  60. package/dist/packem_shared/exported-procedure-chains-CVzkVdq4.mjs +1 -0
  61. package/dist/packem_shared/fingerprintSchemaSources-eVG9aVt0.mjs +1 -0
  62. package/dist/packem_shared/formatAdvisories-BCVASH7N.mjs +2 -0
  63. package/dist/packem_shared/handler-reference-vIeqkhV_.mjs +1 -0
  64. package/dist/packem_shared/index-BPUxZYM5.mjs +1 -0
  65. package/dist/packem_shared/isD1GlobalTable-udvHAAzD.mjs +1 -0
  66. package/dist/packem_shared/isTestPath-B81lOULB.mjs +1 -0
  67. package/dist/packem_shared/isTypedSchema-CKzc3ioR.mjs +4 -0
  68. package/dist/packem_shared/json-data-Chfs2Cz5.mjs +1 -0
  69. package/dist/packem_shared/loadProjectConfig-NO0dVJSl.mjs +1 -0
  70. package/dist/packem_shared/module-specifiers-BctA0m_p.mjs +1 -0
  71. package/dist/packem_shared/modules-CjOcuQnK.mjs +1 -0
  72. package/dist/packem_shared/parse-validator-IDBKIT7M.mjs +1 -0
  73. package/dist/packem_shared/platform-8oj7iXQy.mjs +1 -0
  74. package/dist/packem_shared/project-config-file-BV7RR-l6.mjs +1 -0
  75. package/dist/packem_shared/qualifiers-DEdXn5wP.mjs +1 -0
  76. package/dist/packem_shared/readPackageDependencies-RHhGiz0k.mjs +1 -0
  77. package/dist/packem_shared/readServiceBindings-DvqIThzd.mjs +1 -0
  78. package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
  79. package/dist/packem_shared/reserved-words-CW1QFbTd.mjs +1 -0
  80. package/dist/packem_shared/schema-BgM8A3XV.mjs +1 -0
  81. package/dist/packem_shared/schemaFromIr-BWFnvCVg.mjs +1 -0
  82. package/dist/packem_shared/server-DAvi_bv_.mjs +368 -0
  83. package/dist/packem_shared/shard-CsfiXxV0.mjs +1635 -0
  84. package/dist/packem_shared/shard-runtime-BpoCV-aM.mjs +331 -0
  85. package/dist/packem_shared/shared-DnCokNcE.mjs +13 -0
  86. package/dist/packem_shared/unwrap-handler-return-CeaOifqX.mjs +1 -0
  87. package/dist/sdk/index.d.mts +288 -0
  88. package/dist/sdk/index.d.ts +288 -0
  89. package/dist/sdk/index.mjs +372 -0
  90. package/package.json +21 -8
  91. package/dist/packem_shared/CONTAINERS_FILENAME-DjpXMqhp.mjs +0 -224
  92. package/dist/packem_shared/CodegenDiagnosticError-DyQ5FwkM.mjs +0 -24
  93. package/dist/packem_shared/FLAGS_FILENAME-BjpS5w08.mjs +0 -139
  94. package/dist/packem_shared/GENERATED_HEADER-CLwPlCQe.mjs +0 -3
  95. package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
  96. package/dist/packem_shared/MUTATORS_FILENAME-BZOfUhlY.mjs +0 -81
  97. package/dist/packem_shared/OPENRPC_VERSION-4YIeMkOI.mjs +0 -60
  98. package/dist/packem_shared/QUEUES_FILENAME-BF0iUmx7.mjs +0 -119
  99. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-C9FkE1cW.mjs +0 -3521
  100. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-D0ARY6rL.mjs +0 -249
  101. package/dist/packem_shared/SHAPES_FILENAME-DOhPGi-6.mjs +0 -94
  102. package/dist/packem_shared/WORKFLOWS_FILENAME-CCC_42o3.mjs +0 -124
  103. package/dist/packem_shared/buildOpenApiDocument-bp1pYSV6.mjs +0 -183
  104. package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
  105. package/dist/packem_shared/discoverAuthApiCalls-URDoTADN.mjs +0 -62
  106. package/dist/packem_shared/discoverCrons-DdZOeroL.mjs +0 -257
  107. package/dist/packem_shared/discoverFunctions-BJdF7lRs.mjs +0 -514
  108. package/dist/packem_shared/discoverHttpRoutes-CcwP-Rkr.mjs +0 -131
  109. package/dist/packem_shared/discoverInserts-BpFhM32L.mjs +0 -61
  110. package/dist/packem_shared/discoverMaskProcedures-DT-v8wvj.mjs +0 -273
  111. package/dist/packem_shared/discoverMigrations-cG1idBVM.mjs +0 -97
  112. package/dist/packem_shared/discoverNondeterministicCalls-CEOjmfk4.mjs +0 -122
  113. package/dist/packem_shared/discoverQueries-DeVBQVAG.mjs +0 -62
  114. package/dist/packem_shared/discoverR2sqlCalls-CWCAU-xJ.mjs +0 -80
  115. package/dist/packem_shared/discoverRlsMetadata-BL0oukaK.mjs +0 -280
  116. package/dist/packem_shared/discoverSchema-CeXJWVKV.mjs +0 -874
  117. package/dist/packem_shared/discoverStorageRulesMetadata-CFHByjIl.mjs +0 -97
  118. package/dist/packem_shared/emit-CBwEvCXQ.mjs +0 -3451
  119. package/dist/packem_shared/emitApp-nQ2oC-8G.mjs +0 -668
  120. package/dist/packem_shared/formatAdvisories-DLIqHq5l.mjs +0 -114
  121. package/dist/packem_shared/parse-validator-D6zI2i85.mjs +0 -134
  122. package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
  123. package/dist/packem_shared/redact-oTmsol5A.mjs +0 -33
  124. package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
@@ -0,0 +1,331 @@
1
+ import{r as b}from"./json-data-Chfs2Cz5.mjs";import{CAPABILITIES as N}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{a as l,G as g}from"./shared-DnCokNcE.mjs";import{s as k}from"./platform-8oj7iXQy.mjs";const I=e=>e?{importFragment:"serveRelationFanout, ",override:`
2
+ protected override async runRelationFanoutRead(functionPath: string, args: Record<string, unknown>): Promise<unknown> {
3
+ this.ensureMigrated();
4
+
5
+ const { db } = this.buildCtx({ functionPath }) as { db: DatabaseWriterLike };
6
+
7
+ return serveRelationFanout(schema as unknown as SchemaLike, db, functionPath, args);
8
+ }
9
+ `}:{importFragment:"",override:""},f=(e,r,t,{cast:n="",sync:a=[]}={})=>{const u=`throw new Error(${JSON.stringify(r)});`,c=t.map(s=>` ${s}: ${a===!0||a.includes(s)?"":"async "}() => {
10
+ ${u}
11
+ },`).join(`
12
+ `);return`
13
+ const ${e} = {
14
+ ${c}
15
+ }${n};
16
+ `},h={build:"",configField:"",contextField:"",importLines:[],stub:""},D=e=>e.size===0?{configField:"",constant:"",override:""}:{configField:"\n /** The `ShardRegistryDO` namespace (typically `env.SHARD_REGISTRY`). This shard registers its key for each `.shardBy()` table it writes, so cross-shard export, sync and migrations reach it. */\n shardRegistry?: (env: Record<string, unknown>) => unknown;",constant:`
17
+ /** The \`.shardBy()\` tables this shard registers with the shard registry when it writes them. */
18
+ const SHARDED_TABLES: ReadonlySet<string> = new Set([${[...e].map(r=>JSON.stringify(r)).join(", ")}]);
19
+ `,override:`
20
+ protected override shardRegistry(): undefined | { namespace: unknown; shardedTables: ReadonlySet<string> } {
21
+ const namespace = config.shardRegistry?.((this.env ?? {}) as Record<string, unknown>);
22
+
23
+ return namespace === undefined ? undefined : { namespace, shardedTables: SHARDED_TABLES };
24
+ }
25
+ `},j=(e,r)=>e?{build:`
26
+ const flags: import("${r}").LunoraFlags = createFlags(flagsConfig, env, {
27
+ provider: () => config.flags?.(env),
28
+ targetingKey: () => flagsConfig.identify?.({ identity: identity ?? null, userId: userId ?? null }),
29
+ });
30
+ `,configField:`
31
+ flags?: (env: Record<string, unknown>) => import("${r}").Provider;`,contextField:`
32
+ flags,`,importLines:[`import { createFlags } from "${r}";`,'import flagsConfig from "../flags.js";'],stub:""}:h,U=e=>e?{build:`
33
+ const { notify, push } = createNotify(notifyConfig, env, { log, metrics });
34
+ `,configField:"",contextField:`
35
+ notify,
36
+ push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:h,Q=e=>e?{build:`
37
+ const envConfig = lunoraEnvContract.${e.exportName}(env);
38
+ `,configField:"",contextField:`
39
+ env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:h,M=(e,r,t)=>{if(!r)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const n=s=>`
40
+ const env = (this.env ?? {}) as Record<string, unknown>;
41
+ const flags: import("${t}").LunoraFlags = createFlags(flagsConfig, env, {
42
+ provider: () => config.flags?.(env),
43
+ targetingKey: ${s},
44
+ });`,a=`
45
+ /** Statically-discovered feature flags (\`ctx.flags.<type>("key")\` reads) served via \`__lunora_admin__:listFlags\` + the reactive \`__lunora_flags__:\` channel. */
46
+ const LUNORA_FLAG_KEYS = ${b(e,'ReadonlyArray<{ key: string; type: "boolean" | "number" | "object" | "string" }>')};
47
+ `,u=`
48
+ protected override async evaluateFlags(context?: Record<string, unknown>): Promise<FlagsResult> {${n("undefined")}
49
+ const evalContext = context as import("${t}").EvaluationContext | undefined;
50
+ const evaluations: FlagsResult["flags"] = [];
51
+
52
+ for (const entry of LUNORA_FLAG_KEYS) {
53
+ // eslint-disable-next-line no-await-in-loop -- flags evaluate sequentially; each shares the single memoized provider client
54
+ const details =
55
+ entry.type === "boolean"
56
+ ? await flags.details.boolean(entry.key, false, evalContext)
57
+ : entry.type === "number"
58
+ ? await flags.details.number(entry.key, 0, evalContext)
59
+ : entry.type === "string"
60
+ ? await flags.details.string(entry.key, "", evalContext)
61
+ : await flags.details.object(entry.key, {}, evalContext);
62
+
63
+ evaluations.push({ errorCode: details.errorCode, key: entry.key, reason: details.reason, type: entry.type, value: details.value, variant: details.variant });
64
+ }
65
+
66
+ return { configured: true, flags: evaluations };
67
+ }
68
+ `,c=`
69
+ protected override runFlagSubscriptionRead(_functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<unknown> {${n("() => flagsConfig.identify?.({ identity: identity?.identity ?? null, userId: identity?.userId ?? null })")}
70
+ const key = typeof args.key === "string" ? args.key : "";
71
+
72
+ // SECURITY: the reactive channel is public (any socket, no auth). Serve
73
+ // ONLY statically-discovered flag keys — an arbitrary client-supplied key
74
+ // would let a subscriber probe the value of internal/unreleased flags the
75
+ // app never exposes. Unknown key ⇒ the "nothing to deliver" sentinel.
76
+ // eslint-disable-next-line unicorn/no-null -- the base hook's "nothing to deliver" sentinel
77
+ if (key.length === 0 || !LUNORA_FLAG_KEYS.some((entry) => entry.key === key)) {
78
+ return Promise.resolve(null);
79
+ }
80
+
81
+ // SECURITY: evaluate under the socket's server-verified identity ONLY
82
+ // (the targetingKey resolved above). Client-supplied targeting context is
83
+ // NOT honored on this public channel — otherwise a subscriber could spoof
84
+ // targeting attributes (e.g. plan/role) to unlock a flag gated on them.
85
+ const context = undefined;
86
+
87
+ if (args.type === "number") {
88
+ return flags.number(key, typeof args.default === "number" ? args.default : 0, context);
89
+ }
90
+
91
+ if (args.type === "string") {
92
+ return flags.string(key, typeof args.default === "string" ? args.default : "", context);
93
+ }
94
+
95
+ if (args.type === "object") {
96
+ return flags.object(key, (args.default ?? {}) as import("${t}").JsonValue, context);
97
+ }
98
+
99
+ return flags.boolean(key, typeof args.default === "boolean" ? args.default : false, context);
100
+ }
101
+ `;return{constant:a,evaluateOverride:u,subscriptionOverride:c}},R=()=>({build:`
102
+ const aiBinding = config.ai?.(env) ?? (env as Record<string, unknown>).AI;
103
+ // Correlate AI-Gateway-routed calls with the Lunora trace: thread the
104
+ // function path + trace id into createAi, which folds them into the
105
+ // gateway's \`metadata\`. Mirror the tracer's anchor guard — a deferred
106
+ // subscription re-run must not borrow a concurrent dispatch's trace, so
107
+ // read \`getCurrentTrace()\` only on the synchronous (non-threaded-identity) path.
108
+ const aiTrace = options.identity ? undefined : this.getCurrentTrace();
109
+ // \`telemetry\` gives every model call an \`ai.generate\` / \`ai.stream\` span
110
+ // and \`gen_ai.usage.*\` token + cost counters attributed to this function.
111
+ const ai: LunoraAi = createAi({
112
+ binding: aiBinding as AiBindingLike | undefined,
113
+ env: env as Record<string, unknown>,
114
+ metadata: { functionPath: options.functionPath, traceId: aiTrace?.traceId },
115
+ telemetry: { metrics, trace },
116
+ });
117
+ `,configField:`
118
+ ai?: (env: Record<string, unknown>) => AiBindingLike;`,importLines:['import type { AiBindingLike, LunoraAi } from "@lunora/ai/create";','import { createAi } from "@lunora/ai/create";'],stub:""}),S=()=>({build:`
119
+ const access = accessFacade(identity, userId);
120
+ `,configField:"",importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}),w=()=>({build:`
121
+ const r2sqlEnv = env as Record<string, unknown>;
122
+ const r2sqlAccountId = (r2sqlEnv.R2_SQL_ACCOUNT_ID ?? r2sqlEnv.CLOUDFLARE_ACCOUNT_ID) as string | undefined;
123
+ const r2sqlToken = r2sqlEnv.R2_SQL_TOKEN as string | undefined;
124
+ const r2sqlBucket = r2sqlEnv.R2_SQL_BUCKET as string | undefined;
125
+ const r2sql: R2SqlClient = config.r2sql
126
+ ? config.r2sql(env)
127
+ : r2sqlAccountId && r2sqlToken && r2sqlBucket
128
+ ? createR2Sql({ accountId: r2sqlAccountId, apiToken: r2sqlToken, bucket: r2sqlBucket })
129
+ : r2sqlStub;
130
+ `,configField:`
131
+ r2sql?: (env: Record<string, unknown>) => R2SqlClient;`,importLines:['import type { R2SqlClient } from "@lunora/bindings/r2sql";','import { createR2Sql } from "@lunora/bindings/r2sql";'],stub:f("r2sqlStub: R2SqlClient","ctx.r2sql: no R2 SQL credentials found. Set `R2_SQL_TOKEN`, `R2_SQL_ACCOUNT_ID` (or `CLOUDFLARE_ACCOUNT_ID`), and `R2_SQL_BUCKET` in your env/.dev.vars, or pass an `r2sql` config thunk to createShardDO().",["describe","explain","from","query","showDatabases","showTables"],{sync:["from"]})}),L=()=>({build:`
132
+ const x402: X402Pay = config.x402
133
+ ? lazyX402Pay(config.x402(env), { getSecret: (name: string) => secrets.get(name) })
134
+ : x402Stub;
135
+ `,configField:`
136
+ x402?: (env: Record<string, unknown>) => X402PayConfig;`,importLines:['import type { X402Pay, X402PayConfig } from "@lunora/x402/pay";','import { lazyX402Pay } from "@lunora/x402/pay";'],stub:f("x402Stub: X402Pay","ctx.x402: no pay rail configured. Pass `x402` to createShardDO().",["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}),A={access:S,ai:R,r2sql:w,x402:L},C=e=>e.shardBinding==="bespoke",_=e=>typeof e.shardBinding=="object",m=" ",F=(e,r,t)=>{const n=`${e}Binding`,{factory:a}=t;let u=`(${n} as ${r})`;if(a!==void 0){const c=`${n} as ${t.bindingType??r}`;u=a.option===void 0?`${a.name}(${c})`:`${a.name}({ ${a.option}: ${c} })`}return`${n} ? ${u} : ${e}Stub`},O=(e,r,t)=>{const n=F(e,r,t),a=`${m}const ${e}Binding = config.${e}?.(env) ?? (env as Record<string, unknown>).${t.envName};
137
+ `,u=t.unvouchableReads??[];return u.length===0?`
138
+ ${a}${m}const ${e}: ${r} = ${n};
139
+ `:`
140
+ ${a}${m}// ${t.envName} is not this shard's SQLite, so nothing appends a \`__cdc_log\` entry
141
+ ${m}// when a value changes — a subscription that read one can never be proven
142
+ ${m}// current on reconnect and must re-snapshot. Reads only; writes stay unstamped.
143
+ ${m}const ${e}: ${r} = markUnvouchableReads(${n}, options.onRead, [
144
+ ${u.map(c=>`${m} ${JSON.stringify(c)},`).join(`
145
+ `)}
146
+ ${m}]);
147
+ `},E=(e,r,t)=>{const{binding:n,clientType:a}=t,u=f(`${e}Stub: ${a}`,t.missingMessage,t.stubMethods,{sync:t.syncStubMethods});if(n===void 0){const o=t.instrument===void 0?`config.${e}(env)`:`this.${t.instrument}(config.${e}(env), logFunctionPath, traceAnchor, observability)`;return{build:`
148
+ ${m}const ${e}: ${a} = config.${e} ? ${o} : ${e}Stub;
149
+ `,configField:`
150
+ ${e}?: (env: Record<string, unknown>) => ${a};`,importLines:[`import type { ${a} } from "${r}";`],stub:u}}const c=n.bindingType??a,s=[...new Set([c,a])].toSorted((o,i)=>o.localeCompare(i));return{build:O(e,a,n),configField:`
151
+ ${e}?: (env: Record<string, unknown>) => ${c};`,importLines:[`import type { ${s.join(", ")} } from "${r}";`,...n.factory===void 0?[]:[`import { ${n.factory.name} } from "${r}";`]],stub:u}},K=e=>{const r=[],t=[];let n="",a="",u="",c="",s="";for(const o of N.filter(({key:i})=>e.has(i))){let i;if(C(o))i=A[o.key]();else if(_(o))i=E(o.contextProperty,o.moduleSpecifier,o.shardBinding);else continue;const d=o.contextProperty;t.push(...i.importLines),a+=i.configField,s+=i.stub,o.tier==="every"?(u+=i.build,c+=`
152
+ ${d},`):(n+=i.build,r.push(d))}return{actionBuild:n,actionFields:r,configFields:a,everyBuild:u,everyFields:c,importLines:t,stubs:s}},G=(e,r)=>{if(e.length===0)return"";const t=r?`, ${JSON.stringify(r)}`:"",n=e.map(i=>{l(i.exportName,`container export "${i.exportName}"`),l(i.className,`container class "${i.className}"`);const d=i.sandbox===!0?"LunoraSandboxContainer":"LunoraContainer";return`/** Container DO for the \`${i.exportName}\` definition (binding \`${i.bindingName}\`). */
153
+ export class ${i.className} extends ${d} {
154
+ public constructor(ctx: ConstructorParameters<typeof ${d}>[0], env: Record<string, unknown>) {
155
+ super(ctx, env, ${i.exportName}, "${i.exportName}"${t});
156
+ }
157
+ }
158
+ `}).join(`
159
+ `),a=e.map(i=>i.exportName).join(", "),u=e.some(i=>i.sandbox===!0),c=e.some(i=>i.sandbox!==!0)?`import { LunoraContainer } from "@lunora/container/do";
160
+ `:"";return`${g}/**
161
+ * Container-enabled Durable Object classes for the containers declared in
162
+ * \`lunora/containers.ts\`. Re-export them from your worker entry — wrangler
163
+ * requires each \`containers[].class_name\` to be exported by the worker:
164
+ *
165
+ * \`export * from "./lunora/_generated/containers.js";\`
166
+ *
167
+ * \`ContainerProxy\` is re-exported alongside them: the egress-interception path
168
+ * (\`allowedHosts\`/\`deniedHosts\`/\`interceptHttps\` and the runtime
169
+ * \`handle.egress\` controls) routes container outbound traffic through this
170
+ * WorkerEntrypoint, so it too must be exported by the deployed worker.
171
+ */
172
+ ${c}${u?`import { LunoraSandboxContainer } from "@lunora/container/sandbox";
173
+ `:""}
174
+ import { ${a} } from "../containers.js";
175
+
176
+ export { ContainerProxy } from "@lunora/container/do";
177
+ ${u?`
178
+ /**
179
+ * \`DirectoryBackup\` and \`S3Mount\` route a \`sandbox: true\` container's storage
180
+ * traffic through these WorkerEntrypoints, so the deployed worker must export them.
181
+ */
182
+ export { DirectoryBackupGateway, S3Gateway } from "@lunora/container/sandbox";
183
+ `:""}
184
+ ${n}`},H=(e,r)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)l(n.exportName,`container export "${n.exportName}"`),l(n.bindingName,`container binding "${n.bindingName}"`);const t=e.map(n=>{const a=n.schedulingPolicy!==void 0||n.maxInstances===void 0?"":`, maxInstances: ${String(n.maxInstances)}`;return` { binding: "${n.bindingName}", exportName: "${n.exportName}"${a} },`}).join(`
185
+ `);return{build:`
186
+ const containers = createContainerContext(env, LUNORA_CONTAINERS, ${r?JSON.stringify(r):"undefined"}, this.getCurrentTraceparent(), this.getCurrentSampleErrors());
187
+ `,contextField:`
188
+ containers,`,importLines:['import type { ContainerBindingSpec } from "@lunora/container";','import { createContainerContext } from "@lunora/container";'],specs:`
189
+ /** Wiring specs for \`ctx.containers\` (codegen-derived from \`lunora/containers.ts\`). */
190
+ const LUNORA_CONTAINERS: ReadonlyArray<ContainerBindingSpec> = [
191
+ ${t}
192
+ ];
193
+ `}},J=e=>{if(e.length===0)return"";const r=e.map(n=>(l(n.exportName,`workflow export "${n.exportName}"`),l(n.className,`workflow class "${n.className}"`),`/** WorkflowEntrypoint for the \`${n.exportName}\` definition, reached as \`ctx.exports.${n.className}\`. */
194
+ export class ${n.className} extends LunoraWorkflow<WorkflowParamsOf<typeof ${n.exportName}>, WorkflowOutputOf<typeof ${n.exportName}>> {
195
+ public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
196
+ super(ctx, env, ${n.exportName}, "${n.exportName}");
197
+ }
198
+ }
199
+ `)).join(`
200
+ `),t=e.map(n=>n.exportName).join(", ");return`${g}/**
201
+ * WorkflowEntrypoint classes for the workflows declared in
202
+ * \`lunora/workflows.ts\`. Re-export them from your worker entry — wrangler
203
+ * requires each \`workflows[].class_name\` to be exported by the worker:
204
+ *
205
+ * \`export * from "./lunora/_generated/workflows.js";\`
206
+ */
207
+ import LunoraWorkflow from "@lunora/workflow/do";
208
+
209
+ import { ${t} } from "../workflows.js";
210
+
211
+ /** Params type carried by a \`defineWorkflow\` definition (its phantom \`__params\`), so each entrypoint keeps the authored \`ctx.params\` type. */
212
+ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params }
213
+ ? unknown extends Params
214
+ ? Record<string, unknown>
215
+ : NonNullable<Params>
216
+ : Record<string, unknown>;
217
+
218
+ /** Output type carried by a \`defineWorkflow\` definition (its phantom \`__output\`), so each entrypoint keeps the authored return type. */
219
+ type WorkflowOutputOf<Definition> = Definition extends { __output?: infer Output } ? Output : unknown;
220
+
221
+ ${r}`},V=e=>{if(e.length===0)return"";const t=e.filter(s=>s.voice).length>0,n=e.map(s=>{l(s.exportName,`agent export "${s.exportName}"`),l(s.className,`agent class "${s.className}"`);const o=`/** WorkflowEntrypoint for the \`${s.exportName}\` agent, reached as \`ctx.exports.${s.className}\`. */
222
+ export class ${s.className} extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
223
+ public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
224
+ super(ctx, env, compileAgentWorkflow(${s.exportName}, "${s.exportName}"), "${s.exportName}");
225
+ }
226
+ }
227
+ `;if(!s.voice)return o;const i=s.voiceClassName??"",d=s.voiceBindingName??"";l(i,`agent voice class "${i}"`);const p=`
228
+ /** Voice-session Durable Object for the \`${s.exportName}\` agent (binding \`${d}\`). */
229
+ export class ${i} extends VoiceSessionDO {
230
+ public constructor(ctx: ConstructorParameters<typeof VoiceSessionDO>[0], env: Record<string, unknown>) {
231
+ super(ctx, env, ${s.exportName}, "${s.exportName}");
232
+ }
233
+ }
234
+ `;return`${o}${p}`}).join(`
235
+ `),a=e.map(s=>s.exportName).join(", ");return`${g}/**
236
+ * WorkflowEntrypoint classes for the agents declared in \`lunora/agents.ts\`.
237
+ * Each \`defineAgent\` compiles a replay-safe tool-loop onto a Cloudflare
238
+ * Workflow. Re-export them from your worker entry — wrangler requires each
239
+ * \`workflows[].class_name\` to be exported by the worker:
240
+ *
241
+ * \`export * from "./lunora/_generated/agents.js";\`${t?"\n *\n * Voice-enabled agents ALSO get a `VoiceSessionDO` subclass here — a real\n * Durable Object (unlike the Workflow), so wrangler needs both its\n * `durable_objects` binding and its `class_name` export (the same re-export\n * line covers it).":""}
242
+ */
243
+ import LunoraWorkflow from "@lunora/workflow/do";
244
+ ${t?'import { compileAgentWorkflow, VoiceSessionDO } from "@lunora/agent";':'import { compileAgentWorkflow } from "@lunora/agent";'}
245
+ import type { AgentRunInput, AgentRunResult } from "@lunora/agent";
246
+
247
+ import { ${a} } from "../agents.js";
248
+
249
+ ${n}`},y=e=>e.env===void 0?"the top level":`env.${e.env}`,$=(e,r)=>{const t=e.filter(o=>o.mode==="push"),n=new Map(t.map(o=>[o.bindingName,o])),a=new Map(e.map(o=>[o.name,o])),u=new Map(t.map(o=>[o.name,o])),c=new Map,s=[];for(const o of r){const i=n.get(o.binding);if(i===void 0||o.queue===i.name)continue;const d=a.get(o.queue);if(d!==void 0){s.push(`${y(o)} maps \`${o.binding}\` to "${o.queue}", the declared name of queue \`${d.exportName}\` — batches for "${o.queue}" go to \`${d.exportName}\`, never \`${i.exportName}\`.`);continue}const p=u.get(o.queue);if(p===void 0)u.set(o.queue,i),c.set(o.queue,o);else if(p!==i){const x=c.get(o.queue);s.push(`"${o.queue}" is aliased to \`${p.exportName}\` by ${x===void 0?"an earlier producer":y(x)} and to \`${i.exportName}\` by ${y(o)} — batches for it go to \`${p.exportName}\`.`)}}return{conflicts:s,routes:u}},Y=(e,r)=>$(e,r).conflicts.map(t=>({cacheKey:`queue_alias_conflict:${t}`,categories:["SCHEMA"],description:"Codegen routes a delivered batch by its queue name. A wrangler.jsonc producer that maps a queue's binding to another name adds that name as a route, so it must not be another queue's declared name or an alias another scope gives a different queue.",detail:t,facing:"INTERNAL",level:"WARN",metadata:{},name:"queue_alias_conflict",remediation:"Give each queue a distinct name in every `env.<name>` block of wrangler.jsonc, then rerun codegen.",title:"Queue name routes to a different handler than wrangler.jsonc implies"})),X=(e,r=[])=>{const t=e.filter(c=>c.mode==="push");if(t.length===0)return"";for(const c of t)l(c.exportName,`queue export "${c.exportName}"`);const n=[...Map.groupBy(t,c=>c.filePath)].map(([c,s])=>`import { ${s.map(o=>o.exportName).join(", ")} } from "../${c}.js";`).join(`
250
+ `),{routes:a}=$(e,r),u=[...a].map(([c,s])=>` ${JSON.stringify(c)}: { binding: ${JSON.stringify(s.bindingName)}, definition: ${s.exportName}, exportName: ${JSON.stringify(s.exportName)} },`).join(`
251
+ `);return`${g}/**
252
+ * Push-consumer registry for the queues declared in \`lunora/queues.ts\`. The
253
+ * composed worker's \`queue(batch, env, ctx)\` entry routes each delivered batch
254
+ * by \`batch.queue\` to the matching \`defineQueue\` handler. Wired automatically
255
+ * by \`defineApp\` — you don't import this directly.
256
+ */
257
+ import type { QueueRegistry } from "@lunora/queue";
258
+
259
+ ${n}
260
+
261
+ /** Wrangler queue name (declared, or a per-environment rename) → { binding, definition, exportName } for batch routing. */
262
+ export const LUNORA_QUEUE_REGISTRY: QueueRegistry = {
263
+ ${u}
264
+ };
265
+ `},z=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const t of e)l(t.exportName,`workflow export "${t.exportName}"`),l(t.className,`workflow class "${t.className}"`);const r=e.map(t=>` { className: "${t.className}", exportName: "${t.exportName}" },`).join(`
266
+ `);return{build:`
267
+ const workflows = createWorkflowContext(env, LUNORA_WORKFLOWS, this.state.exports);
268
+ `,contextField:`
269
+ workflows,`,importLines:['import type { WorkflowBindingSpec } from "@lunora/workflow";','import { createWorkflowContext } from "@lunora/workflow";'],specs:`
270
+ /** Wiring specs for \`ctx.workflows\` (codegen-derived from \`lunora/workflows.ts\`). */
271
+ const LUNORA_WORKFLOWS: ReadonlyArray<WorkflowBindingSpec> = [
272
+ ${r}
273
+ ];
274
+ `}},Z=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const t of e)l(t.exportName,`queue export "${t.exportName}"`),l(t.bindingName,`queue binding "${t.bindingName}"`);const r=e.map(t=>` { binding: "${t.bindingName}", exportName: "${t.exportName}", name: ${JSON.stringify(t.name)} },`).join(`
275
+ `);return{build:`
276
+ const queues = createQueueContext(env, LUNORA_QUEUES);
277
+ `,contextField:`
278
+ queues,`,importLines:['import type { QueueBindingSpec } from "@lunora/queue";','import { createQueueContext } from "@lunora/queue";'],specs:`
279
+ /** Wiring specs for \`ctx.queues\` (codegen-derived from \`lunora/queues.ts\`). */
280
+ const LUNORA_QUEUES: ReadonlyArray<QueueBindingSpec> = [
281
+ ${r}
282
+ ];
283
+ `}},ee=(e,r)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};const t=e.map(n=>{l(n.exportName,`topic export "${n.exportName}"`);const a=k(r,n.exportName).map(u=>`{ binding: "${u.bindingName}", exportName: "${u.exportName}" }`).join(", ");return` { exportName: "${n.exportName}", subscriptions: [${a}] },`}).join(`
284
+ `);return{build:`
285
+ const topics = createTopicContext(env, LUNORA_TOPICS);
286
+ `,contextField:`
287
+ topics,`,importLines:['import type { TopicBindingSpec } from "@lunora/queue";','import { createTopicContext } from "@lunora/queue";'],specs:`
288
+ /** Wiring specs for \`ctx.topics\` (codegen-derived from \`lunora/queues.ts\`): each topic's subscription queues. */
289
+ const LUNORA_TOPICS: ReadonlyArray<TopicBindingSpec> = [
290
+ ${t}
291
+ ];
292
+ `}},te=(e,r)=>{if(e.length===0)return{build:"",importLines:[],specs:""};const t=e.map(n=>(l(n.name,`service "${n.name}"`),l(n.binding,`service binding "${n.binding}"`),` { binding: "${n.binding}", name: "${n.name}"${n.rpcEntrypoint===void 0?"":", rpc: true"} },`)).join(`
293
+ `);return{build:`
294
+ const services = createServices(env, LUNORA_SERVICES);
295
+ `,importLines:[`import type { ServiceBindingSpec } from "${r}";`,`import { createServices } from "${r}";`],specs:`
296
+ /** Wiring specs for \`ctx.services\` (codegen-derived from \`lunora.config\` \`services\`). */
297
+ const LUNORA_SERVICES: ReadonlyArray<ServiceBindingSpec> = [
298
+ ${t}
299
+ ];
300
+ `}},ne=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const t of e)l(t.exportName,`agent export "${t.exportName}"`),l(t.className,`agent class "${t.className}"`);const r=e.map(t=>` { className: "${t.className}", exportName: "${t.exportName}"${t.publicRun===!0?", publicRun: true":""} },`).join(`
301
+ `);return{build:`
302
+ const agents = createAgentContext(env, LUNORA_AGENTS, { exports: this.state.exports });
303
+ `,contextField:`
304
+ agents,`,importLines:['import { createAgentContext } from "@lunora/agent";','import type { AgentBindingSpec } from "@lunora/agent";'],specs:`
305
+ /** Wiring specs for \`ctx.agents\` (codegen-derived from \`lunora/agents.ts\`). */
306
+ const LUNORA_AGENTS: ReadonlyArray<AgentBindingSpec> = [
307
+ ${r}
308
+ ];
309
+ `}},v=(e,r,t,n,a)=>({constant:`
310
+ ${a}
311
+ const ${e} = ${b(n,r)};
312
+ `,override:`
313
+ protected override ${t}(): ${r} {
314
+ return ${e};
315
+ }
316
+ `}),re=e=>{if(e.length===0)return{constant:"",override:""};const r={workflows:e.map(t=>({className:t.className,exportName:t.exportName,name:t.name}))};return v("LUNORA_WORKFLOWS_INFO","WorkflowsResult","workflowsMetadata",r,"/** Read-only declared-workflow metadata (discovered from `lunora/workflows.ts`) served via `__lunora_admin__:listWorkflows` for the studio's workflows view. */")},oe=e=>{if(e.length===0)return{constant:"",override:""};const r={queues:e.map(t=>({binding:t.bindingName,...t.tuning.deadLetterQueue===void 0?{}:{deadLetterQueue:t.tuning.deadLetterQueue},exportName:t.exportName,mode:t.mode,name:t.name,...t.topic===void 0?{}:{topic:t.topic}}))};return v("LUNORA_QUEUES_INFO","QueuesResult","queuesMetadata",r,"/** Read-only declared-queue metadata (discovered from `lunora/queues.ts`) served via `__lunora_admin__:listQueues` for the studio's queues view. */")},P=["attach","cancelPayment","cancelSubscription","capturePayment","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","refundPayment","track"],se=e=>e?{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
317
+ const paymentsByContext = new WeakMap<object, LunoraPayment>();
318
+ `,configField:`
319
+ payment?: (env: Record<string, unknown>) => PaymentsFromContextOptions;`,contextField:`
320
+ get payments(): LunoraPayment {
321
+ let payments = paymentsByContext.get(this);
322
+
323
+ if (payments === undefined) {
324
+ payments = config.payment
325
+ ? paymentsFromContext({ auth: { userId: userId ?? null }, db: this.db as unknown as LunoraPaymentDbLike }, config.payment(env))
326
+ : paymentStub;
327
+ paymentsByContext.set(this, payments);
328
+ }
329
+
330
+ return payments;
331
+ },`,stub:f("paymentStub: LunoraPayment","ctx.payments: no payment configured. Pass `payment` to createShardDO().",P,{cast:" as unknown as LunoraPayment",sync:!0})}:{build:"",configField:"",contextField:"",imports:[],stub:""},ae=(e,r,t,n,a)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","DispatchBookmark","ExportRow",...n?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...t?["QueuesResult"]:[],"RelatedPage","RunShardApplyCdcArgs","RunShardExportArgs","RunShardFindRelatedArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike",...a?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","DeliveryAuthorization","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SubscriptionIdentity","SystemReaderStorageLike","TelemetrySink",...e?["VectorBackfillProgress"]:[],...r?["WorkflowsResult"]:[],...e?["WriteHook"]:[]];export{j as a,M as b,Q as c,Z as d,K as e,ee as f,te as g,H as h,z as i,ne as j,se as k,re as l,oe as m,D as n,ae as o,I as p,U as q,f as r,V as s,G as t,J as u,Y as v,X as w};
@@ -0,0 +1,13 @@
1
+ import{LunoraError as y}from"@lunora/errors";import{R}from"./reserved-words-CW1QFbTd.mjs";import{acceptsAbsentIr as A}from"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{n as E}from"./dispatch-namespace-DwTjD7BU.mjs";const S=/^(?:"(?:[^"\\]|\\(?:["\\/bfnrt]|u[0-9A-Fa-f]{4}))*"|'[^'\\]*'|-?\d+(?:\.\d+)?|true|false|null)$/u,M=`// GENERATED by @lunora/codegen — do not edit.
2
+ // Run \`lunora codegen\` to regenerate.
3
+
4
+ `,K=(e=!1)=>e?{client:"lunorash/client",do:"lunorash/do",flags:"lunorash/flags",server:"lunorash/server",serverDataModel:"lunorash/server/data-model",serverDrizzle:"lunorash/server/drizzle",serverTypes:"lunorash/server/types",values:"lunorash/values"}:{client:"@lunora/client",do:"@lunora/do",flags:"@lunora/flags",server:"@lunora/server",serverDataModel:"@lunora/server/data-model",serverDrizzle:"@lunora/server/drizzle",serverTypes:"@lunora/server/types",values:"@lunora/values"},b=/^[A-Za-z_$][\w$]*$/u,B=/^[\w./-]+$/u,w=(e,n)=>{if(!b.test(e)||R.has(e))throw new y("INTERNAL",`@lunora/codegen: ${n} is not a valid JS identifier: ${JSON.stringify(e)}`)},F=(e,n)=>{if(!b.test(e))throw new y("INTERNAL",`@lunora/codegen: ${n} is not a valid JS identifier: ${JSON.stringify(e)}`)},G=e=>e.charAt(0).toUpperCase()+e.slice(1),g=e=>b.test(e)?e:JSON.stringify(e),k=e=>e==="__proto__"?`[${JSON.stringify(e)}]`:g(e),O=e=>{const n=new Map;for(const r of e){const t=n.get(r.filePath)??[];t.push(r),n.set(r.filePath,t)}return[...n.entries()].toSorted(([r],[t])=>r.localeCompare(t))},U=(e,n,r)=>{const[t,l]=r==="type"?[g,";"]:[k,","],d={children:new Map};for(const[o,$]of O(e)){let a=d;for(const f of E(o)){let c=a.children.get(f);c===void 0&&(c={children:new Map},a.children.set(f,c)),a=c}a.file={entries:$,path:o}}const u=o=>o.file?.path??u(o.children.values().next().value),p=(o,$)=>{const a=" ".repeat($),{entries:f=[],path:c=""}=o.file??{},h=f.find(s=>o.children.has(s.exportName));if(h!==void 0){const s=u(o.children.get(h.exportName));throw new y("NAMESPACE_COLLISION",`Namespace collision: the export "${h.exportName}" of "${c}" and "${s}" both resolve to api.${[...E(c),h.exportName].join(".")}. Rename the export or the folder.`)}const _=f.toSorted((s,m)=>s.exportName.localeCompare(m.exportName)).map(s=>`${a}${n(s)}`),I=[...o.children.entries()].toSorted(([s],[m])=>s.localeCompare(m)).map(([s,m])=>`${a}${t(s)}: {
5
+ ${p(m,$+1).join(`
6
+ `)}
7
+ ${a}}${l}`);return[..._,...I]};return p(d,1).join(`
8
+ `)},j={any:"unknown",bigint:"bigint",boolean:"boolean",bytes:"ArrayBuffer",date:"number",geoPoint:"{ lat: number; lng: number }",null:"null",number:"number",storage:"string",string:"string",timestamp:"number"},D=e=>{if(e===void 0)return"unknown";if(!S.test(e))throw new y("INTERNAL",`@lunora/codegen: v.literal() argument is not a parseable string/number/boolean/null literal: ${JSON.stringify(e)}`);return e},i=e=>e.column?.notNull===!1?`${T(e)} | null`:T(e),T=e=>{const n=j[e.kind];if(n!==void 0)return n;switch(e.kind){case"array":return`Array<${e.inner?i(e.inner):"unknown"}>`;case"from":return e.tsType??"unknown";case"id":{const r=e.tableName??"_unknown_";return w(r,"v.id() table name"),`Id<"${r}">`}case"literal":return D(e.literalValue);case"object":return e.shape?`{ ${Object.entries(e.shape).map(([t,l])=>N(t,l)).join("; ")} }`:"Record<string, unknown>";case"optional":return`${e.inner?i(e.inner):"unknown"} | undefined`;case"record":{const r=e.keyType?i(e.keyType):"string",t=e.valueType?i(e.valueType):"unknown";return`Record<${r}, ${t}>`}case"union":return e.members&&e.members.length>0?e.members.map(r=>i(r)).join(" | "):"never";default:return"unknown"}},N=(e,n)=>{const r=g(e);if(n.kind==="optional"){const t=n.inner?i(n.inner):"unknown";return`${r}?: ${t}`}return A(n)?`${r}?: ${i(n)}`:`${r}: ${i(n)}`},V=e=>{const n=Object.entries(e);return n.length===0?"{}":`{ ${n.map(([r,t])=>N(r,t)).join("; ")} }`},x=e=>e.kind==="optional"||!!e.column?.hasDefault,L=e=>e.kind==="optional"&&e.inner?e.inner:e,v=e=>{w(e.name,"table name");const n=Object.entries(e.shape).map(([t,l])=>{const d=L(l),u=i(d),p=g(t);return x(l)?` ${p}?: ${u};`:` ${p}: ${u};`}).join(`
9
+ `),r=n?`
10
+ ${n}
11
+ `:"";return`export interface Insert_${e.name} {
12
+ _id?: Id<"${e.name}">;
13
+ _creationTime?: number;${r}}`};export{M as G,B as I,S as L,w as a,U as b,k as c,K as d,g as e,v as f,F as g,x as i,G as p,V as r,L as u,i as v};
@@ -0,0 +1 @@
1
+ import{posix as h,dirname as w,join as F}from"node:path";import{Node as l,SyntaxKind as g,DiagnosticCategory as K}from"ts-morph";import{lunoraRelativePath as B}from"./isTestPath-B81lOULB.mjs";let v,S;const Oe=e=>{const t=v,n=[];v=n;try{return{erased:n,value:e()}}finally{v=t}},Ue=e=>{v?.push(...e)},V=e=>{for(const t of e.getAncestors())if(l.isVariableDeclaration(t))return t.getName()},y=(e,t)=>{v?.push({exportName:V(e),filePath:e.getSourceFile().getFilePath(),line:e.getStartLineNumber(),rendered:t})},Pe=e=>{S!==void 0&&y(S,e)},Le=(e,t)=>{const n=S;S=e;try{return t()}finally{S=n}},W=(e,t)=>{const n=e.exportName??`line ${e.line.toString()}`;return{cacheKey:`procedure_return_type_erased:${t}:${n}`,categories:["SCHEMA"],description:"Codegen renders a procedure's return type into `_generated/`, where only names that resolve from that directory may appear. A type it can neither name nor reproduce structurally — a class instance, a call or index signature, a recursive or very deeply nested shape — is emitted as `unknown` instead, so callers lose the shape while the runtime still returns it.",detail:`\`${n}\` in \`${t}\` (line ${e.line.toString()}) returns \`${e.rendered}\`, which codegen could not reproduce — its generated type is \`unknown\`.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,filePath:t,line:e.line,rendered:e.rendered},name:"procedure_return_type_erased",remediation:"Declare the shape explicitly with `.output(...)`, or export the type from the module that declares it so codegen can name it. A class instance cannot cross the wire at all — return a plain object.",title:"Procedure return type is missing from the generated type"}},Fe=(e,t)=>{const n=new Map;for(const r of e){const s=W(r,B(t,r.filePath));n.set(s.cacheKey,s)}return[...n.values()].toSorted((r,s)=>r.cacheKey.localeCompare(s.cacheKey))},q=/\bany\b(?!\s*(?:\?\s*)?:)/u,G=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,X=e=>q.test(e.replaceAll(G,"")),H="/_generated/",J=e=>{const t=[e.getSymbol(),e.getAliasSymbol()].flatMap(n=>n?.getDeclarations()??[]);return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},Y=/^(?<quote>["'])(?<specifier>.*)\k<quote>$/su,x=e=>{for(const t of e.getAncestors())if(l.isModuleDeclaration(t)){const n=Y.exec(t.getName());if(n?.groups?.specifier!==void 0)return n.groups.specifier}},M=new WeakMap,z=(e,t)=>{const n=e.getSymbol();if(n===void 0)return;let r=M.get(n.compilerSymbol);return r===void 0&&(r=new Map,M.set(n.compilerSymbol,r)),r.has(t)||r.set(t,n.getExport(t)??e.getExportSymbols().find(s=>s.getName()===t)),r.get(t)},C=(e,t)=>e.getNamespaceImport()!==void 0||e.getNamedImports().some(n=>n.getName()===t),Q=(e,t,n)=>e.getModuleSpecifierValue()===t&&C(e,n)?n:void 0,Z=(e,t)=>{const n=e.getDefaultImport();if(n===void 0)return;const r=n.getSymbol();return(r?.getAliasedSymbol()??r)?.getDeclarations().includes(t)===!0?"default":void 0},ee=(e,t,n)=>{if(!C(e,n))return;const r=e.getModuleSpecifierSourceFile(),s=r===void 0?void 0:z(r,n);return(s?.getAliasedSymbol()??s)?.getDeclarations().includes(t)===!0?n:void 0},te=/^\.\.?(?:$|\/)/u,ne=new Map([[".cjs",".cjs"],[".cts",".cjs"],[".d.ts",".js"],[".js",".js"],[".jsx",".jsx"],[".mjs",".mjs"],[".mts",".mjs"],[".ts",".js"],[".tsx",".js"]]),re=(e,t)=>{const n=t.getModuleSpecifierValue();if(!te.test(n))return;const r=t.getModuleSpecifierSourceFile(),s=r===void 0?void 0:ne.get(r.getExtension());if(r===void 0||s===void 0)return;const i=`${h.join(r.getDirectoryPath(),r.getBaseNameWithoutExtension())}${s}`,o=h.relative(e.getDirectoryPath(),i);return o.startsWith(".")?o:`./${o}`},se=(e,t,n)=>{const r=x(t);for(const s of e.getImportDeclarations()){const i=r===void 0?Z(s,t)??ee(s,t,n):Q(s,r,n);if(i!==void 0)return{exportName:i,specifier:re(e,s)??s.getModuleSpecifierValue()}}},oe=(e,t)=>Object.keys(t.getProject().getCompilerOptions().paths??{}).some(n=>{const r=n.indexOf("*");return r===-1?e===n:e.startsWith(n.slice(0,r))&&e.endsWith(n.slice(r+1))}),f={kind:"verbatim"},p={kind:"expand"},ie=new Set([g.ClassDeclaration,g.EnumDeclaration,g.EnumMember,g.InterfaceDeclaration,g.TypeAliasDeclaration]),ae=e=>x(e)!==void 0||l.isExportable(e)&&e.isExported(),ce=(e,t)=>new RegExp(String.raw`(?<![$\w])${t.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`)}(?![$\w])`,"u").test(e),O=(e,t,n,r)=>{const s=e.getSourceFile();if(s.getSymbol()===void 0&&x(e)===void 0||!ie.has(e.getKind()))return f;const i=s.getFilePath();if(i.includes(H))return f;if(i===n)return p;const o=l.isEnumMember(e)?e.getParent():e;if(!l.hasName(o))return p;const c=se(t.getSourceFile(),o,o.getName());return c===void 0?ae(o)||!ce(r(),o.getName())?f:p:oe(c.specifier,t)?p:{kind:"qualify",qualified:c}},ue=new Set([g.ClassDeclaration,g.EnumDeclaration,g.FunctionDeclaration,g.ModuleDeclaration]),_=e=>{const t=e?.getDeclarations()??[];return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},le=e=>{for(const t of e.getDeclarations()){const n=t.getFirstChildByKind(g.ComputedPropertyName);if(n!==void 0){let r=n.getExpression();for(;l.isPropertyAccessExpression(r);)r=r.getExpression();return r}}},ge=(e,t)=>{if(e.getProperties().some(s=>{if(!s.getName().startsWith("__@"))return!1;const i=le(s);return i===void 0||!_(i.getSymbol())}))return!0;const r=e.getSymbol();return r!==void 0&&r.getDeclarations().some(s=>ue.has(s.getKind()))&&!_(r)&&t().startsWith("typeof ")},U=(e,t,n)=>{const r=e.getAliasSymbol(),s=e.getSymbol(),i=new Set((r??s)?.getDeclarations());let o=!1,c;const a=()=>(c??=e.getText(t),c);for(const u of[s,r].flatMap(d=>d?.getDeclarations()??[])){const d=O(u,t,n,a);if(d.kind==="qualify"&&i.has(u))return d;o||=d.kind!=="verbatim"}return o||ge(e,a)?p:f},de=(e,t,n)=>{const r=l.isPropertySignature(e)||l.isPropertyDeclaration(e)?e.getTypeNode():void 0;if(r===void 0)return f;let s=!1;for(const i of[r,...r.getDescendantsOfKind(g.TypeReference)].filter(o=>l.isTypeReference(o))){const o=i.getTypeName().getSymbol();for(const c of(o?.getAliasedSymbol()??o)?.getDeclarations()??[]){const a=O(c,t,n,()=>i.getText());if(a.kind==="qualify")return a;s||=a.kind!=="verbatim"}}return s?p:f},fe=/^[A-Za-z_$][\w$]*$/u,me=e=>fe.test(e)?e:JSON.stringify(e),P=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},A=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0&&!e.getProperties().some(t=>t.getName().startsWith("__@")),T=(e,t,n,r=new Set)=>r.has(e)?!1:(r.add(e),U(e,t,n).kind!=="verbatim"||P(e).some(s=>T(s,t,n,r))?!0:A(e)?e.getProperties().some(s=>s.getDeclarations().some(i=>de(i,t,n).kind!=="verbatim")?!0:T(s.getTypeAtLocation(t),t,n,r)):!1),pe=(e,t)=>{const n=e.getValueDeclaration()??e.getDeclarations()[0];return n&&(l.isPropertySignature(n)||l.isPropertyDeclaration(n))&&n.hasQuestionToken()?!0:t.isUnion()&&t.getUnionTypes().some(r=>r.isUndefined())},L=(e,t)=>e!==void 0&&(A(e)||e.isString()||e.isNumber()||e.isBigInt()||e.isBoolean()||e.isLiteral()||e.isBooleanLiteral()||e.isEnumLiteral()||e.isTemplateLiteral()||e.isNull()||e.isUndefined()||e.isAny()||e.isUnknown()||e.isNever()||e.isVoid())?t:`(${t})`,ve=32,Se=8,ye=(e,t,n,r,s,i)=>{const o=e.getArrayElementType(),c=o?i(o,t,n,r,s):void 0;if(c!==void 0)return`${L(o,c)}[]`},Ee=(e,t,n,r,s,i)=>{const o=[];for(const c of e.getUnionTypes()){const a=i(c,t,n,r,s);if(a===void 0)return;o.push(a)}return o.join(" | ")},be=(e,t,n,r,s,i)=>{const o=[];for(const c of e.getIntersectionTypes()){const a=i(c,t,n,r,s);if(a===void 0)return;o.push(L(c,a))}return o.join(" & ")},Te=(e,t,n,r,s,i)=>{if(!A(e))return;const o=[];for(const c of e.getProperties()){const a=c.getTypeAtLocation(t),u=pe(c,a),d=u&&a.isUnion()?a.getUnionTypes().filter(N=>!N.isUndefined()):[a],D=[];for(const N of d){const I=i(N,t,n,r+1,s);if(I===void 0)return;D.push(I)}o.push(`${me(c.getName())}${u?"?":""}: ${D.join(" | ")}`)}return o.length>0?`{ ${o.join("; ")} }`:"{}"},Ae=e=>{const t=e.getLiteralValue();return typeof t=="string"?JSON.stringify(t):typeof t=="number"?String(t):void 0},Ne=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isClassDeclaration(t)||l.isClassExpression(t)),E=(e,t,n,r,s=new Set)=>{if(r.has(e)||s.has(e))return!1;if(n>ve)return!0;const i=new Set(r).add(e);if(P(e).some(u=>E(u,t,n+1,i,s)))return!0;const o=e.getArrayElementType();if(o!==void 0)return E(o,t,n+1,i,s);if(J(e))return s.add(e),!1;if(e.getCallSignatures().length>0||e.getConstructSignatures().length>0||[e.getSymbol(),e.getAliasSymbol()].flatMap(u=>u?.getDeclarations()??[]).some(u=>l.isClassDeclaration(u)||l.isClassExpression(u)))return!0;const a=A(e)&&e.getProperties().some(u=>E(u.getTypeAtLocation(t),t,n+1,i,s));return a||s.add(e),a},xe=(e,t,n,r,s,i,o)=>{const c=[];for(const a of t.getAliasSymbol()===void 0?t.getTypeArguments():t.getAliasTypeArguments()){const u=o(a,n,r,s+1,i);if(u===void 0)return;c.push(u)}return`import("${e.specifier}").${e.exportName}${c.length>0?`<${c.join(", ")}>`:""}`},De=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isEnumDeclaration(t)||l.isEnumMember(t)),m=(e,t,n,r,s)=>{if(r>Se||s.has(e))return;const i=U(e,t,n);if(i.kind==="verbatim"&&!T(e,t,n))return e.getText(t);const o=new Set(s).add(e);if(!Ne(e)){if(e.isEnumLiteral())return Ae(e);if(i.kind==="qualify"&&!De(e)){const c=xe(i.qualified,e,t,n,r,o,m);if(c!==void 0)return c}return e.isArray()?ye(e,t,n,r,o,m):e.isUnion()?Ee(e,t,n,r,o,m):e.isIntersection()?be(e,t,n,r,o,m):Te(e,t,n,r,o,m)}},R=new WeakMap,Ie=e=>{const t=R.get(e.compilerNode);if(t)return t;const n=e.getPreEmitDiagnostics().filter(r=>r.getCategory()===K.Error);return R.set(e.compilerNode,n),n},b=e=>{const t=e.getMessageText();return typeof t=="string"?t:t.getMessageText()},he=/is of type 'unknown'|on type '\{\}'/,we=e=>he.test(e),Me=/has no exported member '([^']+)'/,_e=(e,t,n,r)=>{const s=e.getSourceFile();for(const i of e.getDescendantsOfKind(g.Identifier))for(const o of i.getSymbol()?.getDeclarations()??[]){const c=o.getStart();if(o.getSourceFile()!==s||c>=n&&c<=r)continue;const a=t.find(u=>{const d=u.getStart();return d!==void 0&&d>=o.getStart()&&d<=o.getEnd()});if(a!==void 0)return b(a)}},$=e=>{const t=e.getStart(),n=e.getEnd(),r=Ie(e.getSourceFile()),s=r.find(a=>{const u=a.getStart();return u!==void 0&&u>=t&&u<=n});if(s===void 0){const a=_e(e,r,t,n);return a===void 0?void 0:{derivative:!0,message:a}}const i=b(s);if(!we(i))return{derivative:!1,message:i};const o=new Set(e.getDescendantsOfKind(g.Identifier).map(a=>a.getText())),c=r.find(a=>{const u=Me.exec(b(a))?.[1];return u!==void 0&&o.has(u)});return{derivative:!0,message:c?`${i}; caused by: ${b(c)}`:i}},Re=e=>{const t=e.getProject().getFileSystem();let n=w(e.getFilePath());for(;;){const r=F(n,"package.json");if(t.fileExistsSync(r)){let i;try{i=JSON.parse(t.readFileSync(r))}catch{return}const o=typeof i=="object"&&i!==null?i.name:void 0;return typeof o=="string"?o:void 0}const s=w(n);if(s===n)return;n=s}},k=e=>{const t=e.getSymbol()??e.getAliasSymbol(),n=t?.getName()==="SseEvent"?t.getDeclarations()[0]:void 0;return n!==void 0&&Re(n.getSourceFile())==="@lunora/server"},$e=e=>{const t=e.isUnion()?e.getUnionTypes():[e];if(t.some(n=>k(n)))return t.flatMap(n=>{const r=k(n)?n.getTypeArguments()[0]??n:n;return r.isUnion()?r.getUnionTypes():[r]})},j=(e,t)=>{const n=e.getText(t);if(!n||n==="any"||n==="never"||n==="unknown"){const s=$(t);return s!==void 0&&(n!=="unknown"||s.derivative)&&y(t,`${n||"any"} (${s.message})`),"unknown"}if(X(n)){const s=$(t);return s!==void 0&&y(t,`${n} (${s.message})`),"unknown"}if(E(e,t,0,new Set))return"unknown";const r=t.getSourceFile().getFilePath();if(T(e,t,r)){const s=m(e,t,r,0,new Set);return s===void 0&&y(t,n),s??"unknown"}return n},Ke=(e,t=!1)=>{const n=e.getType().getCallSignatures()[0];if(!n)return"unknown";let r=n.getReturnType();const i=(r.getSymbol()??r.getAliasSymbol())?.getName();if(i==="Promise"||i==="AsyncIterable"||i==="AsyncIterableIterator"||i==="AsyncGenerator"){const a=r.getTypeArguments()[0];a&&(r=a)}const o=t?$e(r):void 0;if(o===void 0)return j(r,e);const c=o.map(a=>j(a,e));return c.includes("unknown")?"unknown":[...new Set(c)].join(" | ")};export{T as a,Pe as b,Oe as c,Fe as d,m as e,X as i,Le as p,Ue as r,Ke as u};