@lunora/codegen 1.0.0-alpha.4 → 1.0.0-alpha.400

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/LICENSE.md +6 -0
  2. package/README.md +1 -1
  3. package/__assets__/package-og.svg +1 -1
  4. package/dist/index.d.mts +4600 -1095
  5. package/dist/index.d.ts +4600 -1095
  6. package/dist/index.mjs +1 -29
  7. package/dist/packem_shared/AGENTS_FILENAME-Cli3X44r.mjs +1 -0
  8. package/dist/packem_shared/ALL_NOTIFY_CHANNELS-D1SaOfnm.mjs +1 -0
  9. package/dist/packem_shared/CAPABILITY_PROBES-BuNEmlCO.mjs +25 -0
  10. package/dist/packem_shared/COMPANION_BINDING-Da_v9XpC.mjs +1 -0
  11. package/dist/packem_shared/CONTAINERS_FILENAME-BX1_ALLp.mjs +1 -0
  12. package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
  13. package/dist/packem_shared/DEFAULT_TARGET-C-gcdslJ.mjs +1 -0
  14. package/dist/packem_shared/FLAGS_FILENAME-DY3yo1u_.mjs +1 -0
  15. package/dist/packem_shared/GENERATED_HEADER-B-tYRlRG.mjs +1 -0
  16. package/dist/packem_shared/LUNORA_ERROR_CODES-CjACC-MQ.mjs +1 -0
  17. package/dist/packem_shared/MUTATORS_FILENAME-Ck_l1lz7.mjs +1 -0
  18. package/dist/packem_shared/OPENRPC_VERSION-Dr6Xjldk.mjs +3 -0
  19. package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs +1 -0
  20. package/dist/packem_shared/QUEUES_FILENAME-C5xotY-M.mjs +1 -0
  21. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-CxmZ2igT.mjs +52 -0
  22. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs +2 -0
  23. package/dist/packem_shared/SHAPES_FILENAME-DCtGHMEm.mjs +1 -0
  24. package/dist/packem_shared/SchemaSnapshotParseError-DnAuFdpl.mjs +17 -0
  25. package/dist/packem_shared/WORKFLOWS_FILENAME-CyV1HQaP.mjs +1 -0
  26. package/dist/packem_shared/attribution-DjweYNgJ.mjs +1 -0
  27. package/dist/packem_shared/buildOpenApiDocument-BTp9vkHw.mjs +3 -0
  28. package/dist/packem_shared/capabilitiesUsedBy-SSrieNZ1.mjs +1 -0
  29. package/dist/packem_shared/chain-DWwd9wXd.mjs +1 -0
  30. package/dist/packem_shared/classify-procedure-call-BuF5PNwV.mjs +1 -0
  31. package/dist/packem_shared/companionServiceBinding-ChINWo8k.mjs +1 -0
  32. package/dist/packem_shared/context-property-calls-BcUYQ6ph.mjs +1 -0
  33. package/dist/packem_shared/context-root-2wag3akK.mjs +1 -0
  34. package/dist/packem_shared/createCodegenProject-C8N4Zm8h.mjs +1 -0
  35. package/dist/packem_shared/database-calls-B_85LJIk.mjs +1 -0
  36. package/dist/packem_shared/declared-output-Iaar469J.mjs +1 -0
  37. package/dist/packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs +1 -0
  38. package/dist/packem_shared/discoverAuthApiCalls-f8_WRQEA.mjs +1 -0
  39. package/dist/packem_shared/discoverCrons-DTqSuSDh.mjs +1 -0
  40. package/dist/packem_shared/discoverFunctions-D4GIaVIP.mjs +1 -0
  41. package/dist/packem_shared/discoverHttpRoutes-2gxHuLgt.mjs +1 -0
  42. package/dist/packem_shared/discoverHyperdriveCalls-DaJLewG0.mjs +1 -0
  43. package/dist/packem_shared/discoverInserts-CLh70kVu.mjs +1 -0
  44. package/dist/packem_shared/discoverMaskProcedures-C0VcUGpb.mjs +1 -0
  45. package/dist/packem_shared/discoverMigrations-e5_NQdf-.mjs +1 -0
  46. package/dist/packem_shared/discoverNondeterministicCalls-CrXAegUc.mjs +1 -0
  47. package/dist/packem_shared/discoverQueries-T8b_7ZZ-.mjs +1 -0
  48. package/dist/packem_shared/discoverR2sqlCalls-CY0xmIWX.mjs +1 -0
  49. package/dist/packem_shared/discoverRlsMetadata-CnVvP2Ps.mjs +1 -0
  50. package/dist/packem_shared/discoverRlsProcedures-DttY0Jld.mjs +1 -0
  51. package/dist/packem_shared/discoverSandboxUsage-X0SECo-x.mjs +1 -0
  52. package/dist/packem_shared/discoverSchema-DDvMQheA.mjs +1 -0
  53. package/dist/packem_shared/discoverStorageRulesMetadata-t_oMSn0L.mjs +1 -0
  54. package/dist/packem_shared/dispatch-namespace-DwTjD7BU.mjs +1 -0
  55. package/dist/packem_shared/emitAgents-ChXyTTzS.mjs +1 -0
  56. package/dist/packem_shared/emitApi-Cdc8MeNK.mjs +147 -0
  57. package/dist/packem_shared/emitApp-xunr1-_c.mjs +1142 -0
  58. package/dist/packem_shared/emitCrons-BQjDleCe.mjs +138 -0
  59. package/dist/packem_shared/emitDataModel-MjAOi3KM.mjs +114 -0
  60. package/dist/packem_shared/emitDrizzleSchema-Dszoyymv.mjs +15 -0
  61. package/dist/packem_shared/emitFunctions-BIMKBLQ8.mjs +528 -0
  62. package/dist/packem_shared/emitServer-DNwuNiay.mjs +1 -0
  63. package/dist/packem_shared/emitShard-CueduzG1.mjs +1 -0
  64. package/dist/packem_shared/exported-procedure-chains-BaxQ8C-S.mjs +1 -0
  65. package/dist/packem_shared/fingerprintSchemaSources-PmhepCVj.mjs +1 -0
  66. package/dist/packem_shared/formatAdvisories-BCVASH7N.mjs +2 -0
  67. package/dist/packem_shared/handler-reference-D2EE2q-4.mjs +1 -0
  68. package/dist/packem_shared/index-Dd6T5nSP.mjs +1 -0
  69. package/dist/packem_shared/index-fVYBrxkP.mjs +1 -0
  70. package/dist/packem_shared/ip-reads-WFubgB1G.mjs +1 -0
  71. package/dist/packem_shared/isD1GlobalTable-udvHAAzD.mjs +1 -0
  72. package/dist/packem_shared/isTestPath-ClgKgMYM.mjs +1 -0
  73. package/dist/packem_shared/isTypedSchema-CDv3pJB6.mjs +4 -0
  74. package/dist/packem_shared/json-data-Chfs2Cz5.mjs +1 -0
  75. package/dist/packem_shared/loadProjectConfig-CtcJHHKS.mjs +1 -0
  76. package/dist/packem_shared/module-specifiers-BctA0m_p.mjs +1 -0
  77. package/dist/packem_shared/modules-DE0ksIeR.mjs +1 -0
  78. package/dist/packem_shared/parse-validator-BisfC8bR.mjs +1 -0
  79. package/dist/packem_shared/platform-8oj7iXQy.mjs +1 -0
  80. package/dist/packem_shared/property-name-7cBlgK_O.mjs +1 -0
  81. package/dist/packem_shared/qualifiers-ClaCHu0X.mjs +1 -0
  82. package/dist/packem_shared/readPackageDependencies-RHhGiz0k.mjs +1 -0
  83. package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
  84. package/dist/packem_shared/reserved-words-CW1QFbTd.mjs +1 -0
  85. package/dist/packem_shared/schema-BgM8A3XV.mjs +1 -0
  86. package/dist/packem_shared/schemaFromIr-CByOxuZb.mjs +1 -0
  87. package/dist/packem_shared/server-C4h6-BZx.mjs +369 -0
  88. package/dist/packem_shared/shard-DNpjvEod.mjs +1885 -0
  89. package/dist/packem_shared/shard-runtime-knn-ER8x.mjs +349 -0
  90. package/dist/packem_shared/shared-DhqnD5R3.mjs +13 -0
  91. package/dist/packem_shared/static-literal-BwDHHjEJ.mjs +1 -0
  92. package/dist/packem_shared/unwrap-handler-return-BpigsVD6.mjs +1 -0
  93. package/dist/sdk/index.d.mts +288 -0
  94. package/dist/sdk/index.d.ts +288 -0
  95. package/dist/sdk/index.mjs +372 -0
  96. package/package.json +22 -7
  97. package/dist/packem_shared/CONTAINERS_FILENAME-0K-pjNb8.mjs +0 -224
  98. package/dist/packem_shared/CodegenDiagnosticError-54jWDxA9.mjs +0 -22
  99. package/dist/packem_shared/GENERATED_HEADER-DF1hQcix.mjs +0 -2495
  100. package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
  101. package/dist/packem_shared/OPENRPC_VERSION-C7zKVeKi.mjs +0 -60
  102. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-C5UlpWKF.mjs +0 -922
  103. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-DzLDbWk3.mjs +0 -233
  104. package/dist/packem_shared/WORKFLOWS_FILENAME-DRDQdhfq.mjs +0 -84
  105. package/dist/packem_shared/buildOpenApiDocument-Cns1EkCQ.mjs +0 -183
  106. package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
  107. package/dist/packem_shared/discoverAuthApiCalls-C35R6z0T.mjs +0 -62
  108. package/dist/packem_shared/discoverCrons-BL6iGuJ3.mjs +0 -254
  109. package/dist/packem_shared/discoverFunctions-DEgAcRuD.mjs +0 -460
  110. package/dist/packem_shared/discoverHttpRoutes-C978pBiG.mjs +0 -131
  111. package/dist/packem_shared/discoverInserts-CRQdXvHO.mjs +0 -39
  112. package/dist/packem_shared/discoverMaskProcedures-B64zA740.mjs +0 -217
  113. package/dist/packem_shared/discoverMigrations-Doj_-BAA.mjs +0 -91
  114. package/dist/packem_shared/discoverNondeterministicCalls-4KiPQxQU.mjs +0 -122
  115. package/dist/packem_shared/discoverQueries-BkIi0dBD.mjs +0 -62
  116. package/dist/packem_shared/discoverR2sqlCalls-BpDqvcUn.mjs +0 -80
  117. package/dist/packem_shared/discoverRlsMetadata-DpRB1HMe.mjs +0 -280
  118. package/dist/packem_shared/discoverSchema-BBulgGbH.mjs +0 -542
  119. package/dist/packem_shared/discoverStorageRulesMetadata-DAqJUxUv.mjs +0 -97
  120. package/dist/packem_shared/emitApp-Ci_hcJNO.mjs +0 -599
  121. package/dist/packem_shared/formatAdvisories-8NIv1k0I.mjs +0 -69
  122. package/dist/packem_shared/parse-validator-tuQtHrsr.mjs +0 -132
  123. package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
  124. package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
