@lunora/codegen 1.0.0-alpha.26 → 1.0.0-alpha.260
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +6 -0
- package/README.md +1 -1
- package/dist/index.d.mts +3851 -1254
- package/dist/index.d.ts +3851 -1254
- package/dist/index.mjs +1 -34
- package/dist/packem_shared/AGENTS_FILENAME-UhIaG4BZ.mjs +1 -0
- package/dist/packem_shared/CAPABILITY_PROBES-DFsutD7g.mjs +25 -0
- package/dist/packem_shared/CONTAINERS_FILENAME-DhUL5rDc.mjs +1 -0
- package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
- package/dist/packem_shared/DEFAULT_TARGET-7sHexLjO.mjs +1 -0
- package/dist/packem_shared/FLAGS_FILENAME-BINQ51Zq.mjs +1 -0
- package/dist/packem_shared/GENERATED_HEADER-dFyrHgQ0.mjs +1 -0
- package/dist/packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs +1 -0
- package/dist/packem_shared/MUTATORS_FILENAME-D1Q6EUII.mjs +1 -0
- package/dist/packem_shared/NOTIFY_FILENAME-bbHHFQ_t.mjs +1 -0
- package/dist/packem_shared/OPENRPC_VERSION-CGu1_YK7.mjs +3 -0
- package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs +1 -0
- package/dist/packem_shared/QUEUES_FILENAME-CSLmXUQA.mjs +1 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-BVhRHIbS.mjs +11 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs +2 -0
- package/dist/packem_shared/SDK_LANGUAGES-Df_CnJx5.mjs +372 -0
- package/dist/packem_shared/SHAPES_FILENAME-DuR5hLW1.mjs +1 -0
- package/dist/packem_shared/SchemaSnapshotParseError-CPOXlFhI.mjs +18 -0
- package/dist/packem_shared/WORKFLOWS_FILENAME-IqUyMQgM.mjs +1 -0
- package/dist/packem_shared/attribution-sW_DHmLO.mjs +1 -0
- package/dist/packem_shared/buildOpenApiDocument-DOsv1HEF.mjs +3 -0
- package/dist/packem_shared/capabilitiesUsedBy-CzqyN9dX.mjs +1 -0
- package/dist/packem_shared/chain-BTbLDrrU.mjs +1 -0
- package/dist/packem_shared/classify-procedure-call-OnJoKgqu.mjs +1 -0
- package/dist/packem_shared/context-property-calls-BEBjylgc.mjs +1 -0
- package/dist/packem_shared/context-root-KWXRWlv6.mjs +1 -0
- package/dist/packem_shared/database-calls-rLPCL3-U.mjs +1 -0
- package/dist/packem_shared/declared-output-Iaar469J.mjs +1 -0
- package/dist/packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs +1 -0
- package/dist/packem_shared/discoverAuthApiCalls-CNj9-Jch.mjs +1 -0
- package/dist/packem_shared/discoverCrons-BqTY53L5.mjs +1 -0
- package/dist/packem_shared/discoverFunctions-DPH4drkg.mjs +1 -0
- package/dist/packem_shared/discoverHttpRoutes-MRFziTCb.mjs +1 -0
- package/dist/packem_shared/discoverHyperdriveCalls-BcVkR6nw.mjs +1 -0
- package/dist/packem_shared/discoverInserts-Duz40u-s.mjs +1 -0
- package/dist/packem_shared/discoverMaskProcedures-DYJhbHF3.mjs +1 -0
- package/dist/packem_shared/discoverMigrations-D2P2n7JE.mjs +1 -0
- package/dist/packem_shared/discoverNondeterministicCalls-Cxf6T2Oi.mjs +1 -0
- package/dist/packem_shared/discoverQueries-CWmNPVHm.mjs +1 -0
- package/dist/packem_shared/discoverR2sqlCalls-DnKwop5c.mjs +1 -0
- package/dist/packem_shared/discoverRlsMetadata-BXXEFXjf.mjs +1 -0
- package/dist/packem_shared/discoverRlsProcedures-Des596JU.mjs +1 -0
- package/dist/packem_shared/discoverSandboxUsage-Bjl8A_hj.mjs +1 -0
- package/dist/packem_shared/discoverSchema-Cd3iH6q5.mjs +1 -0
- package/dist/packem_shared/discoverStorageRulesMetadata-DGFonj0I.mjs +1 -0
- package/dist/packem_shared/emitAgents-Dotqck8w.mjs +1 -0
- package/dist/packem_shared/emitApi-xDIHPRPH.mjs +154 -0
- package/dist/packem_shared/emitApp-RNU41dtm.mjs +860 -0
- package/dist/packem_shared/emitCrons-DsXsg1uG.mjs +83 -0
- package/dist/packem_shared/emitDataModel-DSk9AkJe.mjs +113 -0
- package/dist/packem_shared/emitDrizzleSchema-DohtnI8c.mjs +15 -0
- package/dist/packem_shared/emitFunctions-evl8Mx1a.mjs +249 -0
- package/dist/packem_shared/emitServer-DymRagL2.mjs +368 -0
- package/dist/packem_shared/emitShard-DHMYSP4m.mjs +1 -0
- package/dist/packem_shared/exported-procedure-chains-58yS9zc8.mjs +1 -0
- package/dist/packem_shared/fingerprintSchemaSources-BzFVnBfa.mjs +1 -0
- package/dist/packem_shared/formatAdvisories-DwmUKYuc.mjs +2 -0
- package/dist/packem_shared/handler-reference-C1oBljnl.mjs +1 -0
- package/dist/packem_shared/index-BusOvbeQ.mjs +1 -0
- package/dist/packem_shared/ir-DBSvhNa-.mjs +1 -0
- package/dist/packem_shared/isD1GlobalTable-udvHAAzD.mjs +1 -0
- package/dist/packem_shared/isTypedSchema-CKzc3ioR.mjs +4 -0
- package/dist/packem_shared/json-data-Chfs2Cz5.mjs +1 -0
- package/dist/packem_shared/listLunoraSourceFiles-DRes9d5p.mjs +1 -0
- package/dist/packem_shared/loadProjectConfig-CuGQsqYS.mjs +1 -0
- package/dist/packem_shared/module-specifiers-WF8iAydP.mjs +1 -0
- package/dist/packem_shared/modules-CsA-QVJ6.mjs +1 -0
- package/dist/packem_shared/parse-validator-B4mFs19C.mjs +1 -0
- package/dist/packem_shared/paths-C-9fwEgQ.mjs +1 -0
- package/dist/packem_shared/qualifiers-Cw8dEDbh.mjs +1 -0
- package/dist/packem_shared/readPackageDependencies-C6h6FZuP.mjs +1 -0
- package/dist/packem_shared/readServiceBindings-CnvEGOir.mjs +1 -0
- package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
- package/dist/packem_shared/reserved-words-CW1QFbTd.mjs +1 -0
- package/dist/packem_shared/schemaFromIr-BWFnvCVg.mjs +1 -0
- package/dist/packem_shared/shard-WXSIZRpD.mjs +1438 -0
- package/dist/packem_shared/shard-runtime-B1nU9CRa.mjs +321 -0
- package/dist/packem_shared/shared-BXUKWh7t.mjs +9 -0
- package/dist/packem_shared/unwrap-handler-return-D7E2TKkS.mjs +1 -0
- package/package.json +16 -7
- package/dist/packem_shared/CONTAINERS_FILENAME-DlP6YM_Q.mjs +0 -224
- package/dist/packem_shared/CodegenDiagnosticError-DeblMkzO.mjs +0 -23
- package/dist/packem_shared/FLAGS_FILENAME-B1vE0LIo.mjs +0 -139
- package/dist/packem_shared/GENERATED_HEADER-CYaSI_qY.mjs +0 -3268
- package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
- package/dist/packem_shared/LUNORA_SOLUTION_RULES-BTejmZp-.mjs +0 -131
- package/dist/packem_shared/MUTATORS_FILENAME-BhqdPtKp.mjs +0 -81
- package/dist/packem_shared/OPENRPC_VERSION-CRe5l79E.mjs +0 -60
- package/dist/packem_shared/QUEUES_FILENAME-B5_eWCRe.mjs +0 -119
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-cgOjZTVY.mjs +0 -1137
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-wWGP2_5E.mjs +0 -245
- package/dist/packem_shared/SHAPES_FILENAME-ChV7MqgE.mjs +0 -94
- package/dist/packem_shared/WORKFLOWS_FILENAME-CCisG0Vy.mjs +0 -124
- package/dist/packem_shared/buildOpenApiDocument-BlpXQe2K.mjs +0 -183
- package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
- package/dist/packem_shared/discoverAuthApiCalls-CoirYbg6.mjs +0 -62
- package/dist/packem_shared/discoverCrons-Cev7RRAf.mjs +0 -257
- package/dist/packem_shared/discoverFunctions-BWMczzBx.mjs +0 -465
- package/dist/packem_shared/discoverHttpRoutes-CfP6cMzt.mjs +0 -131
- package/dist/packem_shared/discoverInserts-C7zxXkUf.mjs +0 -61
- package/dist/packem_shared/discoverMaskProcedures-Cm81kwrb.mjs +0 -217
- package/dist/packem_shared/discoverMigrations-Bi5nJ0mJ.mjs +0 -97
- package/dist/packem_shared/discoverNondeterministicCalls-C4M8AXmQ.mjs +0 -122
- package/dist/packem_shared/discoverQueries-B0wGT-xe.mjs +0 -62
- package/dist/packem_shared/discoverR2sqlCalls-BVNMd428.mjs +0 -80
- package/dist/packem_shared/discoverRlsMetadata-BS9GOGC5.mjs +0 -280
- package/dist/packem_shared/discoverSchema-KYq55qu3.mjs +0 -864
- package/dist/packem_shared/discoverStorageRulesMetadata-Da8BKXcI.mjs +0 -97
- package/dist/packem_shared/emitApp-C38fHt_1.mjs +0 -675
- package/dist/packem_shared/formatAdvisories-DdjK7sgh.mjs +0 -81
- package/dist/packem_shared/parse-validator-Cabb60UV.mjs +0 -133
- package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
- package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const m=(e,t=2166136261)=>{let i=t;for(let o=0;o<e.length;o+=1)i^=e.charCodeAt(o),i=Math.imul(i,16777619);return(i>>>0).toString(16).padStart(8,"0")},S=e=>`${m(e,2166136261)}${m(e,16777619)}`,H=1;function w(e){const t={},i=Object.keys(e);i.sort();for(const o of i)t[o]=e[o];return t}const O=e=>`${JSON.stringify(e,void 0,2)}
|
|
2
|
+
`,P=e=>S(O(e)),c=e=>typeof e=="object"&&e!==null,x=e=>c(e)&&c(e.fields)&&c(e.indexes)&&c(e.relations)&&typeof e.shardMode=="string",J=e=>{if(e===void 0||e.trim()==="")return{status:"absent"};let t;try{t=JSON.parse(e)}catch(o){return{error:`baseline is not valid JSON: ${o instanceof Error?o.message:String(o)}`,status:"invalid"}}if(!c(t)||t.version!==1||!c(t.tables))return{error:`baseline is malformed or written by an incompatible version (expected version ${String(1)})`,status:"invalid"};for(const[o,r]of Object.entries(t.tables))if(!x(r))return{error:`baseline table "${o}" has an invalid structure`,status:"invalid"};return{snapshot:{jurisdiction:typeof t.jurisdiction=="string"?t.jurisdiction:void 0,migrationIds:Array.isArray(t.migrationIds)?t.migrationIds:[],tables:t.tables,version:1},status:"ok"}},F=(e,t)=>e.unique===t.unique&&e.fields.length===t.fields.length&&e.fields.every((i,o)=>i===t.fields[o]),y=e=>e.unique!==void 0,p=({nullable:e,optional:t,refined:i,unique:o,...r})=>JSON.stringify(w(r)),g=e=>({form:JSON.stringify([p(e),e.optional===!0,e.nullable===!0]),refined:e.refined===!0}),v=e=>e.kind==="union"&&e.members?e.members.map(t=>g(t)):[g({...e,nullable:!1,optional:!1})],T=(e,t)=>{if(t.kind!=="union")return!1;const i=v(t);return v(e).every(o=>i.some(r=>r.form===o.form&&(o.refined||!r.refined)))},a=e=>{switch(e.kind){case"array":return`array(${e.of?a(e.of):"?"})`;case"id":return`id(${e.ref??"?"})`;case"literal":return`literal(${e.literal??"?"})`;case"object":return`object({ ${Object.keys(e.fields??{}).join(", ")} })`;case"record":return`record(${e.key?a(e.key):"?"}, ${e.of?a(e.of):"?"})`;case"union":return(e.members??[]).map(t=>a(t)).join(" | ");default:return e.kind}},l=(e,t,i)=>({remediation:"backfill",scope:"table",severity:"breaking",summary:i,table:e,type:t}),f=(e,t,i)=>({remediation:"none",scope:"table",severity:"safe",summary:i,table:e,type:t}),_=(e,t,i,o,r)=>{if(!(i.kind===o.kind&&(!r||p(i)===p(o))))return r&&T(i,o)?f(e,"widenedFieldShape",`field ${e}.${t} widened: ${a(i)} → ${a(o)} — every stored value stays valid`):i.kind!==o.kind?l(e,"changedFieldKind",`field ${e}.${t} changed type: ${i.kind} → ${o.kind} — add a data migration to convert existing values`):l(e,"changedFieldShape",`field ${e}.${t} changed shape: ${a(i)} → ${a(o)} — stored values were written against the old shape; add a data migration to convert them`)},j=(e,t,i,o)=>{const r=[];return i.unique!==o.unique&&r.push(o.unique===!0?l(e,"addedFieldConstraint",`field ${e}.${t} became unique — existing duplicates would violate it; add a data migration to de-duplicate first`):f(e,"relaxedFieldConstraint",`field ${e}.${t} is no longer unique`)),i.nullable!==o.nullable&&r.push(o.nullable===!0?f(e,"relaxedFieldConstraint",`field ${e}.${t} became nullable`):l(e,"addedFieldConstraint",`field ${e}.${t} is no longer nullable — rows holding NULL would be invalid; add a data migration to backfill them`)),i.refined!==o.refined&&r.push(o.refined===!0?l(e,"addedFieldConstraint",`field ${e}.${t} gained a validation refinement — stored values were never checked against it; add a data migration if any could fail`):f(e,"relaxedFieldConstraint",`field ${e}.${t} dropped its validation refinement`)),r},q=(e,t,i,o)=>{const r=[],n=y(i)&&y(o),s=_(e,t,i,o,n);return s&&r.push(s),n&&r.push(...j(e,t,i,o)),i.optional&&!o.optional?r.push({remediation:"backfill",severity:"breaking",summary:`field ${e}.${t} became required — rows missing it would be invalid; add a data migration to backfill it`,table:e,scope:"table",type:"fieldOptionalToRequired"}):!i.optional&&o.optional&&r.push({remediation:"none",scope:"table",severity:"safe",summary:`field ${e}.${t} became optional`,table:e,type:"fieldRequiredToOptional"}),r},E=(e,t,i)=>i.optional?{remediation:"none",scope:"table",severity:"safe",summary:`added optional field ${e}.${t}`,table:e,type:"addedOptionalField"}:{remediation:"backfill",severity:"breaking",summary:`added required field ${e}.${t} — existing rows have no value; add a data migration to backfill it`,table:e,scope:"table",type:"addedRequiredField"},A=(e,t,i,o)=>{for(const[r,n]of Object.entries(i.fields)){const s=t.fields[r];s===void 0?o.push(E(e,r,n)):o.push(...q(e,r,s,n))}for(const r of Object.keys(t.fields))i.fields[r]===void 0&&o.push({remediation:"backfill",severity:"breaking",summary:`removed field ${e}.${r} — add a data migration if stored data must be cleaned up`,table:e,scope:"table",type:"removedField"})},M=(e,t,i,o)=>{for(const[r,n]of Object.entries(i.indexes)){const s=t.indexes[r];if(s===void 0){o.push(n.unique?{remediation:"backfill",scope:"table",severity:"breaking",summary:`added unique index ${r} on ${e} — existing duplicates would violate it; add a data migration to de-duplicate first`,table:e,type:"addedIndex"}:{remediation:"none",scope:"table",severity:"safe",summary:`added index ${r} on ${e}`,table:e,type:"addedIndex"});continue}F(s,n)||o.push({remediation:"code",severity:"breaking",summary:`index ${r} on ${e} changed shape — a query may have relied on the old index`,table:e,scope:"table",type:"changedIndex"})}for(const r of Object.keys(t.indexes))i.indexes[r]===void 0&&o.push({remediation:"code",severity:"breaking",summary:`removed index ${r} on ${e} — a query that used \`.withIndex("${r}")\` would break`,table:e,scope:"table",type:"removedIndex"})},C=(e,t,i,o)=>{for(const r of Object.keys(i.relations))t.relations[r]===void 0&&o.push({remediation:"none",scope:"schema",severity:"safe",summary:`added relation ${e}.${r}`,table:e,type:"addedRelation"});for(const r of Object.keys(t.relations))i.relations[r]===void 0&&o.push({remediation:"code",scope:"schema",severity:"breaking",summary:`removed relation ${e}.${r}`,table:e,type:"removedRelation"})},$="shardBy:_unknown_",u="global",I=(e,t)=>e===u&&t.startsWith(`${u}:`)||t===u&&e.startsWith(`${u}:`),R=(e,t,i)=>{if(t===i)return i!==$?void 0:{remediation:"rehome",scope:"table",severity:"breaking",summary:`table ${e} declares a non-literal .shardBy(...) key, so codegen cannot read which column partitions it — every such key records as "${$}" and two DIFFERENT keys would compare equal. Pass the shard key as a string literal; until then this is reported on every run, because the alternative is a silent pass on a re-home that strands every row (export/import is the only way back).`,table:e,type:"changedShardMode"};if(!I(t,i))return{remediation:"rehome",severity:"breaking",summary:`table ${e} changed shard mode: ${t} → ${i} — its physical storage moves, and existing rows do NOT follow the schema; re-home them with an export/import round trip (https://lunora.sh/docs/concepts/sharding#migrating-a-populated-table)`,table:e,scope:"table",type:"changedShardMode"}},b=e=>e.memory!==void 0,k=e=>e.after??0,d=e=>e.after===void 0?`.ttl("${e.field}")`:`.ttl("${e.field}", { after: ${String(e.after)} })`,V=(e,t,i)=>{if(t===void 0&&i===void 0)return;const o=h=>({remediation:"backfill",scope:"table",severity:"breaking",summary:h,table:e,type:"changedTtlPolicy"}),r=h=>({remediation:"none",scope:"table",severity:"safe",summary:h,table:e,type:"changedTtlPolicy"});if(i===void 0)return r(`table ${e} dropped its TTL policy — its rows are no longer swept`);if(t===void 0)return o(`table ${e} gained a TTL policy ${d(i)} — every row already past the cutoff is deleted on the next alarm sweep; add a data migration to refresh or clear "${i.field}" on the rows written before it`);if(t.field!==i.field)return o(`table ${e} moved its TTL to a different column: ${d(t)} → ${d(i)} — rows are now expired by a column they were never written against; add a data migration to populate "${i.field}"`);const n=k(t),s=k(i);return s<n?o(`table ${e} shortened its TTL: ${d(t)} → ${d(i)} — rows that were not expired under the old offset are deleted on the next alarm sweep; add a data migration to refresh "${i.field}" on the rows that must survive`):s>n?r(`table ${e} lengthened its TTL: ${d(t)} → ${d(i)}`):void 0},L=(e,t,i)=>{const o=[];return t.memory!==i.memory&&o.push(i.memory===!0?{remediation:"rehome",scope:"table",severity:"breaking",summary:`table ${e} became a .memory() table — every row is deleted in every shard on the next Durable Object cold start, and no data migration survives that; export the rows first if they must be kept, or revert`,table:e,type:"changedMemoryMode"}:{remediation:"none",scope:"table",severity:"safe",summary:`table ${e} is no longer a .memory() table — its rows now survive a cold start`,table:e,type:"changedMemoryMode"}),t.commitOrdered!==i.commitOrdered&&o.push(i.commitOrdered===!0?{remediation:"backfill",scope:"table",severity:"breaking",summary:`table ${e} became .commitOrdered() — rows written before it carry no _commitSeq, so a \`_commitSeq > cursor\` changefeed never offers them; add a data migration over the table to stamp them (the rewrite allocates a sequence)`,table:e,type:"changedCommitOrdering"}:{remediation:"code",scope:"table",severity:"breaking",summary:`table ${e} is no longer .commitOrdered() — new rows carry no _commitSeq, so a \`_commitSeq > cursor\` changefeed stops advancing without erroring; update the consumers before deploying`,table:e,type:"changedCommitOrdering"}),o},D=(e,t,i,o)=>{const r=R(e,t.shardMode,i.shardMode);if(r&&o.push(r),b(t)&&b(i)){o.push(...L(e,t,i));const n=V(e,t.ttl,i.ttl);n&&o.push(n)}A(e,t,i,o),M(e,t,i,o),C(e,t,i,o)},B=(e,t)=>{const i=[],o=e?.tables??{};for(const[r,n]of Object.entries(t.tables)){const s=o[r];if(s===void 0){i.push({remediation:"none",scope:"table",severity:"safe",summary:`added table ${r}`,table:r,type:"addedTable"});continue}D(r,s,n,i)}for(const r of Object.keys(o))t.tables[r]===void 0&&i.push({remediation:"rehome",scope:"table",severity:"breaking",summary:`removed table ${r} — its rows stay in each shard's SQLite, unreachable through the schema; export the shard first if the data must be kept`,table:r,type:"removedTable"});if(e!==void 0&&e.jurisdiction!==t.jurisdiction){const r=e.jurisdiction??"(none)",n=t.jurisdiction??"(none)";i.push({remediation:"rehome",scope:"schema",severity:"breaking",summary:`Durable Object jurisdiction changed from ${r} to ${n} — this re-homes every DO and strands all existing shard, scheduler, and session-DO data in the old region (no in-place migration; export then import to move it). Revert the change, or override the gate to proceed intentionally.`,type:"changedJurisdiction"})}return{changes:i}};export{H as SCHEMA_SNAPSHOT_VERSION,a as describeShape,q as diffExistingField,B as diffSchemaSnapshots,P as hashSchemaSnapshot,x as isValidTableSnapshot,J as parseSnapshotJson,O as serializeSchemaSnapshot,w as sortKeys};
|
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
import{modelSources as pe,assertDistinctMembers as T,toPascalCase as l,referencedModels as W,generatedHeaderLines as f,commentText as p,argsChoice as $,stringLiteral as m,kotlinLiteral as w,allMethods as x,toSnakeCase as E,parseSpec as Ne,assertGeneratable as Oe,withDeclaredModels as Ce,unrepresentableFunctions as Le,undeclaredModels as Re}from"./isTypedSchema-CKzc3ioR.mjs";import{isTypedSchema as St}from"./isTypedSchema-CKzc3ioR.mjs";const We=async(e,n)=>{if(n.quicktype===void 0)return"";const t=pe(e);if(t.length===0)return"";const{InputData:r,JSONSchemaInput:a,JSONSchemaStore:i,quicktype:o}=await import("quicktype-core");class s extends i{fetch(){return Promise.resolve(void 0)}}const d=new a(new s);for(const g of t)await d.addSource({name:g.name,schema:JSON.stringify(g.schema)});const c=new r;c.addInput(d);const{lines:u}=await o({inputData:c,lang:n.quicktype.lang,rendererOptions:n.quicktype.rendererOptions??{}});return u.join(`
|
|
2
|
+
`)},D=`${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
|
+
`,De=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"]),j=e=>{const n=l(e),t=n.charAt(0).toLowerCase()+n.slice(1);return De.has(t)?`${t}_`:t},de=e=>m(e).replaceAll("$",String.raw`\$`),Pe=e=>e.replaceAll(" == null ? [] : List<"," == null ? null : List<").replaceAll(/Map\.from\((?<source>[^()]*?)!\)/gu,"$<source> == null ? null : Map.from($<source>!)"),Z=" ".repeat(8),Ve=/^class (\w+) \{/u,Ke=/^class \w+ \{\n[\s\S]*?\n\}$/gmu,Ie=/^ {4}\w+\(\{\n([\s\S]*?)^ {4}\}\);$/mu,xe=/^ {8}(?:required )?this\.\w+,$/gmu,Fe=/^ {4}Map<String, dynamic> toJson\(\) => \{\n([\s\S]*?)^ {4}\};$/mu,qe=/^ {8}"(?:[^\\"]|\\.)*": .*,$/gmu,Ue=e=>e.replaceAll(Ke,n=>{const[,t]=Ie.exec(n)??[],[,r]=Fe.exec(n)??[];if(t===void 0||r===void 0)return n;const a=[...t.matchAll(xe)].map(d=>{const c=d[0].trim();return{field:c.slice(c.indexOf("this.")+5,-1),optional:!c.startsWith("required ")}}),i=[...r.matchAll(qe)],o=a.filter(d=>d.optional);if(a.length!==i.length){if(o.length===0)return n;throw new Error(`dart models: cannot place the optional-field guards in ${Ve.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 s=r;for(const[d,c]of i.entries()){const u=a[d];if(!u?.optional)continue;const g=c[0],ke=g.slice(Z.length).replace(`${u.field} == null ? null : `,"");s=s.replace(g,`${Z}if (${u.field} != null) ${ke}`)}return n.replace(r,s)}),$e=e=>$(e,{none:"null",typed:()=>"LunoraClient.wireValue(args)",untyped:"args"}),me={declaration:"LunoraOptimistic? optimistic, LunoraOptimisticUpdate? optimisticUpdate, bool Function()? precondition",forward:"optimistic: optimistic, optimisticUpdate: optimisticUpdate, precondition: precondition"},X=e=>{const n=e.verb==="mutation"?`{String? shardKey, ${me.declaration}}`:"{String? shardKey}";return $(e,{none:n,typed:t=>`${t} args, ${n}`,untyped:`Object? args, ${n}`})},ye=(e,n)=>`${e}.fromJson(${n} as Map<String, dynamic>)`,Q=e=>{const n=e.verb==="mutation"?`, ${me.forward}`:"",t=`_client.${e.verb}("${de(e.functionPath)}", args: ${$e(e)}, shardKey: shardKey${n})`;return e.resultType===void 0?[` /// ${p(e.summary)}`,` Future<Object?> ${j(e.functionName)}(${X(e)}) => ${t};`].join(`
|
|
25
|
+
`):[` /// ${p(e.summary)}`,` Future<${e.resultType}> ${j(e.functionName)}(${X(e)}) async =>`,` ${ye(e.resultType,`await ${t}`)};`].join(`
|
|
26
|
+
`)},He=e=>{const n=$(e,{none:"",typed:o=>`${o} args`,untyped:"Object? args"}),t=n===""?"":`${n}, `,r=$e(e),a=`"${de(e.functionPath)}"`,i=`_client.watch(${a}, args: ${r})`;return[` /// live ${p(e.summary)} — re-runs on every write to the tables it reads.`,` LunoraUnsubscribe subscribe${l(e.functionName)}(`,` ${t}{LunoraDataCallback? onData, LunoraErrorCallback? onError}`,` ) => _client.subscribe(${a}, args: ${r}, onData: onData, onError: onError);`,"",` /// live ${p(e.summary)}, as a Stream — bind it with StreamBuilder.`,e.resultType===void 0?` Stream<Object?> watch${l(e.functionName)}(${n}) => ${i};`:[` Stream<${e.resultType}> watch${l(e.functionName)}(${n}) =>`,` ${i}.map((raw) => ${ye(e.resultType,"raw")});`].join(`
|
|
27
|
+
`)].join(`
|
|
28
|
+
`)},Ge=e=>{const n=`${l(e.name)}Api`,t=e.methods.map(r=>r.verb==="query"?`${Q(r)}
|
|
29
|
+
|
|
30
|
+
${He(r)}`:Q(r)).join(`
|
|
31
|
+
|
|
32
|
+
`);return[`/// Functions declared in \`${p(e.name)}\`.`,`class ${n} {`,` const ${n}(this._client);`,""," final LunoraClient _client;","",t,"}"].join(`
|
|
33
|
+
`)},Be=(e,n)=>{const t=r=>{if(r===void 0)return;const a=`${r.charAt(0).toLowerCase()}${r.slice(1)}FromJson`;if(!new RegExp(String.raw`^\S+ ${a}\(String str\) =>`,"mu").test(n))throw new Error(`sdk: the dart models declare "${r}" but no top-level decoder "${a}" — quicktype's Dart naming has changed; update objectResultsOnly in targets/dart.ts.`);return new RegExp(String.raw`^${r} ${a}\(String str\) => ${r}\.fromJson\(`,"mu").test(n)?r:void 0};return e.map(r=>({methods:r.methods.map(a=>({...a,resultType:t(a.resultType)})),name:r.name}))},Je=({models:e,namespaces:n})=>{T(n,"Dart",s=>[j(s.functionName)]);const t=Be(n,e),r=t.map(s=>` final ${l(s.name)}Api ${j(s.name)};`).join(`
|
|
34
|
+
`),a=t.map(s=>` ${j(s.name)} = ${l(s.name)}Api(client)`).join(`,
|
|
35
|
+
`),i=W(t).length>0?`import 'models.dart';
|
|
36
|
+
`:"";return{"lib/lunora_api.dart":[D,`/// 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
|
+
`,i,`
|
|
45
|
+
`,t.map(s=>Ge(s)).join(`
|
|
46
|
+
|
|
47
|
+
`),t.length>0?`
|
|
48
|
+
|
|
49
|
+
`:"","/// Typed entry point: `Api(client).<namespace>.<function>(args)`.\n",`class Api {
|
|
50
|
+
`,t.length>0?` Api(LunoraClient client)
|
|
51
|
+
: ${a.trimStart()};
|
|
52
|
+
|
|
53
|
+
${r}
|
|
54
|
+
`:` const Api(LunoraClient client);
|
|
55
|
+
`,`}
|
|
56
|
+
`].join(""),"lib/models.dart":e.length>0?`${D}${Ue(Pe(e))}
|
|
57
|
+
`:`${D}// No typed argument or result schemas in this deployment.
|
|
58
|
+
`,"pubspec.yaml":Me}},Ye={id:"dart",quicktype:{lang:"dart"},render:Je,requires:[],vendor:[{from:"lib",to:"lib"}]},P=`${f("go").map(e=>`// ${e}`).join(`
|
|
59
|
+
`)}
|
|
60
|
+
|
|
61
|
+
`,b="lunoraapi",N="lunorasdk",ze=`${N}/lunora`,Ze="1.22",F=e=>l(e),ee=(e,n)=>{const t=$(n,{none:"",typed:s=>`args ${s}, `,untyped:"args any, "}),r=$(n,{none:"nil",typed:()=>"args",untyped:"args"}),a=n.resultType??"any",i=`lunora.Verb${n.verb.charAt(0).toUpperCase()}${n.verb.slice(1)}`,o=`lunora.Call[${a}](a.client, ${i}, "${m(n.functionPath)}", ${r}, shardKey)`;return[`// ${F(n.functionName)} invokes ${p(n.summary)}.`,`func (a *${e}) ${F(n.functionName)}(${t}shardKey string) (${a}, error) {`,` return ${o}`,"}"].join(`
|
|
62
|
+
`)},Xe=(e,n)=>{const t=$(n,{none:"",typed:i=>`args ${i}, `,untyped:"args any, "}),r=$(n,{none:"nil",typed:()=>"args",untyped:"args"}),a=`Subscribe${F(n.functionName)}`;return[`// ${a} opens a live ${p(n.functionPath)}; it re-runs on every write to the tables it reads.`,`func (a *${e}) ${a}(${t}onData lunora.DataHandler, onError lunora.ErrorHandler, shardKey string) lunora.Unsubscribe {`,` return a.client.Subscribe("${m(n.functionPath)}", ${r}, onData, onError, shardKey)`,"}"].join(`
|
|
63
|
+
`)},Qe=e=>{const n=`${l(e.name)}API`,t=e.methods.map(r=>r.verb==="query"?`${ee(n,r)}
|
|
64
|
+
|
|
65
|
+
${Xe(n,r)}`:ee(n,r)).join(`
|
|
66
|
+
|
|
67
|
+
`);return[`// ${n} groups the functions declared in ${p(e.name)}.`,`type ${n} struct{ client *lunora.Client }`,"",t].join(`
|
|
68
|
+
`)},en=e=>{const n=new Map;for(const a of e.matchAll(/^type (\w+) (struct \{\n[\s\S]*?^\}|.*)$/gmu))n.set(a[1],a[2]);const t=new Set([...n].filter(([,a])=>a.startsWith(`struct {
|
|
69
|
+
`)&&!a.includes("`")).map(([a])=>a));let r=!0;for(;r;){r=!1;for(const[a,i]of n)!t.has(a)&&[...t].some(o=>new RegExp(String.raw`\b${o}\b`,"u").test(i))&&(t.add(a),r=!0)}return t},nn=({models:e,namespaces:n})=>{const t=en(e),r=c=>c!==void 0&&t.has(c)?void 0:c,a=n.map(c=>({methods:c.methods.map(u=>({...u,argsType:r(u.argsType),resultType:r(u.resultType)})),name:c.name})),i=a.map(c=>` ${l(c.name)} *${l(c.name)}API`).join(`
|
|
70
|
+
`),o=a.map(c=>` ${l(c.name)}: &${l(c.name)}API{client: client},`).join(`
|
|
71
|
+
`),s=[P,`package ${b}
|
|
72
|
+
`,`
|
|
73
|
+
`,`import "${ze}"
|
|
74
|
+
`,`
|
|
75
|
+
`,`// API is the typed entry point: api.<Namespace>.<Function>(args, shardKey).
|
|
76
|
+
`,`type API struct {
|
|
77
|
+
`,`${i}
|
|
78
|
+
`,`}
|
|
79
|
+
`,`
|
|
80
|
+
`,`// NewAPI binds the generated surface to a client.
|
|
81
|
+
`,`func NewAPI(client *lunora.Client) *API {
|
|
82
|
+
`,` return &API{
|
|
83
|
+
`,`${o}
|
|
84
|
+
`,` }
|
|
85
|
+
`,`}
|
|
86
|
+
`,`
|
|
87
|
+
`,a.map(c=>Qe(c)).join(`
|
|
88
|
+
|
|
89
|
+
`),`
|
|
90
|
+
`].join(""),d=e.length>0?`${P}package ${b}
|
|
91
|
+
|
|
92
|
+
${e}
|
|
93
|
+
`:`${P}package ${b}
|
|
94
|
+
|
|
95
|
+
// No typed argument or result schemas in this deployment.
|
|
96
|
+
`;return{[`${b}/api.go`]:s,[`${b}/models.go`]:d,"go.mod":[`// The generated Lunora Go SDK, with the transport vendored under ./lunora.
|
|
97
|
+
`,`//
|
|
98
|
+
`,`// A consuming module wires it in without a network fetch:
|
|
99
|
+
`,`//
|
|
100
|
+
`,`// require ${N} v0.0.0
|
|
101
|
+
`,`// replace ${N} => ./path/to/this/directory
|
|
102
|
+
`,`module ${N}
|
|
103
|
+
`,`
|
|
104
|
+
`,`go ${Ze}
|
|
105
|
+
`].join("")}},tn={id:"go",quicktype:{lang:"go",rendererOptions:{"just-types":"true",package:b}},render:nn,requires:[],vendor:[{from:"lunora",to:"lunora"}]},h="lunoraapi.models",q="lunoraapi/models",rn=24,an=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"]),sn=/[^A-Za-z0-9]+/gu,on=/([a-z0-9])([A-Z])/gu,ln=/^[A-Za-z]/u,cn=/^[A-Z]/u;class fe extends Error{}const y=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,un=e=>{const n=e.anyOf??e.oneOf;if(!Array.isArray(n)||n.length===0)return;const t=n.map(r=>y(r)?.const);if(t.every(r=>typeof r=="string"))return[...new Set(t)].toSorted((r,a)=>r.localeCompare(a))},ge=e=>{const n=e.anyOf??e.oneOf;if(!Array.isArray(n)||n.length!==2)return e;const t=n.filter(r=>y(r)?.type!=="null");return t.length===1?y(t[0])??e:e},pn=e=>{const n=l(e),t=n.charAt(0).toLowerCase()+n.slice(1),r=ln.test(t)?t:`value${n}`;return an.has(r)?`${r}_`:r},dn=e=>{const n=e.replaceAll(on,"$1_$2").replaceAll(sn,"_").toUpperCase().split("_").filter(t=>t.length>0).join("_");return cn.test(n)?n:`VALUE_${n}`},be=(e,n)=>{if(!n.has(e))return n.add(e),e;let t=2;for(;n.has(`${e}${String(t)}`);)t+=1;return n.add(`${e}${String(t)}`),`${e}${String(t)}`},ne=(e,n)=>{if(e.has(n.name))throw new fe(`sdk: two schemas both produce the JVM model "${n.name}"`);e.set(n.name,n)},$n=(e,n,t,r,a)=>{const i=new Set(Array.isArray(n)?n.filter(s=>typeof s=="string"):[]),o=new Set;return Object.entries(e).map(([s,d])=>{const c=y(d)??{},u=!i.has(s);return{name:be(pn(s),o),nullable:!u&&ge(c)!==c,optional:u,type:A(c,`${t}${l(s)}`,r+1,a),wireKey:s}})},A=(e,n,t,r)=>{if(t>=rn)return{kind:"unknown"};const a=un(e);if(a!==void 0){const c=new Set;return ne(r,{constants:a.map(u=>({name:be(dn(u),c),wireValue:u})),kind:"enum",name:n}),{kind:"enum",name:n}}const i=ge(e);if(i!==e)return A(i,n,t+1,r);const o=y(e.properties);if(o!==void 0)return ne(r,{fields:$n(o,e.required,n,t,r),kind:"class",name:n}),{kind:"class",name:n};const s=y(e.additionalProperties);if(s!==void 0)return{kind:"record",value:A(s,`${n}Value`,t+1,r)};const d=y(e.items);if(d!==void 0)return{item:A(d,`${n}Item`,t+1,r),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"}}},ve=e=>{const n=new Map;for(const t of pe(e)){if(y(t.schema.properties)===void 0)continue;const r=new Map;try{A(t.schema,t.name,0,r)}catch(a){if(a instanceof fe)continue;throw a}if(![...r.keys()].some(a=>n.has(a)))for(const[a,i]of r)n.set(a,i)}return[...n.values()].toSorted((t,r)=>t.name.localeCompare(r.name))},M=e=>[`// GENERATED by \`lunora sdk generate --lang ${e}\` — do not edit.`,"// Run the command again to regenerate."],L=e=>{switch(e.kind){case"boolean":return"Boolean";case"class":case"enum":return e.name;case"list":return`java.util.List<${L(e.item)}>`;case"number":return"Double";case"record":return`java.util.Map<String, ${L(e.value)}>`;case"string":return"String";default:return"Object"}},U=e=>{switch(e.kind){case"class":case"enum":return!0;case"list":return U(e.item);case"record":return U(e.value);default:return!1}},H=(e,n,t)=>{if(!U(e))return n;const r=`item${String(t)}`;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}, ${r} -> ${H(e.item,r,t+1)})`;case"record":return`ModelWire.writeRecord(${n}, ${r} -> ${H(e.value,r,t+1)})`;default:return n}},G=(e,n,t)=>{const r=`item${String(t)}`;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}, ${r} -> ${G(e.item,r,t+1)})`;case"number":return`ModelWire.number(${n})`;case"record":return`ModelWire.readRecord(${n}, ${r} -> ${G(e.value,r,t+1)})`;case"string":return`ModelWire.text(${n})`;default:return n}},mn=e=>{const n=p(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.":""} */`]},yn=100,fn=e=>{const n=e.fields.map(r=>`${L(r.type)} ${r.name}`),t=` public ${e.name}(${n.join(", ")}) {`;return t.length<=yn?[t]:[` public ${e.name}(`,...n.map((r,a)=>` ${r}${a===n.length-1?") {":","}`)]},gn=e=>{const n=e.fields.flatMap(r=>{const a=`wire.put("${m(r.wireKey)}", ${H(r.type,`this.${r.name}`,0)});`;return r.optional?[` if (this.${r.name} != null) {`,` ${a}`," }"]:[` ${a}`]}),t=e.fields.map(r=>` ${G(r.type,`wire.get("${m(r.wireKey)}")`,0)}`);return[...M("java"),"",`package ${h};`,"","/**",` * 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(r=>[...mn(r),` public final ${L(r.type)} ${r.name};`,""]),...fn(e),...e.fields.map(r=>` this.${r.name} = ${r.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);","",...t.length===0?[` return new ${e.name}();`]:[` return new ${e.name}(`,`${t.join(`,
|
|
106
|
+
`)});`]," }","}",""].join(`
|
|
107
|
+
`)},bn=e=>[...M("java"),"",`package ${h};`,"",`/** The \`${e.name}\` union. Each constant keeps the wire string it encodes to. */`,`public enum ${e.name} {`,...e.constants.map((n,t)=>` ${n.name}("${m(n.wireValue)}")${t===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(`
|
|
108
|
+
`),vn=[{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"}],wn=e=>{const n=vn.filter(t=>e.includes(`ModelWire.${t.name}(`));return[...M("java"),"",`package ${h};`,"","/** Wire readers and writers shared by the generated models. */","final class ModelWire {"," private ModelWire() {}",...n.flatMap(t=>["",...t.lines]),"}",""].join(`
|
|
109
|
+
`)},hn=e=>{const n=ve(e);if(n.length===0)return{};const t={};for(const r of n)t[`${q}/${r.name}.java`]=r.kind==="enum"?bn(r):gn(r);return{[`${q}/ModelWire.java`]:wn(Object.values(t).join(`
|
|
110
|
+
`)),...t}},B=e=>{switch(e.kind){case"boolean":return"Boolean";case"class":case"enum":return e.name;case"list":return`List<${B(e.item)}>`;case"number":return"Double";case"record":return`Map<String, ${B(e.value)}>`;case"string":return"String";default:return"WireValue"}},S=(e,n,t)=>{const r=`item${String(t)}`,a=`entry${String(t)}`;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 { ${r} -> ${S(e.item,r,t+1)} })`;case"number":return`WireValue.Num(${n})`;case"record":return`WireValue.Obj(${n}.map { ${a} -> ${a}.key to ${S(e.value,`${a}.value`,t+1)} })`;case"string":return`WireValue.Text(${n})`;default:return n}},J=(e,n,t,r)=>`wireNeed(${we(e,n,t,r)}, "${w(r)}")`,we=(e,n,t,r)=>{const a=`item${String(t)}`,i=`entry${String(t)}`;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} -> ${J(e.item,a,t+1,`${r}[]`)} }`;case"number":return`wireNum(${n})`;case"record":return`wireObj(${n})?.fields?.associate { ${i} -> ${i}.first to ${J(e.value,`${i}.second`,t+1,`${r}{}`)} }`;case"string":return`wireText(${n})`;default:return n}},jn=e=>{const n=e.fields.map(a=>{const i=p(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}: ${B(a.type)}${a.optional||a.nullable?"?":""}${a.optional?" = null":""},`]}),t=e.fields.map(a=>{const i=w(a.wireKey),o=`this@${e.name}.${a.name}`;return a.optional?` ${o}?.let { add("${i}" to ${S(a.type,"it",0)}) }`:a.nullable?` add("${i}" to (${o}?.let { ${S(a.type,"it",0)} } ?: WireValue.Null))`:` add("${i}" to ${S(a.type,o,0)})`}),r=e.fields.map(a=>{const i=`wireField(value, "${w(a.wireKey)}")`,o=a.optional||a.nullable?we(a.type,i,0,a.wireKey):J(a.type,i,0,a.wireKey);return` ${a.name} = ${o},`});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 {",...t," },"," )",""," companion object {"," /** Rebuild from a decoded wire value. */",` fun fromWire(value: WireValue): ${e.name} =`,` ${e.name}(`,...r," )"," }","}"]},An=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}("${w(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)`," }","}"],Sn=[{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"}],_n=e=>{const n=ve(e);if(n.length===0)return{};const t=n.flatMap(o=>[...o.kind==="enum"?An(o):jn(o),""]),r=Sn.filter(o=>t.some(s=>s.includes(`${o.name}(`))),a=r.flatMap((o,s)=>s===0?[...o.lines]:["",...o.lines]),i=[...M("kotlin"),"",`package ${h}`,"",...r.some(o=>o.name==="wireNeed")?["import dev.lunora.WireFormatException"]:[],"import dev.lunora.WireValue","",...t,...a,""].join(`
|
|
111
|
+
`);return{[`${q}/Models.kt`]:i}},Tn=`${f("java").map(e=>`// ${e}`).join(`
|
|
112
|
+
`)}
|
|
113
|
+
|
|
114
|
+
`,te="lunoraapi",En=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"]),O=e=>{const n=l(e),t=n.charAt(0).toLowerCase()+n.slice(1);return En.has(t)?`${t}_`:t},kn=e=>`Client.Verb.${e.toUpperCase()}`,he=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=he(e),t=`client.call(
|
|
115
|
+
${kn(e.verb)}, "${m(e.functionPath)}", ${n.payload}, shardKey)`;return[` /** ${p(e.summary)} */`,` public ${e.resultType??"Object"} ${O(e.functionName)}(${n.type} args, String shardKey) {`,` return ${e.resultType===void 0?t:`${e.resultType}.fromWire(${t})`};`," }"].join(`
|
|
116
|
+
`)},Nn=e=>{const n=he(e);return[` /** live ${p(e.summary)} — re-runs on every write to the tables it reads. */`,` public Runnable subscribe${l(e.functionName)}(`,` ${n.type} args,`," java.util.function.Consumer<Object> onData,"," java.util.function.Consumer<Client.SubscriptionError> onError,"," String shardKey) {"," return client.subscribe(",` "${m(e.functionPath)}", ${n.payload}, onData, onError, shardKey);`," }"].join(`
|
|
117
|
+
`)},On=e=>{const n=`${l(e.name)}Api`,t=e.methods.map(r=>r.verb==="query"?`${re(r)}
|
|
118
|
+
|
|
119
|
+
${Nn(r)}`:re(r)).join(`
|
|
120
|
+
|
|
121
|
+
`);return[` /** Functions declared in \`${p(e.name)}\`. */`,` public static final class ${n} {`," private final Client client;","",` ${n}(Client client) {`," this.client = client;"," }","",t.replaceAll(/^ {4}/gmu," ")," }"].join(`
|
|
122
|
+
`)},Cn=({namespaces:e})=>{T(e,"Java",i=>[O(i.functionName)]);const n=e.map(i=>` public final ${l(i.name)}Api ${O(i.name)};`).join(`
|
|
123
|
+
`),t=e.map(i=>` this.${O(i.name)} = new ${l(i.name)}Api(client);`).join(`
|
|
124
|
+
`),r=W(e).map(i=>`import ${h}.${i};
|
|
125
|
+
`),a=[Tn,`package ${te};
|
|
126
|
+
`,`
|
|
127
|
+
`,`import dev.lunora.Client;
|
|
128
|
+
`,...r,`
|
|
129
|
+
`,"/** Typed entry point: `new Api(client).<namespace>.<function>(args, shardKey)`. */\n",`public final class Api {
|
|
130
|
+
`,n.length>0?`${n}
|
|
131
|
+
|
|
132
|
+
`:"",` public Api(Client client) {
|
|
133
|
+
`,t.length>0?`${t}
|
|
134
|
+
`:` // No functions in this deployment.
|
|
135
|
+
`,` }
|
|
136
|
+
`,`
|
|
137
|
+
`,e.map(i=>On(i)).join(`
|
|
138
|
+
|
|
139
|
+
`),`
|
|
140
|
+
}
|
|
141
|
+
`].join("");return{[`${te}/Api.java`]:a}},Ln={id:"java",render:Cn,renderModels:hn,requires:[],vendor:[{from:"src/dev/lunora",to:"dev/lunora"}]},Rn=`${f("kotlin").map(e=>`// ${e}`).join(`
|
|
142
|
+
`)}
|
|
143
|
+
|
|
144
|
+
`,ae="lunoraapi",Wn=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=l(e),t=n.charAt(0).toLowerCase()+n.slice(1);return Wn.has(t)?`\`${t}\``:t},Mn=e=>`Verb.${e.toUpperCase()}`,Ae=e=>e.argsType===void 0?{declaration:"args: WireValue? = null",payload:"args"}:{declaration:`args: ${e.argsType}`,payload:"args.toWire()"},ie=e=>{const n=Ae(e),t=`client.call(${Mn(e.verb)}, "${w(e.functionPath)}", ${n.payload}, shardKey)`;return[` /** ${p(e.summary)} */`,` fun ${je(e.functionName)}(${n.declaration}, shardKey: String? = null): ${e.resultType??"WireValue"} =`,` ${e.resultType===void 0?t:`${e.resultType}.fromWire(${t})`}`].join(`
|
|
145
|
+
`)},Dn=e=>{const n=Ae(e);return[` /** live ${p(e.summary)} — re-runs on every write to the tables it reads. */`,` fun subscribe${l(e.functionName)}(`,` ${n.declaration},`," onData: ((WireValue) -> Unit)?,"," onError: ((SubscriptionError) -> Unit)? = null,"," shardKey: String? = null,"," ): () -> Unit =",` client.subscribe("${w(e.functionPath)}", ${n.payload}, onData, onError, shardKey)`].join(`
|
|
146
|
+
`)},Pn=e=>{const n=`${l(e.name)}Api`,t=e.methods.map(r=>r.verb==="query"?`${ie(r)}
|
|
147
|
+
|
|
148
|
+
${Dn(r)}`:ie(r)).join(`
|
|
149
|
+
|
|
150
|
+
`);return[`/** Functions declared in \`${p(e.name)}\`. */`,`class ${n}(private val client: Client) {`,t,"}"].join(`
|
|
151
|
+
`)},Vn=({namespaces:e})=>{const n=e.map(i=>` val ${je(i.name)}: ${l(i.name)}Api = ${l(i.name)}Api(client)`).join(`
|
|
152
|
+
`),t=e.flatMap(i=>i.methods),r=[`import dev.lunora.Client
|
|
153
|
+
`,...t.some(i=>i.verb==="query")?[`import dev.lunora.SubscriptionError
|
|
154
|
+
`]:[],`import dev.lunora.Verb
|
|
155
|
+
`,...t.some(i=>i.argsType===void 0||i.resultType===void 0)?[`import dev.lunora.WireValue
|
|
156
|
+
`]:[],...W(e).map(i=>`import ${h}.${i}
|
|
157
|
+
`)],a=[Rn,`package ${ae}
|
|
158
|
+
`,`
|
|
159
|
+
`,...r,`
|
|
160
|
+
`,e.map(i=>Pn(i)).join(`
|
|
161
|
+
|
|
162
|
+
`),`
|
|
163
|
+
|
|
164
|
+
`,"/** Typed entry point: `Api(client).<namespace>.<function>(args)`. */\n",`class Api(client: Client) {
|
|
165
|
+
`,n.length>0?`${n}
|
|
166
|
+
`:` init { require(true) { client } }
|
|
167
|
+
`,`}
|
|
168
|
+
`].join("");return{[`${ae}/Api.kt`]:a}},Kn={id:"kotlin",render:Vn,renderModels:_n,requires:[],vendor:[{from:"src",to:"dev/lunora"}]},In=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"]),k=`"""${f("python").join(`
|
|
169
|
+
|
|
170
|
+
`)}
|
|
171
|
+
"""
|
|
172
|
+
|
|
173
|
+
`,V="lunora_api",_=e=>{const n=E(e);return In.has(n)?`${n}_`:n},Se=e=>$(e,{none:"{}",typed:()=>"args.to_dict()",untyped:"args"}),xn=(e,n,t,r)=>$(e,{none:n,typed:t,untyped:r}),se=e=>{const n=e.resultType??"Any",t=xn(e,"self",i=>`self, args: ${i}`,"self, args: Any"),r=Se(e),a=`await self._client.${e.verb}("${m(e.functionPath)}", ${r}, shard_key)`;return[` async def ${_(e.functionName)}(${t}, *, shard_key: Optional[str] = None) -> ${n}:`,` """${p(e.summary)}"""`,` ${e.resultType===void 0?`return ${a}`:`return ${e.resultType}.from_dict(${a})`}`].join(`
|
|
174
|
+
`)},Fn=e=>{const n=Se(e),t=["self",...$(e,{none:[],typed:r=>[`args: ${r}`],untyped:["args: Any"]}),"on_data: Callback","on_error: Optional[ErrorCallback] = None","*","shard_key: Optional[str] = None"];return[` def subscribe_${_(e.functionName)}(`,...t.map(r=>` ${r},`)," ) -> Unsubscribe:",` """live ${p(e.summary)} — re-runs on every write to the tables it reads."""`,` return self._client.subscribe("${m(e.functionPath)}", ${n}, on_data, on_error, shard_key)`].join(`
|
|
175
|
+
`)},qn=e=>{const n=e.methods.map(t=>t.verb==="query"?`${se(t)}
|
|
176
|
+
|
|
177
|
+
${Fn(t)}`:se(t)).join(`
|
|
178
|
+
|
|
179
|
+
`);return[`class ${l(e.name)}Api:`,` """Functions declared in \`${p(e.name)}\`."""`,""," def __init__(self, client: LunoraClient) -> None:"," self._client = client","",n].join(`
|
|
180
|
+
`)},Un=e=>e.replaceAll(/^([ \t]*)except:$/gmu,"$1except Exception:"),Hn=({models:e,namespaces:n})=>{T(n,"Python",u=>[_(u.functionName),`subscribe_${_(u.functionName)}`]);const t=W(n),r=t.length>0?`from .models import ${t.join(", ")}
|
|
181
|
+
`:"",i=x(n).some(u=>u.verb==="query")?"Callback, ErrorCallback, LunoraClient, Unsubscribe":"LunoraClient",o=x(n).some(u=>u.resultType===void 0),s=n.map(u=>` self.${_(u.name)} = ${l(u.name)}Api(client)`).join(`
|
|
182
|
+
`),d=[k,`from typing import ${o?"Any, Optional":"Optional"}
|
|
183
|
+
`,`
|
|
184
|
+
`,`from lunora.client import ${i}
|
|
185
|
+
`,r,`
|
|
186
|
+
|
|
187
|
+
`,n.map(u=>qn(u)).join(`
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
`),`
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
`,`class Api:
|
|
194
|
+
`,' """Typed entry point: `Api(client).<namespace>.<function>(args)`."""\n',`
|
|
195
|
+
`,` def __init__(self, client: LunoraClient) -> None:
|
|
196
|
+
`,s.length>0?`${s}
|
|
197
|
+
`:` pass
|
|
198
|
+
`].join(""),c=["Api",...n.map(u=>`${l(u.name)}Api`)];return{[`${V}/__init__.py`]:[k,`from .api import ${c.join(", ")}
|
|
199
|
+
`,`
|
|
200
|
+
`,`__all__ = [${c.map(u=>`"${u}"`).join(", ")}]
|
|
201
|
+
`].join(""),[`${V}/api.py`]:d,[`${V}/models.py`]:e.length>0?`${k}${Un(e)}
|
|
202
|
+
`:`${k}# No typed argument or result schemas in this deployment.
|
|
203
|
+
`}},Gn={id:"python",quicktype:{lang:"python",rendererOptions:{"python-version":"3.7"}},render:Hn,requires:[],vendor:[{from:"lunora",to:"lunora"}]},K=`${f("ruby").map(e=>`# ${e}`).join(`
|
|
204
|
+
`)}
|
|
205
|
+
|
|
206
|
+
`,Bn=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"]),z=e=>m(e).replaceAll("#","\\#"),v=e=>{const n=E(e);return Bn.has(n)?`${n}_`:n},Jn=` # Delegates to the transport, which owns the projection and its tests — see
|
|
207
|
+
# \`Lunora.wire_args\`. The path list is generated per model because only the
|
|
208
|
+
# schema knows which nils may be dropped.
|
|
209
|
+
def self.wire_args(model, optional_paths = [])
|
|
210
|
+
Lunora.wire_args(model, optional_paths)
|
|
211
|
+
end
|
|
212
|
+
|
|
213
|
+
`,Yn=e=>`[${e.map(n=>`[${n.map(t=>`"${z(t)}"`).join(", ")}]`).join(", ")}]`,_e=e=>$(e,{none:"{}",typed:()=>`LunoraApi.wire_args(args, ${Yn(e.argsNullPaths.optional)})`,untyped:"args"}),oe=e=>{const n=e.argsType===void 0&&!e.takesArgs?"shard_key: nil":"args, shard_key: nil",t=_e(e),r=`@client.${e.verb}("${z(e.functionPath)}", ${t}, shard_key)`,a=e.resultType===void 0?r:`${e.resultType}.from_dynamic!(${r})`;return[` # ${p(e.summary)}`,` def ${v(e.functionName)}(${n})`,` ${a}`," end"].join(`
|
|
214
|
+
`)},zn=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",t=_e(e);return[` # live ${p(e.summary)} — re-runs on every write to the tables it reads.`,` def subscribe_${v(e.functionName)}(${n})`,` @client.subscribe("${z(e.functionPath)}", ${t}, on_data, on_error, shard_key)`," end"].join(`
|
|
215
|
+
`)},Zn=e=>{const n=e.methods.map(t=>t.verb==="query"?`${oe(t)}
|
|
216
|
+
|
|
217
|
+
${zn(t)}`:oe(t)).join(`
|
|
218
|
+
|
|
219
|
+
`);return[` # Functions declared in \`${p(e.name)}\`.`,` class ${l(e.name)}Api`," def initialize(client)"," @client = client"," end","",n," end"].join(`
|
|
220
|
+
`)},Xn=/^class \w+ < Dry::Struct\n[\s\S]*?def self\.from_dynamic!\(d\)\n\s*d = Types::Hash\[d\]/u,Qn=(e,n)=>{const t=new Map;for(const s of n.matchAll(/^class (\w+)\b[^\n]*\n[\s\S]*?^end$/gmu))t.set(s[1],s[0]);const r=s=>Xn.test(s),a=new Set([...t].filter(([,s])=>s.includes("< Dry::Struct")&&!r(s)).map(([s])=>s));let i=!0;for(;i;){i=!1;for(const[s,d]of t)!a.has(s)&&[...a].some(c=>new RegExp(String.raw`\b${c}\b`,"u").test(d))&&(a.add(s),i=!0)}const o=s=>{const d=s===void 0?void 0:t.get(s);return d!==void 0&&r(d)&&!a.has(s)?s:void 0};return e.map(s=>({methods:s.methods.map(d=>({...d,argsType:o(d.argsType),resultType:o(d.resultType)})),name:s.name}))},et=({models:e,namespaces:n})=>{T(n,"Ruby",o=>[v(o.functionName),`subscribe_${v(o.functionName)}`]);const t=Qn(n,e),r=t.map(o=>`:${v(o.name)}`).join(", "),a=t.map(o=>` @${v(o.name)} = ${l(o.name)}Api.new(client)`).join(`
|
|
221
|
+
`);return{"api.rb":[`# frozen_string_literal: true
|
|
222
|
+
|
|
223
|
+
`,K,`require_relative "models"
|
|
224
|
+
`,`
|
|
225
|
+
`,`module LunoraApi
|
|
226
|
+
`,x(t).some(o=>o.argsType!==void 0)?Jn:"",t.map(o=>Zn(o)).join(`
|
|
227
|
+
|
|
228
|
+
`),`
|
|
229
|
+
|
|
230
|
+
`," # Typed entry point: `Api.new(client).<namespace>.<function>(args)`.\n",` class Api
|
|
231
|
+
`,r.length>0?` attr_reader ${r}
|
|
232
|
+
|
|
233
|
+
`:"",` def initialize(client)
|
|
234
|
+
`,a.length>0?`${a}
|
|
235
|
+
`:` @client = client
|
|
236
|
+
`,` end
|
|
237
|
+
`,` end
|
|
238
|
+
`,`end
|
|
239
|
+
`].join(""),"models.rb":e.length>0?`# frozen_string_literal: true
|
|
240
|
+
|
|
241
|
+
${K}${e}
|
|
242
|
+
`:`# frozen_string_literal: true
|
|
243
|
+
|
|
244
|
+
${K}# No typed argument or result schemas in this deployment.
|
|
245
|
+
`}},nt={id:"ruby",quicktype:{lang:"ruby",rendererOptions:{}},render:et,requires:["dry-struct + dry-types (gems, required by the generated models)"],vendor:[{from:"lib/lunora.rb",to:"lunora.rb"},{from:"lib/lunora",to:"lunora"}]},C=`${f("rust").map(e=>`// ${e}`).join(`
|
|
246
|
+
`)}
|
|
247
|
+
|
|
248
|
+
`,tt=`${C}pub mod api;
|
|
249
|
+
pub mod models;
|
|
250
|
+
`,rt=`# The generated Lunora Rust SDK, with the transport vendored under ./lunora.
|
|
251
|
+
#
|
|
252
|
+
# Add to a consuming crate:
|
|
253
|
+
#
|
|
254
|
+
# lunora-api = { path = "sdk/rust" }
|
|
255
|
+
|
|
256
|
+
[package]
|
|
257
|
+
name = "lunora-api"
|
|
258
|
+
version = "0.1.0"
|
|
259
|
+
edition = "2021"
|
|
260
|
+
publish = false
|
|
261
|
+
|
|
262
|
+
# Its own workspace root, so a consumer whose project IS a workspace does not
|
|
263
|
+
# adopt this directory as a member (which then fails to build on its own).
|
|
264
|
+
[workspace]
|
|
265
|
+
|
|
266
|
+
[dependencies]
|
|
267
|
+
lunora = { path = "lunora" }
|
|
268
|
+
serde = { version = "1", features = ["derive"] }
|
|
269
|
+
serde_json = "1"
|
|
270
|
+
`,at=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"]),it=new Set(["crate","self","Self","super"]),R=e=>{const n=E(e);return it.has(n)?`${n}_`:at.has(n)?`r#${n}`:n},st=e=>`Verb::${l(e)}`,Te=e=>e.length===0?"&[]":`&[${e.map(n=>`&["${n.map(t=>m(t)).join('", "')}"][..]`).join(", ")}]`,le=e=>{const n=$(e,{none:"&self, shard_key: Option<&str>",typed:a=>`&self, args: &${a}, shard_key: Option<&str>`,untyped:"&self, args: &WireValue, shard_key: Option<&str>"}),t=$(e,{none:"&WireValue::Object(Vec::new())",typed:()=>`&from_model_json(&serde_json::to_value(args).map_err(|error| ClientError::Transport(error.to_string()))?, ${Te(e.argsNullPaths.optional)})`,untyped:"args"}),r=`self.client.call(${st(e.verb)}, "${m(e.functionPath)}", ${t}, shard_key)`;return e.resultType===void 0?[` /// ${p(e.summary)}`,` pub fn ${R(e.functionName)}(${n}) -> Result<WireValue, ClientError> {`,` ${r}`," }"].join(`
|
|
271
|
+
`):[` /// ${p(e.summary)}`,` pub fn ${R(e.functionName)}(${n}) -> Result<${e.resultType}, ClientError> {`,` let raw = ${r}?;`," let json = encode_wire(&raw).map_err(ClientError::Wire)?;"," serde_json::from_value(json).map_err(|error| ClientError::Transport(error.to_string()))"," }"].join(`
|
|
272
|
+
`)},ot=e=>{const n=$(e,{none:"",typed:r=>`args: &${r}, `,untyped:"args: &WireValue, "}),t=$(e,{none:"WireValue::Object(Vec::new())",typed:()=>`from_model_json(&serde_json::to_value(args).map_err(|error| ClientError::Transport(error.to_string()))?, ${Te(e.argsNullPaths.optional)})`,untyped:"args.clone()"});return[` /// live ${p(e.summary)} — re-runs on every write to the tables it reads.`,` pub fn subscribe_${E(e.functionName)}(`," &mut self,",` ${n}on_data: DataHandler,`," on_error: ErrorHandler,"," shard_key: Option<&str>,"," ) -> Result<String, ClientError> {",` Ok(self.client.subscribe_on_shard("${m(e.functionPath)}", ${t}, on_data, on_error, shard_key))`," }"].join(`
|
|
273
|
+
`)},lt=e=>{const n=`${l(e.name)}Api`,t=e.methods.map(r=>r.verb==="query"?`${le(r)}
|
|
274
|
+
|
|
275
|
+
${ot(r)}`:le(r)).join(`
|
|
276
|
+
|
|
277
|
+
`);return[`/// Functions declared in \`${p(e.name)}\`.`,`pub struct ${n}<'client> {`," client: &'client mut Client,","}","",`impl<'client> ${n}<'client> {`,t,"}"].join(`
|
|
278
|
+
`)},ct=({models:e,namespaces:n})=>{T(n,"Rust",a=>[R(a.functionName),`subscribe_${E(a.functionName)}`]);const t=n.map(a=>[` /// Functions declared in \`${p(a.name)}\`.`,` pub fn ${R(a.name)}(&mut self) -> ${l(a.name)}Api<'_> {`,` ${l(a.name)}Api { client: self.client }`," }"].join(`
|
|
279
|
+
`)).join(`
|
|
280
|
+
|
|
281
|
+
`),r=[C,`#![allow(dead_code, unused_imports)]
|
|
282
|
+
`,`
|
|
283
|
+
`,`use lunora::client::{Client, ClientError, DataHandler, ErrorHandler, Verb};
|
|
284
|
+
`,`use lunora::wire::{encode_wire, from_model_json, WireValue};
|
|
285
|
+
`,`
|
|
286
|
+
`,`use crate::models::*;
|
|
287
|
+
`,`
|
|
288
|
+
`,n.map(a=>lt(a)).join(`
|
|
289
|
+
|
|
290
|
+
`),`
|
|
291
|
+
|
|
292
|
+
`,"/// Typed entry point: `Api::new(&client).<namespace>().<function>(args)`.\n",`pub struct Api<'client> {
|
|
293
|
+
`,` client: &'client mut Client,
|
|
294
|
+
`,`}
|
|
295
|
+
`,`
|
|
296
|
+
`,`impl<'client> Api<'client> {
|
|
297
|
+
`,` pub fn new(client: &'client mut Client) -> Self {
|
|
298
|
+
`,` Self { client }
|
|
299
|
+
`,` }
|
|
300
|
+
`,t.length>0?`
|
|
301
|
+
${t}
|
|
302
|
+
`:"",`}
|
|
303
|
+
`].join("");return{"Cargo.toml":rt,"src/api.rs":r,"src/lib.rs":tt,"src/models.rs":e.length>0?`${C}#![allow(dead_code)]
|
|
304
|
+
|
|
305
|
+
${e}
|
|
306
|
+
`:`${C}#![allow(dead_code)]
|
|
307
|
+
|
|
308
|
+
// No typed argument or result schemas in this deployment.
|
|
309
|
+
`}},ut={id:"rust",quicktype:{lang:"rust",rendererOptions:{"just-types":"true"}},render:ct,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"}]},I=`${f("swift").map(e=>`// ${e}`).join(`
|
|
310
|
+
`)}
|
|
311
|
+
|
|
312
|
+
`,ce="Sources/LunoraApi",pt=`// swift-tools-version:5.9
|
|
313
|
+
|
|
314
|
+
import PackageDescription
|
|
315
|
+
|
|
316
|
+
// The generated Lunora Swift SDK, with the transport vendored under
|
|
317
|
+
// Sources/Lunora. Add to a consuming package — where "swift" below is the NAME OF
|
|
318
|
+
// THE DIRECTORY THIS FILE IS IN, which is how SwiftPM identifies a local path
|
|
319
|
+
// dependency. It ignores the "name:" field for that, and a bare product name in a
|
|
320
|
+
// target's dependencies does not resolve at all, so the directory name is the one
|
|
321
|
+
// spelling that works:
|
|
322
|
+
//
|
|
323
|
+
// dependencies: [.package(path: "sdk/swift")],
|
|
324
|
+
// targets: [
|
|
325
|
+
// .target(
|
|
326
|
+
// name: "YourTarget",
|
|
327
|
+
// dependencies: [.product(name: "LunoraApi", package: "swift")]
|
|
328
|
+
// )
|
|
329
|
+
// ]
|
|
330
|
+
let package = Package(
|
|
331
|
+
name: "LunoraSdk",
|
|
332
|
+
platforms: [.macOS(.v12), .iOS(.v15)],
|
|
333
|
+
products: [
|
|
334
|
+
.library(name: "LunoraApi", targets: ["LunoraApi"]),
|
|
335
|
+
.library(name: "Lunora", targets: ["Lunora"]),
|
|
336
|
+
],
|
|
337
|
+
targets: [
|
|
338
|
+
.target(name: "Lunora"),
|
|
339
|
+
.target(name: "LunoraApi", dependencies: ["Lunora"]),
|
|
340
|
+
]
|
|
341
|
+
)
|
|
342
|
+
`,dt=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"]),Y=e=>{const n=l(e),t=n.charAt(0).toLowerCase()+n.slice(1);return dt.has(t)?`\`${t}\``:t},$t=e=>`[${e.map(n=>`["${n.map(t=>m(t)).join('", "')}"]`).join(", ")}]`,Ee=e=>$(e,{none:"nil",typed:()=>{const{nullable:n}=e.argsNullPaths;return n.length===0?"try LunoraClient.wireValue(args)":`try LunoraClient.wireValue(args, nullablePaths: ${$t(n)})`},untyped:"args"}),ue=e=>{const n=$(e,{none:"shardKey: String? = nil",typed:o=>`_ args: ${o}, shardKey: String? = nil`,untyped:"_ args: Any, shardKey: String? = nil"}),t=Ee(e),r=e.resultType??"Any",a=`try client.${e.verb}("${m(e.functionPath)}", args: ${t}, shardKey: shardKey)`,i=e.resultType===void 0?`return ${a}`:[`let raw = ${a}`," let data = Data(Wire.stableStringify(raw).utf8)",` return try JSONDecoder().decode(${e.resultType}.self, from: data)`].join(`
|
|
343
|
+
`);return[` /// ${p(e.summary)}`,` public func ${Y(e.functionName)}(${n}) throws -> ${r} {`,` ${i}`," }"].join(`
|
|
344
|
+
`)},mt=e=>{const n=$(e,{none:"",typed:r=>`_ args: ${r}, `,untyped:"_ args: Any, "}),t=Ee(e);return[` /// live ${p(e.summary)} — re-runs on every write to the tables it reads.`," @discardableResult",` public func subscribe${l(e.functionName)}(`,` ${n}onData: ((Any) -> Void)?,`," onError: ((LunoraSubscriptionError) -> Void)? = nil,"," shardKey: String? = nil"," ) throws -> LunoraUnsubscribe {",` client.subscribe("${m(e.functionPath)}", args: ${t}, onData: onData, onError: onError, shardKey: shardKey)`," }"].join(`
|
|
345
|
+
`)},yt=e=>{const n=`${l(e.name)}API`,t=e.methods.map(r=>r.verb==="query"?`${ue(r)}
|
|
346
|
+
|
|
347
|
+
${mt(r)}`:ue(r)).join(`
|
|
348
|
+
|
|
349
|
+
`);return[`/// Functions declared in \`${p(e.name)}\`.`,`public struct ${n} {`," let client: LunoraClient","",t,"}"].join(`
|
|
350
|
+
`)},ft=({models:e,namespaces:n})=>{const t=n.map(i=>` public let ${Y(i.name)}: ${l(i.name)}API`).join(`
|
|
351
|
+
`),r=n.map(i=>` ${Y(i.name)} = ${l(i.name)}API(client: client)`).join(`
|
|
352
|
+
`),a=[I,`import Foundation
|
|
353
|
+
`,`import Lunora
|
|
354
|
+
`,`
|
|
355
|
+
`,n.map(i=>yt(i)).join(`
|
|
356
|
+
|
|
357
|
+
`),`
|
|
358
|
+
|
|
359
|
+
`,"/// Typed entry point: `API(client:).<namespace>.<function>(args)`.\n",`public struct API {
|
|
360
|
+
`,t.length>0?`${t}
|
|
361
|
+
|
|
362
|
+
`:"",` public init(client: LunoraClient) {
|
|
363
|
+
`,r.length>0?`${r}
|
|
364
|
+
`:` _ = client
|
|
365
|
+
`,` }
|
|
366
|
+
`,`}
|
|
367
|
+
`].join("");return{"Package.swift":pt,[`${ce}/Api.swift`]:a,[`${ce}/Models.swift`]:e.length>0?`${I}${e}
|
|
368
|
+
`:`${I}import Foundation
|
|
369
|
+
|
|
370
|
+
// No typed argument or result schemas in this deployment.
|
|
371
|
+
`}},gt={id:"swift",quicktype:{lang:"swift",rendererOptions:{"access-level":"public",initializers:"false"}},render:ft,requires:[],vendor:[{from:"Sources/Lunora",to:"Sources/Lunora"}]},bt={dart:Ye,go:tn,java:Ln,kotlin:Kn,python:Gn,ruby:nt,rust:ut,swift:gt},wt=Object.keys(bt).toSorted((e,n)=>e.localeCompare(n)),ht=async(e,n)=>{const t=Ne(e);Oe(t);const r=n.renderModels?.(e),a=r===void 0?await We(e,n):Object.values(r).join(`
|
|
372
|
+
`),i=Ce(t,a);return{files:{...r,...n.render({models:a,namespaces:i})},undeclared:Re(t,a),unrepresentable:Le(e)}};export{wt as SDK_LANGUAGES,bt as SDK_TARGETS,ht as generateSdk,St as isTypedSchema};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as m}from"node:fs";import{join as u}from"node:path";import{SyntaxKind as p,Node as o}from"ts-morph";import{diagnosticAt as g}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as f}from"./module-specifiers-WF8iAydP.mjs";import{p as d}from"./parse-validator-B4mFs19C.mjs";import{findObjectProperty as l}from"./listLunoraSourceFiles-DRes9d5p.mjs";import{a as S}from"./attribution-sW_DHmLO.mjs";const h="shapes.ts",b=r=>{const t=r.getSymbol();if(!t)return r.getText()==="defineShape";for(const e of t.getDeclarations())if(o.isImportSpecifier(e))return f(e.getImportDeclaration().getModuleSpecifierValue())?e.getNameNode().getText()==="defineShape":!1;return!1},x=r=>{const t=r.getSymbol();if(!t)return!1;for(const e of t.getDeclarations()){if(!o.isNamespaceImport(e))continue;const i=e.getFirstAncestorByKind(p.ImportDeclaration);return i!==void 0&&f(i.getModuleSpecifierValue())}return!1},y=r=>{if(o.isIdentifier(r))return b(r);if(o.isPropertyAccessExpression(r)){const t=r.getExpression();return r.getName()==="defineShape"&&o.isIdentifier(t)&&x(t)}return!1},N=r=>{const[t]=r.getArguments();if(!t||!o.isObjectLiteralExpression(t))return;const e=l(t,"table");if(!e||!o.isPropertyAssignment(e))return;const i=e.getInitializer();return i&&o.isStringLiteral(i)?i.getLiteralValue():void 0},E=r=>{const[t]=r.getArguments();if(!t||!o.isObjectLiteralExpression(t))return{};const e=l(t,"args");if(!e||!o.isPropertyAssignment(e))return{};const i=e.getInitializer();return!i||!o.isObjectLiteralExpression(i)?{}:d(i)},I=r=>{const t=[];for(const e of r.getVariableDeclarations()){const i=e.getInitializer();if(i?.getKind()!==p.CallExpression)continue;const s=i,a=s.getExpression();if(!y(a))continue;const n=e.getNameNode();if(!o.isIdentifier(n)){if(e.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw g(n,"defineShape exports must be plain named exports (no destructuring)")}const c=S(e,"binding");c!==void 0&&t.push({args:E(s),exportName:c,filePath:"shapes",table:N(s)})}return t},z=(r,t)=>{const e=u(t,h);if(!m(e))return[];const i=r.getSourceFile(e)??r.addSourceFileAtPath(e),s=I(i);return s.sort((a,n)=>a.exportName.localeCompare(n.exportName)),s};export{h as SHAPES_FILENAME,z as discoverShapes};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import{LunoraError as E}from"@lunora/errors";import{SCHEMA_SNAPSHOT_VERSION as v,sortKeys as f,diffSchemaSnapshots as I,parseSnapshotJson as A}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as L}from"./isD1GlobalTable-udvHAAzD.mjs";const O=e=>{const t=e.shardMode;return t==="global"?`global:${L(e)?"hyperdrive":"d1"}`:t==="root"?t:`shardBy:${t.field}`},_=(e,t)=>{const n=JSON.stringify(e),s=JSON.stringify(t);return n===s?0:n<s?-1:1},l=e=>{const t=e.kind==="optional",n=t?e.inner:void 0,s=n??e,r={kind:t?n?.kind??"unknown":e.kind,nullable:s.column?.notNull===!1||e.column?.notNull===!1,optional:t,unique:s.column?.unique===!0||e.column?.unique===!0,...j[s.kind]?.(s)};return(s.hasRefinement===!0||e.hasRefinement===!0)&&(r.refined=!0),r},N=e=>{const t={};for(const[n,s]of Object.entries(e))t[n]=l(s);return f(t)},j={array:e=>e.inner?{of:l(e.inner)}:{},id:e=>e.tableName===void 0?{}:{ref:e.tableName},literal:e=>e.literalValue===void 0?{}:{literal:e.literalValue},object:e=>e.shape?{fields:N(e.shape)}:{},record:e=>({...e.keyType?{key:l(e.keyType)}:{},...e.valueType?{of:l(e.valueType)}:{}}),union:e=>e.members?{members:e.members.map(t=>l(t)).toSorted(_)}:{}},D=e=>{const t={};for(const[o,a]of Object.entries(e.shape))t[o]=l(a);const n={};for(const o of e.indexes)n[o.name]={fields:[...o.fields],unique:o.unique??!1};const s={};for(const o of e.relations)s[o.name]={field:o.field,kind:o.kind,table:o.table};const r={commitOrdered:e.commitOrdered===!0,fields:f(t),indexes:f(n),memory:e.memory===!0,relations:f(s),shardMode:O(e)};return e.ttl&&(r.ttl=e.ttl.after===void 0?{field:e.ttl.field}:{after:e.ttl.after,field:e.ttl.field}),r},C=(e,t)=>{const n={};for(const r of e.tables)n[r.name]=D(r);const s=[...t].sort();return{jurisdiction:e.jurisdiction,migrationIds:s,tables:f(n),version:v}};class R extends E{constructor(t){super("SCHEMA_SNAPSHOT_PARSE",t,{name:"SchemaSnapshotParseError"})}}const J=e=>{const t=A(e);if(t.status==="invalid")throw new R(t.error);return t.status==="ok"?t.snapshot:void 0},M={build:{allowDrift:!0,updateBaseline:!1},deploy:{allowDrift:!0,updateBaseline:!0},prepare:{allowDrift:!0,updateBaseline:!0},verify:{allowDrift:!0,updateBaseline:!1}},y=" • For backward-compatible changes (e.g. adding an optional field): pass `--allow-schema-drift` to skip the block.",k=" • To accept the new shape without a migration (you know data is compatible): pass `--update-schema-baseline`.",B=e=>{const t=e===void 0?void 0:M[e];if(e===void 0||t===void 0)return`${y}
|
|
2
|
+
${k}
|
|
3
|
+
`;const n=t.updateBaseline?k:` • To accept the new shape without a migration, run \`lunora prepare --update-schema-baseline\` — \`lunora ${e}\` does not take that flag.`;return`${y}
|
|
4
|
+
${n}
|
|
5
|
+
`},p=e=>e.map(t=>` - ${t.summary}`).join(`
|
|
6
|
+
`),w=e=>e.remediation==="backfill"&&e.table!==void 0,x=/^[A-Za-z_]\w*$/u,F=e=>` lunora migrate create backfill_${e} --table ${e}`,P=(e,t,n)=>{const s=[...new Set(e.filter(o=>w(o)).map(o=>o.table))],r=[];if(s.length>0){r.push(" • Add a `defineMigration({ id, table, up })` in lunora/ for each affected table, then re-run this command — the baseline is re-blessed on a successful deploy, not by `lunora migrate` itself.\n");const o=s.filter(a=>x.test(a));o.length>0&&r.push(`
|
|
7
|
+
Scaffold the missing migration(s) — the generated \`up\` is an identity placeholder you must fill in:
|
|
8
|
+
${o.map(a=>F(a)).join(`
|
|
9
|
+
`)}
|
|
10
|
+
|
|
11
|
+
`)}return t.length>0&&r.push(` • Migration(s) ${t.join(", ")} declare a non-literal \`table\`, so codegen cannot tell which table they visit and they cover nothing. Use a string literal.
|
|
12
|
+
`),r.push(B(n)),[`${n??"deploy"} blocked: ${String(e.length)} unresolved breaking schema change(s) since the last blessed schema baseline:`,p(e),"",`To fix:
|
|
13
|
+
${r.join("")}Docs: https://lunora.dev/docs/migrations`].join(`
|
|
14
|
+
`)},V=e=>{const{allowDrift:t=!1,baseline:n,command:s,current:r,migrations:o}=e,a=I(n,r),u=a.changes.filter(i=>i.severity==="breaking"),b=r.migrationIds.filter(i=>!(n?.migrationIds??[]).includes(i)),m=o.filter(i=>b.includes(i.id)),c=(i,h)=>({blocked:i,changes:a.changes,newMigrationIds:b,reason:h}),T=new Set(m.filter(i=>i.table!=="").map(i=>i.table)),$=m.filter(i=>i.table==="").map(i=>i.id);if(a.changes.length===0||n===void 0)return c(!1,"");if(u.length===0)return c(!1,`schema drift detected (all additive/safe):
|
|
15
|
+
${p(a.changes)}`);const g=u.filter(i=>!w(i)||!T.has(i.table));if(g.length===0){const i=new Set(u.map(d=>d.table)),h=m.filter(d=>i.has(d.table)).map(d=>d.id);return c(!1,`breaking schema drift detected, covered by ${String(h.length)} new migration(s) (${h.join(", ")}):
|
|
16
|
+
${p(u)}`)}const S=P(g,$,s);return t?c(!1,`${S}
|
|
17
|
+
|
|
18
|
+
(overridden by --allow-schema-drift)`):c(!0,S)};export{R as SchemaSnapshotParseError,C as buildSchemaSnapshot,V as evaluateSchemaDrift,J as parseSchemaSnapshot};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as b}from"node:fs";import{join as y}from"node:path";import{LunoraError as w}from"@lunora/errors";import{isValidCronExpression as k}from"@lunora/scheduler";import{workflowDefaultName as E,workflowClassName as v}from"@lunora/workflow";import{Node as n,VariableDeclarationKind as S,SyntaxKind as x}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{unwrapToCallExpression as N,findObjectProperty as d,stringPropertyFor as L}from"./listLunoraSourceFiles-DRes9d5p.mjs";import{a as P}from"./attribution-sW_DHmLO.mjs";import{r as $}from"./handler-reference-C1oBljnl.mjs";const A="workflows.ts",W=new Set(["do","sleep","sleepUntil","waitForEvent"]),C=o=>{const e=o.getSymbol();if(!e)return o.getText()==="defineWorkflow";for(const t of e.getDeclarations())if(n.isImportSpecifier(t))return t.getImportDeclaration().getModuleSpecifierValue()!=="@lunora/workflow"?!1:t.getNameNode().getText()==="defineWorkflow";return!1},m=L("workflow"),O=(o,e,t)=>{if(n.isNumericLiteral(o))return o.getLiteralValue();throw c(o,`workflow "${e}": \`${t}\` must be a static number literal — it is deploy configuration codegen writes into wrangler.jsonc`)},f=(o,e)=>{const t=d(o,e);return t&&n.isPropertyAssignment(t)?t.getInitializerOrThrow():void 0},g=(o,e,t)=>{if(n.isObjectLiteralExpression(o))return o;throw c(o,`workflow "${e}": \`${t}\` must be an inline object literal — it is deploy configuration codegen writes into wrangler.jsonc`)},D=(o,e)=>{if(!n.isArrayLiteralExpression(o)||o.getElements().length===0)throw c(o,`workflow "${e}": \`schedules\` must be a non-empty inline array of cron expression string literals`);return o.getElements().map(t=>{const r=m(t,e,"schedules[]");if(!k(r))throw c(t,`workflow "${e}": schedule "${r}" is not a valid cron expression`);return r})},I=(o,e)=>{const t={},r=f(o,"schedules");r!==void 0&&(t.schedules=D(r,e));const s=f(o,"limits");if(s!==void 0){const i=f(g(s,e,"limits"),"steps");if(i===void 0)t.limits={};else{const l=O(i,e,"limits.steps");if(!Number.isInteger(l)||l<=0)throw c(i,`workflow "${e}": \`limits.steps\` must be a positive integer (got ${String(l)})`);t.limits={steps:l}}}const a=f(o,"defaultRetention");if(a!==void 0){const i=g(a,e,"defaultRetention"),l={};for(const u of["errorRetention","successRetention"]){const p=f(i,u);p!==void 0&&(l[u]=m(p,e,`defaultRetention.${u}`))}t.defaultRetention=l}return t},F=o=>{const e=o.getExpression();if(!n.isPropertyAccessExpression(e)||!W.has(e.getName()))return!1;const t=e.getExpression();return n.isPropertyAccessExpression(t)&&t.getName()==="step"?!0:n.isIdentifier(t)&&t.getText()==="step"},T=o=>{if(!o)return[];const e=[];for(const t of o.getDescendantsOfKind(x.CallExpression)){if(!F(t))continue;const r=t.getArguments()[0];!r||!(n.isStringLiteral(r)||n.isNoSubstitutionTemplateLiteral(r))||e.push({line:t.getStartLineNumber(),method:t.getExpression().getName(),name:r.getLiteralValue()})}return e},h=o=>{let e=o;for(;e&&(n.isAsExpression(e)||n.isSatisfiesExpression(e)||n.isParenthesizedExpression(e));)e=e.getExpression();return e},R=o=>{const e=h(o);if(e&&n.isObjectLiteralExpression(e))return e;if(!(!e||!n.isIdentifier(e)))for(const t of e.getSymbol()?.getDeclarations()??[]){const s=n.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===S.Const?h(t.getInitializer()):void 0;if(s&&n.isObjectLiteralExpression(s))return s}},j=(o,e)=>{const t=d(o,"handler"),r=$(t,e);return r!==void 0?r:{body:t!==void 0&&n.isPropertyAssignment(t)?t.getInitializer():t}},K=(o,e,t)=>{const r=R(o.getArguments()[0]);if(!r)throw c(o,`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 s=j(r,t),a={className:v(e),exportName:e,name:E(e),steps:T(s.body),...s.file===void 0?{}:{handlerFile:s.file},...s.site===void 0?{}:{handlerSite:s.site}},i=d(r,"name");return i&&n.isPropertyAssignment(i)&&(a.name=m(i.getInitializerOrThrow(),e,"name")),{...a,...I(r,e)}},V=(o,e)=>{const t=[];for(const r of o.getVariableDeclarations()){const s=N(r.getInitializer());if(!s)continue;const a=s.getExpression();if(!n.isIdentifier(a)||!C(a))continue;const i=r.getNameNode();if(!n.isIdentifier(i)){if(r.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw c(i,"defineWorkflow exports must be plain named exports (no destructuring)")}const l=P(r,"binding");l!==void 0&&t.push(K(s,l,e))}return t},z=o=>{const e=new Map,t=new Map;for(const r of o){const s=e.get(r.name);if(s!==void 0)throw new w("DUPLICATE_WORKFLOW_NAME",`Duplicate workflow name "${r.name}": produced by both "${s}" and "${r.exportName}". Deployed workflow names must be unique across the project.`,{status:500});e.set(r.name,r.exportName);const a=t.get(r.className);if(a!==void 0)throw new w("DUPLICATE_WORKFLOW_CLASS",`Duplicate workflow class "${r.className}": produced by both "${a}" and "${r.exportName}". Workflow export names must yield unique generated class names.`,{status:500});t.set(r.className,r.exportName)}},Y=(o,e)=>{const t=y(e,A);if(!b(t))return[];const r=o.getSourceFile(t)??o.addSourceFileAtPath(t),s=V(r,e);return s.sort((a,i)=>a.exportName.localeCompare(i.exportName)),z(s),s};export{A as WORKFLOWS_FILENAME,Y as discoverWorkflows};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{byCodepoint as w,callSiteCallers as k}from"@lunora/advisor";import{Node as r,SyntaxKind as p,VariableDeclarationKind as M,ts as O}from"ts-morph";import{i as A}from"./reserved-words-CW1QFbTd.mjs";import{isWriteTarget as V}from"./listLunoraSourceFiles-DRes9d5p.mjs";const N=new WeakMap,T=e=>e.getStatements().flatMap(t=>r.isFunctionDeclaration(t)?[t]:r.isVariableStatement(t)?t.getDeclarations().filter(o=>r.isIdentifier(o.getNameNode())):[]),x=e=>r.isStringLiteral(e)?e.getLiteralValue():e.getText(),F=e=>{if(r.isFunctionDeclaration(e)||r.isClassDeclaration(e)){const t=e.getName();return e.hasExportKeyword()?[[t??"default",e.hasDefaultKeyword()?"default":t??"default"]]:[]}return!r.isVariableStatement(e)||!e.hasExportKeyword()?[]:e.getDeclarations().flatMap(t=>{const o=t.getNameNode();return r.isIdentifier(o)?[[o.getText(),o.getText()]]:o.getDescendantsOfKind(p.BindingElement).flatMap(n=>r.isIdentifier(n.getNameNode())?[[n.getName(),n.getName()]]:[])})},C=e=>{if(r.isExportDeclaration(e))return e.hasModuleSpecifier()||e.isTypeOnly()?[]:e.getNamedExports().filter(o=>!o.isTypeOnly()).map(o=>{const n=x(o.getNameNode()),s=o.getAliasNode();return[n,s===void 0?n:x(s)]});const t=r.isExportAssignment(e)&&!e.isExportEquals()?e.getExpression():void 0;return r.isIdentifier(t)?[[t.getText(),"default"]]:F(e)},h=new WeakMap,K=e=>{const t=h.get(e.compilerNode);if(t!==void 0)return t;const o=new Map;for(const[s,c]of e.getStatements().flatMap(i=>C(i)))o.set(s,(o.get(s)??new Set).add(c));const n=new Map([...o].map(([s,c])=>[s,[...c].toSorted(H)]));return h.set(e.compilerNode,n),n},g=e=>{const t=r.isBindingElement(e)?e.getFirstAncestorByKind(p.VariableStatement):void 0,o=r.isVariableDeclaration(e)?e.getVariableStatement():void 0,n=r.isFunctionDeclaration(e)?e:t??o;if(n===void 0||!r.isSourceFile(n.getParent()))return[];const s=r.isFunctionDeclaration(e)?e.getName()??"default":e.getName();return K(e.getSourceFile()).get(s)??[]},P=e=>new Map(e.flatMap(t=>{const o=g(t);return o.length===0?[]:[[t.compilerNode,o]]})),b=(e,t)=>{for(const o of e.getAncestors()){if(r.isExportAssignment(o)&&!o.isExportEquals())return{kind:"export",name:"default"};if((r.isFunctionDeclaration(o)&&r.isSourceFile(o.getParent())||r.isVariableDeclaration(o)&&r.isSourceFile(o.getVariableStatement()?.getParent())&&r.isIdentifier(o.getNameNode()))&&(r.isFunctionDeclaration(o)||r.isVariableDeclaration(o))){const s=t.get(o.compilerNode)?.[0];return s===void 0?{declaration:o,kind:"helper"}:{kind:"export",name:s}}}return{kind:"untracked"}},y=e=>{for(const t of e.getAncestors()){if(r.isExpressionWithTypeArguments(t)){const o=t.getParent();return!(r.isHeritageClause(o)&&o.getToken()===p.ExtendsKeyword&&(r.isClassDeclaration(o.getParent())||r.isClassExpression(o.getParent())))}if(O.isTypeNode(t.compilerNode))return!0}return!1},G=e=>{const t=e.getParent(),o=r.isPropertyAccessExpression(t)&&t.getNameNode()===e,n=(r.isPropertyAssignment(t)||r.isMethodDeclaration(t))&&t.getNameNode()===e;return!o&&!n&&!y(e)},E=e=>{const t=e.getParent();return r.isShorthandPropertyAssignment(t)&&t.getNameNode()===e?t.getValueSymbol():e.getSymbol()},I=e=>{const t=E(e);return t?.getValueDeclaration()??t?.getDeclarations()[0]},S=new WeakMap,Z=e=>{const t=e.getNameNode(),o=r.isFunctionDeclaration(e)?void 0:e.getFirstAncestorByKind(p.VariableDeclarationList);if(!r.isIdentifier(t)||o?.getDeclarationKind()===M.Const)return!1;let n=S.get(e.compilerNode);if(n===void 0){const s=r.isFunctionDeclaration(e)?e.getSourceFile():e.getFirstAncestor(i=>r.isFunctionLikeDeclaration(i)||r.isArrowFunction(i))??e.getSourceFile(),c=t.getText();n=s.getDescendantsOfKind(p.Identifier).some(i=>i!==t&&i.getText()===c&&V(i)&&I(i)?.compilerNode===e.compilerNode),S.set(e.compilerNode,n)}return n},B=e=>{const t=new Map,o=new Set,n=new Set;for(const s of e){const c=s.getNameNode(),i=c?.getSymbol()?.compilerSymbol;c!==void 0&&i!==void 0&&(t.set(i,s.compilerNode),o.add(c.compilerNode),n.add(c.getText()))}return{bySymbol:t,nameNodes:o,spellings:n}},L=(e,t,o)=>{const{bySymbol:n,nameNodes:s,spellings:c}=B(t),i=new Map;for(const a of e.getDescendantsOfKind(p.Identifier)){if(!c.has(a.getText())||s.has(a.compilerNode)||y(a))continue;const l=E(a)?.compilerSymbol,d=l===void 0?void 0:n.get(l);d!==void 0&&i.set(d,[...i.get(d)??[],b(a,o)])}return i},R=(e,t)=>{const o=new Map(e.map(a=>[a.compilerNode,new Set])),n=new Set,s=a=>(o.get(a)?.size??0)+(n.has(a)?1:0),c=(a,l)=>{const d=s(a),m=o.get(a),u=l.kind==="helper"?l.declaration.compilerNode:void 0;l.kind==="export"&&m?.add(l.name);for(const v of u===void 0?[]:o.get(u)??[])m?.add(v);return(l.kind==="untracked"||u!==void 0&&n.has(u))&&n.add(a),s(a)!==d};let i=!0;for(;i;){i=!1;for(const[a,l]of t)for(const d of l)i=c(a,d)||i}return new Map([...o].map(([a,l])=>[a,{callers:[...l].toSorted((d,m)=>d.localeCompare(m)),untracked:n.has(a)}]))},$=e=>{const t=N.get(e.compilerNode);if(t!==void 0)return t;const o=T(e),n=P(o),s=o.filter(i=>!n.has(i.compilerNode)),c={exportNames:n,helperReach:s.length===0?new Map:R(s,L(e,s,n))};return N.set(e.compilerNode,c),c},J=e=>{const t=$(e.getSourceFile()),o=b(e,t.exportNames);switch(o.kind){case"export":return{kind:"export",name:o.name};case"helper":{const n=o.declaration.getName(),s=t.helperReach.get(o.declaration.compilerNode);if(n===void 0||s===void 0)throw new Error(`call-site attribution: helper at ${o.declaration.getSourceFile().getFilePath()} is not indexed`);return{callers:s.callers,kind:"helper",name:n,...s.untracked?{untracked:!0}:{}}}default:return{kind:"module"}}},_=(e,t)=>{const o=k(e).map(s=>t(s));return o.includes("public")?"public":o.length===0||o.includes(void 0)||e.kind==="helper"&&e.untracked===!0?void 0:"internal"},Q=(e,t)=>{const o=new Map(t.map(n=>[`${n.filePath}:${n.exportName}`,n.visibility]));return e.map(n=>{const s=_(n.scope,c=>o.get(`${n.file}:${c}`));return s===void 0?n:{...n,visibility:s}})},f=/^[$A-Z_a-z][\w$]*$/u,D=e=>f.test(e),W=e=>{const t=g(e);return t.length===0?r.isVariableDeclaration(e)&&e.getVariableStatement()?.hasExportKeyword()===!0?e.getName():void 0:t.find(o=>D(o))??e.getName()},U=e=>e.getVariableStatements().flatMap(t=>t.getDeclarations()).filter(t=>W(t)!==void 0),Y=(e,t)=>{if(r.isIdentifier(e.getNameNode()))return e.getVariableStatement()?.hasExportKeyword()===!0?e.getName():g(e).find(o=>t==="binding"?A(o):D(o))},H=(e,t)=>Number(f.test(t))-Number(f.test(e))||w(e,t);export{Y as a,U as b,J as c,W as d,K as e,I as f,Z as g,G as h,D as i,g as j,y as k,E as r,Q as w};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{m as b}from"./modules-CsA-QVJ6.mjs";import{r as E}from"./json-data-Chfs2Cz5.mjs";import{s as l}from"./paths-C-9fwEgQ.mjs";import{LUNORA_ERROR_CODES as P,objectSchema as g,validatorIrToJsonSchema as m}from"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{G as A}from"./shared-BXUKWh7t.mjs";const T="/_lunora/rest",x=["authorization","cf-access-jwt-assertion","cookie","payment-signature","x-payment"],v=["x-d1-bookmark","x-lunora-shard-key"],j=e=>[...x,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],O=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,$=(...e)=>{const t=[];for(const r of e)for(const n of r?.split(",")??[]){const s=n.trim().toLowerCase();s!==""&&!t.includes(s)&&t.push(s)}return t.length===0?void 0:t.join(", ")},k=(e,t)=>{const r=[t,`max-age=${String(O(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(O(e.staleWhileRevalidate))}`),r.join(", ")},N=e=>e.scope==="public"?$(e.vary,...j(e),...v):$(e.vary,...v),q=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)}},_=e=>{const t=q(e);if(t!==void 0)return`${T}/${t.namespace}/${t.name}`},C=e=>e==="query"?"GET":"POST",y="#/components/responses/LunoraError",R=/:([A-Za-z_$][\w$]*)/gu,w=e=>[...e.matchAll(R)].map(t=>t[1]),D=e=>e.replaceAll(R,"{$1}"),f=e=>e.kind==="optional"?e.inner??e:e,I=e=>{const t=new Set(w(e.path)),r=[];for(const[n,s]of Object.entries(e.searchParams)){const c=f(s);r.push({description:`Query parameter \`${n}\``,in:"query",name:n,required:s.kind!=="optional",schema:m(c)})}for(const[n,s]of Object.entries(e.params)){const c=f(s);r.push({description:`Path parameter \`${n}\``,in:t.has(n)?"path":"query",name:n,required:t.has(n)?!0:s.kind!=="optional",schema:m(c)})}return r},S=e=>e?{content:{"application/json":{schema:m(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."},L=(e,t)=>{const r=I(e),n={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${l(e.path)}`,responses:{200:S(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:y}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(n.parameters=r),Object.keys(e.body).length>0&&(n.requestBody={content:{"application/json":{schema:g(e.body)}},required:!0}),e.stream&&(n["x-lunora-stream"]="text/event-stream"),n},F=(e,t)=>{const r=`${l(e.filePath)}:${e.exportName}`,n={additionalProperties:!1,properties:{args:g(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:n}},required:!0},responses:{200:S(e.output),default:{$ref:y}},summary:`${e.kind}: ${r}`,tags:[t],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${r}`}},H=(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}},n={"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:k(r,r.scope),type:"string"}}};r.tag!==void 0&&(n["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const s=N(r);return s!==void 0&&(n.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:n}},M=(e,t)=>{const r=`${l(e.filePath)}:${e.exportName}`,n=_(r);if(n===void 0)return;const s=C(e.kind),c=s==="GET",i={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_${l(n)}`,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).",...H(e.expose?.cache,c?"get":"post")},default:{$ref:y}},summary:`${s} ${n}`,tags:[t],"x-lunora-function-kind":e.kind};if(c){const d=Object.entries(e.args).map(([u,h])=>{const o=f(h);return{description:`Argument \`${u}\` (JSON-encoded for non-string values).`,in:"query",name:u,required:h.kind!=="optional",schema:m(o)}});return d.length>0&&(i.parameters=d),{method:"get",operation:i,path:n}}return i.requestBody={content:{"application/json":{schema:g(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:i,path:n}},J=e=>{const t=e.version??"0.0.0",r=Object.create(null),n=o=>r[o]??Object.create(null),s=new Set,c=e.modules??[],i=o=>b(c,o);for(const o of e.httpRoutes){const a=D(o.path),p=n(a);p[o.method.toLowerCase()]=L(o,i(o.filePath)),r[a]=p,s.add(i(o.filePath))}const d=e.functions.filter(o=>o.visibility!=="internal"&&o.kind!=="stream");for(const o of d){const{operation:a,pathKey:p}=F(o,i(o.filePath));r[p]={post:a},s.add(i(o.filePath))}for(const o of d){if(o.expose?.rest!==!0)continue;const a=M(o,i(o.filePath));if(a===void 0)continue;const p=n(a.path);p[a.method]=a.operation,r[a.path]=p}const u=[...s].toSorted((o,a)=>o.localeCompare(a)).map(o=>({description:c.find(p=>p.name===o)?.description??`Operations declared in \`lunora/${o}\`.`,name:o}));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:P,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:Object.fromEntries(Object.entries(r).map(([o,a])=>[o,{...a}])),tags:u}},z=e=>`${JSON.stringify(J(e),void 0,2)}
|
|
2
|
+
`,K=e=>`${A}export const openApiSpec = ${E(e,"Record<string, unknown>")};
|
|
3
|
+
`;export{J as buildOpenApiDocument,z as emitOpenApi,K as emitOpenApiModule};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{SyntaxKind as c,Node as r}from"ts-morph";import{CAPABILITIES as f}from"./CAPABILITY_PROBES-DFsutD7g.mjs";import{bindingKeyName as p,listLunoraSourceFiles as g}from"./listLunoraSourceFiles-DRes9d5p.mjs";import{scanImportDeclaration as u,noSandboxUsage as l}from"./discoverSandboxUsage-Bjl8A_hj.mjs";const d="ctx",x=e=>{const t=new Set,n=new Set([d]),s=o=>{if(r.isObjectBindingPattern(o))for(const i of o.getElements()){const m=p(i);m&&t.add(m)}};for(const o of e.getDescendantsOfKind(c.BindingElement)){if(p(o)!==d)continue;const i=o.getNameNode();r.isIdentifier(i)?n.add(i.getText()):s(i)}const a=o=>r.isIdentifier(o)&&n.has(o.getText());for(const o of e.getDescendantsOfKind(c.PropertyAccessExpression))a(o.getExpression())&&t.add(o.getName());for(const o of e.getDescendantsOfKind(c.VariableDeclaration)){const i=o.getInitializer();i!==void 0&&a(i)&&s(o.getNameNode())}return t},E=e=>{if(e.isTypeOnly())return!0;if(r.isExportDeclaration(e)){const n=e.getNamedExports();return!e.isNamespaceExport()&&n.length>0&&n.every(s=>s.isTypeOnly())}const t=e.getNamedImports();return e.getDefaultImport()===void 0&&e.getNamespaceImport()===void 0&&t.length>0&&t.every(n=>n.isTypeOnly())},S=e=>{const t=new Set;for(const n of e.getDescendantsOfKind(c.CallExpression)){const[s]=n.getArguments();n.getExpression().getKind()===c.ImportKeyword&&(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s))&&t.add(s.getLiteralValue())}return t},y=e=>{const t=e.getImportDeclarations(),n=l();for(const s of t){const a=u(s);for(const o of Object.keys(n))n[o]||=a[o]}return{contextReads:x(e),dynamicImports:S(e),sandboxTools:n,valueImports:new Set([...t,...e.getExportDeclarations()].flatMap(s=>{const a=s.getModuleSpecifierValue();return a===void 0||E(s)?[]:[a]}))}},T=e=>{const t=new Set,n=new Set,s=l(),a=new Set;for(const o of e){for(const i of o.contextReads)t.add(i);for(const i of o.dynamicImports)n.add(i);for(const i of o.valueImports)a.add(i);for(const i of Object.keys(s))s[i]||=o.sandboxTools[i]}return{contextReads:t,dynamicImports:n,sandboxTools:s,valueImports:a}},I=e=>new Set(f.filter(({contextProperty:t,moduleSpecifier:n})=>e.valueImports.has(n)||t!==void 0&&e.contextReads.has(t)).map(({key:t})=>t)),N=new RegExp(String.raw`\b${d}\b`,"u"),b=new RegExp(String.raw`\b(?:${f.flatMap(({contextProperty:e})=>e===void 0?[]:[e]).join("|")})\b`,"u"),C=e=>N.test(e)&&b.test(e),D=(e,t)=>{const n=T(g(t).map(a=>y(e.getSourceFile(a)??e.addSourceFileAtPath(a)))),s=I(n);return Object.fromEntries(f.map(({key:a})=>[a,s.has(a)]))};export{I as capabilitiesUsedBy,x as contextPropertiesRead,D as discoverFeatureUsage,T as foldCapabilitySignals,C as mayReadCapabilityContext,y as sourceCapabilitySignals};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{w as a}from"./classify-procedure-call-OnJoKgqu.mjs";const l=s=>a(s,"use","rls");export{l as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as o}from"ts-morph";import{unwrapExpression as a}from"./listLunoraSourceFiles-DRes9d5p.mjs";import{a as u}from"./module-specifiers-WF8iAydP.mjs";const A=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},h=(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,x=(t,i,e)=>f(t).filter(r=>r.name===i).map(r=>r.call.getArguments()[0]).filter(r=>r!==void 0&&o.isCallExpression(r)&&h(r.getExpression(),e)),w=(t,i)=>f(t).some(e=>e.name===i),P=(t,i,e)=>x(t,i,e).length>0,l=new Set(["action","mutation","query","stream"]),m={internalAction:"action",internalMutation:"mutation",internalQuery:"query"},N={onConnect:"connect",onDisconnect:"disconnect",onQueryChange:"reactor",onShardInit:"init",onWhisper:"whisper"},I=t=>t==="whisper"?"query":"mutation",C=t=>{const{root:i}=p(t);return i&&o.isIdentifier(i)?i:void 0},g=(t,i=!1)=>{const e=C(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},E=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}},D=t=>{const i=t.getExpression();if(o.isPropertyAccessExpression(i))return E(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=N[e];if(n)return{kind:I(n),lifecycle:n,visibility:"internal"}};export{A as a,f as b,D as c,P as d,w as e,x as w};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as i}from"ts-morph";import{listLunoraSourceFiles as a,lunoraRelativePath as c,handlerOf as l}from"./listLunoraSourceFiles-DRes9d5p.mjs";import{b as d,d as f}from"./attribution-sW_DHmLO.mjs";import{c as u}from"./context-root-KWXRWlv6.mjs";import{c as m}from"./classify-procedure-call-OnJoKgqu.mjs";const p=t=>{const r=t.getInitializer();if(!r||!i.isCallExpression(r))return;const e=m(r);if(!e||e.kind!=="query"&&e.kind!=="mutation")return;const o=l(r,e.receiver);return o?{exportName:f(t)??t.getName(),handler:o,kind:e.kind}:void 0},x=(t,r)=>{const e=t.getParent();return e&&i.isPropertyAccessExpression(e)&&e.getExpression()===t?`ctx.${r}.${e.getName()}`:`ctx.${r}`},h=(t,r,e)=>{const o=[];for(const n of u(t.handler,e))o.push({callee:x(n,e),exportName:t.exportName,file:r,kind:t.kind,line:n.getStartLineNumber()});return o},N=(t,r,e)=>{const o=[];for(const n of d(t)){const s=p(n);s&&o.push(...h(s,r,e))}return o},F=(t,r,e)=>{const o=[];for(const n of a(r)){const s=t.getSourceFile(n)??t.addSourceFileAtPath(n);o.push(...N(s,c(r,n),e))}return o};export{F as d};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as s,SyntaxKind as d}from"ts-morph";import{unwrapExpression as l,memberAccessOf as P,bindingKeyName as C,findObjectProperty as p,isConstDeclaration as D,walkChain as A}from"./listLunoraSourceFiles-DRes9d5p.mjs";import{f as v,g as I,h as M}from"./attribution-sW_DHmLO.mjs";import{c as F}from"./classify-procedure-call-OnJoKgqu.mjs";import{isDefineMutatorCallee as b}from"./MUTATORS_FILENAME-D1Q6EUII.mjs";const x=8,E=t=>{if(s.isMethodDeclaration(t))return t;const e=s.isPropertyAssignment(t)?l(t.getInitializer()):void 0,o=s.isShorthandPropertyAssignment(t)?t.getNameNode():e;if(s.isArrowFunction(o)||s.isFunctionExpression(o))return o;const i=s.isIdentifier(o)?v(o):void 0;if(s.isFunctionDeclaration(i))return i;const n=D(i)?l(i.getInitializer()):void 0;return s.isArrowFunction(n)||s.isFunctionExpression(n)?n:void 0},w=t=>{const e=l(t.getArguments()[0]),o=s.isObjectLiteralExpression(e)?e:void 0,i=p(o,"server"),n=p(o,"handler"),r=i!==void 0&&b(t.getExpression()),a=n===void 0?void 0:F(t),u=a!==void 0&&a.receiver===void 0;return[r?E(i):void 0,u?E(n):void 0].filter(f=>f!==void 0)},h=new WeakMap,O=t=>{const e=t.getSourceFile(),o=h.get(e.compilerNode);if(o!==void 0)return o;const i=new Set(e.getDescendantsOfKind(d.CallExpression).flatMap(n=>w(n)).map(n=>n.compilerNode));return h.set(e.compilerNode,i),i},S=t=>{const e=t.getParent();return(s.isArrowFunction(e)||s.isFunctionExpression(e)||s.isFunctionDeclaration(e)||s.isMethodDeclaration(e))&&e.getParameters()[0]===t&&O(t).has(e.compilerNode)},G=t=>{const e=t.getParent();return(s.isArrowFunction(e)||s.isFunctionExpression(e)||s.isFunctionDeclaration(e)||s.isMethodDeclaration(e))&&e.getParameters()[1]===t&&O(t).has(e.compilerNode)},T=t=>t.getNameNode().getDescendantsOfKind(d.BindingElement).some(e=>e.getParent().getParent()===t&&["args","ctx"].includes(C(e))),g=(t,e,o)=>{const i=t.getParent().getParent(),n=C(t);if(t.getDotDotDotToken()!==void 0||e==="trust"&&I(t))return;let r;if(s.isParameterDeclaration(i)){if(!S(i)||T(i))return n==="ctx"?[]:void 0;r=[]}else s.isBindingElement(i)?r=g(i,e,o):s.isVariableDeclaration(i)&&o>0&&(r=c(i.getInitializer(),e,o-1));return r===void 0?void 0:[...r,n]},c=(t,e="discover",o=x)=>{const i=l(t),n=P(i);if(n!==void 0){const r=c(n.object,e,o);return r===void 0?void 0:[...r,n.member]}return s.isIdentifier(i)?B(i,e,o):void 0},B=(t,e,o)=>{const i=t.getText()==="ctx",n=e==="trust"||!i?v(t):void 0;return i&&!s.isVariableDeclaration(n)?s.isBindingElement(n)?g(n,e,o):[]:s.isParameterDeclaration(n)?s.isIdentifier(n.getNameNode())&&S(n)?[]:void 0:s.isBindingElement(n)?g(n,e,o):!(s.isVariableDeclaration(n)&&s.isIdentifier(n.getNameNode())&&o>0)||e==="trust"&&I(n)?void 0:c(n.getInitializer(),e,o-1)},Q=t=>c(t,"discover"),H=t=>{const e=c(t);return e===void 0?void 0:["ctx",...e].join(".")},q=(t,e)=>{if(e(t.getText()))return!0;const o=H(t);return o!==void 0&&e(o)},J=(t,e)=>{const o=l(t),i=P(o);if(i!==void 0&&i.member!==e.at(-1))return!1;const n=o===void 0?void 0:c(o);return n?.length===e.length&&n.every((r,a)=>r===e[a])},Y=(t,e)=>U(t).get(e)??[],K=t=>{const e=new Map;for(const i of t.getDescendantsOfKind(d.BindingElement)){const n=s.isIdentifier(i.getNameNode())?g(i,"discover",x):void 0;n?.length===1&&n[0]!==void 0&&e.set(i.compilerNode,n[0])}const o=new Set([...e.keys()].map(i=>i.name.getText()));return t.getDescendantsOfKind(d.Identifier).flatMap(i=>{const r=o.has(i.getText())&&!s.isBindingElement(i.getParent())?v(i):void 0,a=r===void 0?void 0:e.get(r.compilerNode);return a===void 0?[]:[[a,i]]})},N=new WeakMap,U=t=>{const e=N.get(t.compilerNode);if(e!==void 0)return e;const o=new Map;for(const[n,r]of[...y(t),...K(t)])o.set(n,[...o.get(n)??[],r]);const i=new Map([...o].map(([n,r])=>[n,r.toSorted((a,u)=>a.getPos()-u.getPos())]));return N.set(t.compilerNode,i),i},y=t=>t.getDescendantsOfKind(d.PropertyAccessExpression).flatMap(e=>z(e.getExpression())?[[e.getName(),e]]:[]),z=t=>s.isIdentifier(t)&&c(t)?.length===0,Z=t=>{const e=c(t);return e?.length===1&&e[0]==="db"},_=new Set(["asId","createMultipartUpload","fetch","generateUploadUrl","getPresignedUrl","getSignedUrl","getUrl","normalizeId","resumeMultipartUpload","runAction","runMutation","runQuery","store","upload"]),R=new Set(["catch","flatMap","map","reduce","reduceRight","then"]),k=(t,e=x)=>{const o=A(t,u=>{const f=l(u.getExpression()),m=s.isPropertyAccessExpression(f)?f.getName():void 0;return m!==void 0&&(_.has(m)||R.has(m))?!1:void 0}),i=o.root;if(o.verdict!==void 0||!s.isIdentifier(i))return o.verdict??!1;if(c(i,"trust")!==void 0)return!0;const n=v(i),r=s.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n,a=D(r)&&e>0?r.getInitializer():void 0;return a!==void 0&&k(a,e-1)},$=t=>(s.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(o=>M(o)&&c(o,"trust")!==void 0);export{R as C,_ as E,G as a,H as b,Y as c,Z as d,Q as e,k as f,z as g,J as i,q as m,$ as r};
|