@lunora/codegen 1.0.0-alpha.14 → 1.0.0-alpha.141

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 (86) hide show
  1. package/LICENSE.md +6 -0
  2. package/dist/index.d.mts +3018 -1005
  3. package/dist/index.d.ts +3018 -1005
  4. package/dist/index.mjs +1 -31
  5. package/dist/packem_shared/AGENTS_FILENAME-D1qA0h5m.mjs +1 -0
  6. package/dist/packem_shared/CONTAINERS_FILENAME-oKaARMoA.mjs +1 -0
  7. package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
  8. package/dist/packem_shared/DEFAULT_TARGET-CrhWLUK7.mjs +1 -0
  9. package/dist/packem_shared/FLAGS_FILENAME-BasxlnVS.mjs +1 -0
  10. package/dist/packem_shared/GENERATED_HEADER-BgmuZY9e.mjs +1 -0
  11. package/dist/packem_shared/LUNORA_ERROR_CODES-BYg8Lpgb.mjs +1 -0
  12. package/dist/packem_shared/MUTATORS_FILENAME-DJvAhDlD.mjs +1 -0
  13. package/dist/packem_shared/NOTIFY_FILENAME-B-eIjru_.mjs +1 -0
  14. package/dist/packem_shared/OPENRPC_VERSION-B9ZC0SrC.mjs +3 -0
  15. package/dist/packem_shared/QUEUES_FILENAME-D229WtRm.mjs +1 -0
  16. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-iOZaWN69.mjs +9 -0
  17. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-DLXXalg2.mjs +2 -0
  18. package/dist/packem_shared/SDK_LANGUAGES-CFyux-74.mjs +371 -0
  19. package/dist/packem_shared/SHAPES_FILENAME-BTdasTq2.mjs +1 -0
  20. package/dist/packem_shared/SchemaSnapshotParseError-CvPTjDrT.mjs +16 -0
  21. package/dist/packem_shared/WORKFLOWS_FILENAME-DRaiCNa6.mjs +1 -0
  22. package/dist/packem_shared/ast-CjWtsS6S.mjs +1 -0
  23. package/dist/packem_shared/buildOpenApiDocument-DLEWgA5Y.mjs +3 -0
  24. package/dist/packem_shared/chain-CtC3-wwZ.mjs +1 -0
  25. package/dist/packem_shared/classify-procedure-call-AKeIK05y.mjs +1 -0
  26. package/dist/packem_shared/describeErrorLevelFindings-D23VSkFP.mjs +1 -0
  27. package/dist/packem_shared/discoverAuthApiCalls-C35kkayg.mjs +1 -0
  28. package/dist/packem_shared/discoverCrons-wXBfQcfn.mjs +1 -0
  29. package/dist/packem_shared/discoverFunctions-BBDziFXy.mjs +1 -0
  30. package/dist/packem_shared/discoverHttpRoutes-Dmow2gql.mjs +1 -0
  31. package/dist/packem_shared/discoverInserts-C5l2INmE.mjs +1 -0
  32. package/dist/packem_shared/discoverMaskProcedures-Df4JQp_2.mjs +1 -0
  33. package/dist/packem_shared/discoverMigrations-CWH7T6qz.mjs +1 -0
  34. package/dist/packem_shared/discoverNondeterministicCalls-JsO91i57.mjs +1 -0
  35. package/dist/packem_shared/discoverQueries-iypfwfdZ.mjs +1 -0
  36. package/dist/packem_shared/discoverR2sqlCalls-BbfOpwE4.mjs +1 -0
  37. package/dist/packem_shared/discoverRlsMetadata-DGUGYgWs.mjs +1 -0
  38. package/dist/packem_shared/discoverRlsProcedures-CRshfYZE.mjs +1 -0
  39. package/dist/packem_shared/discoverSandboxUsage-DdewAOuj.mjs +1 -0
  40. package/dist/packem_shared/discoverSchema-Bp8DcNq7.mjs +1 -0
  41. package/dist/packem_shared/discoverStorageRulesMetadata-gyO60A5S.mjs +1 -0
  42. package/dist/packem_shared/emit-s6mHBmXu.mjs +2268 -0
  43. package/dist/packem_shared/emitApp-D1qxNeh1.mjs +646 -0
  44. package/dist/packem_shared/exported-procedure-chains-MlZRKqSD.mjs +1 -0
  45. package/dist/packem_shared/formatAdvisories-CkEu1eye.mjs +2 -0
  46. package/dist/packem_shared/index-CCDlo9L7.mjs +1 -0
  47. package/dist/packem_shared/isTypedSchema-B_qlBbE-.mjs +2 -0
  48. package/dist/packem_shared/module-specifiers-WF8iAydP.mjs +1 -0
  49. package/dist/packem_shared/parse-validator-BFTp87yz.mjs +1 -0
  50. package/dist/packem_shared/paths-C-9fwEgQ.mjs +1 -0
  51. package/dist/packem_shared/queries-B_xEHIeL.mjs +1 -0
  52. package/dist/packem_shared/readPackageDependencies-C6h6FZuP.mjs +1 -0
  53. package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
  54. package/dist/packem_shared/schemaFromIr-BWFnvCVg.mjs +1 -0
  55. package/dist/packem_shared/unwrap-handler-return-CmIWbykC.mjs +1 -0
  56. package/package.json +16 -7
  57. package/dist/packem_shared/CONTAINERS_FILENAME-DlP6YM_Q.mjs +0 -224
  58. package/dist/packem_shared/CodegenDiagnosticError-DeblMkzO.mjs +0 -23
  59. package/dist/packem_shared/GENERATED_HEADER-BEA7oWGC.mjs +0 -2841
  60. package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
  61. package/dist/packem_shared/LUNORA_SOLUTION_RULES-BTejmZp-.mjs +0 -131
  62. package/dist/packem_shared/OPENRPC_VERSION-CQ3f8YQ-.mjs +0 -60
  63. package/dist/packem_shared/QUEUES_FILENAME-B5_eWCRe.mjs +0 -119
  64. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-BXtduJFE.mjs +0 -954
  65. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-wWGP2_5E.mjs +0 -245
  66. package/dist/packem_shared/WORKFLOWS_FILENAME-D62dcBGg.mjs +0 -84
  67. package/dist/packem_shared/buildOpenApiDocument-699G4RP4.mjs +0 -183
  68. package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
  69. package/dist/packem_shared/discoverAuthApiCalls-CoirYbg6.mjs +0 -62
  70. package/dist/packem_shared/discoverCrons-Cev7RRAf.mjs +0 -257
  71. package/dist/packem_shared/discoverFunctions-BWMczzBx.mjs +0 -465
  72. package/dist/packem_shared/discoverHttpRoutes-CfP6cMzt.mjs +0 -131
  73. package/dist/packem_shared/discoverInserts-C7zxXkUf.mjs +0 -61
  74. package/dist/packem_shared/discoverMaskProcedures-Cm81kwrb.mjs +0 -217
  75. package/dist/packem_shared/discoverMigrations-Bi5nJ0mJ.mjs +0 -97
  76. package/dist/packem_shared/discoverNondeterministicCalls-C4M8AXmQ.mjs +0 -122
  77. package/dist/packem_shared/discoverQueries-B0wGT-xe.mjs +0 -62
  78. package/dist/packem_shared/discoverR2sqlCalls-BVNMd428.mjs +0 -80
  79. package/dist/packem_shared/discoverRlsMetadata-BS9GOGC5.mjs +0 -280
  80. package/dist/packem_shared/discoverSchema-BnWHHJ4T.mjs +0 -822
  81. package/dist/packem_shared/discoverStorageRulesMetadata-Da8BKXcI.mjs +0 -97
  82. package/dist/packem_shared/emitApp-DiK0QSBn.mjs +0 -617
  83. package/dist/packem_shared/formatAdvisories-8NIv1k0I.mjs +0 -69
  84. package/dist/packem_shared/parse-validator-Cabb60UV.mjs +0 -133
  85. package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
  86. package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