@@ -0,0 +1,349 @@
1
+ import{LunoraError as R}from"@lunora/errors";import{r as $}from"./json-data-Chfs2Cz5.mjs";import{CAPABILITIES as S}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{a as l,G as f,I as w}from"./shared-DhqnD5R3.mjs";import{s as L}from"./platform-8oj7iXQy.mjs";const M=e=>e?{importFragment:"serveRelationFanout, ",override:`
2
+ protected override async runRelationFanoutRead(functionPath: string, args: Record<string, unknown>): Promise<unknown> {
3
+ this.ensureServable();
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:""},y=(e,r,t,{cast:n="",sync:s=[]}={})=>{const i=`throw new Error(${JSON.stringify(r)});`,c=t.map(u=>` ${u}: ${s===!0||s.includes(u)?"":"async "}() => {
10
+ ${i}
11
+ },`).join(`
12
+ `);return`
13
+ const ${e} = {
14
+ ${c}
15
+ }${n};
16
+ `},x={build:"",configField:"",contextField:"",importLines:[],stub:""},K=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
+ `},H=(e,r)=>e?{build:`
26
+ const flags: import("${r}").LunoraFlags = createFlags(flagsConfig, env, {
27
+ provider: () => config.flags?.(env),
28
+ targetingKey: () => flagsConfig.identify?.({ identity: readIdentity() ?? null, userId: readUserId() ?? 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:""}:x,G=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:""}:x,V=e=>e?{build:`
37
+ const envConfig = lunoraEnvContract.${e.exportName}(env);
38
+ `,configField:"",contextField:`
39
+ env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:x,J=(e,r,t)=>{if(!r)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const n=a=>`
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: ${a},
44
+ });`,s=`
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 = ${$(e,'ReadonlyArray<{ key: string; type: "boolean" | "number" | "object" | "string" }>')};
47
+ `,c=`
48
+ protected override async evaluateFlags(context?: Record<string, unknown>): Promise<FlagsResult> {${n("undefined")}
49
+ const evalContext = context as import("${t}").EvaluationContext | undefined;
50
+ // Concurrent, not sequential: against a remote provider every read is a round
51
+ // trip, and the request-scoped bind in createFlags is shared by all of them.
52
+ const evaluations: FlagsResult["flags"] = await Promise.all(
53
+ LUNORA_FLAG_KEYS.map(async (entry) => {
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
+ return { errorCode: details.errorCode, key: entry.key, reason: details.reason, type: entry.type, value: details.value, variant: details.variant };
64
+ }),
65
+ );
66
+
67
+ return { configured: true, flags: evaluations };
68
+ }
69
+ `,u=`
70
+ protected override runFlagSubscriptionRead(_functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<unknown> {${n("() => flagsConfig.identify?.({ identity: identity?.identity ?? null, userId: identity?.userId ?? null })")}
71
+ const key = typeof args.key === "string" ? args.key : "";
72
+
73
+ // SECURITY: the reactive channel is public (any socket, no auth). Serve
74
+ // ONLY statically-discovered flag keys — an arbitrary client-supplied key
75
+ // would let a subscriber probe the value of internal/unreleased flags the
76
+ // app never exposes. Unknown key ⇒ the "nothing to deliver" sentinel.
77
+ // eslint-disable-next-line unicorn/no-null -- the base hook's "nothing to deliver" sentinel
78
+ if (key.length === 0 || !LUNORA_FLAG_KEYS.some((entry) => entry.key === key)) {
79
+ return Promise.resolve(null);
80
+ }
81
+
82
+ // SECURITY: evaluate under the socket's server-verified identity ONLY
83
+ // (the targetingKey resolved above). Client-supplied targeting context is
84
+ // NOT honored on this public channel — otherwise a subscriber could spoof
85
+ // targeting attributes (e.g. plan/role) to unlock a flag gated on them.
86
+ const context = undefined;
87
+
88
+ if (args.type === "number") {
89
+ return flags.number(key, typeof args.default === "number" ? args.default : 0, context);
90
+ }
91
+
92
+ if (args.type === "string") {
93
+ return flags.string(key, typeof args.default === "string" ? args.default : "", context);
94
+ }
95
+
96
+ if (args.type === "object") {
97
+ return flags.object(key, (args.default ?? {}) as import("${t}").JsonValue, context);
98
+ }
99
+
100
+ return flags.boolean(key, typeof args.default === "boolean" ? args.default : false, context);
101
+ }
102
+ `;return{constant:s,evaluateOverride:c,subscriptionOverride:u}},A=()=>({build:`
103
+ const aiBinding = config.ai?.(env) ?? (env as Record<string, unknown>).AI;
104
+ // Correlate AI-Gateway-routed calls with the Lunora trace: thread the
105
+ // function path + trace id into createAi, which folds them into the
106
+ // gateway's \`metadata\`. Mirror the tracer's anchor guard — a deferred
107
+ // subscription re-run must not borrow a concurrent dispatch's trace, so
108
+ // read \`getCurrentTrace()\` only on the synchronous (non-threaded-identity) path.
109
+ const aiTrace = options.identity ? undefined : this.getCurrentTrace();
110
+ // \`telemetry\` gives every model call an \`ai.generate\` / \`ai.stream\` span
111
+ // and \`gen_ai.usage.*\` token + cost counters attributed to this function.
112
+ const ai: LunoraAi = createAi({
113
+ binding: aiBinding as AiBindingLike | undefined,
114
+ env: env as Record<string, unknown>,
115
+ metadata: { functionPath: options.functionPath, traceId: aiTrace?.traceId },
116
+ telemetry: { metrics, trace },
117
+ });
118
+ `,configField:`
119
+ ai?: (env: Record<string, unknown>) => AiBindingLike;`,importLines:['import type { AiBindingLike, LunoraAi } from "@lunora/ai/create";','import { createAi } from "@lunora/ai/create";'],stub:""}),_=()=>({build:`
120
+ const access = lazyAccessFacade(readIdentity, readUserId);
121
+ `,configField:"",importLines:['import { lazyAccessFacade } from "@lunora/cloudflare-access/context";'],stub:""}),C=()=>({build:`
122
+ const r2sqlEnv = env as Record<string, unknown>;
123
+ const r2sqlAccountId = (r2sqlEnv.R2_SQL_ACCOUNT_ID ?? r2sqlEnv.CLOUDFLARE_ACCOUNT_ID) as string | undefined;
124
+ const r2sqlToken = r2sqlEnv.R2_SQL_TOKEN as string | undefined;
125
+ const r2sqlBucket = r2sqlEnv.R2_SQL_BUCKET as string | undefined;
126
+ const r2sql: R2SqlClient = config.r2sql
127
+ ? config.r2sql(env)
128
+ : r2sqlAccountId && r2sqlToken && r2sqlBucket
129
+ ? createR2Sql({ accountId: r2sqlAccountId, apiToken: r2sqlToken, bucket: r2sqlBucket })
130
+ : r2sqlStub;
131
+ `,configField:`
132
+ r2sql?: (env: Record<string, unknown>) => R2SqlClient;`,importLines:['import type { R2SqlClient } from "@lunora/bindings/r2sql";','import { createR2Sql } from "@lunora/bindings/r2sql";'],stub:y("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"]})}),F=()=>({build:`
133
+ const x402: X402Pay = config.x402
134
+ ? lazyX402Pay(config.x402(env), { getSecret: (name: string) => secrets.get(name) })
135
+ : x402Stub;
136
+ `,configField:`
137
+ x402?: (env: Record<string, unknown>) => X402PayConfig;`,importLines:['import type { X402Pay, X402PayConfig } from "@lunora/x402/pay";','import { lazyX402Pay } from "@lunora/x402/pay";'],stub:y("x402Stub: X402Pay","ctx.x402: no pay rail configured. Pass `x402` to createShardDO().",["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}),E={access:_,ai:A,r2sql:C,x402:F},O=e=>e.shardBinding==="bespoke",P=e=>typeof e.shardBinding=="object",m=" ",q=(e,r,t)=>{const n=`${e}Binding`,{factory:s}=t;let i=`(${n} as ${r})`;if(s!==void 0){const c=`${n} as ${t.bindingType??r}`;i=s.option===void 0?`${s.name}(${c})`:`${s.name}({ ${s.option}: ${c} })`}return`${n} ? ${i} : ${e}Stub`},W=(e,r,t)=>{const n=q(e,r,t),s=`${m}const ${e}Binding = config.${e}?.(env) ?? (env as Record<string, unknown>).${t.envName};
138
+ `,i=t.unvouchableReads??[];return i.length===0?`
139
+ ${s}${m}const ${e}: ${r} = ${n};
140
+ `:`
141
+ ${s}${m}// ${t.envName} is not this shard's SQLite, so nothing appends a \`__cdc_log\` entry
142
+ ${m}// when a value changes — a subscription that read one can never be proven
143
+ ${m}// current on reconnect and must re-snapshot. Reads only; writes stay unstamped.
144
+ ${m}const ${e}: ${r} = markUnvouchableReads(${n}, options.onRead, [
145
+ ${i.map(c=>`${m} ${JSON.stringify(c)},`).join(`
146
+ `)}
147
+ ${m}]);
148
+ `},T=(e,r,t)=>{const{binding:n,clientType:s}=t,i=y(`${e}Stub: ${s}`,t.missingMessage,t.stubMethods,{sync:t.syncStubMethods});if(n===void 0){const a=t.instrument===void 0?`config.${e}(env)`:`this.${t.instrument}(config.${e}(env), logFunctionPath, traceAnchor, observability)`;return{build:`
149
+ ${m}const ${e}: ${s} = config.${e} ? ${a} : ${e}Stub;
150
+ `,configField:`
151
+ ${e}?: (env: Record<string, unknown>) => ${s};`,importLines:[`import type { ${s} } from "${r}";`],stub:i}}const c=n.bindingType??s,u=[...new Set([c,s])].toSorted((a,o)=>a.localeCompare(o));return{build:W(e,s,n),configField:`
152
+ ${e}?: (env: Record<string, unknown>) => ${c};`,importLines:[`import type { ${u.join(", ")} } from "${r}";`,...n.factory===void 0?[]:[`import { ${n.factory.name} } from "${r}";`]],stub:i}},Y=e=>{const r=[],t=[];let n="",s="",i="",c="",u="";for(const a of S.filter(({key:o})=>e.has(o))){let o;if(O(a))o=E[a.key]();else if(P(a))o=T(a.contextProperty,a.moduleSpecifier,a.shardBinding);else continue;const d=a.contextProperty;t.push(...o.importLines),s+=o.configField,u+=o.stub,a.tier==="every"?(i+=o.build,c+=`
153
+ ${d},`):(n+=o.build,r.push(d))}return{actionBuild:n,actionFields:r,configFields:s,everyBuild:i,everyFields:c,importLines:t,stubs:u}},z=(e,r)=>{if(e.length===0)return"";const t=r?`, ${JSON.stringify(r)}`:"",n=e.map(o=>{l(o.exportName,`container export "${o.exportName}"`),l(o.className,`container class "${o.className}"`);const d=o.sandbox===!0?"LunoraSandboxContainer":"LunoraContainer";return`/** Container DO for the \`${o.exportName}\` definition (binding \`${o.bindingName}\`). */
154
+ export class ${o.className} extends ${d} {
155
+ public constructor(ctx: ConstructorParameters<typeof ${d}>[0], env: Record<string, unknown>) {
156
+ super(ctx, env, ${o.exportName}, "${o.exportName}"${t});
157
+ }
158
+ }
159
+ `}).join(`
160
+ `),s=e.map(o=>o.exportName).join(", "),i=e.some(o=>o.sandbox===!0),c=e.some(o=>o.sandbox!==!0)?`import { LunoraContainer } from "@lunora/container/do";
161
+ `:"";return`${f}/**
162
+ * Container-enabled Durable Object classes for the containers declared in
163
+ * \`lunora/containers.ts\`. Re-export them from your worker entry — wrangler
164
+ * requires each \`containers[].class_name\` to be exported by the worker:
165
+ *
166
+ * \`export * from "./lunora/_generated/containers.js";\`
167
+ *
168
+ * \`ContainerProxy\` is re-exported alongside them: the egress-interception path
169
+ * (\`allowedHosts\`/\`deniedHosts\`/\`interceptHttps\` and the runtime
170
+ * \`handle.egress\` controls) routes container outbound traffic through this
171
+ * WorkerEntrypoint, so it too must be exported by the deployed worker.
172
+ */
173
+ ${c}${i?`import { LunoraSandboxContainer } from "@lunora/container/sandbox";
174
+ `:""}
175
+ import { ${s} } from "../containers.js";
176
+
177
+ export { ContainerProxy } from "@lunora/container/do";
178
+ ${i?`
179
+ /**
180
+ * \`DirectoryBackup\` and \`S3Mount\` route a \`sandbox: true\` container's storage
181
+ * traffic through these WorkerEntrypoints, so the deployed worker must export them.
182
+ */
183
+ export { DirectoryBackupGateway, S3Gateway } from "@lunora/container/sandbox";
184
+ `:""}
185
+ ${n}`},X=(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 s=n.schedulingPolicy!==void 0||n.maxInstances===void 0?"":`, maxInstances: ${String(n.maxInstances)}`;return` { binding: "${n.bindingName}", exportName: "${n.exportName}"${s} },`}).join(`
186
+ `);return{build:`
187
+ const containers = createContainerContext(env, LUNORA_CONTAINERS, ${r?JSON.stringify(r):"undefined"}, this.getCurrentTraceparent(), this.getCurrentSampleErrors());
188
+ `,contextField:`
189
+ containers,`,importLines:['import type { ContainerBindingSpec } from "@lunora/container";','import { createContainerContext } from "@lunora/container";'],specs:`
190
+ /** Wiring specs for \`ctx.containers\` (codegen-derived from \`lunora/containers.ts\`). */
191
+ const LUNORA_CONTAINERS: ReadonlyArray<ContainerBindingSpec> = [
192
+ ${t}
193
+ ];
194
+ `}},Z=(e,r={})=>{if(e.length===0)return"";const t=r.lazy===!0,n=e.map(i=>{l(i.exportName,`workflow export "${i.exportName}"`),l(i.className,`workflow class "${i.className}"`);const c=t?`async () => (await import("../workflows.js")).${i.exportName}`:i.exportName;return`/** WorkflowEntrypoint for the \`${i.exportName}\` definition, reached as \`ctx.exports.${i.className}\`. */
195
+ export class ${i.className} extends LunoraWorkflow<WorkflowParamsOf<typeof ${i.exportName}>, WorkflowOutputOf<typeof ${i.exportName}>> {
196
+ public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
197
+ super(ctx, env, ${c}, "${i.exportName}");
198
+ }
199
+ }
200
+ `}).join(`
201
+ `),s=e.map(i=>i.exportName).join(", ");return`${f}/**
202
+ * WorkflowEntrypoint classes for the workflows declared in
203
+ * \`lunora/workflows.ts\`. Re-export them from your worker entry — wrangler
204
+ * requires each \`workflows[].class_name\` to be exported by the worker:
205
+ *
206
+ * \`export * from "./lunora/_generated/workflows.js";\`
207
+ */
208
+ import LunoraWorkflow from "@lunora/workflow/do";
209
+
210
+ import ${t?"type ":""}{ ${s} } from "../workflows.js";
211
+
212
+ /** Params type carried by a \`defineWorkflow\` definition (its phantom \`__params\`), so each entrypoint keeps the authored \`ctx.params\` type. */
213
+ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params }
214
+ ? unknown extends Params
215
+ ? Record<string, unknown>
216
+ : NonNullable<Params>
217
+ : Record<string, unknown>;
218
+
219
+ /** Output type carried by a \`defineWorkflow\` definition (its phantom \`__output\`), so each entrypoint keeps the authored return type. */
220
+ type WorkflowOutputOf<Definition> = Definition extends { __output?: infer Output } ? Output : unknown;
221
+
222
+ ${n}`},ee=(e,r={})=>{if(e.length===0)return"";const n=e.filter(o=>o.voice).length>0,s=r.lazy===!0&&!n,i=e.map(o=>{l(o.exportName,`agent export "${o.exportName}"`),l(o.className,`agent class "${o.className}"`);const d=`/** WorkflowEntrypoint for the \`${o.exportName}\` agent, reached as \`ctx.exports.${o.className}\`. */
223
+ export class ${o.className} extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
224
+ public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
225
+ super(ctx, env, ${s?`async () => {
226
+ const [{ compileAgentWorkflow }, { ${o.exportName}: definition }] = await Promise.all([import("@lunora/agent"), import("../agents.js")]);
227
+
228
+ return compileAgentWorkflow(definition, "${o.exportName}");
229
+ }`:`compileAgentWorkflow(${o.exportName}, "${o.exportName}")`}, "${o.exportName}");
230
+ }
231
+ }
232
+ `;if(!o.voice)return d;const p=o.voiceClassName??"",g=o.voiceBindingName??"";l(p,`agent voice class "${p}"`);const k=`
233
+ /** Voice-session Durable Object for the \`${o.exportName}\` agent (binding \`${g}\`). */
234
+ export class ${p} extends VoiceSessionDO {
235
+ public constructor(ctx: ConstructorParameters<typeof VoiceSessionDO>[0], env: Record<string, unknown>) {
236
+ super(ctx, env, ${o.exportName}, "${o.exportName}");
237
+ }
238
+ }
239
+ `;return`${d}${k}`}).join(`
240
+ `),c=e.map(o=>o.exportName).join(", ");let u='import { compileAgentWorkflow } from "@lunora/agent/core";';return n?u=`import { compileAgentWorkflow } from "@lunora/agent/core";
241
+ import { VoiceSessionDO } from "@lunora/agent";`:s&&(u=""),`${f}/**
242
+ * WorkflowEntrypoint classes for the agents declared in \`lunora/agents.ts\`.
243
+ * Each \`defineAgent\` compiles a replay-safe tool-loop onto a Cloudflare
244
+ * Workflow. Re-export them from your worker entry — wrangler requires each
245
+ * \`workflows[].class_name\` to be exported by the worker:
246
+ *
247
+ * \`export * from "./lunora/_generated/agents.js";\`${n?"\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).":""}
248
+ */
249
+ import LunoraWorkflow from "@lunora/workflow/do";
250
+ ${u===""?"":`${u}
251
+ `}import type { AgentRunInput, AgentRunResult } from "@lunora/agent/core";
252
+ ${s?"":`
253
+ import { ${c} } from "../agents.js";
254
+ `}
255
+ ${i}`},h=e=>e.env===void 0?"the top level":`env.${e.env}`,v=(e,r)=>{const t=e.filter(a=>a.mode==="push"),n=new Map(t.map(a=>[a.bindingName,a])),s=new Map(e.map(a=>[a.name,a])),i=new Map(t.map(a=>[a.name,a])),c=new Map,u=[];for(const a of r){const o=n.get(a.binding);if(o===void 0||a.queue===o.name)continue;const d=s.get(a.queue);if(d!==void 0){u.push(`${h(a)} maps \`${a.binding}\` to "${a.queue}", the declared name of queue \`${d.exportName}\` — batches for "${a.queue}" go to \`${d.exportName}\`, never \`${o.exportName}\`.`);continue}const p=i.get(a.queue);if(p===void 0)i.set(a.queue,o),c.set(a.queue,a);else if(p!==o){const g=c.get(a.queue);u.push(`"${a.queue}" is aliased to \`${p.exportName}\` by ${g===void 0?"an earlier producer":h(g)} and to \`${o.exportName}\` by ${h(a)} — batches for it go to \`${p.exportName}\`.`)}}return{conflicts:u,routes:i}},te=(e,r)=>v(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"})),ne=(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,u])=>`import { ${u.map(a=>a.exportName).join(", ")} } from "../${c}.js";`).join(`
256
+ `),{routes:s}=v(e,r),i=[...s].map(([c,u])=>` ${JSON.stringify(c)}: { binding: ${JSON.stringify(u.bindingName)}, definition: ${u.exportName}, exportName: ${JSON.stringify(u.exportName)} },`).join(`
257
+ `);return`${f}/**
258
+ * Push-consumer registry for the queues declared in \`lunora/queues.ts\`. The
259
+ * composed worker's \`queue(batch, env, ctx)\` entry routes each delivered batch
260
+ * by \`batch.queue\` to the matching \`defineQueue\` handler. Wired automatically
261
+ * by \`defineApp\` — you don't import this directly.
262
+ */
263
+ import type { QueueRegistry } from "@lunora/queue";
264
+
265
+ ${n}
266
+
267
+ /** Wrangler queue name (declared, or a per-environment rename) → { binding, definition, exportName } for batch routing. */
268
+ export const LUNORA_QUEUE_REGISTRY: QueueRegistry = {
269
+ ${i}
270
+ };
271
+ `},re=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(`
272
+ `);return{build:`
273
+ const workflows = createWorkflowContext(env, LUNORA_WORKFLOWS, this.state.exports);
274
+ `,contextField:`
275
+ workflows,`,importLines:['import type { WorkflowBindingSpec } from "@lunora/workflow";','import { createWorkflowContext } from "@lunora/workflow";'],specs:`
276
+ /** Wiring specs for \`ctx.workflows\` (codegen-derived from \`lunora/workflows.ts\`). */
277
+ const LUNORA_WORKFLOWS: ReadonlyArray<WorkflowBindingSpec> = [
278
+ ${r}
279
+ ];
280
+ `}},oe=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(`
281
+ `);return{build:`
282
+ const queues = createQueueContext(env, LUNORA_QUEUES);
283
+ `,contextField:`
284
+ queues,`,importLines:['import type { QueueBindingSpec } from "@lunora/queue";','import { createQueueContext } from "@lunora/queue";'],specs:`
285
+ /** Wiring specs for \`ctx.queues\` (codegen-derived from \`lunora/queues.ts\`). */
286
+ const LUNORA_QUEUES: ReadonlyArray<QueueBindingSpec> = [
287
+ ${r}
288
+ ];
289
+ `}},se=(e,r)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};const t=e.map(n=>{l(n.exportName,`topic export "${n.exportName}"`);const s=L(r,n.exportName).map(i=>`{ binding: "${i.bindingName}", exportName: "${i.exportName}" }`).join(", ");return` { exportName: "${n.exportName}", subscriptions: [${s}] },`}).join(`
290
+ `);return{build:`
291
+ const topics = createTopicContext(env, LUNORA_TOPICS);
292
+ `,contextField:`
293
+ topics,`,importLines:['import type { TopicBindingSpec } from "@lunora/queue";','import { createTopicContext } from "@lunora/queue";'],specs:`
294
+ /** Wiring specs for \`ctx.topics\` (codegen-derived from \`lunora/queues.ts\`): each topic's subscription queues. */
295
+ const LUNORA_TOPICS: ReadonlyArray<TopicBindingSpec> = [
296
+ ${t}
297
+ ];
298
+ `}},ae=(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(`
299
+ `);return{build:`
300
+ const services = createServices(env, LUNORA_SERVICES);
301
+ `,importLines:[`import type { ServiceBindingSpec } from "${r}";`,`import { createServices } from "${r}";`],specs:`
302
+ /** Wiring specs for \`ctx.services\` (codegen-derived from \`lunora.config\` \`services\`). */
303
+ const LUNORA_SERVICES: ReadonlyArray<ServiceBindingSpec> = [
304
+ ${t}
305
+ ];
306
+ `}},b="(config.scheduler?.(env) ?? schedulerStub) as SchedulerLike",ie=(e,r)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],schedulerSource:b,specs:"",stampsOutbox:!1};for(const n of e)l(n.exportName,`agent export "${n.exportName}"`),l(n.className,`agent class "${n.className}"`);const t=e.map(n=>` { className: "${n.className}", exportName: "${n.exportName}"${n.publicRun===!0?", publicRun: true":""} },`).join(`
307
+ `);return{build:`
308
+ const agents = createAgentContext(env, LUNORA_AGENTS, { exports: this.state.exports, shardKey: this.currentShardKey() });
309
+ `,contextField:r?`
310
+ agents,
311
+ agentSecrets: this.secretValues,`:`
312
+ agents,`,importLines:['import { createAgentContext } from "@lunora/agent/core";','import { withAgentScheduleShard } from "@lunora/agent/core";','import type { AgentBindingSpec } from "@lunora/agent/core";'],schedulerSource:`withAgentScheduleShard(${b}, LUNORA_AGENTS, this.currentShardKey())`,stampsOutbox:!0,specs:`
313
+ /** Wiring specs for \`ctx.agents\` (codegen-derived from \`lunora/agents.ts\`). */
314
+ const LUNORA_AGENTS: ReadonlyArray<AgentBindingSpec> = [
315
+ ${t}
316
+ ];
317
+ `}},N=(e,r,t,n,s)=>({constant:`
318
+ ${s}
319
+ const ${e} = ${$(n,r)};
320
+ `,override:`
321
+ protected override ${t}(): ${r} {
322
+ return ${e};
323
+ }
324
+ `}),ce=(e,r)=>{if(e.length===0)return{constant:"",override:""};const t={...r.length===0?{}:{eventTypes:r.map(n=>n.type)},workflows:e.map(n=>({className:n.className,exportName:n.exportName,name:n.name}))};return N("LUNORA_WORKFLOWS_INFO","WorkflowsResult","workflowsMetadata",t,"/** Read-only declared-workflow metadata (discovered from `lunora/workflows.ts`) served via `__lunora_admin__:listWorkflows` for the studio's workflows view. */")},ue=(e,r)=>{if(e.length===0||r.length===0)return{constant:"",override:""};for(const t of r)if(l(t.exportName,"workflow event export name"),!w.test(t.filePath))throw new R("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe workflow event file path: ${JSON.stringify(t.filePath)}`);return{constant:`
325
+ /** Declared workflow events (\`defineWorkflowEvent\` exports), loaded by type when an admin \`sendWorkflowEvent\` parses its payload. */
326
+ const LUNORA_WORKFLOW_EVENTS: ReadonlyMap<string, () => Promise<{ payload: { parse: (value: unknown) => unknown } }>> = new Map([
327
+ ${r.map(t=>` [${JSON.stringify(t.type)}, () => import("../${t.filePath}.js").then((module) => module.${t.exportName})],`).join(`
328
+ `)}
329
+ ]);
330
+ `,override:`
331
+ protected override async workflowEvent(type: string): Promise<{ payload: { parse: (value: unknown) => unknown } } | undefined> {
332
+ return LUNORA_WORKFLOW_EVENTS.get(type)?.();
333
+ }
334
+ `}},le=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 N("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. */")},I=["attach","cancelPayment","cancelSubscription","capturePayment","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","refundPayment","track"],de=e=>e?{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
335
+ const paymentsByContext = new WeakMap<object, LunoraPayment>();
336
+ `,configField:`
337
+ payment?: (env: Record<string, unknown>) => PaymentsFromContextOptions;`,contextField:`
338
+ get payments(): LunoraPayment {
339
+ let payments = paymentsByContext.get(this);
340
+
341
+ if (payments === undefined) {
342
+ payments = config.payment
343
+ ? paymentsFromContext({ auth: { userId: readUserId() ?? null }, db: this.db as unknown as LunoraPaymentDbLike }, config.payment(env))
344
+ : paymentStub;
345
+ paymentsByContext.set(this, payments);
346
+ }
347
+
348
+ return payments;
349
+ },`,stub:y("paymentStub: LunoraPayment","ctx.payments: no payment configured. Pass `payment` to createShardDO().",I,{cast:" as unknown as LunoraPayment",sync:!0})}:{build:"",configField:"",contextField:"",imports:[],stub:""},me=(e,r,t,n,s)=>["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","SensitiveScope",...s?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","DeliveryAuthorization","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SubscriptionIdentity","SystemReaderStorageLike","TelemetrySink",...e?["VectorBackfillProgress"]:[],...r?["WorkflowsResult"]:[],...e?["WriteHook"]:[]];export{H as a,J as b,V as c,oe as d,Y as e,se as f,ae as g,X as h,re as i,ie as j,de as k,ce as l,ue as m,le as n,K as o,me as p,M as q,y as r,G as s,ee as t,z as u,Z as v,te as w,ne as x};
@@ -0,0 +1,13 @@
1
+ import{LunoraError as $}from"@lunora/errors";import{v as _}from"./parse-validator-BisfC8bR.mjs";import{R as k}from"./reserved-words-CW1QFbTd.mjs";import{acceptsAbsentIr as I}from"./LUNORA_ERROR_CODES-CjACC-MQ.mjs";import{n as E}from"./dispatch-namespace-DwTjD7BU.mjs";const R=/^(?:"(?:[^"\\]|\\(?:["\\/bfnrt]|u[0-9A-Fa-f]{4}))*"|'[^'\\]*'|-?\d+(?:\.\d+)?|true|false|null)$/u,O=e=>Object.keys(e).filter(n=>_(e[n])),B=e=>e.typeDerivedArgs===!0&&Object.keys(e.args).length>0||O(e.args).length>0,F=`// GENERATED by @lunora/codegen — do not edit.
2
+ // Run \`lunora codegen\` to regenerate.
3
+
4
+ `,G=(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,U=/^[\w./-]+$/u,w=(e,n)=>{if(!b.test(e)||k.has(e))throw new $("INTERNAL",`@lunora/codegen: ${n} is not a valid JS identifier: ${JSON.stringify(e)}`)},V=(e,n)=>{if(!b.test(e))throw new $("INTERNAL",`@lunora/codegen: ${n} is not a valid JS identifier: ${JSON.stringify(e)}`)},H=e=>e.charAt(0).toUpperCase()+e.slice(1),g=e=>b.test(e)?e:JSON.stringify(e),j=e=>e==="__proto__"?`[${JSON.stringify(e)}]`:g(e),D=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))},Y=(e,n,r)=>{const[t,l]=r==="type"?[g,";"]:[j,","],h={children:new Map};for(const[o,d]of D(e)){let a=h;for(const m of E(o)){let c=a.children.get(m);c===void 0&&(c={children:new Map},a.children.set(m,c)),a=c}a.file={entries:d,path:o}}const u=o=>o.file?.path??u(o.children.values().next().value),p=(o,d)=>{const a=" ".repeat(d),{entries:m=[],path:c=""}=o.file??{},y=m.find(s=>o.children.has(s.exportName));if(y!==void 0){const s=u(o.children.get(y.exportName));throw new $("NAMESPACE_COLLISION",`Namespace collision: the export "${y.exportName}" of "${c}" and "${s}" both resolve to api.${[...E(c),y.exportName].join(".")}. Rename the export or the folder.`)}const A=m.toSorted((s,f)=>s.exportName.localeCompare(f.exportName)).map(s=>`${a}${n(s)}`),S=[...o.children.entries()].toSorted(([s],[f])=>s.localeCompare(f)).map(([s,f])=>`${a}${t(s)}: {
5
+ ${p(f,d+1).join(`
6
+ `)}
7
+ ${a}}${l}`);return[...A,...S]};return p(h,1).join(`
8
+ `)},x={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"},L=e=>{if(e===void 0)return"unknown";if(!R.test(e))throw new $("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=x[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 L(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 I(n)?`${r}?: ${i(n)}`:`${r}: ${i(n)}`},W=e=>{const n=Object.entries(e);return n.length===0?"{}":`{ ${n.map(([r,t])=>N(r,t)).join("; ")} }`},z=e=>e.kind==="optional"||!!e.column?.hasDefault,C=e=>e.kind==="optional"&&e.inner?e.inner:e,Z=e=>{w(e.name,"table name");const n=Object.entries(e.shape).map(([t,l])=>{const h=C(l),u=i(h),p=g(t);return z(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{F as G,U as I,R as L,w as a,Y as b,j as c,G as d,g as e,Z as f,V as g,z as h,B as i,H as p,W as r,O as s,C as u,i as v};
@@ -0,0 +1 @@
1
+ import{Node as i,SyntaxKind as a}from"ts-morph";const n=Symbol("not-literal"),p=e=>Number(e.getText().replaceAll("_","")),f=e=>i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e)?e.getLiteralValue():i.isNumericLiteral(e)?p(e):i.isPrefixUnaryExpression(e)&&e.getOperatorToken()===a.MinusToken&&i.isNumericLiteral(e.getOperand())?-p(e.getOperand()):i.isTrueLiteral(e)||i.isFalseLiteral(e)?e.getLiteralValue():i.isBinaryExpression(e)?m(e):i.isNullLiteral(e)?null:n,g={[a.AsteriskAsteriskToken]:(e,t)=>e**t,[a.AsteriskToken]:(e,t)=>e*t,[a.MinusToken]:(e,t)=>e-t,[a.PercentToken]:(e,t)=>e%t,[a.PlusToken]:(e,t)=>e+t,[a.SlashToken]:(e,t)=>e/t},m=e=>{const t=g[e.getOperatorToken().getKind()],[r,s]=[l(e.getLeft()),l(e.getRight())];return t!==void 0&&typeof r=="number"&&typeof s=="number"&&Number.isFinite(r)&&Number.isFinite(s)?t(r,s):n},l=e=>{if(i.isParenthesizedExpression(e)||i.isAsExpression(e)||i.isSatisfiesExpression(e))return l(e.getExpression());if(i.isArrayLiteralExpression(e)){const t=e.getElements().map(r=>l(r));return t.includes(n)?n:t}return i.isObjectLiteralExpression(e)?L(e):f(e)},L=e=>{const t=[];for(const r of e.getProperties()){const s=i.isPropertyAssignment(r)?r.getNameNode():void 0,o=i.isPropertyAssignment(r)?r.getInitializer():void 0,u=o===void 0?n:l(o);if(s===void 0||u===n||!(i.isIdentifier(s)||i.isStringLiteral(s)))return n;const c=i.isStringLiteral(s)?s.getLiteralValue():s.getText();if(c==="__proto__")return n;t.push([c,u])}return Object.fromEntries(t)};export{n as N,l};
@@ -0,0 +1 @@
1
+ import{posix as w,dirname as h,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-ClgKgMYM.mjs";let S,v;const Oe=e=>{const t=S,n=[];S=n;try{return{erased:n,value:e()}}finally{S=t}},Ue=e=>{S?.push(...e)},V=e=>{for(const t of e.getAncestors())if(l.isVariableDeclaration(t))return t.getName()},y=(e,t)=>{S?.push({exportName:V(e),filePath:e.getSourceFile().getFilePath(),line:e.getStartLineNumber(),rendered:t})},Pe=e=>{v!==void 0&&y(v,e)},Le=(e,t)=>{const n=v;v=e;try{return t()}finally{v=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=`${w.join(r.getDirectoryPath(),r.getBaseNameWithoutExtension())}${s}`,o=w.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})`,Se=32,ve=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[...new Set(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>Se)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>ve||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()},we=/is of type 'unknown'|on type '\{\}'/,he=e=>we.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(!he(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=h(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=h(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{Ue as a,T as b,Oe as c,Pe as d,m as e,Fe as f,X as i,Le as p,j as r,Ke as u};