@@ -0,0 +1,371 @@
1
+ import{modelSources as ce,toPascalCase as o,referencedModels as N,generatedHeaderLines as f,commentText as l,argsChoice as p,stringLiteral as $,kotlinLiteral as v,allMethods as P,toSnakeCase as B,parseSpec as ke,assertGeneratable as Oe,withDeclaredModels as Ne,unrepresentableFunctions as Ce,undeclaredModels as Le}from"./isTypedSchema-B_qlBbE-.mjs";import{isTypedSchema as br}from"./isTypedSchema-B_qlBbE-.mjs";const We=async(e,n)=>{if(n.quicktype===void 0)return"";const r=ce(e);if(r.length===0)return"";const{InputData:t,JSONSchemaInput:a,JSONSchemaStore:i,quicktype:s}=await import("quicktype-core");class u extends i{fetch(){return Promise.resolve(void 0)}}const m=new a(new u);for(const g of r)await m.addSource({name:g.name,schema:JSON.stringify(g.schema)});const d=new t;d.addInput(m);const{lines:c}=await s({inputData:d,lang:n.quicktype.lang,rendererOptions:n.quicktype.rendererOptions??{}});return c.join(`
2
+ `)},L=`${f("dart").map(e=>`// ${e}`).join(`
3
+ `)}
4
+
5
+ `,Me=`# GENERATED by \`lunora sdk generate --lang dart\` — do not edit.
6
+ #
7
+ # The transport is vendored under lib/, so this package has no dependencies and
8
+ # nothing to fetch. Add it to a consuming app as a path dependency — pub takes a
9
+ # path dependency's identity from the "name" below, NOT from the directory, so
10
+ # this is the name you write no matter where you generated into:
11
+ #
12
+ # dependencies:
13
+ # lunora_sdk:
14
+ # path: sdk/dart
15
+ #
16
+ # import 'package:lunora_sdk/lunora_api.dart';
17
+ name: lunora_sdk
18
+ description: Generated Lunora SDK, transport included.
19
+ version: 0.0.0
20
+ publish_to: none
21
+
22
+ environment:
23
+ sdk: ^3.6.0
24
+ `,Re=new Set(["assert","break","case","catch","class","const","continue","default","do","else","enum","extends","false","final","finally","for","if","in","is","new","null","rethrow","return","super","switch","this","throw","true","try","var","void","while","with"]),E=e=>{const n=o(e),r=n.charAt(0).toLowerCase()+n.slice(1);return Re.has(r)?`${r}_`:r},pe=e=>$(e).replaceAll("$",String.raw`\$`),De=e=>e.replaceAll(" == null ? [] : List<"," == null ? null : List<").replaceAll(/Map\.from\((?<source>[^()]*?)!\)/gu,"$<source> == null ? null : Map.from($<source>!)"),z=" ".repeat(8),Pe=/^class (\w+) \{/u,Ve=/^class \w+ \{\n[\s\S]*?\n\}$/gmu,Ke=/^ {4}\w+\(\{\n([\s\S]*?)^ {4}\}\);$/mu,Ie=/^ {8}(?:required )?this\.\w+,$/gmu,Fe=/^ {4}Map<String, dynamic> toJson\(\) => \{\n([\s\S]*?)^ {4}\};$/mu,xe=/^ {8}"(?:[^\\"]|\\.)*": .*,$/gmu,qe=e=>e.replaceAll(Ve,n=>{const[,r]=Ke.exec(n)??[],[,t]=Fe.exec(n)??[];if(r===void 0||t===void 0)return n;const a=[...r.matchAll(Ie)].map(m=>{const d=m[0].trim();return{field:d.slice(d.indexOf("this.")+5,-1),optional:!d.startsWith("required ")}}),i=[...t.matchAll(xe)],s=a.filter(m=>m.optional);if(a.length!==i.length){if(s.length===0)return n;throw new Error(`dart models: cannot place the optional-field guards in ${Pe.exec(n)?.[1]??"a generated class"} — ${String(a.length)} constructor parameter(s) against ${String(i.length)} toJson entr(ies). quicktype's Dart output has changed shape; \`guardOptionalFields\` in targets/dart.ts must be updated to match.`)}let u=t;for(const[m,d]of i.entries()){const c=a[m];if(!c?.optional)continue;const g=d[0],Te=g.slice(z.length).replace(`${c.field} == null ? null : `,"");u=u.replace(g,`${z}if (${c.field} != null) ${Te}`)}return n.replace(t,u)}),de=e=>p(e,{none:"null",typed:()=>"LunoraClient.wireValue(args)",untyped:"args"}),$e={declaration:"LunoraOptimistic? optimistic, LunoraOptimisticUpdate? optimisticUpdate, bool Function()? precondition",forward:"optimistic: optimistic, optimisticUpdate: optimisticUpdate, precondition: precondition"},Z=e=>{const n=e.verb==="mutation"?`{String? shardKey, ${$e.declaration}}`:"{String? shardKey}";return p(e,{none:n,typed:r=>`${r} args, ${n}`,untyped:`Object? args, ${n}`})},me=(e,n)=>`${e}.fromJson(${n} as Map<String, dynamic>)`,X=e=>{const n=e.verb==="mutation"?`, ${$e.forward}`:"",r=`_client.${e.verb}("${pe(e.functionPath)}", args: ${de(e)}, shardKey: shardKey${n})`;return e.resultType===void 0?[` /// ${l(e.summary)}`,` Future<Object?> ${E(e.functionName)}(${Z(e)}) => ${r};`].join(`
25
+ `):[` /// ${l(e.summary)}`,` Future<${e.resultType}> ${E(e.functionName)}(${Z(e)}) async =>`,` ${me(e.resultType,`await ${r}`)};`].join(`
26
+ `)},Ue=e=>{const n=p(e,{none:"",typed:s=>`${s} args`,untyped:"Object? args"}),r=n===""?"":`${n}, `,t=de(e),a=`"${pe(e.functionPath)}"`,i=`_client.watch(${a}, args: ${t})`;return[` /// live ${l(e.summary)} — re-runs on every write to the tables it reads.`,` LunoraUnsubscribe subscribe${o(e.functionName)}(`,` ${r}{LunoraDataCallback? onData, LunoraErrorCallback? onError}`,` ) => _client.subscribe(${a}, args: ${t}, onData: onData, onError: onError);`,"",` /// live ${l(e.summary)}, as a Stream — bind it with StreamBuilder.`,e.resultType===void 0?` Stream<Object?> watch${o(e.functionName)}(${n}) => ${i};`:[` Stream<${e.resultType}> watch${o(e.functionName)}(${n}) =>`,` ${i}.map((raw) => ${me(e.resultType,"raw")});`].join(`
27
+ `)].join(`
28
+ `)},He=e=>{const n=`${o(e.name)}Api`,r=e.methods.map(t=>t.verb==="query"?`${X(t)}
29
+
30
+ ${Ue(t)}`:X(t)).join(`
31
+
32
+ `);return[`/// Functions declared in \`${l(e.name)}\`.`,`class ${n} {`,` const ${n}(this._client);`,""," final LunoraClient _client;","",r,"}"].join(`
33
+ `)},Ge=({models:e,namespaces:n})=>{const r=n.map(s=>` final ${o(s.name)}Api ${E(s.name)};`).join(`
34
+ `),t=n.map(s=>` ${E(s.name)} = ${o(s.name)}Api(client)`).join(`,
35
+ `),a=N(n).length>0?`import 'models.dart';
36
+ `:"";return{"lib/lunora_api.dart":[L,`/// The generated Lunora surface. Re-exports the vendored transport, so one
37
+ `,`/// import gives a consumer the client, the wire types and the models.
38
+ `,`library;
39
+ `,`
40
+ `,`export 'lunora.dart';
41
+ `,`export 'models.dart';
42
+ `,`
43
+ `,`import 'lunora.dart';
44
+ `,a,`
45
+ `,n.map(s=>He(s)).join(`
46
+
47
+ `),n.length>0?`
48
+
49
+ `:"","/// Typed entry point: `Api(client).<namespace>.<function>(args)`.\n",`class Api {
50
+ `,n.length>0?` Api(LunoraClient client)
51
+ : ${t.trimStart()};
52
+
53
+ ${r}
54
+ `:` const Api(LunoraClient client);
55
+ `,`}
56
+ `].join(""),"lib/models.dart":e.length>0?`${L}${qe(De(e))}
57
+ `:`${L}// No typed argument or result schemas in this deployment.
58
+ `,"pubspec.yaml":Me}},Be={id:"dart",quicktype:{lang:"dart"},render:Ge,requires:[],vendor:[{from:"lib",to:"lib"}]},W=`${f("go").map(e=>`// ${e}`).join(`
59
+ `)}
60
+
61
+ `,b="lunoraapi",_="lunorasdk",Je=`${_}/lunora`,Ye="1.22",V=e=>o(e),Q=(e,n)=>{const r=p(n,{none:"",typed:u=>`args ${u}, `,untyped:"args any, "}),t=p(n,{none:"nil",typed:()=>"args",untyped:"args"}),a=n.resultType??"any",i=`lunora.Verb${n.verb.charAt(0).toUpperCase()}${n.verb.slice(1)}`,s=`lunora.Call[${a}](a.client, ${i}, "${$(n.functionPath)}", ${t}, shardKey)`;return[`// ${V(n.functionName)} invokes ${l(n.summary)}.`,`func (a *${e}) ${V(n.functionName)}(${r}shardKey string) (${a}, error) {`,` return ${s}`,"}"].join(`
62
+ `)},ze=(e,n)=>{const r=p(n,{none:"",typed:i=>`args ${i}, `,untyped:"args any, "}),t=p(n,{none:"nil",typed:()=>"args",untyped:"args"}),a=`Subscribe${V(n.functionName)}`;return[`// ${a} opens a live ${l(n.functionPath)}; it re-runs on every write to the tables it reads.`,`func (a *${e}) ${a}(${r}onData lunora.DataHandler, onError lunora.ErrorHandler, shardKey string) lunora.Unsubscribe {`,` return a.client.Subscribe("${$(n.functionPath)}", ${t}, onData, onError, shardKey)`,"}"].join(`
63
+ `)},Ze=e=>{const n=`${o(e.name)}API`,r=e.methods.map(t=>t.verb==="query"?`${Q(n,t)}
64
+
65
+ ${ze(n,t)}`:Q(n,t)).join(`
66
+
67
+ `);return[`// ${n} groups the functions declared in ${l(e.name)}.`,`type ${n} struct{ client *lunora.Client }`,"",r].join(`
68
+ `)},Xe=({models:e,namespaces:n})=>{const r=n.map(s=>` ${o(s.name)} *${o(s.name)}API`).join(`
69
+ `),t=n.map(s=>` ${o(s.name)}: &${o(s.name)}API{client: client},`).join(`
70
+ `),a=[W,`package ${b}
71
+ `,`
72
+ `,`import "${Je}"
73
+ `,`
74
+ `,`// API is the typed entry point: api.<Namespace>.<Function>(args, shardKey).
75
+ `,`type API struct {
76
+ `,`${r}
77
+ `,`}
78
+ `,`
79
+ `,`// NewAPI binds the generated surface to a client.
80
+ `,`func NewAPI(client *lunora.Client) *API {
81
+ `,` return &API{
82
+ `,`${t}
83
+ `,` }
84
+ `,`}
85
+ `,`
86
+ `,n.map(s=>Ze(s)).join(`
87
+
88
+ `),`
89
+ `].join(""),i=e.length>0?`${W}package ${b}
90
+
91
+ ${e}
92
+ `:`${W}package ${b}
93
+
94
+ // No typed argument or result schemas in this deployment.
95
+ `;return{[`${b}/api.go`]:a,[`${b}/models.go`]:i,"go.mod":[`// The generated Lunora Go SDK, with the transport vendored under ./lunora.
96
+ `,`//
97
+ `,`// A consuming module wires it in without a network fetch:
98
+ `,`//
99
+ `,`// require ${_} v0.0.0
100
+ `,`// replace ${_} => ./path/to/this/directory
101
+ `,`module ${_}
102
+ `,`
103
+ `,`go ${Ye}
104
+ `].join("")}},Qe={id:"go",quicktype:{lang:"go",rendererOptions:{"just-types":"true",package:b}},render:Xe,requires:[],vendor:[{from:"lunora",to:"lunora"}]},w="lunoraapi.models",K="lunoraapi/models",en=24,nn=new Set(["abstract","as","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","false","final","finally","float","for","fromWire","fun","goto","if","implements","import","in","instanceof","int","interface","is","long","native","new","null","object","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","toWire","transient","true","try","typealias","typeof","val","var","void","volatile","when","while","wireValue"]),rn=/[^A-Za-z0-9]+/gu,tn=/([a-z0-9])([A-Z])/gu,an=/^[A-Za-z]/u,sn=/^[A-Z]/u;class ye extends Error{}const y=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,on=e=>{const n=e.anyOf??e.oneOf;if(!Array.isArray(n)||n.length===0)return;const r=n.map(t=>y(t)?.const);if(r.every(t=>typeof t=="string"))return[...new Set(r)].toSorted((t,a)=>t.localeCompare(a))},fe=e=>{const n=e.anyOf??e.oneOf;if(!Array.isArray(n)||n.length!==2)return e;const r=n.filter(t=>y(t)?.type!=="null");return r.length===1?y(r[0])??e:e},ln=e=>{const n=o(e),r=n.charAt(0).toLowerCase()+n.slice(1),t=an.test(r)?r:`value${n}`;return nn.has(t)?`${t}_`:t},un=e=>{const n=e.replaceAll(tn,"$1_$2").replaceAll(rn,"_").toUpperCase().split("_").filter(r=>r.length>0).join("_");return sn.test(n)?n:`VALUE_${n}`},ge=(e,n)=>{if(!n.has(e))return n.add(e),e;let r=2;for(;n.has(`${e}${String(r)}`);)r+=1;return n.add(`${e}${String(r)}`),`${e}${String(r)}`},ee=(e,n)=>{if(e.has(n.name))throw new ye(`sdk: two schemas both produce the JVM model "${n.name}"`);e.set(n.name,n)},cn=(e,n,r,t,a)=>{const i=new Set(Array.isArray(n)?n.filter(u=>typeof u=="string"):[]),s=new Set;return Object.entries(e).map(([u,m])=>{const d=y(m)??{},c=!i.has(u);return{name:ge(ln(u),s),nullable:!c&&fe(d)!==d,optional:c,type:j(d,`${r}${o(u)}`,t+1,a),wireKey:u}})},j=(e,n,r,t)=>{if(r>=en)return{kind:"unknown"};const a=on(e);if(a!==void 0){const d=new Set;return ee(t,{constants:a.map(c=>({name:ge(un(c),d),wireValue:c})),kind:"enum",name:n}),{kind:"enum",name:n}}const i=fe(e);if(i!==e)return j(i,n,r+1,t);const s=y(e.properties);if(s!==void 0)return ee(t,{fields:cn(s,e.required,n,r,t),kind:"class",name:n}),{kind:"class",name:n};const u=y(e.additionalProperties);if(u!==void 0)return{kind:"record",value:j(u,`${n}Value`,r+1,t)};const m=y(e.items);if(m!==void 0)return{item:j(m,`${n}Item`,r+1,t),kind:"list"};switch(e.type){case"boolean":return{kind:"boolean"};case"integer":case"number":return{kind:"number"};case"string":return{kind:"string"};default:return{kind:"unknown"}}},be=e=>{const n=new Map;for(const r of ce(e)){if(y(r.schema.properties)===void 0)continue;const t=new Map;try{j(r.schema,r.name,0,t)}catch(a){if(a instanceof ye)continue;throw a}if(![...t.keys()].some(a=>n.has(a)))for(const[a,i]of t)n.set(a,i)}return[...n.values()].toSorted((r,t)=>r.name.localeCompare(t.name))},C=e=>[`// GENERATED by \`lunora sdk generate --lang ${e}\` — do not edit.`,"// Run the command again to regenerate."],T=e=>{switch(e.kind){case"boolean":return"Boolean";case"class":case"enum":return e.name;case"list":return`java.util.List<${T(e.item)}>`;case"number":return"Double";case"record":return`java.util.Map<String, ${T(e.value)}>`;case"string":return"String";default:return"Object"}},I=e=>{switch(e.kind){case"class":case"enum":return!0;case"list":return I(e.item);case"record":return I(e.value);default:return!1}},F=(e,n,r)=>{if(!I(e))return n;const t=`item${String(r)}`;switch(e.kind){case"class":return`${n} == null ? null : ${n}.toWire()`;case"enum":return`${n} == null ? null : ${n}.toValue()`;case"list":return`ModelWire.writeList(${n}, ${t} -> ${F(e.item,t,r+1)})`;case"record":return`ModelWire.writeRecord(${n}, ${t} -> ${F(e.value,t,r+1)})`;default:return n}},x=(e,n,r)=>{const t=`item${String(r)}`;switch(e.kind){case"boolean":return`ModelWire.flag(${n})`;case"class":return`ModelWire.readObject(${n}, ${e.name}::fromWire)`;case"enum":return`ModelWire.readEnum(${n}, ${e.name}::forValue)`;case"list":return`ModelWire.readList(${n}, ${t} -> ${x(e.item,t,r+1)})`;case"number":return`ModelWire.number(${n})`;case"record":return`ModelWire.readRecord(${n}, ${t} -> ${x(e.value,t,r+1)})`;case"string":return`ModelWire.text(${n})`;default:return n}},pn=e=>{const n=l(e.wireKey);return e.optional?[" /**",` * Wire key {@code ${n}} — OPTIONAL: null omits the key entirely, because`," * `v.optional` accepts the value or `undefined` and rejects an explicit null."," */"]:[` /** Wire key {@code ${n}}.${e.nullable?" Nullable: null is sent as an explicit null.":""} */`]},dn=100,$n=e=>{const n=e.fields.map(t=>`${T(t.type)} ${t.name}`),r=` public ${e.name}(${n.join(", ")}) {`;return r.length<=dn?[r]:[` public ${e.name}(`,...n.map((t,a)=>` ${t}${a===n.length-1?") {":","}`)]},mn=e=>{const n=e.fields.flatMap(t=>{const a=`wire.put("${$(t.wireKey)}", ${F(t.type,`this.${t.name}`,0)});`;return t.optional?[` if (this.${t.name} != null) {`,` ${a}`," }"]:[` ${a}`]}),r=e.fields.map(t=>` ${x(t.type,`wire.get("${$(t.wireKey)}")`,0)}`);return[...C("java"),"",`package ${w};`,"","/**",` * The \`${e.name}\` model.`," *"," * <p>Field names are local; the keys {@link #toWire()} and {@link #fromWire(Object)} use are"," * the schema's own, emitted verbatim, so a renamed field cannot reach the wire."," */",`public final class ${e.name} {`,...e.fields.flatMap(t=>[...pn(t),` public final ${T(t.type)} ${t.name};`,""]),...$n(e),...e.fields.map(t=>` this.${t.name} = ${t.name};`)," }",""," /** This model as the wire-shaped map the transport encodes. */"," public java.util.Map<String, Object> toWire() {"," java.util.Map<String, Object> wire = new java.util.LinkedHashMap<>();",...n,""," return wire;"," }",""," /** Rebuild from a decoded wire value. */",` public static ${e.name} fromWire(Object value) {`," java.util.Map<String, Object> wire = ModelWire.object(value);","",...r.length===0?[` return new ${e.name}();`]:[` return new ${e.name}(`,`${r.join(`,
105
+ `)});`]," }","}",""].join(`
106
+ `)},yn=e=>[...C("java"),"",`package ${w};`,"",`/** The \`${e.name}\` union. Each constant keeps the wire string it encodes to. */`,`public enum ${e.name} {`,...e.constants.map((n,r)=>` ${n.name}("${$(n.wireValue)}")${r===e.constants.length-1?";":","}`),""," private final String value;","",` ${e.name}(String value) {`," this.value = value;"," }",""," /** The wire string this constant encodes to. */"," public String toValue() {"," return this.value;"," }",""," /** The constant a wire string decodes to. */",` public static ${e.name} forValue(String value) {`,` for (${e.name} candidate : values()) {`," if (candidate.value.equals(value)) {"," return candidate;"," }"," }","",` throw new IllegalArgumentException("${e.name}: unknown wire value " + value);`," }","}",""].join(`
107
+ `),fn=[{lines:[' @SuppressWarnings("unchecked")'," static java.util.Map<String, Object> object(Object value) {"," return value instanceof java.util.Map"," ? (java.util.Map<String, Object>) value"," : new java.util.LinkedHashMap<String, Object>();"," }"],name:"object"},{lines:[" static String text(Object value) {"," return value instanceof String ? (String) value : null;"," }"],name:"text"},{lines:[" static Double number(Object value) {"," return value instanceof Number ? ((Number) value).doubleValue() : null;"," }"],name:"number"},{lines:[" static Boolean flag(Object value) {"," return value instanceof Boolean ? (Boolean) value : null;"," }"],name:"flag"},{lines:[" /** A nested model, or null when the payload carried no object there. */"," static <T> T readObject(Object value, java.util.function.Function<Object, T> read) {"," return value instanceof java.util.Map ? read.apply(value) : null;"," }"],name:"readObject"},{lines:[" /** An enum constant, or null when the payload carried no string there. */"," static <T> T readEnum(Object value, java.util.function.Function<String, T> read) {"," return value instanceof String ? read.apply((String) value) : null;"," }"],name:"readEnum"},{lines:[" static <T> java.util.List<T> readList("," Object value, java.util.function.Function<Object, T> read) {"," if (!(value instanceof java.util.List)) {"," return null;"," }",""," java.util.List<T> items = new java.util.ArrayList<T>();",""," for (Object item : (java.util.List<?>) value) {"," items.add(read.apply(item));"," }",""," return items;"," }"],name:"readList"},{lines:[" static <T> java.util.Map<String, T> readRecord("," Object value, java.util.function.Function<Object, T> read) {"," if (!(value instanceof java.util.Map)) {"," return null;"," }",""," java.util.Map<String, T> entries = new java.util.LinkedHashMap<String, T>();",""," for (java.util.Map.Entry<?, ?> entry : ((java.util.Map<?, ?>) value).entrySet()) {"," entries.put(String.valueOf(entry.getKey()), read.apply(entry.getValue()));"," }",""," return entries;"," }"],name:"readRecord"},{lines:[" static <T> java.util.List<Object> writeList("," java.util.List<T> items, java.util.function.Function<T, Object> write) {"," if (items == null) {"," return null;"," }",""," java.util.List<Object> encoded = new java.util.ArrayList<Object>(items.size());",""," for (T item : items) {"," encoded.add(write.apply(item));"," }",""," return encoded;"," }"],name:"writeList"},{lines:[" static <T> java.util.Map<String, Object> writeRecord("," java.util.Map<String, T> entries, java.util.function.Function<T, Object> write) {"," if (entries == null) {"," return null;"," }",""," java.util.Map<String, Object> encoded = new java.util.LinkedHashMap<String, Object>();",""," for (java.util.Map.Entry<String, T> entry : entries.entrySet()) {"," encoded.put(entry.getKey(), write.apply(entry.getValue()));"," }",""," return encoded;"," }"],name:"writeRecord"}],gn=e=>{const n=fn.filter(r=>e.includes(`ModelWire.${r.name}(`));return[...C("java"),"",`package ${w};`,"","/** Wire readers and writers shared by the generated models. */","final class ModelWire {"," private ModelWire() {}",...n.flatMap(r=>["",...r.lines]),"}",""].join(`
108
+ `)},bn=e=>{const n=be(e);if(n.length===0)return{};const r={};for(const t of n)r[`${K}/${t.name}.java`]=t.kind==="enum"?yn(t):mn(t);return{[`${K}/ModelWire.java`]:gn(Object.values(r).join(`
109
+ `)),...r}},q=e=>{switch(e.kind){case"boolean":return"Boolean";case"class":case"enum":return e.name;case"list":return`List<${q(e.item)}>`;case"number":return"Double";case"record":return`Map<String, ${q(e.value)}>`;case"string":return"String";default:return"WireValue"}},h=(e,n,r)=>{const t=`item${String(r)}`,a=`entry${String(r)}`;switch(e.kind){case"boolean":return`WireValue.Bool(${n})`;case"class":return`${n}.toWire()`;case"enum":return`WireValue.Text(${n}.wireValue)`;case"list":return`WireValue.Arr(${n}.map { ${t} -> ${h(e.item,t,r+1)} })`;case"number":return`WireValue.Num(${n})`;case"record":return`WireValue.Obj(${n}.map { ${a} -> ${a}.key to ${h(e.value,`${a}.value`,r+1)} })`;case"string":return`WireValue.Text(${n})`;default:return n}},U=(e,n,r,t)=>`wireNeed(${ve(e,n,r,t)}, "${v(t)}")`,ve=(e,n,r,t)=>{const a=`item${String(r)}`,i=`entry${String(r)}`;switch(e.kind){case"boolean":return`wireBool(${n})`;case"class":return`wireObj(${n})?.let { ${a} -> ${e.name}.fromWire(${a}) }`;case"enum":return`wireText(${n})?.let { ${a} -> ${e.name}.forValue(${a}) }`;case"list":return`wireArr(${n})?.items?.map { ${a} -> ${U(e.item,a,r+1,`${t}[]`)} }`;case"number":return`wireNum(${n})`;case"record":return`wireObj(${n})?.fields?.associate { ${i} -> ${i}.first to ${U(e.value,`${i}.second`,r+1,`${t}{}`)} }`;case"string":return`wireText(${n})`;default:return n}},vn=e=>{const n=e.fields.map(a=>{const i=l(a.wireKey);return[...a.optional?[" /**",` * Wire key \`${i}\` — OPTIONAL: null omits the key entirely, because`," * `v.optional` accepts the value or `undefined` and rejects an explicit null."," */"]:[` /** Wire key \`${i}\`.${a.nullable?" Nullable: null is sent as an explicit null.":""} */`],` val ${a.name}: ${q(a.type)}${a.optional||a.nullable?"?":""}${a.optional?" = null":""},`]}),r=e.fields.map(a=>{const i=v(a.wireKey);return a.optional?` ${a.name}?.let { add("${i}" to ${h(a.type,"it",0)}) }`:a.nullable?` add("${i}" to (${a.name}?.let { ${h(a.type,"it",0)} } ?: WireValue.Null))`:` add("${i}" to ${h(a.type,a.name,0)})`}),t=e.fields.map(a=>{const i=`wireField(value, "${v(a.wireKey)}")`,s=a.optional||a.nullable?ve(a.type,i,0,a.wireKey):U(a.type,i,0,a.wireKey);return` ${a.name} = ${s},`});return["/**",` * The \`${e.name}\` model.`," *"," * Property names are local; the keys [toWire] and [fromWire] use are the schema's own,"," * emitted verbatim, so a renamed property cannot reach the wire."," */",`class ${e.name}(`,...n.flat(),") {"," /** This model as the wire-shaped object the transport encodes. */"," fun toWire(): WireValue ="," WireValue.Obj("," buildList {",...r," },"," )",""," companion object {"," /** Rebuild from a decoded wire value. */",` fun fromWire(value: WireValue): ${e.name} =`,` ${e.name}(`,...t," )"," }","}"]},wn=e=>[`/** The \`${e.name}\` union. Each entry keeps the wire string it encodes to. */`,`enum class ${e.name}(val wireValue: String) {`,...e.constants.map(n=>` ${n.name}("${v(n.wireValue)}"),`)," ;",""," companion object {"," /** The entry a wire string decodes to. */",` fun forValue(value: String): ${e.name} =`," entries.firstOrNull { it.wireValue == value }",` ?: throw IllegalArgumentException("${e.name}: unknown wire value " + value)`," }","}"],jn=[{lines:["private fun wireField(value: WireValue, key: String): WireValue? ="," (value as? WireValue.Obj)?.fields?.firstOrNull { it.first == key }?.second"],name:"wireField"},{lines:["private fun wireText(value: WireValue?): String? = (value as? WireValue.Text)?.value"],name:"wireText"},{lines:["private fun wireNum(value: WireValue?): Double? = (value as? WireValue.Num)?.value"],name:"wireNum"},{lines:["private fun wireBool(value: WireValue?): Boolean? = (value as? WireValue.Bool)?.value"],name:"wireBool"},{lines:["private fun wireArr(value: WireValue?): WireValue.Arr? = value as? WireValue.Arr"],name:"wireArr"},{lines:["private fun wireObj(value: WireValue?): WireValue.Obj? = value as? WireValue.Obj"],name:"wireObj"},{lines:["/** A required field the payload omitted or mistyped is a contract violation, not a null. */","private fun <T> wireNeed(read: T?, label: String): T =",' read ?: throw WireFormatException("lunora: the wire payload is missing or mistyped " + label)'],name:"wireNeed"}],hn=e=>{const n=be(e);if(n.length===0)return{};const r=n.flatMap(s=>[...s.kind==="enum"?wn(s):vn(s),""]),t=jn.filter(s=>r.some(u=>u.includes(`${s.name}(`))),a=t.flatMap((s,u)=>u===0?[...s.lines]:["",...s.lines]),i=[...C("kotlin"),"",`package ${w}`,"",...t.some(s=>s.name==="wireNeed")?["import dev.lunora.WireFormatException"]:[],"import dev.lunora.WireValue","",...r,...a,""].join(`
110
+ `);return{[`${K}/Models.kt`]:i}},An=`${f("java").map(e=>`// ${e}`).join(`
111
+ `)}
112
+
113
+ `,ne="lunoraapi",_n=new Set(["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","try","void","volatile","while"]),H=e=>{const n=o(e),r=n.charAt(0).toLowerCase()+n.slice(1);return _n.has(r)?`${r}_`:r},Sn=e=>`Client.Verb.${e.toUpperCase()}`,we=e=>e.argsType===void 0?{payload:"args",type:"java.util.Map<String, Object>"}:{payload:"args == null ? null : args.toWire()",type:e.argsType},re=e=>{const n=we(e),r=`client.call(
114
+ ${Sn(e.verb)}, "${$(e.functionPath)}", ${n.payload}, shardKey)`;return[` /** ${l(e.summary)} */`,` public ${e.resultType??"Object"} ${H(e.functionName)}(${n.type} args, String shardKey) {`,` return ${e.resultType===void 0?r:`${e.resultType}.fromWire(${r})`};`," }"].join(`
115
+ `)},En=e=>{const n=we(e);return[` /** live ${l(e.summary)} — re-runs on every write to the tables it reads. */`,` public Runnable subscribe${o(e.functionName)}(`,` ${n.type} args,`," java.util.function.Consumer<Object> onData,"," java.util.function.Consumer<Client.SubscriptionError> onError,"," String shardKey) {"," return client.subscribe(",` "${$(e.functionPath)}", ${n.payload}, onData, onError, shardKey);`," }"].join(`
116
+ `)},Tn=e=>{const n=`${o(e.name)}Api`,r=e.methods.map(t=>t.verb==="query"?`${re(t)}
117
+
118
+ ${En(t)}`:re(t)).join(`
119
+
120
+ `);return[` /** Functions declared in \`${l(e.name)}\`. */`,` public static final class ${n} {`," private final Client client;","",` ${n}(Client client) {`," this.client = client;"," }","",r.replaceAll(/^ {4}/gmu," ")," }"].join(`
121
+ `)},kn=({namespaces:e})=>{const n=e.map(i=>` public final ${o(i.name)}Api ${H(i.name)};`).join(`
122
+ `),r=e.map(i=>` this.${H(i.name)} = new ${o(i.name)}Api(client);`).join(`
123
+ `),t=N(e).map(i=>`import ${w}.${i};
124
+ `),a=[An,`package ${ne};
125
+ `,`
126
+ `,`import dev.lunora.Client;
127
+ `,...t,`
128
+ `,"/** Typed entry point: `new Api(client).<namespace>.<function>(args, shardKey)`. */\n",`public final class Api {
129
+ `,n.length>0?`${n}
130
+
131
+ `:"",` public Api(Client client) {
132
+ `,r.length>0?`${r}
133
+ `:` // No functions in this deployment.
134
+ `,` }
135
+ `,`
136
+ `,e.map(i=>Tn(i)).join(`
137
+
138
+ `),`
139
+ }
140
+ `].join("");return{[`${ne}/Api.java`]:a}},On={id:"java",render:kn,renderModels:bn,requires:[],vendor:[{from:"src/dev/lunora",to:"dev/lunora"}]},Nn=`${f("kotlin").map(e=>`// ${e}`).join(`
141
+ `)}
142
+
143
+ `,te="lunoraapi",Cn=new Set(["as","break","class","continue","do","else","false","for","fun","if","in","interface","is","null","object","package","return","super","this","throw","true","try","typealias","typeof","val","var","when","while"]),je=e=>{const n=o(e),r=n.charAt(0).toLowerCase()+n.slice(1);return Cn.has(r)?`\`${r}\``:r},Ln=e=>`Verb.${e.toUpperCase()}`,he=e=>e.argsType===void 0?{declaration:"args: WireValue? = null",payload:"args"}:{declaration:`args: ${e.argsType}`,payload:"args.toWire()"},ae=e=>{const n=he(e),r=`client.call(${Ln(e.verb)}, "${v(e.functionPath)}", ${n.payload}, shardKey)`;return[` /** ${l(e.summary)} */`,` fun ${je(e.functionName)}(${n.declaration}, shardKey: String? = null): ${e.resultType??"WireValue"} =`,` ${e.resultType===void 0?r:`${e.resultType}.fromWire(${r})`}`].join(`
144
+ `)},Wn=e=>{const n=he(e);return[` /** live ${l(e.summary)} — re-runs on every write to the tables it reads. */`,` fun subscribe${o(e.functionName)}(`,` ${n.declaration},`," onData: ((WireValue) -> Unit)?,"," onError: ((SubscriptionError) -> Unit)? = null,"," shardKey: String? = null,"," ): () -> Unit =",` client.subscribe("${v(e.functionPath)}", ${n.payload}, onData, onError, shardKey)`].join(`
145
+ `)},Mn=e=>{const n=`${o(e.name)}Api`,r=e.methods.map(t=>t.verb==="query"?`${ae(t)}
146
+
147
+ ${Wn(t)}`:ae(t)).join(`
148
+
149
+ `);return[`/** Functions declared in \`${l(e.name)}\`. */`,`class ${n}(private val client: Client) {`,r,"}"].join(`
150
+ `)},Rn=({namespaces:e})=>{const n=e.map(i=>` val ${je(i.name)}: ${o(i.name)}Api = ${o(i.name)}Api(client)`).join(`
151
+ `),r=e.flatMap(i=>i.methods),t=[`import dev.lunora.Client
152
+ `,...r.some(i=>i.verb==="query")?[`import dev.lunora.SubscriptionError
153
+ `]:[],`import dev.lunora.Verb
154
+ `,...r.some(i=>i.argsType===void 0||i.resultType===void 0)?[`import dev.lunora.WireValue
155
+ `]:[],...N(e).map(i=>`import ${w}.${i}
156
+ `)],a=[Nn,`package ${te}
157
+ `,`
158
+ `,...t,`
159
+ `,e.map(i=>Mn(i)).join(`
160
+
161
+ `),`
162
+
163
+ `,"/** Typed entry point: `Api(client).<namespace>.<function>(args)`. */\n",`class Api(client: Client) {
164
+ `,n.length>0?`${n}
165
+ `:` init { require(true) { client } }
166
+ `,`}
167
+ `].join("");return{[`${te}/Api.kt`]:a}},Dn={id:"kotlin",render:Rn,renderModels:hn,requires:[],vendor:[{from:"src",to:"dev/lunora"}]},Pn=new Set(["and","as","assert","async","await","break","class","continue","def","del","elif","else","except","False","finally","for","from","global","if","import","in","is","lambda","None","nonlocal","not","or","pass","raise","return","True","try","while","with","yield"]),A=`"""${f("python").join(`
168
+
169
+ `)}
170
+ """
171
+
172
+ `,M="lunora_api",J=e=>{const n=B(e);return Pn.has(n)?`${n}_`:n},Ae=e=>p(e,{none:"{}",typed:()=>"args.to_dict()",untyped:"args"}),Vn=(e,n,r,t)=>p(e,{none:n,typed:r,untyped:t}),ie=e=>{const n=e.resultType??"Any",r=Vn(e,"self",i=>`self, args: ${i}`,"self, args: Any"),t=Ae(e),a=`await self._client.${e.verb}("${$(e.functionPath)}", ${t}, shard_key)`;return[` async def ${J(e.functionName)}(${r}, *, shard_key: Optional[str] = None) -> ${n}:`,` """${l(e.summary)}"""`,` ${e.resultType===void 0?`return ${a}`:`return ${e.resultType}.from_dict(${a})`}`].join(`
173
+ `)},Kn=e=>{const n=Ae(e),r=["self",...p(e,{none:[],typed:t=>[`args: ${t}`],untyped:["args: Any"]}),"on_data: Callback","on_error: Optional[ErrorCallback] = None","*","shard_key: Optional[str] = None"];return[` def subscribe_${J(e.functionName)}(`,...r.map(t=>` ${t},`)," ) -> Unsubscribe:",` """live ${l(e.summary)} — re-runs on every write to the tables it reads."""`,` return self._client.subscribe("${$(e.functionPath)}", ${n}, on_data, on_error, shard_key)`].join(`
174
+ `)},In=e=>{const n=e.methods.map(r=>r.verb==="query"?`${ie(r)}
175
+
176
+ ${Kn(r)}`:ie(r)).join(`
177
+
178
+ `);return[`class ${o(e.name)}Api:`,` """Functions declared in \`${l(e.name)}\`."""`,""," def __init__(self, client: LunoraClient) -> None:"," self._client = client","",n].join(`
179
+ `)},Fn=e=>e.replaceAll(/^([ \t]*)except:$/gmu,"$1except Exception:"),xn=({models:e,namespaces:n})=>{const r=N(n),t=r.length>0?`from .models import ${r.join(", ")}
180
+ `:"",i=P(n).some(c=>c.verb==="query")?"Callback, ErrorCallback, LunoraClient, Unsubscribe":"LunoraClient",s=P(n).some(c=>c.resultType===void 0),u=n.map(c=>` self.${J(c.name)} = ${o(c.name)}Api(client)`).join(`
181
+ `),m=[A,`from typing import ${s?"Any, Optional":"Optional"}
182
+ `,`
183
+ `,`from lunora.client import ${i}
184
+ `,t,`
185
+
186
+ `,n.map(c=>In(c)).join(`
187
+
188
+
189
+ `),`
190
+
191
+
192
+ `,`class Api:
193
+ `,' """Typed entry point: `Api(client).<namespace>.<function>(args)`."""\n',`
194
+ `,` def __init__(self, client: LunoraClient) -> None:
195
+ `,u.length>0?`${u}
196
+ `:` pass
197
+ `].join(""),d=["Api",...n.map(c=>`${o(c.name)}Api`)];return{[`${M}/__init__.py`]:[A,`from .api import ${d.join(", ")}
198
+ `,`
199
+ `,`__all__ = [${d.map(c=>`"${c}"`).join(", ")}]
200
+ `].join(""),[`${M}/api.py`]:m,[`${M}/models.py`]:e.length>0?`${A}${Fn(e)}
201
+ `:`${A}# No typed argument or result schemas in this deployment.
202
+ `}},qn={id:"python",quicktype:{lang:"python",rendererOptions:{"python-version":"3.7"}},render:xn,requires:[],vendor:[{from:"lunora",to:"lunora"}]},R=`${f("ruby").map(e=>`# ${e}`).join(`
203
+ `)}
204
+
205
+ `,Un=new Set(["alias","and","begin","break","case","class","def","defined?","do","else","elsif","end","ensure","false","for","if","in","module","next","nil","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield"]),Y=e=>$(e).replaceAll("#","\\#"),k=e=>{const n=B(e);return Un.has(n)?`${n}_`:n},Hn=` # Delegates to the transport, which owns the projection and its tests — see
206
+ # \`Lunora.wire_args\`. The path list is generated per model because only the
207
+ # schema knows which nils may be dropped.
208
+ def self.wire_args(model, optional_paths = [])
209
+ Lunora.wire_args(model, optional_paths)
210
+ end
211
+
212
+ `,Gn=e=>`[${e.map(n=>`[${n.map(r=>`"${Y(r)}"`).join(", ")}]`).join(", ")}]`,_e=e=>p(e,{none:"{}",typed:()=>`LunoraApi.wire_args(args, ${Gn(e.argsNullPaths.optional)})`,untyped:"args"}),se=e=>{const n=e.argsType===void 0&&!e.takesArgs?"shard_key: nil":"args, shard_key: nil",r=_e(e),t=`@client.${e.verb}("${Y(e.functionPath)}", ${r}, shard_key)`,a=e.resultType===void 0?t:`${e.resultType}.from_dynamic!(${t})`;return[` # ${l(e.summary)}`,` def ${k(e.functionName)}(${n})`,` ${a}`," end"].join(`
213
+ `)},Bn=e=>{const n=e.argsType===void 0&&!e.takesArgs?"on_data, on_error = nil, shard_key: nil":"args, on_data, on_error = nil, shard_key: nil",r=_e(e);return[` # live ${l(e.summary)} — re-runs on every write to the tables it reads.`,` def subscribe_${k(e.functionName)}(${n})`,` @client.subscribe("${Y(e.functionPath)}", ${r}, on_data, on_error, shard_key)`," end"].join(`
214
+ `)},Jn=e=>{const n=e.methods.map(r=>r.verb==="query"?`${se(r)}
215
+
216
+ ${Bn(r)}`:se(r)).join(`
217
+
218
+ `);return[` # Functions declared in \`${l(e.name)}\`.`,` class ${o(e.name)}Api`," def initialize(client)"," @client = client"," end","",n," end"].join(`
219
+ `)},Yn=({models:e,namespaces:n})=>{const r=n.map(i=>`:${k(i.name)}`).join(", "),t=n.map(i=>` @${k(i.name)} = ${o(i.name)}Api.new(client)`).join(`
220
+ `);return{"api.rb":[`# frozen_string_literal: true
221
+
222
+ `,R,`require_relative "models"
223
+ `,`
224
+ `,`module LunoraApi
225
+ `,P(n).some(i=>i.argsType!==void 0)?Hn:"",n.map(i=>Jn(i)).join(`
226
+
227
+ `),`
228
+
229
+ `," # Typed entry point: `Api.new(client).<namespace>.<function>(args)`.\n",` class Api
230
+ `,r.length>0?` attr_reader ${r}
231
+
232
+ `:"",` def initialize(client)
233
+ `,t.length>0?`${t}
234
+ `:` @client = client
235
+ `,` end
236
+ `,` end
237
+ `,`end
238
+ `].join(""),"models.rb":e.length>0?`# frozen_string_literal: true
239
+
240
+ ${R}${e}
241
+ `:`# frozen_string_literal: true
242
+
243
+ ${R}# No typed argument or result schemas in this deployment.
244
+ `}},zn={id:"ruby",quicktype:{lang:"ruby",rendererOptions:{}},render:Yn,requires:["dry-struct + dry-types (gems, required by the generated models)"],vendor:[{from:"lib/lunora.rb",to:"lunora.rb"},{from:"lib/lunora",to:"lunora"}]},S=`${f("rust").map(e=>`// ${e}`).join(`
245
+ `)}
246
+
247
+ `,Zn=`${S}pub mod api;
248
+ pub mod models;
249
+ `,Xn=`# The generated Lunora Rust SDK, with the transport vendored under ./lunora.
250
+ #
251
+ # Add to a consuming crate:
252
+ #
253
+ # lunora-api = { path = "sdk/rust" }
254
+
255
+ [package]
256
+ name = "lunora-api"
257
+ version = "0.1.0"
258
+ edition = "2021"
259
+ publish = false
260
+
261
+ # Its own workspace root, so a consumer whose project IS a workspace does not
262
+ # adopt this directory as a member (which then fails to build on its own).
263
+ [workspace]
264
+
265
+ [dependencies]
266
+ lunora = { path = "lunora" }
267
+ serde = { version = "1", features = ["derive"] }
268
+ serde_json = "1"
269
+ `,Qn=new Set(["abstract","as","async","await","become","box","break","const","continue","crate","do","dyn","else","enum","extern","false","final","fn","for","if","impl","in","let","loop","macro","match","mod","move","mut","override","priv","pub","ref","return","self","static","struct","super","trait","true","try","type","typeof","unsafe","unsized","use","virtual","where","while","yield"]),O=e=>{const n=B(e);return Qn.has(n)?`r#${n}`:n},er=e=>`Verb::${o(e)}`,Se=e=>e.length===0?"&[]":`&[${e.map(n=>`&["${n.map(r=>$(r)).join('", "')}"][..]`).join(", ")}]`,oe=e=>{const n=p(e,{none:"&self, shard_key: Option<&str>",typed:a=>`&self, args: &${a}, shard_key: Option<&str>`,untyped:"&self, args: &WireValue, shard_key: Option<&str>"}),r=p(e,{none:"&WireValue::Object(Vec::new())",typed:()=>`&from_model_json(&serde_json::to_value(args).map_err(|error| ClientError::Transport(error.to_string()))?, ${Se(e.argsNullPaths.optional)})`,untyped:"args"}),t=`self.client.call(${er(e.verb)}, "${$(e.functionPath)}", ${r}, shard_key)`;return e.resultType===void 0?[` /// ${l(e.summary)}`,` pub fn ${O(e.functionName)}(${n}) -> Result<WireValue, ClientError> {`,` ${t}`," }"].join(`
270
+ `):[` /// ${l(e.summary)}`,` pub fn ${O(e.functionName)}(${n}) -> Result<${e.resultType}, ClientError> {`,` let raw = ${t}?;`," let json = encode_wire(&raw).map_err(ClientError::Wire)?;"," serde_json::from_value(json).map_err(|error| ClientError::Transport(error.to_string()))"," }"].join(`
271
+ `)},nr=e=>{const n=p(e,{none:"",typed:t=>`args: &${t}, `,untyped:"args: &WireValue, "}),r=p(e,{none:"WireValue::Object(Vec::new())",typed:()=>`from_model_json(&serde_json::to_value(args).map_err(|error| ClientError::Transport(error.to_string()))?, ${Se(e.argsNullPaths.optional)})`,untyped:"args.clone()"});return[` /// live ${l(e.summary)} — re-runs on every write to the tables it reads.`,` pub fn subscribe_${O(e.functionName)}(`," &mut self,",` ${n}on_data: DataHandler,`," on_error: ErrorHandler,"," shard_key: Option<&str>,"," ) -> Result<String, ClientError> {",` Ok(self.client.subscribe_on_shard("${$(e.functionPath)}", ${r}, on_data, on_error, shard_key))`," }"].join(`
272
+ `)},rr=e=>{const n=`${o(e.name)}Api`,r=e.methods.map(t=>t.verb==="query"?`${oe(t)}
273
+
274
+ ${nr(t)}`:oe(t)).join(`
275
+
276
+ `);return[`/// Functions declared in \`${l(e.name)}\`.`,`pub struct ${n}<'client> {`," client: &'client mut Client,","}","",`impl<'client> ${n}<'client> {`,r,"}"].join(`
277
+ `)},tr=({models:e,namespaces:n})=>{const r=n.map(a=>[` /// Functions declared in \`${l(a.name)}\`.`,` pub fn ${O(a.name)}(&mut self) -> ${o(a.name)}Api<'_> {`,` ${o(a.name)}Api { client: self.client }`," }"].join(`
278
+ `)).join(`
279
+
280
+ `),t=[S,`#![allow(dead_code, unused_imports)]
281
+ `,`
282
+ `,`use lunora::client::{Client, ClientError, DataHandler, ErrorHandler, Verb};
283
+ `,`use lunora::wire::{encode_wire, from_model_json, WireValue};
284
+ `,`
285
+ `,`use crate::models::*;
286
+ `,`
287
+ `,n.map(a=>rr(a)).join(`
288
+
289
+ `),`
290
+
291
+ `,"/// Typed entry point: `Api::new(&client).<namespace>().<function>(args)`.\n",`pub struct Api<'client> {
292
+ `,` client: &'client mut Client,
293
+ `,`}
294
+ `,`
295
+ `,`impl<'client> Api<'client> {
296
+ `,` pub fn new(client: &'client mut Client) -> Self {
297
+ `,` Self { client }
298
+ `,` }
299
+ `,r.length>0?`
300
+ ${r}
301
+ `:"",`}
302
+ `].join("");return{"Cargo.toml":Xn,"src/api.rs":t,"src/lib.rs":Zn,"src/models.rs":e.length>0?`${S}#![allow(dead_code)]
303
+
304
+ ${e}
305
+ `:`${S}#![allow(dead_code)]
306
+
307
+ // No typed argument or result schemas in this deployment.
308
+ `}},ar={id:"rust",quicktype:{lang:"rust",rendererOptions:{"just-types":"true"}},render:tr,requires:["serde (derive) + serde_json — declared in the emitted Cargo.toml, fetched by cargo"],vendor:[{from:"Cargo.toml",to:"lunora/Cargo.toml"},{from:"src",to:"lunora/src"}]},D=`${f("swift").map(e=>`// ${e}`).join(`
309
+ `)}
310
+
311
+ `,le="Sources/LunoraApi",ir=`// swift-tools-version:5.9
312
+
313
+ import PackageDescription
314
+
315
+ // The generated Lunora Swift SDK, with the transport vendored under
316
+ // Sources/Lunora. Add to a consuming package — where "swift" below is the NAME OF
317
+ // THE DIRECTORY THIS FILE IS IN, which is how SwiftPM identifies a local path
318
+ // dependency. It ignores the "name:" field for that, and a bare product name in a
319
+ // target's dependencies does not resolve at all, so the directory name is the one
320
+ // spelling that works:
321
+ //
322
+ // dependencies: [.package(path: "sdk/swift")],
323
+ // targets: [
324
+ // .target(
325
+ // name: "YourTarget",
326
+ // dependencies: [.product(name: "LunoraApi", package: "swift")]
327
+ // )
328
+ // ]
329
+ let package = Package(
330
+ name: "LunoraSdk",
331
+ platforms: [.macOS(.v12), .iOS(.v15)],
332
+ products: [
333
+ .library(name: "LunoraApi", targets: ["LunoraApi"]),
334
+ .library(name: "Lunora", targets: ["Lunora"]),
335
+ ],
336
+ targets: [
337
+ .target(name: "Lunora"),
338
+ .target(name: "LunoraApi", dependencies: ["Lunora"]),
339
+ ]
340
+ )
341
+ `,sr=new Set(["as","associatedtype","borrowing","break","case","catch","class","consuming","continue","default","defer","deinit","do","else","enum","extension","fallthrough","false","fileprivate","for","func","guard","if","import","in","init","inout","internal","is","let","nil","nonisolated","open","operator","precedencegroup","private","protocol","public","repeat","rethrows","return","self","static","struct","subscript","super","switch","throw","throws","true","try","typealias","var","where","while"]),G=e=>{const n=o(e),r=n.charAt(0).toLowerCase()+n.slice(1);return sr.has(r)?`\`${r}\``:r},or=e=>`[${e.map(n=>`["${n.map(r=>$(r)).join('", "')}"]`).join(", ")}]`,Ee=e=>p(e,{none:"nil",typed:()=>{const{nullable:n}=e.argsNullPaths;return n.length===0?"try LunoraClient.wireValue(args)":`try LunoraClient.wireValue(args, nullablePaths: ${or(n)})`},untyped:"args"}),ue=e=>{const n=p(e,{none:"shardKey: String? = nil",typed:s=>`_ args: ${s}, shardKey: String? = nil`,untyped:"_ args: Any, shardKey: String? = nil"}),r=Ee(e),t=e.resultType??"Any",a=`try client.${e.verb}("${$(e.functionPath)}", args: ${r}, shardKey: shardKey)`,i=e.resultType===void 0?`return ${a}`:[`let raw = ${a}`," let data = try JSONSerialization.data(withJSONObject: raw, options: [.fragmentsAllowed])",` return try JSONDecoder().decode(${e.resultType}.self, from: data)`].join(`
342
+ `);return[` /// ${l(e.summary)}`,` public func ${G(e.functionName)}(${n}) throws -> ${t} {`,` ${i}`," }"].join(`
343
+ `)},lr=e=>{const n=p(e,{none:"",typed:t=>`_ args: ${t}, `,untyped:"_ args: Any, "}),r=Ee(e);return[` /// live ${l(e.summary)} — re-runs on every write to the tables it reads.`," @discardableResult",` public func subscribe${o(e.functionName)}(`,` ${n}onData: ((Any) -> Void)?,`," onError: ((LunoraSubscriptionError) -> Void)? = nil,"," shardKey: String? = nil"," ) throws -> LunoraUnsubscribe {",` client.subscribe("${$(e.functionPath)}", args: ${r}, onData: onData, onError: onError, shardKey: shardKey)`," }"].join(`
344
+ `)},ur=e=>{const n=`${o(e.name)}API`,r=e.methods.map(t=>t.verb==="query"?`${ue(t)}
345
+
346
+ ${lr(t)}`:ue(t)).join(`
347
+
348
+ `);return[`/// Functions declared in \`${l(e.name)}\`.`,`public struct ${n} {`," let client: LunoraClient","",r,"}"].join(`
349
+ `)},cr=({models:e,namespaces:n})=>{const r=n.map(i=>` public let ${G(i.name)}: ${o(i.name)}API`).join(`
350
+ `),t=n.map(i=>` ${G(i.name)} = ${o(i.name)}API(client: client)`).join(`
351
+ `),a=[D,`import Foundation
352
+ `,`import Lunora
353
+ `,`
354
+ `,n.map(i=>ur(i)).join(`
355
+
356
+ `),`
357
+
358
+ `,"/// Typed entry point: `API(client:).<namespace>.<function>(args)`.\n",`public struct API {
359
+ `,r.length>0?`${r}
360
+
361
+ `:"",` public init(client: LunoraClient) {
362
+ `,t.length>0?`${t}
363
+ `:` _ = client
364
+ `,` }
365
+ `,`}
366
+ `].join("");return{"Package.swift":ir,[`${le}/Api.swift`]:a,[`${le}/Models.swift`]:e.length>0?`${D}${e}
367
+ `:`${D}import Foundation
368
+
369
+ // No typed argument or result schemas in this deployment.
370
+ `}},pr={id:"swift",quicktype:{lang:"swift",rendererOptions:{"access-level":"public"}},render:cr,requires:[],vendor:[{from:"Sources/Lunora",to:"Sources/Lunora"}]},dr={dart:Be,go:Qe,java:On,kotlin:Dn,python:qn,ruby:zn,rust:ar,swift:pr},mr=Object.keys(dr).toSorted((e,n)=>e.localeCompare(n)),yr=async(e,n)=>{const r=ke(e);Oe(r);const t=n.renderModels?.(e),a=t===void 0?await We(e,n):Object.values(t).join(`
371
+ `),i=Ne(r,a);return{files:{...t,...n.render({models:a,namespaces:i})},undeclared:Le(r,a),unrepresentable:Ce(e)}};export{mr as SDK_LANGUAGES,dr as SDK_TARGETS,yr as generateSdk,br as isTypedSchema};
@@ -0,0 +1 @@
1
+ import{existsSync as f}from"node:fs";import{join as l}from"node:path";import{SyntaxKind as c,Node as o}from"ts-morph";import{diagnosticAt as u}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as p}from"./module-specifiers-WF8iAydP.mjs";import{a as g}from"./parse-validator-BFTp87yz.mjs";const m="shapes.ts",d=r=>{const t=r.getSymbol();if(!t)return r.getText()==="defineShape";for(const e of t.getDeclarations())if(o.isImportSpecifier(e))return p(e.getImportDeclaration().getModuleSpecifierValue())?e.getNameNode().getText()==="defineShape":!1;return!1},S=r=>{const t=r.getSymbol();if(!t)return!1;for(const e of t.getDeclarations()){if(!o.isNamespaceImport(e))continue;const i=e.getFirstAncestorByKind(c.ImportDeclaration);return i!==void 0&&p(i.getModuleSpecifierValue())}return!1},h=r=>{if(o.isIdentifier(r))return d(r);if(o.isPropertyAccessExpression(r)){const t=r.getExpression();return r.getName()==="defineShape"&&o.isIdentifier(t)&&S(t)}return!1},x=r=>{const[t]=r.getArguments();if(!t||!o.isObjectLiteralExpression(t))return;const e=t.getProperty("table");if(!e||!o.isPropertyAssignment(e))return;const i=e.getInitializer();return i&&o.isStringLiteral(i)?i.getLiteralValue():void 0},b=r=>{const[t]=r.getArguments();if(!t||!o.isObjectLiteralExpression(t))return{};const e=t.getProperty("args");if(!e||!o.isPropertyAssignment(e))return{};const i=e.getInitializer();return!i||!o.isObjectLiteralExpression(i)?{}:g(i)},y=r=>{const t=[];for(const e of r.getVariableDeclarations()){if(!e.isExported())continue;const i=e.getInitializer();if(i?.getKind()!==c.CallExpression)continue;const s=i,a=s.getExpression();if(!h(a))continue;const n=e.getNameNode();if(!o.isIdentifier(n))throw u(n,"defineShape exports must be plain named exports (no destructuring)");t.push({args:b(s),exportName:n.getText(),filePath:"shapes",table:x(s)})}return t},v=(r,t)=>{const e=l(t,m);if(!f(e))return[];const i=r.getSourceFile(e)??r.addSourceFileAtPath(e),s=y(i);return s.sort((a,n)=>a.exportName.localeCompare(n.exportName)),s};export{m as SHAPES_FILENAME,v as discoverShapes};
@@ -0,0 +1,16 @@
1
+ import{LunoraError as g}from"@lunora/errors";import{SCHEMA_SNAPSHOT_VERSION as m,sortKeys as b,diffSchemaSnapshots as S,parseSnapshotJson as k}from"./SCHEMA_SNAPSHOT_VERSION-DLXXalg2.mjs";import{serializeSchemaSnapshot as O}from"./SCHEMA_SNAPSHOT_VERSION-DLXXalg2.mjs";const w=e=>e==="global"||e==="root"?e:`shardBy:${e.field}`,$=e=>e.kind==="optional"?{kind:e.inner?.kind??"unknown",optional:!0}:{kind:e.kind,optional:!1},v=e=>{const t={};for(const[n,o]of Object.entries(e.shape))t[n]=$(o);const a={};for(const n of e.indexes)a[n.name]={fields:[...n.fields],unique:n.unique??!1};const s={};for(const n of e.relations)s[n.name]={field:n.field,kind:n.kind,table:n.table};return{fields:t,indexes:a,relations:s,shardMode:w(e.shardMode)}},D=(e,t)=>{const a={};for(const n of e.tables)a[n.name]=v(n);const s=[...t].sort();return{jurisdiction:e.jurisdiction,migrationIds:s,tables:b(a),version:m}};class y extends g{constructor(t){super("SCHEMA_SNAPSHOT_PARSE",t,{name:"SchemaSnapshotParseError"})}}const L=e=>{const t=k(e);if(t.status==="invalid")throw new y(t.error);return t.status==="ok"?t.snapshot:void 0},E={deploy:{allowDrift:!0,updateBaseline:!0},prepare:{allowDrift:!0,updateBaseline:!0},verify:{allowDrift:!0,updateBaseline:!1}},f=" • For backward-compatible changes (e.g. adding an optional field): pass `--allow-schema-drift` to skip the block.",p=" • To accept the new shape without a migration (you know data is compatible): pass `--update-schema-baseline`.",I=e=>{const t=e===void 0?void 0:E[e];if(e===void 0||t===void 0)return`${f}
2
+ ${p}
3
+ `;const a=t.updateBaseline?p:` • To accept the new shape without a migration, run \`lunora prepare --update-schema-baseline\` — \`lunora ${e}\` does not take that flag.`;return`${f}
4
+ ${a}
5
+ `},T=e=>{const{allowDrift:t=!1,baseline:a,command:s,current:n}=e,o=S(a,n),d=o.changes.filter(r=>r.severity==="breaking"),l=n.migrationIds.filter(r=>!(a?.migrationIds??[]).includes(r)),i=(r,c)=>({blocked:r,changes:o.changes,newMigrationIds:l,reason:c});if(o.changes.length===0||a===void 0)return i(!1,"");if(d.length===0){const r=o.changes.map(c=>` - ${c.summary}`).join(`
6
+ `);return i(!1,`schema drift detected (all additive/safe):
7
+ ${r}`)}const u=d.map(r=>` - ${r.summary}`).join(`
8
+ `);if(l.length>0)return i(!1,`breaking schema drift detected, but ${String(l.length)} new migration(s) were added (${l.join(", ")}):
9
+ ${u}`);const h=`deploy blocked: ${String(d.length)} breaking schema change(s) detected since the last blessed schema baseline — these changes are incompatible with existing data without a migration:
10
+ ${u}
11
+
12
+ To fix:
13
+ • For breaking changes: add a \`defineMigration({ id, table, up })\` in lunora/ for each affected table, then run \`lunora migrate\` (or \`lunora codegen\`) to apply and re-bless the baseline.
14
+ ${I(s)}Docs: https://lunora.dev/docs/migrations`;return t?i(!1,`${h}
15
+
16
+ (overridden by --allow-schema-drift)`):i(!0,h)};export{m as SCHEMA_SNAPSHOT_VERSION,y as SchemaSnapshotParseError,D as buildSchemaSnapshot,S as diffSchemaSnapshots,T as evaluateSchemaDrift,L as parseSchemaSnapshot,O as serializeSchemaSnapshot};
@@ -0,0 +1 @@
1
+ import{existsSync as p}from"node:fs";import{join as m}from"node:path";import{LunoraError as a}from"@lunora/errors";import{workflowDefaultName as u,workflowClassName as d,workflowBindingName as g}from"@lunora/workflow";import{Node as i,VariableDeclarationKind as w,SyntaxKind as x}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{u as b,s as h}from"./ast-CjWtsS6S.mjs";const k="workflows.ts",N=new Set(["do","sleep","sleepUntil","waitForEvent"]),y=n=>{const e=n.getSymbol();if(!e)return n.getText()==="defineWorkflow";for(const t of e.getDeclarations())if(i.isImportSpecifier(t))return t.getImportDeclaration().getModuleSpecifierValue()!=="@lunora/workflow"?!1:t.getNameNode().getText()==="defineWorkflow";return!1},E=h("workflow"),S=n=>{const e=n.getExpression();if(!i.isPropertyAccessExpression(e)||!N.has(e.getName()))return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="step"?!0:i.isIdentifier(t)&&t.getText()==="step"},D=n=>{const e=n.getProperty("handler");if(!e)return[];const t=i.isPropertyAssignment(e)?e.getInitializer():e;if(!t)return[];const o=[];for(const r of t.getDescendantsOfKind(x.CallExpression)){if(!S(r))continue;const s=r.getArguments()[0];!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s))||o.push({line:r.getStartLineNumber(),method:r.getExpression().getName(),name:s.getLiteralValue()})}return o},l=n=>{let e=n;for(;e&&(i.isAsExpression(e)||i.isSatisfiesExpression(e)||i.isParenthesizedExpression(e));)e=e.getExpression();return e},P=n=>{const e=l(n);if(e&&i.isObjectLiteralExpression(e))return e;if(!(!e||!i.isIdentifier(e)))for(const t of e.getSymbol()?.getDeclarations()??[]){const r=i.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===w.Const?l(t.getInitializer()):void 0;if(r&&i.isObjectLiteralExpression(r))return r}},W=(n,e)=>{const t=P(n.getArguments()[0]);if(!t)throw c(n,`workflow "${e}": defineWorkflow's argument must be an object literal, or a local \`const\` holding one — codegen reads \`name\` and the \`ctx.step.*\` calls out of it statically. Keep the handler wherever you like and pass it through: \`const config = { handler: myHandler }; export const ${e} = defineWorkflow(config);\`.`);const o={bindingName:g(e),className:d(e),exportName:e,name:u(e),steps:D(t)},r=t.getProperty("name");return r&&i.isPropertyAssignment(r)&&(o.name=E(r.getInitializerOrThrow(),e,"name")),o},I=n=>{const e=[];for(const t of n.getVariableDeclarations()){if(!t.isExported())continue;const o=b(t.getInitializer());if(!o)continue;const r=o.getExpression();if(!i.isIdentifier(r)||!y(r))continue;const s=t.getNameNode();if(!i.isIdentifier(s))throw c(s,"defineWorkflow exports must be plain named exports (no destructuring)");e.push(W(o,s.getText()))}return e},A=n=>{const e=new Map,t=new Map;for(const o of n){const r=e.get(o.name);if(r!==void 0)throw new a("DUPLICATE_WORKFLOW_NAME",`Duplicate workflow name "${o.name}": produced by both "${r}" and "${o.exportName}". Deployed workflow names must be unique across the project.`,{status:500});e.set(o.name,o.exportName);const s=t.get(o.bindingName);if(s!==void 0)throw new a("DUPLICATE_WORKFLOW_BINDING",`Duplicate workflow binding "${o.bindingName}": produced by both "${s}" and "${o.exportName}". Workflow export names must yield unique binding names.`,{status:500});t.set(o.bindingName,o.exportName)}},$=(n,e)=>{const t=m(e,k);if(!p(t))return[];const o=n.getSourceFile(t)??n.addSourceFileAtPath(t),r=I(o);return r.sort((s,f)=>s.exportName.localeCompare(f.exportName)),A(r),r};export{k as WORKFLOWS_FILENAME,$ as discoverWorkflows};
@@ -0,0 +1 @@
1
+ import{readdirSync as x,lstatSync as E}from"node:fs";import{join as m,extname as A,relative as b,sep as y}from"node:path";import{Node as r,SyntaxKind as p}from"ts-morph";import{diagnosticAt as S}from"./CodegenDiagnosticError-BUXlG3P-.mjs";const h=/\.ts$/u,P=(e,t)=>b(e,t).split(y).join("/").replace(h,""),f=(e,t=[],s=e)=>{let n;try{n=x(e)}catch{return t}for(const i of n){const o=m(e,i),a=E(o);if(a.isDirectory()){if(i==="_generated"||i==="node_modules")continue;f(o,t,s)}else if(a.isFile()&&A(i)===".ts"){if(i==="schema.ts"&&e===s)continue;t.push(o)}}return t},T=(e,t,s)=>{const n=[];for(const i of f(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i),a=P(t,i);for(const d of o.getDescendantsOfKind(p.CallExpression)){const c=s(d,a);c!==void 0&&n.push(c)}}return n},D=e=>{for(const t of e.getAncestors())if(r.isVariableDeclaration(t)&&t.getVariableStatement()?.hasExportKeyword()===!0)return t.getName();return""},I=(e,t)=>{if(t){const o=e.getArguments()[0];return o&&(r.isArrowFunction(o)||r.isFunctionExpression(o))?o:void 0}const s=e.getArguments()[0];if(!s||!r.isObjectLiteralExpression(s))return;const n=s.getProperty("handler");if(!n||!r.isPropertyAssignment(n))return;const i=n.getInitializer();return i&&(r.isArrowFunction(i)||r.isFunctionExpression(i))?i:void 0},z=(e,t)=>{if(!e||!r.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&r.isPropertyAssignment(s)?s.getInitializer():void 0},l=e=>r.isPropertyAccessExpression(e)&&e.getName()==="db"||r.isIdentifier(e)&&e.getText()==="db",w=new Set(["findFirst","findFirstOrThrow","findMany"]),C=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!w.has(t.getName()))return;const s=t.getExpression();if(l(s)){const n=e.getArguments()[0];return{options:e.getArguments()[1],table:n&&r.isStringLiteral(n)?n.getLiteralText():""}}if(r.isPropertyAccessExpression(s)){const n=s.getExpression();if(l(n))return{options:e.getArguments()[0],table:s.getName()}}},g=(e,t)=>{const s=e.getExpression();return!r.isPropertyAccessExpression(s)||!t.has(s.getName())?!1:l(s.getExpression())},u=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},R=(e,t,s)=>{const n=new Set,i=new Set;for(const o of e.getDescendantsOfKind(p.CallExpression))if(g(o,t)){const a=u(o);a!==""&&n.add(a)}else if(g(o,s)){const a=u(o);a!==""&&i.add(a)}return{tablesRead:[...n],tablesWritten:[...i]}},v=e=>{let t=e;for(;t&&(r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isParenthesizedExpression(t)||r.isNonNullExpression(t));)t=t.getExpression();return t},V=e=>{const t=v(e);return t&&r.isCallExpression(t)?t:void 0},_=e=>{const t=e.getExportAssignment(i=>!i.isExportEquals());if(!t)return;const s=t.getExpression();if(!r.isIdentifier(s))return s;const n=s.getSymbol()?.getValueDeclaration();return n&&r.isVariableDeclaration(n)?n.getInitializer():s},K=e=>{const t=e.getArguments()[1];return t&&r.isStringLiteral(t)?t.getLiteralValue():""},$=(e,t)=>{if(!r.isObjectLiteralExpression(e))return;const s=e.getProperty(t);if(!s||!r.isPropertyAssignment(s))return;const n=s.getInitializer();return n&&r.isStringLiteral(n)?n.getLiteralText():void 0},j=e=>r.isIdentifier(e)&&e.getText()==="ctx",M=e=>(t,s,n)=>{if(r.isStringLiteral(t)||r.isNoSubstitutionTemplateLiteral(t))return t.getLiteralValue();throw S(t,`${e} "${s}": \`${n}\` must be a static string literal — it is deploy configuration codegen writes into wrangler.jsonc`)};export{P as a,v as b,$ as c,_ as d,D as e,T as f,K as g,I as h,l as i,j,f as l,z as p,C as r,M as s,R as t,V as u};
@@ -0,0 +1,3 @@
1
+ import{G as S}from"./emit-s6mHBmXu.mjs";import{s as p}from"./paths-C-9fwEgQ.mjs";import{LUNORA_ERROR_CODES as O,objectSchema as h,validatorIrToJsonSchema as u}from"./LUNORA_ERROR_CODES-BYg8Lpgb.mjs";const E="/_lunora/rest",A=["authorization","cf-access-jwt-assertion","cookie","x-payment"],f=["x-d1-bookmark","x-lunora-shard-key"],P=e=>[...A,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],g=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,y=(...e)=>{const t=[];for(const r of e)for(const o of r?.split(",")??[]){const s=o.trim().toLowerCase();s!==""&&!t.includes(s)&&t.push(s)}return t.length===0?void 0:t.join(", ")},T=(e,t)=>{const r=[t,`max-age=${String(g(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(g(e.staleWhileRevalidate))}`),r.join(", ")},b=e=>e.scope==="public"?y(e.vary,...P(e),...f):y(e.vary,...f),x=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},N=e=>{const t=x(e);if(t!==void 0)return`${E}/${t.namespace}/${t.name}`},k=e=>e==="query"?"GET":"POST",m="#/components/responses/LunoraError",v=/:([A-Za-z_$][\w$]*)/gu,q=e=>[...e.matchAll(v)].map(t=>t[1]),_=e=>e.replaceAll(v,"{$1}"),l=e=>e.kind==="optional"?e.inner??e:e,j=e=>{const t=new Set(q(e.path)),r=[];for(const[o,s]of Object.entries(e.searchParams)){const c=l(s);r.push({description:`Query parameter \`${o}\``,in:"query",name:o,required:s.kind!=="optional",schema:u(c)})}for(const[o,s]of Object.entries(e.params)){const c=l(s);r.push({description:`Path parameter \`${o}\``,in:t.has(o)?"path":"query",name:o,required:t.has(o)?!0:s.kind!=="optional",schema:u(c)})}return r},$=e=>e?{content:{"application/json":{schema:u(e)}},description:"Successful response."}:{content:{"application/json":{schema:{description:"Return shape is TS-inferred (no `.output()` declared); best-effort — any JSON."}}},description:"Successful response. The return shape is TypeScript-inferred and not declared via `.output()`, so it is documented best-effort."},C=e=>{const t=p(e.filePath),r=j(e),o={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${p(e.path)}`,responses:{200:$(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:m}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(o.parameters=r),Object.keys(e.body).length>0&&(o.requestBody={content:{"application/json":{schema:h(e.body)}},required:!0}),e.stream&&(o["x-lunora-stream"]="text/event-stream"),o},w=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o={additionalProperties:!1,properties:{args:h(e.args),functionPath:{const:r,type:"string"},shardKey:{description:"Optional shard key; omitted routes to the default shard.",type:"string"}},required:["functionPath"],type:"object"};return{operation:{description:`Invoke the \`${e.kind}\` \`${r}\` over the Lunora RPC envelope (POST /_lunora/rpc).`,operationId:r,requestBody:{content:{"application/json":{schema:o}},required:!0},responses:{200:$(e.output),default:{$ref:m}},summary:`${e.kind}: ${r}`,tags:[t],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${r}`}},D=(e,t)=>{if(e===void 0||t!=="get"||e.scope===void 0||e.maxAge===void 0)return{};const r={maxAge:e.maxAge,scope:e.scope,...e.staleWhileRevalidate===void 0?{}:{staleWhileRevalidate:e.staleWhileRevalidate},...e.tag===void 0?{}:{tag:e.tag},...e.vary===void 0?{}:{vary:e.vary}},o={"Cache-Control":{description:r.scope==="public"?"Caching policy. `public` applies only to an uncredentialed request — a request carrying `Authorization` or `Cookie` is always answered `private`.":"Caching policy. Restricted to the caller's own cache; never stored by a shared/edge cache.",schema:{example:T(r,r.scope),type:"string"}}};r.tag!==void 0&&(o["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const s=b(r);return s!==void 0&&(o.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:s,type:"string"}}),{headers:o}},L=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o=N(r);if(o===void 0)return;const s=k(e.kind),c=s==="GET",d={description:`Public REST endpoint for the \`${e.kind}\` \`${r}\` (opt-in via \`.expose({ rest: true })\`). Routed through the procedure, so auth / RLS / validators are enforced.`,operationId:`rest_${p(o)}`,responses:{200:{content:{"application/json":{schema:{description:"Procedure result. The shape is TS-inferred from the return type; best-effort — any JSON."}}},description:"Successful result (TypeScript-inferred return shape, documented best-effort).",...D(e.expose?.cache,c?"get":"post")},default:{$ref:m}},summary:`${s} ${o}`,tags:[t],"x-lunora-function-kind":e.kind};if(c){const n=Object.entries(e.args).map(([a,i])=>{const R=l(i);return{description:`Argument \`${a}\` (JSON-encoded for non-string values).`,in:"query",name:a,required:i.kind!=="optional",schema:u(R)}});return n.length>0&&(d.parameters=n),{method:"get",operation:d,path:o}}return d.requestBody={content:{"application/json":{schema:h(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:d,path:o}},I=e=>{const t=e.version??"0.0.0",r={},o=new Set;for(const n of e.httpRoutes){const a=_(n.path),i=r[a]??{};i[n.method.toLowerCase()]=C(n),r[a]=i,o.add(p(n.filePath))}const s=e.functions.filter(n=>n.visibility!=="internal"&&n.kind!=="stream");for(const n of s){const{operation:a,pathKey:i}=w(n);r[i]={post:a},o.add(p(n.filePath))}for(const n of s){if(n.expose?.rest!==!0)continue;const a=L(n);if(a===void 0)continue;const i=r[a.path]??{};i[a.method]=a.operation,r[a.path]=i}const c=[...o].toSorted((n,a)=>n.localeCompare(a)).map(n=>({description:`Operations declared in \`lunora/${n}\`.`,name:n}));return{components:{responses:{LunoraError:{content:{"application/json":{schema:{additionalProperties:!1,description:"Standard Lunora error envelope.",properties:{error:{additionalProperties:!1,properties:{code:{description:"Machine-readable error code. Clients switch on this value.",enum:O,type:"string"},message:{description:"Human-readable error message (never echoes internal details).",type:"string"}},required:["code","message"],type:"object"}},required:["error"],type:"object"}}},description:"A Lunora error response. The HTTP status reflects the error code (e.g. BAD_REQUEST→400, UNAUTHORIZED→401, FORBIDDEN→403, NOT_FOUND→404)."}}},info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora API",version:t},openapi:"3.1.0",paths:r,tags:c}},J=e=>`${JSON.stringify(I(e),void 0,2)}
2
+ `,U=e=>`${S}export const openApiSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
3
+ `;export{I as buildOpenApiDocument,J as emitOpenApi,U as emitOpenApiModule};
@@ -0,0 +1 @@
1
+ import{w as a}from"./classify-procedure-call-AKeIK05y.mjs";const l=s=>a(s,"use","rls");export{l as r};
@@ -0,0 +1 @@
1
+ import{Node as o}from"ts-morph";import{b as a}from"./ast-CjWtsS6S.mjs";import{a as u}from"./module-specifiers-WF8iAydP.mjs";const T=t=>o.isIdentifier(t)?t.getText():o.isPropertyAccessExpression(t)?t.getName():void 0,y=(t,i)=>{const e=new Set;for(const r of t.getImportDeclarations())if(u(r.getModuleSpecifierValue()))for(const n of r.getNamedImports())n.getNameNode().getText()===i&&e.add(n.getAliasNode()?.getText()??n.getName());return e},x=(t,i)=>{if(o.isPropertyAccessExpression(t))return t.getName()===i;if(!o.isIdentifier(t))return!1;const e=t.getText();return e===i||y(t.getSourceFile(),i).has(e)},d=t=>{const i=t.getSymbol();if(!i)return t.getText();for(const e of i.getDeclarations())if(o.isImportSpecifier(e))return u(e.getImportDeclaration().getModuleSpecifierValue())?e.getNameNode().getText():void 0},p=t=>{const i=[];let e=a(t);for(;e&&o.isCallExpression(e);){const r=a(e.getExpression());if(!r||!o.isPropertyAccessExpression(r))return{root:void 0,steps:i};i.push({call:e,name:r.getName()}),e=a(r.getExpression())}return{root:e,steps:i}},f=t=>p(t).steps,N=(t,i,e)=>f(t).filter(r=>r.name===i).map(r=>r.call.getArguments()[0]).filter(r=>r!==void 0&&o.isCallExpression(r)&&x(r.getExpression(),e)),A=(t,i)=>f(t).some(e=>e.name===i),w=(t,i,e)=>N(t,i,e).length>0,l=new Set(["action","mutation","query","stream"]),m={internalAction:"action",internalMutation:"mutation",internalQuery:"query"},I={onConnect:"connect",onDisconnect:"disconnect",onQueryChange:"reactor",onShardInit:"init"},b=t=>{const{root:i}=p(t);return i&&o.isIdentifier(i)?i:void 0},g=(t,i=!1)=>{const e=b(t);if(!e)return;const r=d(e);if(r===void 0){if(i)return;const n=e.getSymbol()?.getValueDeclaration();if(n&&o.isVariableDeclaration(n)){const s=n.getInitializer();return s?g(s,!0):void 0}return}return l.has(r)?"public":m[r]?"internal":void 0},C=t=>{const i=t.getName();if(!l.has(i))return;const e=t.getExpression(),r=a(e)??e,n=e===r?[r]:[e,r];if(n.some(c=>c.getType().getProperty("__lunoraProcedure"))){const c=n.some(v=>v.getType().getProperty("__lunoraVisibility"));return{kind:i,receiver:r,visibility:c?"internal":"public"}}const s=g(r);if(s)return{kind:i,receiver:r,visibility:s}},P=t=>{const i=t.getExpression();if(o.isPropertyAccessExpression(i))return C(i);if(!o.isIdentifier(i))return;const e=d(i);if(!e)return;if(l.has(e))return{kind:e,visibility:"public"};const r=m[e];if(r)return{kind:r,visibility:"internal"};const n=I[e];if(n)return{kind:"mutation",lifecycle:n,visibility:"internal"}};export{T as a,f as b,P as c,w as d,A as e,N as w};
@@ -0,0 +1 @@
1
+ const o=r=>[...new Set(r)].toSorted((e,a)=>e.localeCompare(a)),s=r=>o(r.filter(e=>e.level==="ERROR").map(e=>e.name)),t=r=>o(r.filter(e=>e.level==="error").map(e=>e.name)),i=r=>({advisoryNames:s(r.advisories),platformDiagnosticNames:t(r.platformDiagnostics)});export{i as describeErrorLevelFindings,s as errorAdvisoryNames,t as errorPlatformDiagnosticNames};
@@ -0,0 +1 @@
1
+ import{SyntaxKind as p,Node as s}from"ts-morph";import{l as f,a as g,e as d}from"./ast-CjWtsS6S.mjs";const m=r=>{const t=r.getExpression();if(!s.isPropertyAccessExpression(t))return!1;const e=t.getExpression();return s.isPropertyAccessExpression(e)?e.getName()==="authApi":s.isIdentifier(e)&&e.getText()==="authApi"},h=r=>{const t=r.getArguments()[0];if(t===void 0)return!1;if(!s.isObjectLiteralExpression(t))return!0;for(const e of t.getProperties())if((s.isPropertyAssignment(e)||s.isShorthandPropertyAssignment(e))&&e.getName()==="headers"||s.isSpreadAssignment(e))return!0;return!1},P=(r,t)=>{const e=[];for(const n of f(t)){const c=r.getSourceFile(n)??r.addSourceFileAtPath(n),l=g(t,n);for(const i of c.getDescendantsOfKind(p.CallExpression)){if(!m(i))continue;const o=d(i);if(o==="")continue;const a=i.getExpression(),u=s.isPropertyAccessExpression(a)?a.getName():"";e.push({exportName:o,file:l,hasHeaders:h(i),line:i.getStartLineNumber(),method:u})}}return e};export{P as default};
@@ -0,0 +1 @@
1
+ import{LunoraError as L}from"@lunora/errors";import{CRON_SCHEDULE_KINDS as A,isValidCronExpression as O,warnIfSecondsLeading as S,compileCronSchedule as b}from"@lunora/scheduler";import{SyntaxKind as m,Node as s}from"ts-morph";import{diagnosticAt as f,CodegenDiagnosticError as I}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{i as R}from"./module-specifiers-WF8iAydP.mjs";import{s as $}from"./paths-C-9fwEgQ.mjs";import{l as y}from"./ast-CjWtsS6S.mjs";const P=new Set([...A,"cron"]),D=e=>{const t=e.getSymbol();if(!t)return e.getText()==="cronJobs";for(const r of t.getDeclarations())if(s.isImportSpecifier(r))return R(r.getImportDeclaration().getModuleSpecifierValue())?r.getNameNode().getText()==="cronJobs":!1;return!1},v=e=>{const t=new Set;for(const r of e.getVariableDeclarations()){const o=r.getInitializer();if(o?.getKind()!==m.CallExpression)continue;const i=o.getExpression();s.isIdentifier(i)&&D(i)&&t.add(r.getName())}return t},F=e=>{let t=e;for(;s.isCallExpression(t)||s.isPropertyAccessExpression(t);)t=t.getExpression();return s.isIdentifier(t)?t.getText():void 0},x=(e,t)=>{const r=e.getArguments()[t];return r&&(s.isStringLiteral(r)||s.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},_=(e,t)=>{if(s.isStringLiteral(e)||s.isNoSubstitutionTemplateLiteral(e)||s.isNumericLiteral(e))return e.getLiteralValue();if(s.isTrueLiteral(e))return!0;if(s.isFalseLiteral(e))return!1;if(s.isPrefixUnaryExpression(e)&&e.getOperatorToken()===m.MinusToken){const r=e.getOperand();if(s.isNumericLiteral(r))return-r.getLiteralValue()}if(s.isObjectLiteralExpression(e))return p(e,t);if(s.isArrayLiteralExpression(e))return e.getElements().map(r=>_(r,t));throw f(e,`Cron job "${t}" passes a non-static value where a literal is required; codegen can only read literals.`,{code:"CRON_NON_STATIC_VALUE",name:"LunoraError",status:500})},p=(e,t)=>{const r={};for(const o of e.getProperties()){if(!s.isPropertyAssignment(o))throw f(o,`Cron job "${t}" uses an unsupported object property (shorthand/spread/method) where a static literal is required.`,{code:"CRON_NON_STATIC_VALUE",name:"LunoraError",status:500});const i=o.getInitializer();i&&(r[o.getName()]=_(i,t))}return r},C=(e,t,r)=>{const o=e.getArguments()[t];if(!o||!s.isPropertyAccessExpression(o))throw f(e,`Cron job "${r}" must reference a function statically (e.g. internal.email.digest); codegen cannot resolve a dynamic reference.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500});const i=o.getName(),n=o.getExpression();if(!s.isPropertyAccessExpression(n))throw f(o,`Cron job "${r}" function reference must be of the form internal.file.fn (two property accesses).`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500});const a=n.getName();return`${$(a)}:${i}`},h=e=>({workflow:{binding:e.bindingName,exportName:e.exportName}}),w=e=>({workflow:{binding:e.bindingName,exportName:e.exportName}}),T=(e,t,r,o,i,n)=>{const a=e.getExpression();if(!s.isIdentifier(a)||a.getText()!==t)return;const c=r.get(e.getName());if(c)return n(c);throw f(e,`Cron job "${o}" targets ${t}.${e.getName()}, but no such ${i} is declared in lunora/${i}s.ts.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500})},V=(e,t,r,o,i)=>{const n=e.getArguments()[t];if(n&&s.isPropertyAccessExpression(n)){const a=T(n,"workflows",o,r,"workflow",h);if(a)return a;const c=T(n,"agents",i,r,"agent",w);return c||{functionPath:C(e,t,r)}}if(n&&s.isIdentifier(n)){const a=o.get(n.getText()),c=i.get(n.getText());if(a&&c)throw f(n,`Cron job "${r}" references "${n.getText()}", which is ambiguous: a workflow and an agent are both declared under that name.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500});if(a)return h(a);if(c)return w(c);throw f(n,`Cron job "${r}" references "${n.getText()}", which is neither a function (internal.file.fn / api.file.fn) nor a declared workflow in lunora/workflows.ts nor a declared agent in lunora/agents.ts.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500})}return{functionPath:C(e,t,r)}},j=/^@lunora\/scheduler:\s*/u,k=(e,t)=>{const r=x(e,1);if(r===void 0)throw f(e,`Cron job "${t}" must pass a string-literal cron expression to ".cron(...)".`,{code:"CRON_EXPR_NOT_STATIC",name:"LunoraError",status:500});if(!O(r))throw f(e,`Cron job "${t}" has an invalid cron expression "${r}" — expected 5 or 6 space-separated fields.`,{code:"CRON_EXPR_INVALID",name:"LunoraError",status:500});return S(r,`cron expression for job "${t}"`),r},U=(e,t,r)=>{const o=e.getArguments()[1];if(!o||!s.isObjectLiteralExpression(o))throw f(e,`Cron job "${r}" must pass an object-literal schedule to ".${t}(...)".`,{code:"CRON_SCHEDULE_NOT_STATIC",name:"LunoraError",status:500});try{return b(t,p(o,r),r)}catch(i){if(i instanceof I)throw i;const n=i instanceof Error?i.message.replace(j,""):String(i);throw f(e,n,{code:"CRON_SCHEDULE_INVALID",name:"LunoraError",status:500})}},M=(e,t,r,o,i)=>{const n=t.getName();if(!P.has(n)||!r.has(F(t.getExpression())??""))return;const a=x(e,0);if(a===void 0||a.trim()==="")throw f(e,`A cron ".${n}(...)" registration must pass a non-empty string-literal name as its first argument.`,{code:"CRON_NAME_NOT_STATIC",name:"LunoraError",status:500});const c=n==="cron"?k(e,a):U(e,n,a),u=V(e,2,a,o,i),l=e.getArguments()[3];return{args:l&&s.isObjectLiteralExpression(l)?p(l,a):{},cron:c,name:a,...u}},z=e=>{const t=new Set;for(const r of e){if(t.has(r.name))throw new L("DUPLICATE_CRON_NAME",`Duplicate cron job name "${r.name}": cron names must be unique across the project.`,{status:500});t.add(r.name)}},Q=(e,t,r=[],o=[])=>{const i=y(t),n=[],a=new Map(r.map(u=>[u.exportName,u])),c=new Map(o.map(u=>[u.exportName,u]));for(const u of i){const l=e.getSourceFile(u)??e.addSourceFileAtPath(u),g=v(l);if(g.size!==0)for(const d of l.getDescendantsOfKind(m.CallExpression)){const N=d.getExpression();if(!s.isPropertyAccessExpression(N))continue;const E=M(d,N,g,a,c);E&&n.push(E)}}return n.sort((u,l)=>u.name.localeCompare(l.name)),z(n),n};export{Q as default};
@@ -0,0 +1 @@
1
+ import{s as x}from"./paths-C-9fwEgQ.mjs";import{l as h,a as P}from"./ast-CjWtsS6S.mjs";import{b as f,c as E}from"./classify-procedure-call-AKeIK05y.mjs";import{Node as s,SyntaxKind as b}from"ts-morph";import{p as A,a as d}from"./parse-validator-BFTp87yz.mjs";import{u as v}from"./unwrap-handler-return-CmIWbykC.mjs";const N=i=>{const e=i.getArguments()[0];if(!e||!s.isObjectLiteralExpression(e))return"unknown";const t=e.getProperty("handler");if(!t||!s.isPropertyAssignment(t))return"unknown";const r=t.getInitializer();return!r||!(s.isArrowFunction(r)||s.isFunctionExpression(r))?"unknown":v(r)},F=i=>{const e=i.getArguments()[0];return!e||!(s.isArrowFunction(e)||s.isFunctionExpression(e))?"unknown":v(e)},z=i=>{let e={};for(const t of f(i)){if(t.name!=="input")continue;const r=t.call.getArguments()[0];r&&s.isObjectLiteralExpression(r)&&(e={...d(r),...e})}return e},C=i=>{const e=f(i).find(r=>r.name==="output");if(!e)return;const t=e.call.getArguments()[0];return t&&s.isExpression(t)?A(t):void 0},u=(i,e)=>{const t=i.getProperty(e);if(t===void 0||!s.isPropertyAssignment(t))return;const r=t.getInitializer();return r!==void 0&&s.isStringLiteral(r)?r.getLiteralValue():void 0},m=(i,e)=>{const t=i.getProperty(e);if(t===void 0||!s.isPropertyAssignment(t))return;const r=t.getInitializer();return r!==void 0&&s.isNumericLiteral(r)?r.getLiteralValue():void 0},O=i=>{const e=i.getProperty("cache");if(e===void 0||!s.isPropertyAssignment(e))return;const t=e.getInitializer();if(t===void 0||!s.isObjectLiteralExpression(t))return;const r=u(t,"scope"),n=m(t,"maxAge"),o=m(t,"staleWhileRevalidate"),a=u(t,"tag"),c=u(t,"vary"),g={...n===void 0?{}:{maxAge:n},...r==="private"||r==="public"?{scope:r}:{},...o===void 0?{}:{staleWhileRevalidate:o},...a===void 0?{}:{tag:a},...c===void 0?{}:{vary:c}};return Object.keys(g).length===0?void 0:g},S=i=>{if(i===void 0||!s.isObjectLiteralExpression(i))return{};const e=O(i),t=i.getProperty("rest");return t!==void 0&&s.isPropertyAssignment(t)?{...e===void 0?{}:{cache:e},rest:t.getInitializer()?.getText()==="true"}:e===void 0?{}:{cache:e}},L=i=>{const e=f(i).find(t=>t.name==="expose");return e?S(e.call.getArguments()[0]):void 0},I=i=>{const e=i.getArguments()[0];if(!e||!s.isObjectLiteralExpression(e))return{};const t=e.getProperty("args");if(!t||!s.isPropertyAssignment(t))return{};const r=t.getInitializer();return!r||!s.isObjectLiteralExpression(r)?{}:d(r)},T=8,l=(i,e=0)=>{if(e>T)return;if(s.isCallExpression(i))return i;if(s.isParenthesizedExpression(i)||s.isAsExpression(i)||s.isSatisfiesExpression(i)||s.isNonNullExpression(i))return l(i.getExpression(),e+1);if(!s.isIdentifier(i)&&!s.isPropertyAccessExpression(i))return;const t=i.getSymbol()?.getValueDeclaration();return t?p(t,e+1):void 0},p=(i,e)=>{if(s.isVariableDeclaration(i)||s.isPropertyAssignment(i)){const t=i.getInitializer();return t?l(t,e):void 0}if(s.isShorthandPropertyAssignment(i)){const t=i.getValueSymbol()?.getValueDeclaration();return t?p(t,e+1):void 0}if(s.isBindingElement(i)){const t=i.getPropertyNameNode()?.getText()??i.getName(),o=i.getFirstAncestorByKind(b.VariableDeclaration)?.getInitializer()?.getType().getProperty(t)?.getValueDeclaration();return o?p(o,e+1):void 0}},k=i=>{const e=i.getNameNode();if(s.isObjectBindingPattern(e)){const n=[];for(const o of e.getElements()){const a=l(o.getNameNode());a&&n.push([o.getName(),a])}return n}const t=i.getInitializer(),r=t&&(s.isCallExpression(t)?t:l(t));return r?[[i.getName(),r]]:[]},V=i=>{const e=E(i);if(e){if(e.receiver){const t=L(e.receiver),r=C(e.receiver);return{args:z(e.receiver),...t?{expose:t}:{},kind:e.kind,...r?{output:r}:{},returnType:F(i),visibility:e.visibility}}return e.lifecycle?{args:{},kind:e.kind,lifecycle:e.lifecycle,returnType:"void",visibility:e.visibility}:{args:I(i),kind:e.kind,returnType:N(i),visibility:e.visibility}}},y=(i,e,t)=>{const r=V(i);if(r)return{args:r.args,exportName:e,filePath:t,kind:r.kind,returnType:r.returnType,...r.output?{output:r.output}:{},visibility:r.visibility,...r.expose?{expose:r.expose}:{},...r.lifecycle?{lifecycle:r.lifecycle}:{}}},w=(i,e)=>{const t=[];for(const r of i.getExportAssignments()){if(r.isExportEquals())continue;const n=l(r.getExpression()),o=n?y(n,"default",e):void 0;o&&t.push(o)}return t},D=(i,e)=>{const t=[];for(const r of i.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations())for(const[o,a]of k(n)){const c=y(a,o,e);c&&t.push(c)}return t.push(...w(i,e)),t},j=i=>{const e=new Map;for(const t of i){const r=x(t.filePath),n=e.get(r);if(n&&n!==t.filePath)throw Object.assign(new Error(`Namespace collision: "${n}" and "${t.filePath}" both resolve to "${r}". Rename one of the files so the JS-identifier-sanitized names differ. (note: case-insensitive filesystems may also cause this — \`foo\` and \`FOO\` map to the same identifier)`),{code:"NAMESPACE_COLLISION",name:"LunoraError",paths:[n,t.filePath],status:500});e.set(r,t.filePath)}},K=(i,e)=>{const t=h(e),r=[];for(const n of t){const o=i.getSourceFile(n)??i.addSourceFileAtPath(n),a=P(e,n);r.push(...D(o,a))}return r.sort((n,o)=>`${n.filePath}:${n.exportName}`.localeCompare(`${o.filePath}:${o.exportName}`)),j(r),r};export{K as default};
@@ -0,0 +1 @@
1
+ import{Node as a}from"ts-morph";import{p as l,a as m}from"./parse-validator-BFTp87yz.mjs";import{l as d,a as h}from"./ast-CjWtsS6S.mjs";import{u as f}from"./unwrap-handler-return-CmIWbykC.mjs";const u=new Set(["delete","get","head","options","patch","post","put"]),g=new Set(["body","params","searchParams"]),E=new Set(["handler","stream"]),v=r=>{const e=r.getArguments()[0];if(e&&a.isStringLiteral(e))return e.getLiteralValue()},x=r=>{const e=r.getArguments()[0];return e&&a.isObjectLiteralExpression(e)?m(e):{}},P=r=>{if(!a.isCallExpression(r))return;const e=r.getExpression();if(!a.isPropertyAccessExpression(e))return;const o=e.getName();if(!u.has(o))return;const n=e.getExpression();if(!a.isIdentifier(n)||n.getText()!=="httpRoute")return;const s=v(r);return s===void 0?void 0:{method:o.toUpperCase(),path:s}},S=(r,e)=>{const o={body:{},params:{},searchParams:{},stream:e==="stream"},n=r.getExpression();if(!a.isPropertyAccessExpression(n))return;let s=n.getExpression();for(;a.isCallExpression(s);){const i=s.getExpression();if(!a.isPropertyAccessExpression(i))break;const c=i.getName();if(u.has(c))break;if(g.has(c)){const p=x(s);o[c]={...p,...o[c]}}else if(c==="output"&&o.output===void 0){const p=s.getArguments()[0];p&&a.isExpression(p)&&(o.output=l(p))}s=i.getExpression()}const t=P(s);if(t)return o.method=t.method,o.path=t.path,o},A=r=>{const e=r.getArguments()[0];return!e||!(a.isArrowFunction(e)||a.isFunctionExpression(e))?"unknown":f(e)},T=(r,e,o,n)=>{const s=e.getName();if(!E.has(s))return;const t=S(r,s);if(!(t?.method===void 0||t.path===void 0))return{body:t.body,exportName:o,filePath:n,method:t.method,params:t.params,path:t.path,searchParams:t.searchParams,stream:t.stream,...t.stream?{chunkType:A(r)}:{},...t.output?{output:t.output}:{}}},b=(r,e)=>{const o=[];for(const n of r.getVariableStatements())if(n.isExported())for(const s of n.getDeclarations()){const t=s.getInitializer();if(!t||!a.isCallExpression(t))continue;const i=t.getExpression();if(!a.isPropertyAccessExpression(i))continue;const c=T(t,i,s.getName(),e);c&&o.push(c)}return o},F=(r,e)=>{const o=d(e),n=[];for(const s of o){const t=r.getSourceFile(s)??r.addSourceFileAtPath(s),i=h(e,s);n.push(...b(t,i))}return n.sort((s,t)=>`${s.method} ${s.path}`.localeCompare(`${t.method} ${t.path}`)||s.filePath.localeCompare(t.filePath)),n};export{F as default};
@@ -0,0 +1 @@
1
+ import{SyntaxKind as c,Node as n}from"ts-morph";import{l as f,a as u,e as g,i as d}from"./ast-CjWtsS6S.mjs";const m=t=>{const e=t.getExpression();if(!n.isPropertyAccessExpression(e)||e.getName()!=="insert")return!1;const r=e.getExpression();return d(r)},p=t=>{if(!n.isIdentifier(t))return;const e=t.getSymbol(),r=e?.getAliasedSymbol()?.getDeclarations()??e?.getDeclarations()??[];for(const s of r)if(n.isVariableDeclaration(s)){const i=s.getInitializer();if(i&&n.isStringLiteral(i))return i.getLiteralText()}},x=t=>{const e=t.getArguments()[0];return e?n.isStringLiteral(e)?e.getLiteralText():p(e)??"":""},v=(t,e)=>{const r=[];for(const s of f(e)){const i=t.getSourceFile(s)??t.addSourceFileAtPath(s),l=u(e,s);for(const o of i.getDescendantsOfKind(c.CallExpression)){if(!m(o))continue;const a=g(o);a!==""&&r.push({exportName:a,file:l,line:o.getStartLineNumber(),table:x(o)})}}return r};export{v as default};
@@ -0,0 +1 @@
1
+ import"./ast-CjWtsS6S.mjs";import"./classify-procedure-call-AKeIK05y.mjs";import{d as p}from"./index-CCDlo9L7.mjs";export{p as default};
@@ -0,0 +1 @@
1
+ import{SyntaxKind as f,Node as a}from"ts-morph";import{diagnosticAt as u}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as m}from"./module-specifiers-WF8iAydP.mjs";import{l as p,a as h}from"./ast-CjWtsS6S.mjs";const I=r=>{const i=r.getSymbol();if(!i)return r.getText()==="defineMigration";for(const t of i.getDeclarations())if(a.isImportSpecifier(t))return m(t.getImportDeclaration().getModuleSpecifierValue())?t.getNameNode().getText()==="defineMigration":!1;return!1},d=(r,i)=>{const t=r.getProperty(i);if(!t||!a.isPropertyAssignment(t))return;const e=t.getInitializer();return e&&a.isStringLiteral(e)?e.getLiteralValue():void 0},P=(r,i)=>{const t=r.getInitializer();if(t?.getKind()!==f.CallExpression)return;const e=t.getExpression();if(!a.isIdentifier(e)||!I(e))return;const o=t.getArguments()[0];if(!o||!a.isObjectLiteralExpression(o))return;const n=d(o,"id"),s=r.getName();if(n===void 0||n.trim()==="")throw u(o,`Migration "${s}" in "${i}" must declare \`id\` as a non-empty string literal so codegen can key the registry.`,{code:"MIGRATION_ID_NOT_STATIC",name:"LunoraError",status:500});return{exportName:s,filePath:i,id:n,table:d(o,"table")??""}},M=r=>{const i=new Map;for(const t of r){const e=i.get(t.id);if(e!==void 0)throw Object.assign(new Error(`Duplicate migration id "${t.id}": declared in both "${e}" and "${t.filePath}". Migration ids must be unique across the project.`),{code:"DUPLICATE_MIGRATION_ID",id:t.id,name:"LunoraError",paths:[e,t.filePath],status:500});i.set(t.id,t.filePath)}},y=(r,i)=>{const t=p(i),e=[];for(const o of t){const n=r.getSourceFile(o)??r.addSourceFileAtPath(o),s=h(i,o);for(const c of n.getVariableStatements())if(c.isExported())for(const g of c.getDeclarations()){const l=P(g,s);l&&e.push(l)}}return e.sort((o,n)=>o.id.localeCompare(n.id)),M(e),e};export{y as default};
@@ -0,0 +1 @@
1
+ import{Node as s,SyntaxKind as a}from"ts-morph";import{l,a as c,h as d}from"./ast-CjWtsS6S.mjs";import{c as f}from"./classify-procedure-call-AKeIK05y.mjs";const u={"crypto.getRandomValues":"crypto.getRandomValues","crypto.randomUUID":"crypto.randomUUID","Date.now":"Date.now","Math.random":"Math.random"},m=new Set(["globalThis","self"]),g=new Set(["globalThis","self","window"]),p=e=>{if(s.isIdentifier(e))return e.getText();if(s.isPropertyAccessExpression(e)){const t=e.getExpression();if(s.isIdentifier(t)&&g.has(t.getText()))return e.getName()}},h=e=>{const t=e.getExpression();if(s.isIdentifier(t)){const o=t.getText();return o==="fetch"||o==="Date"?o:void 0}if(!s.isPropertyAccessExpression(t))return;const n=t.getName(),i=p(t.getExpression());if(i!==void 0)return n==="fetch"&&m.has(i)?"fetch":u[`${i}.${n}`]},x=e=>{const t=e.getExpression();if(!s.isIdentifier(t)||t.getText()!=="Date")return;const n=e.getArguments(),i=n.every(o=>s.isNumericLiteral(o)||s.isStringLiteral(o)||s.isNoSubstitutionTemplateLiteral(o));return n.length>0&&i?void 0:"new Date"},N=e=>{const t=e.getInitializer();if(!t||!s.isCallExpression(t))return;const n=f(t);if(!n||n.kind!=="query"&&n.kind!=="mutation")return;const i=d(t,n.receiver);return i?{exportName:e.getName(),handler:i,kind:n.kind}:void 0},E=(e,t)=>{const n=[];for(const i of e.handler.getDescendantsOfKind(a.CallExpression)){const o=h(i);o!==void 0&&n.push({callee:o,exportName:e.exportName,file:t,kind:e.kind,line:i.getStartLineNumber()})}for(const i of e.handler.getDescendantsOfKind(a.NewExpression)){const o=x(i);o!==void 0&&n.push({callee:o,exportName:e.exportName,file:t,kind:e.kind,line:i.getStartLineNumber()})}return n},S=(e,t)=>{const n=[];for(const i of e.getVariableStatements())if(i.isExported())for(const o of i.getDeclarations()){const r=N(o);r&&n.push(...E(r,t))}return n},w=(e,t)=>{const n=[];for(const i of l(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...S(o,c(t,i)))}return n};export{w as default};
@@ -0,0 +1 @@
1
+ import{d as a}from"./queries-B_xEHIeL.mjs";import"./ast-CjWtsS6S.mjs";export{a as default};
@@ -0,0 +1 @@
1
+ import{Node as o,SyntaxKind as a}from"ts-morph";import{l as c,a as l,h as d}from"./ast-CjWtsS6S.mjs";import{c as f}from"./classify-procedure-call-AKeIK05y.mjs";const u=t=>{const r=t.getInitializer();if(!r||!o.isCallExpression(r))return;const e=f(r);if(!e||e.kind!=="query"&&e.kind!=="mutation")return;const s=d(r,e.receiver);return s?{exportName:t.getName(),handler:s,kind:e.kind}:void 0},p=t=>{if(!o.isPropertyAccessExpression(t)||t.getName()!=="r2sql")return;const r=t.getExpression();if(!o.isIdentifier(r)||r.getText()!=="ctx")return;const e=t.getParent();return e&&o.isPropertyAccessExpression(e)&&e.getExpression()===t?`ctx.r2sql.${e.getName()}`:"ctx.r2sql"},x=(t,r)=>{const e=[];for(const s of t.handler.getDescendantsOfKind(a.PropertyAccessExpression)){const n=p(s);n!==void 0&&e.push({callee:n,exportName:t.exportName,file:r,kind:t.kind,line:s.getStartLineNumber()})}return e},m=(t,r)=>{const e=[];for(const s of t.getVariableStatements())if(s.isExported())for(const n of s.getDeclarations()){const i=u(n);i&&e.push(...x(i,r))}return e},P=(t,r)=>{const e=[];for(const s of c(r)){const n=t.getSourceFile(s)??t.addSourceFileAtPath(s);e.push(...m(n,l(r,s)))}return e};export{P as default};