@lunora/codegen 1.0.0-alpha.401 → 1.0.0-alpha.403

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/index.d.mts +87 -2
  2. package/dist/index.d.ts +87 -2
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/{AGENTS_FILENAME-Cli3X44r.mjs → AGENTS_FILENAME-D0Y0_UgB.mjs} +1 -1
  5. package/dist/packem_shared/{ALL_NOTIFY_CHANNELS-D1SaOfnm.mjs → ALL_NOTIFY_CHANNELS-CtrsBtZX.mjs} +1 -1
  6. package/dist/packem_shared/{CONTAINERS_FILENAME-BX1_ALLp.mjs → CONTAINERS_FILENAME-J-e3Vanb.mjs} +1 -1
  7. package/dist/packem_shared/DEFAULT_TARGET-CVYzxQ0y.mjs +1 -0
  8. package/dist/packem_shared/{FLAGS_FILENAME-DY3yo1u_.mjs → FLAGS_FILENAME-6RzszxVW.mjs} +1 -1
  9. package/dist/packem_shared/{MUTATORS_FILENAME-Ck_l1lz7.mjs → MUTATORS_FILENAME-C3OImAxC.mjs} +1 -1
  10. package/dist/packem_shared/{OPENRPC_VERSION-CCp_wKFT.mjs → OPENRPC_VERSION-UNYmA7Ty.mjs} +1 -1
  11. package/dist/packem_shared/{QUEUES_FILENAME-C5xotY-M.mjs → QUEUES_FILENAME-Ba-sK5Ek.mjs} +1 -1
  12. package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-BIELlQsc.mjs → SCHEMA_SNAPSHOT_FILENAME-Cuhl5Xbr.mjs} +15 -13
  13. package/dist/packem_shared/{SHAPES_FILENAME-DCtGHMEm.mjs → SHAPES_FILENAME-CH0KrAdb.mjs} +1 -1
  14. package/dist/packem_shared/{WORKFLOWS_FILENAME-CyV1HQaP.mjs → WORKFLOWS_FILENAME-DfVfBum_.mjs} +1 -1
  15. package/dist/packem_shared/{attribution-DjweYNgJ.mjs → attribution-BhGR_h0Z.mjs} +1 -1
  16. package/dist/packem_shared/{buildOpenApiDocument-B1PEHSSc.mjs → buildOpenApiDocument-B8KEeeRr.mjs} +1 -1
  17. package/dist/packem_shared/{capabilitiesUsedBy-SSrieNZ1.mjs → capabilitiesUsedBy-BwhaHK08.mjs} +1 -1
  18. package/dist/packem_shared/chain-CXiqZFUk.mjs +1 -0
  19. package/dist/packem_shared/{classify-procedure-call-BuF5PNwV.mjs → classify-procedure-call-BZ164dkJ.mjs} +1 -1
  20. package/dist/packem_shared/companionServiceBinding-BZjm486n.mjs +1 -0
  21. package/dist/packem_shared/{context-property-calls-BcUYQ6ph.mjs → context-property-calls-Ggrmu3UL.mjs} +1 -1
  22. package/dist/packem_shared/{context-root-2wag3akK.mjs → context-root-DnvrQxae.mjs} +1 -1
  23. package/dist/packem_shared/{createCodegenProject-C8N4Zm8h.mjs → createCodegenProject-Cfr1xHPC.mjs} +1 -1
  24. package/dist/packem_shared/{database-calls-B_85LJIk.mjs → database-calls-BRI5W-Mp.mjs} +1 -1
  25. package/dist/packem_shared/{discoverAuthApiCalls-f8_WRQEA.mjs → discoverAuthApiCalls-ENLGem4M.mjs} +1 -1
  26. package/dist/packem_shared/{discoverCrons-DTqSuSDh.mjs → discoverCrons-DWVXmktw.mjs} +1 -1
  27. package/dist/packem_shared/discoverFunctions-mAWlAiuj.mjs +1 -0
  28. package/dist/packem_shared/{discoverHttpRoutes-2gxHuLgt.mjs → discoverHttpRoutes-CAoEemno.mjs} +1 -1
  29. package/dist/packem_shared/discoverHyperdriveCalls-BaRayTZe.mjs +1 -0
  30. package/dist/packem_shared/{discoverInserts-CLh70kVu.mjs → discoverInserts-DmSa4WKU.mjs} +1 -1
  31. package/dist/packem_shared/discoverMaskProcedures-CyjXtZgc.mjs +1 -0
  32. package/dist/packem_shared/{discoverMigrations-e5_NQdf-.mjs → discoverMigrations-Duh6HVG3.mjs} +1 -1
  33. package/dist/packem_shared/{discoverNondeterministicCalls-CrXAegUc.mjs → discoverNondeterministicCalls-BoF6ob-B.mjs} +1 -1
  34. package/dist/packem_shared/{discoverQueries-T8b_7ZZ-.mjs → discoverQueries-spxu-wHR.mjs} +1 -1
  35. package/dist/packem_shared/discoverR2sqlCalls-CZjqFVi_.mjs +1 -0
  36. package/dist/packem_shared/{discoverRlsMetadata-CnVvP2Ps.mjs → discoverRlsMetadata-Cc0zA-gZ.mjs} +1 -1
  37. package/dist/packem_shared/{discoverRlsProcedures-DttY0Jld.mjs → discoverRlsProcedures-mjiA0I4S.mjs} +1 -1
  38. package/dist/packem_shared/{discoverSandboxUsage-X0SECo-x.mjs → discoverSandboxUsage-Ccy9n7G1.mjs} +1 -1
  39. package/dist/packem_shared/discoverSchema-ynieYB0n.mjs +1 -0
  40. package/dist/packem_shared/{discoverStorageRulesMetadata-t_oMSn0L.mjs → discoverStorageRulesMetadata-CtE5trUR.mjs} +1 -1
  41. package/dist/packem_shared/{emitApp-BrOgH7YU.mjs → emitApp-C3IUdkkt.mjs} +37 -28
  42. package/dist/packem_shared/{exported-procedure-chains-BaxQ8C-S.mjs → exported-procedure-chains-h8Y7xDjq.mjs} +1 -1
  43. package/dist/packem_shared/{fingerprintSchemaSources-PmhepCVj.mjs → fingerprintSchemaSources-C8H1wOcH.mjs} +1 -1
  44. package/dist/packem_shared/{handler-reference-D2EE2q-4.mjs → handler-reference-DpIVI5BM.mjs} +1 -1
  45. package/dist/packem_shared/index-jtzAVdUp.mjs +1 -0
  46. package/dist/packem_shared/{index-Dd6T5nSP.mjs → index-mFEIaT45.mjs} +1 -1
  47. package/dist/packem_shared/{ip-reads-WFubgB1G.mjs → ip-reads-BPDWkzEu.mjs} +1 -1
  48. package/dist/packem_shared/isTestPath-DRIdZaij.mjs +1 -0
  49. package/dist/packem_shared/loadProjectConfig-BXwH3_gn.mjs +1 -0
  50. package/dist/packem_shared/{modules-DE0ksIeR.mjs → modules-Qpm_zqz4.mjs} +1 -1
  51. package/dist/packem_shared/project-config-file-DR7xrrNB.mjs +1 -0
  52. package/dist/packem_shared/{unwrap-handler-return-BpigsVD6.mjs → unwrap-handler-return-DUzluwPj.mjs} +1 -1
  53. package/package.json +1 -1
  54. package/dist/packem_shared/DEFAULT_TARGET-C-gcdslJ.mjs +0 -1
  55. package/dist/packem_shared/chain-DWwd9wXd.mjs +0 -1
  56. package/dist/packem_shared/companionServiceBinding-ChINWo8k.mjs +0 -1
  57. package/dist/packem_shared/discoverFunctions-D4GIaVIP.mjs +0 -1
  58. package/dist/packem_shared/discoverHyperdriveCalls-DaJLewG0.mjs +0 -1
  59. package/dist/packem_shared/discoverMaskProcedures-C0VcUGpb.mjs +0 -1
  60. package/dist/packem_shared/discoverR2sqlCalls-CY0xmIWX.mjs +0 -1
  61. package/dist/packem_shared/discoverSchema-DDvMQheA.mjs +0 -1
  62. package/dist/packem_shared/index-fVYBrxkP.mjs +0 -1
  63. package/dist/packem_shared/isTestPath-ClgKgMYM.mjs +0 -1
  64. package/dist/packem_shared/loadProjectConfig-CtcJHHKS.mjs +0 -1
  65. package/dist/packem_shared/static-literal-BwDHHjEJ.mjs +0 -1
@@ -1 +0,0 @@
1
- import"./declared-output-Iaar469J.mjs";import"./isTestPath-ClgKgMYM.mjs";import"./attribution-DjweYNgJ.mjs";import"./unwrap-handler-return-BpigsVD6.mjs";import"./ip-reads-WFubgB1G.mjs";import"./classify-procedure-call-BuF5PNwV.mjs";import{d as f}from"./index-fVYBrxkP.mjs";import"./dispatch-namespace-DwTjD7BU.mjs";export{f as default};
@@ -1 +0,0 @@
1
- import{d as o}from"./context-property-calls-BcUYQ6ph.mjs";const t=(r,e)=>o(r,e,"sql");export{t as default};
@@ -1 +0,0 @@
1
- import"./isTestPath-ClgKgMYM.mjs";import"./attribution-DjweYNgJ.mjs";import"./database-calls-B_85LJIk.mjs";import"./classify-procedure-call-BuF5PNwV.mjs";import{d as a}from"./index-Dd6T5nSP.mjs";export{a as default};
@@ -1 +0,0 @@
1
- import{d as r}from"./context-property-calls-BcUYQ6ph.mjs";const t=(s,o)=>r(s,o,"r2sql");export{t as default};
@@ -1 +0,0 @@
1
- import{LunoraError as q}from"@lunora/errors";import{Node as a,SyntaxKind as J}from"ts-morph";import{diagnosticAt as d}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{findObjectProperty as m,descendantsOfKind as U}from"./isTestPath-ClgKgMYM.mjs";import{createRequire as W}from"node:module";import{join as N}from"node:path";import{fileURLToPath as K}from"node:url";import{createJiti as H}from"jiti";import{l as X,N as Z}from"./static-literal-BwDHHjEJ.mjs";import{r as G,p as Q}from"./parse-validator-BisfC8bR.mjs";import{R as Y}from"./reserved-words-CW1QFbTd.mjs";import{a as k}from"./property-name-7cBlgK_O.mjs";const ee=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,te=e=>{switch(typeof e){case"bigint":return e.toString();case"boolean":case"number":return String(e);case"string":return JSON.stringify(e);default:return e===null?"null":void 0}},ne=e=>({...e?.defaultValue!==void 0||e?.defaultFn!==void 0||e?.serverDefault!==void 0?{hasDefault:!0}:{},...e?.onUpdateFn===void 0?{}:{hasOnUpdate:!0},notNull:e?.notNull??!0,...e?.unique===!0?{unique:!0}:{}}),p=e=>{const t=e?._meta??{},n=e?.kind??"unknown",r={column:ne(t.column),kind:n,...t.sensitive===!0?{sensitive:!0}:{}};switch(n){case"array":case"optional":{r.inner=p(t.inner);break}case"from":break;case"id":{r.tableName=t.tableName;break}case"literal":{r.literalValue=te(t.value);break}case"object":{const i=t.shape??{};r.shape=Object.fromEntries(Object.entries(i).map(([o,l])=>[o,p(l)]));break}case"record":{r.valueType=p(t.valueValidator),t.keyValidator!==void 0&&(r.keyType=p(t.keyValidator));break}case"storage":{typeof t.bucket=="string"&&(r.bucket=t.bucket);break}case"union":{const i=t.members??[];r.members=i.map(o=>p(o));break}}const s=t.constraints;return s!==void 0&&Object.keys(s).length>0&&(r.hasRefinement=!0,n==="string"&&typeof s.maxLength=="number"&&(r.stringMaxLength=s.maxLength)),r},re=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",se=e=>{const t=r=>typeof e[r]=="string"?e[r]:void 0,n=Array.isArray(e.columns)?e.columns.filter(r=>typeof r=="string"):void 0;return{binding:t("binding")??"",...n===void 0?{}:{columns:n},hasReconcile:e.reconcileEveryMs!==void 0,hasSoftDelete:e.softDeleteColumn!==void 0,hasTenantBy:e.tenantBy!==void 0,...t("idColumn")===void 0?{}:{idColumn:t("idColumn")},...t("mode")===void 0?{}:{mode:t("mode")},...t("query")===void 0?{}:{query:t("query")}}},ie=(e,t)=>{const n=e.shape??{},r=(e.indexes??[]).map(i=>({fields:i.fields,name:i.name,...i.unique?{unique:!0}:{}})),s=re(e.shardMode);return{...e.aggregateIndexes&&e.aggregateIndexes.length>0?{aggregateIndexed:!0}:{},...e.commitOrderedMode===!0?{commitOrdered:!0}:{},...e.isExternallyManaged?{externallyManaged:!0}:{},...e.externalSource?{externalSource:se(e.externalSource)}:{},...e.isPublic===!0?{isPublic:!0}:{},geoIndexes:(e.geoIndexes??[]).map(({field:i,name:o,precision:l})=>({field:i,name:o,...l===void 0?{}:{precision:l}})),...s==="global"?{globalBackend:e.shardMode?.backend==="hyperdrive"?"hyperdrive":"d1"}:{},indexes:r,...e.memoryMode===!0?{memory:!0}:{},name:t,rankIndexes:(e.rankIndexes??[]).map(({name:i,partitionBy:o,sortBy:l})=>({name:i,...o===void 0?{}:{partitionBy:o},sortBy:l.map(({direction:c,field:u})=>({direction:c,field:u}))})),relations:Object.entries(e.relationMap??{}).map(([i,o])=>o.through!==void 0?{kind:"many",name:i,table:o.table,through:{...o.through}}:{field:o.field,kind:o.kind,name:i,...o.onDelete===void 0?{}:{onDelete:o.onDelete},references:o.references,table:o.table}),searchIndexes:(e.searchIndexes??[]).map(i=>({field:i.field,...i.filterFields?{filterFields:i.filterFields}:{},...i.language===void 0?{}:{language:i.language},...i.staged===void 0?{}:{staged:i.staged},...i.strategy===void 0?{}:{strategy:i.strategy},name:i.name})),shape:Object.fromEntries(Object.entries(n).map(([i,o])=>[i,p(o)])),shardMode:s,...e.softDeleteMode?{softDelete:{field:e.softDeleteMode.field}}:{},...e.ttlPolicy?{ttl:{field:e.ttlPolicy.field,...e.ttlPolicy.after===void 0?{}:{after:e.ttlPolicy.after}}}:{},vectorIndexes:(e.vectorIndexes??[]).map(i=>({...i.dimensions===void 0?{}:{dimensions:i.dimensions},field:i.field,...i.metadata===void 0?{}:{metadata:i.metadata},...i.metric===void 0?{}:{metric:i.metric},name:i.name,table:t}))}},oe=e=>{const{key:t,tables:n}=e;if(typeof t!="string"||typeof n!="object"||n===null)return;const r=Object.entries(n).map(([o,l])=>ie(l,o)),s=e.vectorIndexes??{},i=Object.entries(s??{}).map(([o,l])=>({...l.dimensions===void 0?{}:{dimensions:l.dimensions},...l.field===void 0?{}:{field:l.field},...l.metadata===void 0?{}:{metadata:l.metadata},...l.metric===void 0?{}:{metric:l.metric},name:o,table:l.table??""}));return{bareTables:r,bareVectorIndexes:i,key:t}},ae=e=>{if(a.isIdentifier(e))return e.getText();if(a.isPropertyAccessExpression(e)){const t=e.getExpression();return a.isIdentifier(t)?t.getText():void 0}},le=e=>{const t=ae(e);if(t===void 0)return;const n=a.isPropertyAccessExpression(e)?e.getName():void 0,r=n===void 0?[]:[n];for(const s of e.getSourceFile().getImportDeclarations()){const i=s.getModuleSpecifierValue();for(const o of s.getNamedImports())if((o.getAliasNode()?.getText()??o.getName())===t)return{importedName:o.getName(),moduleSpecifier:i,propertyPath:r};if(s.getDefaultImport()?.getText()===t)return{importedName:"default",moduleSpecifier:i,propertyPath:r};if(s.getNamespaceImport()?.getText()===t&&n!==void 0)return{importedName:n,moduleSpecifier:i,propertyPath:[]}}},j=e=>a.isCallExpression(e)?e:a.isParenthesizedExpression(e)||a.isAsExpression(e)||a.isSatisfiesExpression(e)?j(e.getExpression()):void 0,ce=(e,t,n)=>{const r=n.getSymbol()?.compilerSymbol,s=i=>r!==void 0&&i?.getSymbol()?.compilerSymbol===r;return a.isPropertyAccessExpression(t)?s(e.getNamespaceImport())?t.getName():void 0:s(e.getDefaultImport())?"default":e.getNamedImports().find(i=>s(i.getAliasNode()??i.getNameNode()))?.getName()},de=e=>{if(!a.isPropertyAccessExpression(e)||!a.isIdentifier(e.getExpression()))return;const t=e.getExpression().getSymbol(),n=(t?.getAliasedSymbol()??t)?.getValueDeclaration(),r=a.isVariableDeclaration(n)?n.getInitializer():void 0,s=r===void 0?void 0:j(r),i=s?.getExpression(),o=i!==void 0&&a.isPropertyAccessExpression(i)?i.getExpression():i;if(s===void 0||i===void 0||o===void 0||!a.isIdentifier(o))return;const l=s.getArguments().map(u=>X(u)),c=s.getReturnType().getProperty(e.getName())?.getTypeAtLocation(s).getNonNullableType();if(!(l.includes(Z)||c?.getProperty("tables")===void 0))for(const u of s.getSourceFile().getImportDeclarations()){const h=u.getModuleSpecifierValue();if(h.startsWith("."))continue;const y=ce(u,i,o);if(y!==void 0)return{args:l,importedName:y,moduleSpecifier:h,propertyPath:[e.getName()]}}},$=(e,t)=>{let n=e;for(const r of t){if(typeof n!="object"||n===null)return;n=n[r]}return n},fe=(e,t)=>$(e[t.importedName],t.propertyPath),P=(e,t)=>{const n=H(N(t,"noop.js")).esmResolve(e);return W(N(t,"noop.cjs"))(n.startsWith("file:")?K(n):n)},ue=(e,t)=>{const n=le(e);if(n&&!n.moduleSpecifier.startsWith("."))return fe(P(n.moduleSpecifier,t),n);const r=de(e);if(!r)return;const s=P(r.moduleSpecifier,t)[r.importedName];return typeof s=="function"?$(s(...r.args),r.propertyPath):void 0},me=(e,t)=>{try{const n=ue(e,t);return typeof n!="object"||n===null?void 0:oe(n)}catch{return}},ge=new Set(["cosine","dot-product","euclidean"]),x=(e,t)=>{const n=m(e,t);if(n&&a.isPropertyAssignment(n))return n.getInitializer()},f=(e,t)=>{const n=x(e,t);if(n&&a.isStringLiteral(n))return n.getLiteralText()},E=(e,t)=>{const n=x(e,t);if(n&&a.isNumericLiteral(n))return Number(n.getLiteralText())},D=(e,t)=>{const n=x(e,t);if(n&&(a.isTrueLiteral(n)||a.isFalseLiteral(n)))return n.getLiteralValue()},I=(e,t)=>{const n=x(e,t);if(n&&a.isArrayLiteralExpression(n))return n.getElements().filter(r=>a.isStringLiteral(r)).map(r=>r.getLiteralText())},z=e=>e&&ge.has(e)?e:void 0,S=e=>e&&a.isStringLiteral(e)?e.getLiteralText():"_unnamed_",pe=(e,t)=>{const n=I(e,t);return n!==void 0&&n.length>0?n:void 0},M=(e,t,n,r,s)=>{let i=e;for(;;){const o=i.getParent();if(!o||!a.isPropertyAccessExpression(o))break;const l=o.getParent();if(!l||!a.isCallExpression(l))break;if(o.getName()===t){const c=l.getArguments()[0];if(!c||!a.isStringLiteral(c))throw d(l,`\`.${t}(...)\` expects a string literal (${s})`);const u=c.getLiteralText();if(!r.has(u))throw d(c,`unknown ${n} ${JSON.stringify(u)} — expected ${s}`);return u}i=l}},he=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,be=/^(?:sqlite_|_cf_|__)/u,xe=/__(?:agg|rank|geo|fts)_/u,ye=e=>be.test(e)||xe.test(e),ve=new Set(["cascade","restrict","set null"]),Ee=new Set(["aggregate","asId","assertPatchAllowed","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteRereadTables","deleteWhere","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","inTransaction","lookupById","normalizeId","patch","patchIf","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","relationWrites","replace","restore","softDeleteFields","system","wipeShard"]),R=/^[A-Za-z_$][\w$]*$/u,T=(e,t)=>{if(Ee.has(e))throw d(t,`table name "${e}" is reserved — the generated shard binds each table's facade onto the same object that carries \`ctx.db\`'s own members, so this table would overwrite \`ctx.db.${e}\` and every use of it would break. Rename the table.`);if(Y.has(e))throw d(t,`table name "${e}" is a reserved JavaScript word — codegen interpolates table names into a bare \`const ${e} = sqliteTable(...)\` binding in the generated Drizzle module, which is a syntax error for a keyword. Rename the table.`);if(!R.test(e))throw d(t,`table name ${JSON.stringify(e)} is not a valid JS identifier — table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the table.`);if(ye(e))throw d(t,`table name ${JSON.stringify(e)} is reserved for framework tables — a leading \`__\` and the \`__agg_\`/\`__rank_\`/\`__geo_\`/\`__fts_\` infixes name Lunora's own bookkeeping and index companions, so the Studio and the admin API hide and refuse such a table. Rename the table.`)},Ie=e=>e&&ve.has(e)?e:void 0,Se=e=>{if(!a.isArrowFunction(e))return;let t=e.getBody();if(a.isParenthesizedExpression(t))t=t.getExpression();else if(a.isBlock(t)){const n=t.getStatements().find(r=>a.isReturnStatement(r));t=n&&a.isReturnStatement(n)?n.getExpression()??t:t}return a.isObjectLiteralExpression(t)?t:void 0},we=(e,t,n)=>{const r=a.isPropertyAssignment(e)?e.getInitializer():void 0;if(!r||!a.isObjectLiteralExpression(r))throw d(e,"relation `through` must be an object literal `{ table, from, to }` — codegen resolves it statically.");const[s,i,o]=["table","from","to"].map(l=>f(r,l));if(s===void 0||i===void 0||o===void 0)throw d(r,"relation `through` needs string-literal `table`, `from` and `to` — codegen resolves them statically.");if(i===o)throw d(r,`relation \`through\` has \`from\` and \`to\` both set to "${i}"; a link needs two different columns.`);return{kind:"many",name:t,table:n,through:{from:i,table:s,to:o}}},ke=(e,t,n,r)=>{const s=r&&a.isObjectLiteralExpression(r)?r:void 0,i=e==="many"?s?.getProperty("through"):void 0;return i?we(i,t,n):{field:(s&&f(s,"field"))??"_unknown_",kind:e,name:t,onDelete:e==="one"&&s?Ie(f(s,"onDelete")):void 0,references:(s&&f(s,"references"))??"_id",table:n}},Te=e=>{if(!a.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!a.isCallExpression(t))return;const n=t.getExpression();if(!a.isPropertyAccessExpression(n))return;const r=n.getName();if(r!=="one"&&r!=="many")return;const[s,i]=t.getArguments();if(!s||!a.isStringLiteral(s))throw d(s??t,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${s?s.getText():"no argument"}.`);const o=s.getLiteralText();return ke(r,k(e),o,i)},Ae=e=>{const t=Se(e);if(!t)return[];const n=[];for(const r of t.getProperties()){const s=Te(r);s&&n.push(s)}return n},Oe=(e,t,n)=>{if(!t.includes("."))return;const[r="",...s]=t.split("."),i=`${r}${s.map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join("")}`;throw d(e,`index "${n}" indexes the nested path ${JSON.stringify(t)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${i}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`,{code:"INDEX_FIELD_NESTED_PATH",name:"LunoraError",status:500})},Ne=e=>{if(!e||!a.isObjectLiteralExpression(e))return!1;const t=m(e,"unique");if(!t||!a.isPropertyAssignment(t))return!1;const n=t.getInitializer();if(n===void 0)return!1;if(!a.isTrueLiteral(n)&&!a.isFalseLiteral(n))throw d(n,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(n.getText())}`);return a.isTrueLiteral(n)},Pe=e=>{const[t,n,r]=e,s=Ne(r),i=S(t),o=n&&a.isArrayLiteralExpression(n)?n.getElements():[];for(const c of o)if(!a.isStringLiteral(c))throw d(c,`index "${i}" lists a non-literal field (${JSON.stringify(c.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=o.filter(c=>a.isStringLiteral(c));for(const c of l)Oe(c,c.getLiteralText(),i);return{fields:l.map(c=>c.getLiteralText()),name:i,unique:s}},_e=e=>{const[t,n]=e;let r="_unknown_",s,i,o,l;return n&&a.isObjectLiteralExpression(n)&&(r=f(n,"field")??r,s=I(n,"filterFields"),i=f(n,"language"),o=D(n,"staged"),l=f(n,"strategy")),{field:r,filterFields:s,language:i,name:S(t),staged:o,strategy:l}},Le=e=>{const[t,n]=e;let r="_unknown_",s;return n&&a.isObjectLiteralExpression(n)&&(r=f(n,"field")??r,s=E(n,"precision")),{field:r,name:S(t),precision:s}},je=e=>{const[t,n]=e,r=t&&a.isStringLiteral(t)?t.getLiteralText():"_unknown_";let s;return n&&a.isObjectLiteralExpression(n)&&(s=E(n,"after")),{after:s,field:r}},$e=e=>{if(!a.isObjectLiteralExpression(e))return;const t=f(e,"field");return t===void 0?void 0:{direction:f(e,"direction")==="desc"?"desc":"asc",field:t}},De=e=>{const[t,n]=e;let r=[],s;if(n&&a.isObjectLiteralExpression(n)){const i=m(n,"sortBy");if(i&&a.isPropertyAssignment(i)){const o=i.getInitializer();o&&a.isArrayLiteralExpression(o)&&(r=o.getElements().map(l=>$e(l)).filter(l=>l!==void 0))}s=I(n,"partitionBy")}return{name:S(t),partitionBy:s,sortBy:r}},ze=(e,t)=>{const[n,r]=e,s=n&&a.isStringLiteral(n)?n.getLiteralText():"_unknown_";if(!(!r||!a.isObjectLiteralExpression(r)))return{dimensions:E(r,"dimensions"),field:s,metadata:I(r,"metadata"),metric:z(f(r,"metric")),name:f(r,"index")??"_unnamed_",table:t}},Me=e=>{const t=e[0];return t&&a.isObjectLiteralExpression(t)&&f(t,"backend")==="hyperdrive"?"hyperdrive":"d1"},_=(e,t)=>{if(e===void 0)return t;if(!a.isObjectLiteralExpression(e))throw d(e,"the options must be an object literal — codegen reads the column name from the source and cannot evaluate a variable or an expression here.");const n=m(e,"field");if(n===void 0)return t;const r=a.isPropertyAssignment(n)?n.getInitializer():void 0;if(r&&a.isStringLiteral(r))return r.getLiteralText();throw d(n,"`field` must be a string literal — codegen reads the column name from the source and cannot evaluate a constant or an expression here.")},Re=e=>{const t=e[0];return!t||!a.isObjectLiteralExpression(t)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(t,"binding")??"",columns:pe(t,"columns"),hasReconcile:m(t,"reconcileEveryMs")!==void 0,hasSoftDelete:m(t,"softDeleteColumn")!==void 0,hasTenantBy:m(t,"tenantBy")!==void 0,idColumn:f(t,"idColumn"),mode:f(t,"mode"),query:f(t,"query")}},Ce=(e,t,n,r)=>{switch(t){case"aggregateIndex":{e.aggregateIndexed=!0;break}case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(Le(n));break}case"global":{e.shardMode="global",e.globalBackend=Me(n);break}case"index":{e.indexes.unshift(Pe(n));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(De(n));break}case"relations":{const s=n[0];s&&e.relations.push(...Ae(s));break}case"searchIndex":{e.searchIndexes.push(_e(n));break}case"shardBy":{const s=n[0];e.shardMode={field:s&&a.isStringLiteral(s)?s.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:_(n[0],"deletedAt")};break}case"source":{e.externalSource=Re(n),e.externallyManaged=!0;break}case"timestamps":{e.timestampsFields.push(_(n[0],"updatedAt"));break}case"ttl":{e.ttl=je(n);break}case"vectorize":{const s=ze(n,r);s&&e.vectorIndexes.push(s);break}}},L=["__vocab","_config","_content","_data","_docsize","_idx"],Fe=(e,t,n)=>{const r=new Set(n.map(s=>s.name));for(const s of n)for(const i of L){const o=`${s.name}${i}`;if(!r.has(o))continue;const l=i==="__vocab"?`the \`fts5vocab\` companion for "${o}" is created \`IF NOT EXISTS\`, so it silently resolves to "${s.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${o}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw d(e,`table "${t}" declares search indexes "${s.name}" and "${o}", whose generated FTS5 tables collide: "${s.name}" already owns "${t}__fts_${o}" as its "${i}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${L.join(", ")}.`)}},Be=(e,t,n)=>{if(n.ttl!==void 0&&n.shardMode==="global")throw d(e,he(t))},Ve=(e,t,n)=>{const{softDelete:r,timestampsFields:s}=n,i={};r&&!(r.field in t)&&(i[r.field]={inner:{column:{notNull:!1},kind:"number"},kind:"optional"});const[o]=s;if(o===void 0)return{...t,...i};if(s.length>1)throw d(e,"`.timestamps()` was called more than once; one table tracks one last-change column.");if(o===r?.field)throw d(e,`\`.softDelete()\` and \`.timestamps()\` both use "${o}"; give one of them another field.`);const l=t[o];if(l===void 0)i[o]={column:{hasDefault:!0,hasOnUpdate:!0,notNull:!0},kind:"timestamp"};else if(l.kind!=="timestamp"||l.column?.hasOnUpdate!==!0||l.column.hasDefault!==!0)throw d(e,`\`.timestamps()\` would add "${o}", but the table already declares it as something other than \`v.timestamp().defaultNow().$onUpdateFn(() => Date.now())\`; remove the column or declare it that way.`);return{...t,...i}},C=(e,t)=>{const n={aggregateIndexed:!1,commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",timestampsFields:[],vectorIndexes:[]};let r={},s=e;for(;a.isCallExpression(s);){const i=s.getExpression(),o=s.getArguments();if(a.isPropertyAccessExpression(i))Ce(n,i.getName(),o,t),s=i.getExpression();else if(a.isIdentifier(i)&&i.getText()==="defineTable"){const l=o[0];if(l&&a.isObjectLiteralExpression(l))r=Q(l);else if(l)throw d(l,`table "${t}" calls defineTable(${JSON.stringify(l.getText())}), but codegen reads the field map syntactically and can only read an object literal. Inline the fields into the defineTable(...) call. To reuse them in an \`.input()\`, derive from the generated \`Doc_${t}\` / \`Insert_${t}\` type instead of sharing the runtime value.`);break}else break}return r=Ve(e,r,n),Fe(e,t,n.searchIndexes),Be(e,t,n),{...n.aggregateIndexed?{aggregateIndexed:!0}:{},commitOrdered:n.commitOrdered,externallyManaged:n.externallyManaged,externalSource:n.externalSource,geoIndexes:n.geoIndexes,globalBackend:n.shardMode==="global"?n.globalBackend??"d1":void 0,indexes:n.indexes,isPublic:n.isPublic,memory:n.memory,name:t,rankIndexes:n.rankIndexes,relations:n.relations,searchIndexes:n.searchIndexes,shape:r,shardMode:n.shardMode,softDelete:n.softDelete,ttl:n.ttl,vectorIndexes:n.vectorIndexes}},F=(e,t=[],n=new Set,r=new Set)=>{r.add(e);for(const s of e.getProperties()){if(a.isSpreadAssignment(s)){const o=G(s.getExpression());o!==void 0&&!r.has(o)&&F(o,t,n,r);continue}if(!a.isPropertyAssignment(s))continue;const i=s.getInitializer();if(i){const o=k(s);if(T(o,s.getNameNode()),n.has(o))throw d(s.getNameNode(),`defineSchema({...}): table "${o}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);n.add(o),t.push(C(i,o))}}return t},qe=e=>{const t=m(e,"source");if(t&&a.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&a.isObjectLiteralExpression(n))return f(n,"table")??"_unknown_"}return"_unknown_"},Je=e=>{if(!a.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!a.isCallExpression(t))return;const n=t.getExpression();if(!a.isIdentifier(n)||n.getText()!=="defineVectorIndex")return;const r=t.getArguments()[0];if(!r||!a.isObjectLiteralExpression(r))return;const s=e.getNameNode(),i=a.isStringLiteral(s)?s.getLiteralText():s.getText();return{dimensions:E(r,"dimensions"),metric:z(f(r,"metric")),name:i,table:qe(r)}},B=e=>{const t=[];for(const n of e.getProperties()){const r=Je(n);r&&t.push(r)}return t},A=(e,t)=>`${e}_${t}`,Ue=(e,t)=>{if(!R.test(e))throw d(t,`defineSchemaExtension key ${JSON.stringify(e)} is not a valid JS identifier — it is prefixed onto every table the extension contributes (\`${e}_<table>\`), and table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the extension key.`)},b=(e,t,n)=>n.has(e)?A(t,e):e,v=(e,t)=>{const n=r=>r===void 0?void 0:v(r,t);return{...e,...e.tableName===void 0?{}:{tableName:t(e.tableName)},...e.inner===void 0?{}:{inner:n(e.inner)},...e.keyType===void 0?{}:{keyType:n(e.keyType)},...e.valueType===void 0?{}:{valueType:n(e.valueType)},...e.members===void 0?{}:{members:e.members.map(r=>v(r,t))},...e.shape===void 0?{}:{shape:Object.fromEntries(Object.entries(e.shape).map(([r,s])=>[r,v(s,t)]))}}},We=(e,t,n,r)=>{const s=A(t,e.name);return{...e,extensionKey:t,...r?{extensionFromPackage:!0}:{},name:s,shape:Object.fromEntries(Object.entries(e.shape).map(([i,o])=>[i,v(o,l=>b(l,t,n))])),relations:e.relations.map(i=>{const o=b(i.table,t,n);return i.through===void 0?{...i,table:o}:{...i,table:o,through:{...i.through,table:b(i.through.table,t,n)}}}),vectorIndexes:e.vectorIndexes.map(i=>({...i,table:b(i.table,t,n)}))}},Ke=e=>{if(a.isVariableDeclaration(e)||a.isPropertyAssignment(e))return e.getInitializer();if(a.isShorthandPropertyAssignment(e))return e.getNameNode()},He=e=>{if(!a.isCallExpression(e))return!1;const t=e.getExpression();return a.isIdentifier(t)&&t.getText()==="defineSchemaExtension"},Xe=e=>{if(a.isIdentifier(e))return e;if(a.isPropertyAccessExpression(e)){const t=e.getExpression();return a.isIdentifier(t)?t:void 0}},Ze=e=>{if(a.isObjectLiteralExpression(e))return e;if(a.isCallExpression(e)){const t=e.getExpression();let n;if(a.isIdentifier(t)?n=t.getText():a.isPropertyAccessExpression(t)&&(n=t.getName()),n==="definePlugin"){const r=e.getArguments()[1];return r&&a.isObjectLiteralExpression(r)?r:void 0}}},Ge=(e,t)=>{const n=Ke(e);if(n){if(a.isPropertyAccessExpression(t)){const r=Ze(n);return r?x(r,t.getName()):void 0}return n}},Qe=e=>{let t=e,n=0;for(;t&&n<32;){if(n+=1,He(t))return t;const r=Xe(t),s=r&&a.isIdentifier(r)?r.getSymbol():void 0,o=(s?.getAliasedSymbol()?.getDeclarations()??s?.getDeclarations()??[])[0];if(!o)return;const l=o.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;t=Ge(o,t)}},Ye=e=>{const[t,n]=e.getArguments();if(!(!t||!a.isStringLiteral(t))&&!(!n||!a.isObjectLiteralExpression(n)))return{key:t.getLiteralText(),keyNode:t,options:n}},et=e=>{const t=m(e,"tables");if(!t||!a.isPropertyAssignment(t))return[];const n=t.getInitializer();if(!n||!a.isObjectLiteralExpression(n))return[];const r=[];for(const s of n.getProperties()){if(!a.isPropertyAssignment(s))continue;const i=s.getInitializer();if(!i)continue;const o=k(s);T(o,s.getNameNode()),r.push(C(i,o))}return r},tt=e=>{const t=m(e,"vectorIndexes");if(!t||!a.isPropertyAssignment(t))return[];const n=t.getInitializer();return!n||!a.isObjectLiteralExpression(n)?[]:B(n)},V=(e,t,n,r,s)=>{Ue(e,r);const i=new Set(t.map(c=>c.name)),o=t.map(c=>We(c,e,i,s)),l=n.map(c=>({...c,name:A(e,c.name),table:b(c.table,e,i)}));return{tables:o,vectorIndexes:l}},nt=(e,t,n)=>V(e,et(n),tt(n),t,t.getSourceFile().getFilePath().includes("/node_modules/")),rt=(e,t)=>{const n=e.getArguments()[0];if(!n)return;let r=n;for(;a.isParenthesizedExpression(r)||a.isAsExpression(r)||a.isSatisfiesExpression(r);)r=r.getExpression();const s=Qe(r);if(!s){if(t!==void 0){const o=me(r,t);if(o){for(const l of o.bareTables)T(l.name,r);return V(o.key,o.bareTables,o.bareVectorIndexes,r,!0)}}console.warn(`@lunora/codegen: skipping \`.extend(${r.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${t===void 0?"no project root was available to resolve the package":"the package could not be imported/introspected"}. Extension tables will be absent from the generated types. If the receiver is a component built with options codegen cannot evaluate (a function, a variable), extend with the standalone extension the package exports instead (e.g. \`presenceExtension\`, \`actionCacheExtension\` or \`documentHistoryExtension\` from \`@lunora/server\`).`);return}const i=Ye(s);if(!i){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return nt(i.key,i.keyNode,i.options)},st=e=>{const t=[];let n=e;for(;;){const r=n.getParent();if(!r||!a.isPropertyAccessExpression(r))break;const s=r.getParent();if(!s||!a.isCallExpression(s))break;r.getName()==="extend"&&t.push(s),n=s}return t},it=(e,t,n)=>{const r=new Set(t.map(i=>i.name)),s=[];for(const i of st(e)){const o=rt(i,n);if(o){for(const l of o.tables){if(r.has(l.name))throw d(i,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);r.add(l.name),t.push(l)}s.push(...o.vectorIndexes)}}return s},ot=new Set(["eu","fedramp","us"]),at=e=>M(e,"jurisdiction","jurisdiction",ot,'"eu", "us", or "fedramp"'),lt=e=>{let t=e;for(;;){const n=t.getParent(),r=n?.getParent();if(!n||!a.isPropertyAccessExpression(n)||!r||!a.isCallExpression(r))return!1;if(n.getName()==="jurisdiction"){const s=r.getArguments()[1];return s!==void 0&&a.isObjectLiteralExpression(s)&&D(s,"pinAuth")===!0}t=r}},ct=new Set(["required"]),dt=e=>M(e,"rls","rls mode",ct,'"required"'),ft=e=>{if(!a.isObjectLiteralExpression(e))return;const t=new Set;for(const n of e.getProperties()){const r=a.isPropertyAssignment(n)?n.getInitializer():void 0;if(!r||!a.isCallExpression(r))return;const s=r.getExpression(),i=r.getArguments()[1],o=i&&a.isObjectLiteralExpression(i)?f(i,"on"):void 0;if(!a.isIdentifier(s)||s.getText()!=="defineAggregateIndex"||o===void 0)return;t.add(o)}return t},ut=(e,t)=>{if(t===void 0)return;const n=ft(t);for(const r of e)(n===void 0||n.has(r.name))&&(r.aggregateIndexed=!0)},kt=(e,t,n)=>{const r=e.addSourceFileAtPath(t),s=U(r,J.CallExpression).find(g=>{const O=g.getExpression();return a.isIdentifier(O)&&O.getText()==="defineSchema"});if(!s)throw new q("INTERNAL",`defineSchema() not found in ${t}`);const i=s.getArguments()[0];if(!i||!a.isObjectLiteralExpression(i))throw d(s,"defineSchema() expects an object literal");const o=F(i),l=s.getArguments()[1],c=l&&a.isObjectLiteralExpression(l)?B(l):[],u=it(s,o,n);ut(o,s.getArguments()[2]);const h=[...o.flatMap(g=>g.vectorIndexes),...c,...u],y=new Set(o.filter(g=>g.shardMode==="global").map(g=>g.name)),w=h.find(g=>y.has(g.table));if(w)throw d(s,ee(w.table,w.name));return{jurisdiction:at(s),...lt(s)?{jurisdictionPinsAuth:!0}:{},rlsMode:dt(s),tables:o,vectorIndexes:h}};export{kt as default};
@@ -1 +0,0 @@
1
- import{LunoraError as g}from"@lunora/errors";import{Node as s,SyntaxKind as B}from"ts-morph";import{d as z}from"./declared-output-Iaar469J.mjs";import{findObjectProperty as h,bindingKeyName as H,listLunoraSourceFiles as M,lunoraRelativePath as W}from"./isTestPath-ClgKgMYM.mjs";import{e as K,i as O}from"./attribution-DjweYNgJ.mjs";import{u as R,p as q,r as Y,c as w,a as G}from"./unwrap-handler-return-BpigsVD6.mjs";import{m as J}from"./ip-reads-WFubgB1G.mjs";import{b as L,s as X,c as Q}from"./classify-procedure-call-BuF5PNwV.mjs";import{r as D,p as C,a as Z}from"./parse-validator-BisfC8bR.mjs";import{N as ee,l as te}from"./static-literal-BwDHHjEJ.mjs";import{s as ie}from"./dispatch-namespace-DwTjD7BU.mjs";const I=e=>e!==void 0&&(s.isArrowFunction(e)||s.isFunctionExpression(e))?e:void 0,ne=e=>{const i=e.getArguments()[0],t=I(i);if(t!==void 0)return t;if(i===void 0||!s.isObjectLiteralExpression(i))return;const n=h(i,"handler");return n!==void 0&&s.isPropertyAssignment(n)?I(n.getInitializer()):void 0},re=e=>{const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return"unknown";const t=h(i,"handler");if(!t||!s.isPropertyAssignment(t))return"unknown";const n=t.getInitializer();return!n||!(s.isArrowFunction(n)||s.isFunctionExpression(n))?"unknown":R(n)},oe=e=>{const i=e.getArguments()[0];return!i||!(s.isArrowFunction(i)||s.isFunctionExpression(i))?"unknown":R(i)},se=e=>{let i={};for(const t of L(e)){if(t.name!=="input")continue;const n=t.call.getArguments()[0],o=n!==void 0&&s.isExpression(n)?D(n):void 0;o!==void 0&&(i={...C(o),...i})}return i},ae=e=>{const i=L(e).find(n=>n.name==="output");if(!i)return;const t=i.call.getArguments()[0];return t&&s.isExpression(t)?q(i.call,()=>Z(t)):void 0},E=(e,i)=>{const t=h(e,i);if(t===void 0||!s.isPropertyAssignment(t))return;const n=t.getInitializer();return n!==void 0&&s.isStringLiteral(n)?n.getLiteralValue():void 0},k=(e,i)=>{const t=h(e,i);if(t===void 0||!s.isPropertyAssignment(t))return;const n=t.getInitializer();return n!==void 0&&s.isNumericLiteral(n)?n.getLiteralValue():void 0},ce=e=>{const i=h(e,"cache");if(i===void 0||!s.isPropertyAssignment(i))return;const t=i.getInitializer();if(t===void 0||!s.isObjectLiteralExpression(t))return;const n=E(t,"scope"),o=k(t,"maxAge"),r=k(t,"staleWhileRevalidate"),a=E(t,"tag"),c=E(t,"vary"),l={...o===void 0?{}:{maxAge:o},...n==="private"||n==="public"?{scope:n}:{},...r===void 0?{}:{staleWhileRevalidate:r},...a===void 0?{}:{tag:a},...c===void 0?{}:{vary:c}};return Object.keys(l).length===0?void 0:l},le=e=>{if(e===void 0||!s.isObjectLiteralExpression(e))return{};const i=ce(e),t=h(e,"rest");return t!==void 0&&s.isPropertyAssignment(t)?{...i===void 0?{}:{cache:i},rest:t.getInitializer()?.getText()==="true"}:i===void 0?{}:{cache:i}},ue=e=>{const i=L(e).find(t=>t.name==="expose");return i?le(i.call.getArguments()[0]):void 0},de=e=>{const i=L(e).find(r=>r.name==="x402");if(!i)return;const t=i.call.getArguments()[0];if(t===void 0||!s.isObjectLiteralExpression(t))return{};const n=h(t,"price");if(n===void 0||!s.isPropertyAssignment(n))return{};const o=n.getInitializer();return o===void 0?{}:s.isStringLiteral(o)?{price:o.getLiteralValue()}:s.isNumericLiteral(o)?{price:o.getLiteralValue()}:{}},ge=e=>{const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return{};const t=h(i,"args");if(!t||!s.isPropertyAssignment(t))return{};const n=t.getInitializer(),o=n===void 0?void 0:D(n);return o===void 0?{}:C(o)},f=(e,i)=>{throw new g("INTERNAL",`@lunora/codegen: lazy function registry needs literal ${i} in ${e.getSourceFile().getFilePath()}:${String(e.getStartLineNumber())}`)},S=(e,i,t)=>{if(!e||!s.isObjectLiteralExpression(e))return f(i,"metadata objects");const n=new Set;for(const o of e.getProperties()){if(!s.isPropertyAssignment(o))return f(o,"metadata fields without spreads, getters, or shorthand");const r=o.getNameNode(),a=s.isStringLiteral(r)?r.getLiteralValue():r.getText();if(!s.isIdentifier(r)&&!s.isStringLiteral(r)||!t.includes(a)||n.has(a))return f(o,"supported, unique metadata fields");n.add(a)}return e},y=(e,i)=>{const t=e.getProperty(i);return t&&s.isPropertyAssignment(t)?t.getInitializer():void 0},pe=e=>{const i=S(e,e,["credentialHeaders","maxAge","scope","staleWhileRevalidate","tag","vary"]),t={};for(const r of["maxAge","staleWhileRevalidate"]){const a=y(i,r);if(!(a===void 0&&r!=="maxAge")){if(!a||!s.isNumericLiteral(a))return f(e,`cache.${r}`);t[r]=a.getLiteralValue()}}const n=y(i,"scope");if(!n||!s.isStringLiteral(n)||!["private","public"].includes(n.getLiteralValue()))return f(e,"cache.scope");t.scope=n.getLiteralValue();for(const r of["tag","vary"]){const a=y(i,r);if(a!==void 0){if(!s.isStringLiteral(a))return f(a,`cache.${r}`);t[r]=a.getLiteralValue()}}const o=y(i,"credentialHeaders");if(o!==void 0){if(!s.isArrayLiteralExpression(o))return f(o,"cache.credentialHeaders");t.credentialHeaders=o.getElements().map(r=>s.isStringLiteral(r)?r.getLiteralValue():f(r,"cache.credentialHeaders string entries"))}return t},fe=e=>{const i=S(e.getArguments()[0],e,["rest","cache"]),t=y(i,"rest"),n=y(i,"cache");return t!==void 0&&!s.isTrueLiteral(t)&&!s.isFalseLiteral(t)?f(t,".expose({ rest })"):{...t?{rest:s.isTrueLiteral(t)}:{},...n?{cache:pe(n)}:{}}},me=e=>{const i=S(e.getArguments()[0],e,["price"]),t=y(i,"price");return!t||!s.isStringLiteral(t)&&!s.isNumericLiteral(t)?f(e,"`.x402({ price })` value"):{price:t.getLiteralValue()}},he=e=>{const i=e.map(o=>{const r=o.getArguments()[0];return r===void 0?ee:te(r)}),t=i.every(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)),n=i.reduce((o,r)=>({...r,...o}),{});return t?n:"unloaded"},ye=e=>{const{factory:i,steps:t}=X(e);if(!i)return f(e,"metadata from a resolvable Lunora factory root");const n={visibility:i.startsWith("internal")?"internal":"public"};for(const{call:r,name:a}of t){if(!["expose","input","meta","output","use","x402"].includes(a))return f(r,`known builder modifiers, got .${a}()`);a==="expose"&&n.expose===void 0&&(n.expose=fe(r)),a==="x402"&&n.x402===void 0&&(n.x402=me(r))}const o=t.filter(r=>r.name==="meta").map(r=>r.call);return o.length===0?n:{...n,meta:he(o)}},ve=new Set(["action","mutation","query","stream"]),N=(e,i,t)=>{const n=e.getProperty(i)?.getTypeAtLocation(t);if(n===void 0)return;const o=n.isUnion()?n.getUnionTypes().filter(a=>!a.isUndefined()):[n],r=o.length===1?o[0]?.getLiteralValue():void 0;return typeof r=="string"?r:void 0},U=(e,i)=>{const t=N(e,"kind",i);return t!==void 0&&ve.has(t)&&e.getProperty("handler")!==void 0?t:void 0},be=e=>{const i=e.getParent();if(s.isPropertyAccessExpression(i)&&i.getExpression()===e)return i.getName()==="functions";if(s.isElementAccessExpression(i)&&i.getExpression()===e){const n=i.getArgumentExpression();return n!==void 0&&s.isStringLiteral(n)&&n.getLiteralValue()==="functions"}const t=s.isVariableDeclaration(i)&&i.getNameNode()!==e?i.getNameNode():void 0;return t!==void 0&&s.isObjectBindingPattern(t)&&t.getElements().some(n=>(n.getPropertyNameNode()?.getText()??n.getName())==="functions")},it=(e,i)=>{for(const t of e)for(const n of t.getVariableDeclarations()){const o=n.getNameNode();if(!n.isExported()||!s.isIdentifier(o))continue;const a=(n.getType().getProperty("functions")?.getTypeAtLocation(n)?.getProperties()??[]).filter(u=>U(u.getTypeAtLocation(n),n)!==void 0);if(a.length===0||o.findReferencesAsNodes().some(u=>be(u)))continue;const l=n.getName(),d=a.map(u=>u.getName()).join(", ");console.warn(`@lunora/codegen: ${i(t)}:${l} ships functions (${d}) that nothing re-exports, so none is in the generated api. Add \`export const { ${d} } = ${l}.functions;\` (or export your own wrappers of them).`)}},Ne=new Set(["connect","disconnect","init","reactor","whisper"]),Le={ArrayBuffer:"bytes",GeoPoint:"geoPoint"},Ae=8,P=(e,i)=>{const t=e.getText(i);return t===""?{kind:"from"}:{kind:"from",tsType:t}},Ee=new Set(["false","true"]),Pe=[[e=>e.isAny()||e.isUnknown(),"any"],[e=>e.isString(),"string"],[e=>e.isNumber(),"number"],[e=>e.isBoolean(),"boolean"],[e=>e.isNull(),"null"],[e=>e.isBigInt(),"bigint"]],Te=(e,i,t)=>{if(!e.isObject()||e.isIntersection()||e.getCallSignatures().length>0||e.isClass())return;const n=e.getProperties();if(n.some(r=>r.getTypeAtLocation(i).getCallSignatures().length>0))return;const o=e.getStringIndexType();if(o!==void 0&&n.length===0)return{keyType:{kind:"string"},kind:"record",valueType:b(o,i,t+1)};if(!(o!==void 0||n.length===0))return{kind:"object",shape:Object.fromEntries(n.map(r=>[r.getName(),$(r.getTypeAtLocation(i),r.isOptional(),i,t+1)]))}},b=(e,i,t)=>{if(t>Ae)return P(e,i);const n=Pe.find(([a])=>a(e));if(n!==void 0)return{kind:n[1]};const o=Le[(e.getSymbol()??e.getAliasSymbol())?.getName()??""];if(o!==void 0)return{kind:o};if(e.isStringLiteral()||e.isNumberLiteral()||e.isBooleanLiteral()||e.isBigIntLiteral())return{kind:"literal",literalValue:e.getText(i),sensitive:!0};const r=e.isIntersection()?N(e,"__table",i):void 0;if(r!==void 0)return{kind:"id",tableName:r};if(e.isUnion())return F(e.getUnionTypes(),i,t);if(e.isArray()){const a=e.getArrayElementType();return a===void 0?P(e,i):{inner:b(a,i,t+1),kind:"array"}}return Te(e,i,t)??P(e,i)},F=(e,i,t)=>{const o=new Set(e.filter(l=>l.isBooleanLiteral()).map(l=>l.getText(i))).size===Ee.size,r=e.filter(l=>!(o&&l.isBooleanLiteral())).map(l=>b(l,i,t+1)),a=o?[...r,{kind:"boolean"}]:r,[c]=a;return a.length===1&&c!==void 0?c:{kind:"union",members:a}},$=(e,i,t,n)=>{const o=e.isUnion()?e.getUnionTypes():[e],r=o.filter(l=>!l.isUndefined());if(!i&&r.length===o.length)return b(e,t,n);if(r.length===0)return{inner:{kind:"any"},kind:"optional"};const[a]=r;return{inner:r.length===1&&a!==void 0?b(a,t,n):F(r,t,n),kind:"optional"}},xe=(e,i)=>{const t=e.getProperty("__type")?.getTypeAtLocation(i);if(t===void 0)return{kind:"from"};const n=(e.getSymbol()??e.getAliasSymbol())?.getName();return n==="TimestampColumnValidator"?{kind:"timestamp"}:n==="ObjectColumnValidator"&&t.getProperties().length===0?{kind:"object",shape:{}}:$(t,!1,i,0)},Se=new Set(["AsyncGenerator","AsyncIterable","AsyncIterableIterator"]),Oe=(e,i)=>{const t=e.getProperty("handler")?.getTypeAtLocation(i).getCallSignatures()[0]?.getReturnType();if(t===void 0)return[];if(Se.has((t.getSymbol()??t.getAliasSymbol())?.getName()??"")){const[n]=t.getTypeArguments();return n===void 0?[]:[n]}return(t.isUnion()?t.getUnionTypes():[t]).map(n=>n.getSymbol()?.getName()==="Promise"?n.getTypeArguments()[0]??n:n)},we=(e,i)=>{const t=[...new Set(e.map(n=>Y(n,i)))];return t.length===0||t.includes("unknown")?"unknown":t.join(" | ")},Ie=(e,i,t,n)=>{const o=e.getType(),r=U(o,e);if(r===void 0)return;const a={...n?{description:n}:{},exportName:i,filePath:t,kind:r};if(o.getProperty("channel")?.isOptional()===!1)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a room from a published package; its name is not in the declared type, so codegen cannot route it. Declare the room with \`defineRoom\` in this file instead.`);const c=N(o,"lifecycle",e),l=o.getProperty("lifecycle");if(c===void 0&&l!==void 0&&!l.isOptional())throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a lifecycle hook from a published package whose type does not say which moment it runs at. Declare it with its moment, e.g. \`RegisteredLifecycleHook & { readonly lifecycle: "disconnect" }\` (what \`onDisconnect\` returns).`);if(c!==void 0){if(!Ne.has(c))throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a "${c}" lifecycle hook from a published package; only a locally declared hook can carry its route. Declare it in this file instead.`);return{...a,args:{},lifecycle:c,returnType:"void",visibility:"internal"}}const d=N(o,"visibility",e);if(d!=="internal"&&d!=="public")throw new g("PUBLISHED_FUNCTION_VISIBILITY_UNKNOWN",`${t}:${i} re-exports a function from a published package whose type does not say whether it is internal or public. Declare it in that package as \`RegisteredQuery\` / \`RegisteredMutation\` / \`RegisteredAction\` (public) or their \`RegisteredInternal*\` counterparts, not the bare \`RegisteredFunction\`, so codegen does not list an internal function in the client \`api\`.`);if(d==="internal"&&o.getProperty("visibility")?.isOptional()!==!1)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports an internal function from a published package whose type makes \`visibility\` optional, so the value may not carry it. Declare it with a \`RegisteredInternal*\` type, which requires \`visibility: "internal"\`.`);const u=o.getProperty("args")?.getTypeAtLocation(e);if(u===void 0||u.isAny()||u.isUnknown()||u.getStringIndexType()!==void 0||u.getNumberIndexType()!==void 0)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a function from a published package whose type does not list its arguments. Declare its validator map with one key per argument (an empty \`{}\` for none) so codegen can type the client call.`);const m=Object.fromEntries(u.getProperties().map(p=>[p.getName(),xe(p.getTypeAtLocation(e),e)]));return{...a,args:m,...r==="query"?{readsIp:!0}:{},returnType:we(Oe(o,e),e),typeDerivedArgs:!0,visibility:d}},ke=8,A=(e,i=0)=>{if(i>ke)return;if(s.isCallExpression(e))return{call:e};if(s.isParenthesizedExpression(e)||s.isAsExpression(e)||s.isSatisfiesExpression(e)||s.isNonNullExpression(e))return A(e.getExpression(),i+1);if(!s.isIdentifier(e)&&!s.isPropertyAccessExpression(e))return;const t=e.getSymbol()?.getValueDeclaration();return t?T(t,i+1):void 0},T=(e,i)=>{if(s.isVariableDeclaration(e)||s.isPropertyAssignment(e)){const t=e.getInitializer();return t?A(t,i):{deadEnd:e}}if(s.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol()?.getValueDeclaration();return t?T(t,i+1):void 0}if(s.isBindingElement(e)){const t=H(e),r=e.getFirstAncestorByKind(B.VariableDeclaration)?.getInitializer()?.getType().getProperty(t)?.getValueDeclaration();return r?T(r,i+1):void 0}return{deadEnd:e}},x=e=>{const i=A(e);return i!==void 0&&"call"in i?i.call:void 0},_=e=>{const i=A(e);return i!==void 0&&"deadEnd"in i&&i.deadEnd.getSourceFile().isDeclarationFile()},_e=(e,i=()=>!0)=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t)){const r=[];for(const a of t.getElements().filter(c=>i(c.getName()))){const c=x(a.getNameNode());c&&r.push([a.getName(),c])}return r}if(!i(e.getName()))return[];const n=e.getInitializer(),o=n&&(s.isCallExpression(n)?n:x(n));return o?[[e.getName(),o]]:[]},Re=(e,i)=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t))return t.getElements().filter(o=>i(o.getName())&&_(o.getNameNode())).map(o=>[o.getName(),o.getNameNode()]);const n=e.getInitializer();return i(e.getName())&&n!==void 0&&_(n)?[[e.getName(),t]]:[]},De=e=>{const i=e.getArguments()[0],t=s.isObjectLiteralExpression(i)?i.getProperty("name"):void 0,n=s.isPropertyAssignment(t)?t.getInitializer():void 0;if(!n||!s.isStringLiteral(n))throw new g("ROOM_NAME_NOT_LITERAL",'defineRoom needs a string-literal `name` (e.g. `defineRoom({ name: "chat", … })`) so codegen can type its reference.');return n.getLiteralValue()},Ce=e=>e.startsWith("/")&&new URL(e,"https://lunora.invalid").pathname===e&&e!=="/_lunora"&&!e.startsWith("/_lunora/"),Ue=e=>{const i=e.getArguments()[0];if(!s.isObjectLiteralExpression(i))throw new g("SOCKET_PATH_NOT_LITERAL","defineWebSocket needs an object-literal options argument so codegen can read its `path` and `auth`.");const t=i.getProperty("path"),n=s.isPropertyAssignment(t)?t.getInitializer():void 0;if(!n||!s.isStringLiteral(n))throw new g("SOCKET_PATH_NOT_LITERAL",'defineWebSocket needs a string-literal `path` (e.g. `defineWebSocket({ path: "/chat", … })`) so codegen can route its upgrade.');const o=n.getLiteralValue();if(!Ce(o))throw new g("SOCKET_PATH_INVALID",`defineWebSocket path "${o}" must be a plain URL path starting with "/" (no "?", "#", ".." or unencoded characters) and not under "/_lunora".`);if(i.getProperties().some(l=>s.isSpreadAssignment(l)||s.isPropertyAssignment(l)&&s.isComputedPropertyName(l.getNameNode())))throw new g("SOCKET_AUTH_NOT_LITERAL","defineWebSocket cannot spread its options or use a computed key: codegen must read `auth` as a literal `auth: true` or `auth: false`.");const a=i.getProperty("auth");if(a===void 0)return{auth:!1,path:o};const c=s.isPropertyAssignment(a)?a.getInitializer():void 0;if(c===void 0||!(s.isTrueLiteral(c)||s.isFalseLiteral(c)))throw new g("SOCKET_AUTH_NOT_LITERAL","defineWebSocket needs a literal `auth: true` or `auth: false`, so codegen can read whether the route requires a session. A shorthand or a variable is not read.");return{auth:s.isTrueLiteral(c),path:o}},Fe=(e,i,t,n)=>{const o=n?ye(i):void 0,r=n?o?.expose:ue(i),a=n?o?.x402:de(i),c=w(()=>ae(i)),l=w(()=>oe(e)),d=z({kind:t.kind,output:c.value});return G(d?c.erased:l.erased),{args:se(i),...r?{expose:r}:{},...a?{x402:a}:{},...o?.meta===void 0?{}:{meta:o.meta},...t.adminOnly?{adminOnly:!0}:{},kind:t.kind,...c.value?{output:c.value}:{},returnType:l.value,visibility:o?.visibility==="internal"||t.visibility==="internal"?"internal":"public"}},$e=(e,i)=>{const t=Q(e,i);if(!t)return;if(t.channel)return{args:{},channel:{kind:t.channel,name:De(e)},kind:t.kind,returnType:"void",visibility:t.visibility};const{receiver:n}=t;return n?Fe(e,n,t,i):t.lifecycle?{args:{},kind:t.kind,lifecycle:t.lifecycle,returnType:"void",...t.lifecycle==="socket"?{socket:{...Ue(e),origin:`${e.getSourceFile().getFilePath()}@${String(e.getStart())}`}}:{},visibility:t.visibility}:{args:ge(e),kind:t.kind,returnType:re(e),visibility:t.visibility}},V=e=>{const i=e?.getJsDocs().at(-1)?.getDescription().trim();return i===""?void 0:i},Ve=e=>V(e.getFirstAncestor(i=>s.isVariableStatement(i))),je=e=>{const i=new Map;for(const t of e.getVariableStatements())if(t.isExported())for(const n of t.getDeclarations())i.has(n.getName())||i.set(n.getName(),t);return t=>V(i.get(t))},j=(e,i,t,n,o)=>{const r=$e(e,n);if(!r)return;const a=o??Ve(e);return{args:r.args,...a?{description:a}:{},exportName:i,filePath:t,kind:r.kind,returnType:r.returnType,...r.output?{output:r.output}:{},...r.meta===void 0?{}:{meta:r.meta},visibility:r.visibility,...r.adminOnly?{adminOnly:!0}:{},...r.kind==="query"&&(ne(e)===void 0||J(e))?{readsIp:!0}:{},...r.expose?{expose:r.expose}:{},...r.x402?{x402:r.x402}:{},...r.lifecycle?{lifecycle:r.lifecycle}:{},...r.channel?{channel:r.channel}:{},...r.socket?{socket:r.socket}:{}}},Be=(e,i,t)=>{const n=[];for(const o of e.getExportAssignments()){if(o.isExportEquals())continue;const r=x(o.getExpression()),a=r?j(r,"default",i,t):void 0;r&&a&&n.push({call:r,entry:a})}return n},ze=(e,i,t)=>{const n=K(e),o=je(e),r=new Map,a=(d,u)=>{if(d?.channel?.kind!=="room")return;const m=r.get(d.channel.name);if(m!==void 0&&m!==u)throw new g("DUPLICATE_ROOM_NAME",`Duplicate room name "${d.channel.name}" in ${i}: two defineRoom calls share it. Room names must be unique.`);r.set(d.channel.name,u)},c=e.getVariableStatements().flatMap(d=>d.getDeclarations()).flatMap(d=>_e(d,u=>n.has(u))).flatMap(([d,u])=>(n.get(d)??[]).filter(m=>O(m)).flatMap(m=>{const p=j(u,m,i,t,o(m));return a(p,u),p?[p]:[]})),l=new Set(c.map(d=>d.exportName));for(const d of e.getVariableStatements().flatMap(u=>u.getDeclarations()))for(const[u,m]of Re(d,p=>n.has(p)))for(const p of(n.get(u)??[]).filter(v=>O(v)&&!l.has(v))){const v=Ie(m,p,i,o(p));v&&(c.push(v),l.add(p))}for(const{call:d,entry:u}of Be(e,i,t))l.has(u.exportName)||(a(u,d),c.push(u));return c},He=e=>{const i=new Map;for(const t of e){if(t.channel?.kind!=="room")continue;const n=i.get(t.channel.name);if(n!==void 0&&n.file!==t.filePath)throw new g("DUPLICATE_ROOM_NAME",`Duplicate room name "${t.channel.name}": defined in ${n.origin} and ${t.filePath}:${t.exportName}. Room names must be unique across the project.`);n===void 0&&i.set(t.channel.name,{file:t.filePath,origin:`${t.filePath}:${t.exportName}`})}},Me=e=>{const i=new Map;for(const t of e){const n=ie(t.filePath),o=i.get(n);if(o&&o!==t.filePath)throw Object.assign(new Error(`Namespace collision: "${o}" and "${t.filePath}" both resolve to "${n}". Rename one of the files so the JS-identifier-sanitized names differ. (note: case-insensitive filesystems may also cause this — \`foo\` and \`FOO\` map to the same identifier)`),{code:"NAMESPACE_COLLISION",name:"LunoraError",paths:[o,t.filePath],status:500});i.set(n,t.filePath)}},nt=(e,i,t={})=>{const n=M(i),o=[];for(const r of n){const a=e.getSourceFile(r)??e.addSourceFileAtPath(r),c=W(i,r);o.push(...ze(a,c,t.lazyFunctions===!0))}return o.sort((r,a)=>`${r.filePath}:${r.exportName}`.localeCompare(`${a.filePath}:${a.exportName}`)),Me(o),He(o),o};export{nt as d,I as i,ne as p,it as w};
@@ -1 +0,0 @@
1
- import{statSync as A,readdirSync as P,realpathSync as D,lstatSync as I}from"node:fs";import{dirname as w,join as x,relative as F,sep as N,extname as O,basename as k}from"node:path";import{matcher as z}from"@visulima/fs";import{SyntaxKind as p,Node as s,VariableDeclarationKind as j}from"ts-morph";import{diagnosticAt as M}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{readProjectConfigLiterals as K}from"./loadProjectConfig-CtcJHHKS.mjs";import{findProjectConfigFile as $,findCodegenConfigFile as V}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{p as B,a as U}from"./property-name-7cBlgK_O.mjs";const W=/\.ts$/u,g=(e,t)=>F(e,t).split(N).join("/").replace(W,""),H=new Set(["_generated","node_modules"]),L=new Set(["__fixtures__","__mocks__","__snapshots__","__tests__"]),_=/\.(?:bench|e2e|e2e-spec|spec|spec-d|test|test-d)(?:\.tsx?)?$/u,ve=e=>{const t=e.split("/");return _.test(t.at(-1)??"")||t.slice(0,-1).some(i=>L.has(i))},d=(e,t,i)=>t?H.has(e)||!i&&L.has(e):!i&&_.test(e),v=new Map,E=()=>!1;let f;const X=e=>{const t=V(e),i=t===void 0?void 0:A(t,{throwIfNoEntry:!1});if(t===void 0||i===void 0)return E;const n=`${String(i.mtimeMs)}:${String(i.size)}`,r=v.get(t);if(r?.key===n)return r.isExcluded;const{codegen:o}=K(w(t));o?.unreadable&&console.warn("@lunora/codegen: `codegen.exclude` in lunora.config is not an array of string literals without `!` negations — ignoring it.");const c=o?.exclude?.length?z(o.exclude):E;return v.set(t,{isExcluded:c,key:n}),c},G=(e,t,i)=>e==="schema.ts"&&t===i,Y=e=>{try{return A(e)}catch{console.warn(`@lunora/codegen: skipping ${e} — it is a symlink that does not resolve (or vanished mid-scan).`);return}},R=(e,t,i,n,r)=>{let o,c;try{o=P(e),c=D(e)}catch{return t}if(n.has(c))return t;n.add(c);for(const l of o){const u=x(e,l),a=Y(u);a===void 0||r(l,F(i,u).split(N).join("/"),a.isDirectory())||(a.isDirectory()?R(u,t,i,n,r):a.isFile()&&O(l)===".ts"&&!G(l,e,i)&&t.push(u))}return t},C=(e,t={})=>{const i=t.includeSkipped??!1,n=`${String(i)}\0${e}`,r=f?.get(n);if(r!==void 0)return[...r];const o=i?E:X(e),c=R(e,[],e,new Set,(l,u,a)=>d(l,a,i)||o(u));return f?.set(n,c),[...c]},he=e=>{if(f!==void 0)return e();f=new Map;try{return e()}finally{f=void 0}},q=["src/server","src/index.ts","src/worker.ts"],Q=new Set([".ts",".tsx"]),T=(e,t=[])=>{let i;try{i=I(e)}catch{return t}if(i.isFile())return Q.has(O(e))&&!d(k(e),!1,!1)&&t.push(e),t;if(!i.isDirectory())return t;for(const n of P(e))d(n,!0,!1)||T(x(e,n),t);return t},J=e=>{const t=w(e),i=C(e).map(o=>({displayPath:g(e,o),filePath:o})),n=new Set(i.map(o=>o.filePath)),r=$(t);for(const o of[...q.flatMap(c=>T(x(t,c))),...r===void 0?[]:[r]])n.has(o)||(n.add(o),i.push({displayPath:g(t,o),filePath:o}));return i},Z=e=>Array.isArray(e),h=new WeakMap,ee=(e,t)=>{let i=h.get(e.compilerNode);i===void 0&&(i=new Map,h.set(e.compilerNode,i));let n=i.get(t);return n===void 0&&(n=e.getDescendantsOfKind(t),i.set(t,n)),n},b=(e,t,i,n)=>{const r=[];for(const{displayPath:o,filePath:c}of t){const l=e.getSourceFile(c)??e.addSourceFileAtPath(c);for(const u of ee(l,i)){const a=n(u,o);Z(a)?r.push(...a):a!==void 0&&r.push(a)}}return r},te=e=>C(e).map(t=>({displayPath:g(e,t),filePath:t})),ie=(e,t,i,n)=>b(e,te(t),i,n),ye=(e,t,i)=>ie(e,t,p.CallExpression,i),Ae=(e,t,i)=>b(e,J(t),p.CallExpression,i),Pe=e=>B(e.getPropertyNameNode()??e.getNameNode()),S=(e,t)=>e?.getProperties().find(i=>!s.isSpreadAssignment(i)&&U(i)===t),we=(e,t)=>{if(t){const o=e.getArguments()[0];return o&&(s.isArrowFunction(o)||s.isFunctionExpression(o))?o:void 0}const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return;const n=S(i,"handler");if(!n||!s.isPropertyAssignment(n))return;const r=n.getInitializer();return r&&(s.isArrowFunction(r)||s.isFunctionExpression(r))?r:void 0},Fe=(e,t)=>{if(!e||!s.isObjectLiteralExpression(e))return;const i=S(e,t);return i&&s.isPropertyAssignment(i)?i.getInitializer():void 0},se=e=>{const t=e?.getParent();return s.isVariableDeclaration(e)&&s.isVariableDeclarationList(t)&&t.getDeclarationKind()===j.Const},ne=e=>{let t=e,i=t.getParent();for(;i!==void 0&&(s.isParenthesizedExpression(i)||s.isAsExpression(i)||s.isSatisfiesExpression(i)||s.isTypeAssertion(i)||s.isNonNullExpression(i));)t=i,i=t.getParent();return t},y=e=>{const t=ne(e),i=t.getParent();if(i===void 0)return!1;if(s.isBinaryExpression(i)){const r=i.getOperatorToken().getKind();return i.getLeft()===t&&r>=p.FirstAssignment&&r<=p.LastAssignment}if(s.isPrefixUnaryExpression(i)||s.isPostfixUnaryExpression(i)){const r=i.getOperatorToken();return r===p.PlusPlusToken||r===p.MinusMinusToken}return s.isDeleteExpression(i)?!0:s.isForOfStatement(i)||s.isForInStatement(i)?i.getInitializer()===t:s.isPropertyAssignment(i)?i.getInitializer()===t&&y(i):(s.isShorthandPropertyAssignment(i)||s.isSpreadAssignment(i)||s.isSpreadElement(i)||s.isObjectLiteralExpression(i)||s.isArrayLiteralExpression(i))&&y(i)},re=e=>{const t=e?.getDeclarations().find(n=>s.isVariableDeclaration(n));if(!se(t))return;const i=t.getParent().getParent();return s.isVariableStatement(i)&&s.isSourceFile(i.getParent())?t.getInitializer():void 0},oe=e=>re(e.getSymbol()),Ne=e=>{if(!e)return;if(s.isObjectLiteralExpression(e))return e;if(!s.isIdentifier(e))return;const t=oe(e);return t!==void 0&&s.isObjectLiteralExpression(t)?t:void 0},m=e=>{let t=e;for(;t&&(s.isAsExpression(t)||s.isSatisfiesExpression(t)||s.isParenthesizedExpression(t)||s.isNonNullExpression(t));)t=t.getExpression();return t},ce=(e,t)=>{let i=m(e);for(;s.isAwaitExpression(i)||s.isPropertyAccessExpression(i)||s.isElementAccessExpression(i)||s.isCallExpression(i);){const n=s.isCallExpression(i)?t?.(i):void 0;if(n!==void 0)return{verdict:n};i=m(i.getExpression())}return{root:i}},Oe=e=>ce(e).root,Le=e=>s.isArrowFunction(e)||s.isConstructorDeclaration(e)||s.isFunctionDeclaration(e)||s.isFunctionExpression(e)||s.isGetAccessorDeclaration(e)||s.isMethodDeclaration(e)||s.isSetAccessorDeclaration(e),_e=(e,t)=>e?.compilerNode===t.compilerNode,Re=e=>{if(s.isPropertyAccessExpression(e))return{member:e.getName(),object:e.getExpression()};const t=s.isElementAccessExpression(e)?e.getArgumentExpression():void 0;return s.isElementAccessExpression(e)&&s.isStringLiteral(t)?{member:t.getLiteralValue(),object:e.getExpression()}:void 0},Ce=e=>{const t=e.getParent();return s.isReturnStatement(t)||s.isArrowFunction(t)&&t.getBody()===e?e.getFirstAncestor(n=>s.isFunctionLikeDeclaration(n)||s.isArrowFunction(n)):void 0},Te=e=>{const t=m(e);return t&&s.isCallExpression(t)?t:void 0},be=e=>{const t=e.getExportAssignment(r=>!r.isExportEquals());if(!t)return;const i=t.getExpression();if(!s.isIdentifier(i))return i;const n=i.getSymbol()?.getValueDeclaration();return n&&s.isVariableDeclaration(n)?n.getInitializer():i},De=e=>{const t=e.getArguments()[1];return t&&s.isStringLiteral(t)?t.getLiteralValue():""},Ie=(e,t)=>{if(!s.isObjectLiteralExpression(e))return;const i=S(e,t);if(!i||!s.isPropertyAssignment(i))return;const n=i.getInitializer();return n&&s.isStringLiteral(n)?n.getLiteralText():void 0},ae=e=>{const t=e.getStatements(),[i]=t;if(t.length!==1||i===void 0||!s.isReturnStatement(i))return;const n=i.getExpression();return n!==void 0&&s.isObjectLiteralExpression(n)?n:void 0},ke=e=>{if(s.isObjectLiteralExpression(e))return e;if(s.isParenthesizedExpression(e)){const t=e.getExpression();return s.isObjectLiteralExpression(t)?t:void 0}return s.isBlock(e)?ae(e):void 0},ze=e=>(t,i,n)=>{if(s.isStringLiteral(t)||s.isNoSubstitutionTemplateLiteral(t))return t.getLiteralValue();throw M(t,`${e} "${i}": \`${n}\` must be a static string literal — it is deploy configuration codegen writes into wrangler.jsonc`)},le=new Set(["api","internal"]),je=new Set(["run","runAction","runMutation","runQuery"]),ue=e=>{if(e===void 0||!s.isPropertyAccessExpression(e))return;const t=[];let i=e;for(;s.isPropertyAccessExpression(i);)t.unshift(i.getName()),i=i.getExpression();return s.isIdentifier(i)&&le.has(i.getText())&&t.length>=2?t:void 0},Me=e=>{const t=ue(e);return t===void 0?void 0:`${t.slice(0,-1).join("_")}:${String(t.at(-1))}`};export{je as RUN_METHODS,W as TS_EXTENSION_RE,Pe as bindingKeyName,Oe as chainRootOf,ye as collectCallRows,ie as collectNodeRows,Ae as collectSecurityCallRows,be as defaultExportExpression,ee as descendantsOfKind,S as findObjectProperty,Me as functionKeyOf,ue as functionReferenceSegments,we as handlerOf,se as isConstDeclaration,Le as isFunctionLike,_e as isSameNode,ve as isTestPath,y as isWriteTarget,De as limitNameOf,C as listLunoraSourceFiles,J as listSecurityScanFiles,g as lunoraRelativePath,Re as memberAccessOf,ke as objectLiteralFromCallbackBody,Ne as optionsObjectLiteral,ne as outermostValueWrapper,Fe as propertyInitializer,U as propertyKeyName,B as propertyNameText,Ce as returningFunctionOf,ze as stringPropertyFor,Ie as stringPropertyOf,re as symbolConstInitializer,m as unwrapExpression,Te as unwrapToCallExpression,ce as walkChain,he as withSourceListMemo};
@@ -1 +0,0 @@
1
- import{statSync as E,readFileSync as h}from"node:fs";import{basename as N}from"node:path";import{createJiti as O}from"jiti";import{Project as x,Node as n,VariableDeclarationKind as A}from"ts-morph";import{a as d}from"./property-name-7cBlgK_O.mjs";import{findProjectConfigFile as S,findCodegenConfigFile as P}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{PROJECT_CONFIG_FILENAMES as ie}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";const p=new Map,X=async r=>{const e=S(r);if(e===void 0)return{};let t;try{const s=E(e);t=`${String(s.mtimeMs)}:${String(s.size)}`}catch{return{}}const a=p.get(e);if(a?.key===t)return a.value;const i=(async()=>{try{const o=(await O(e,{interopDefault:!1,moduleCache:!1}).import(e))?.default;return{config:o!==null&&typeof o=="object"?o:void 0}}catch(s){return{error:s instanceof Error?s.message:String(s)}}})();return p.set(e,{key:t,value:i}),i},c=r=>{let e=r;for(;e!==void 0&&(n.isSatisfiesExpression(e)||n.isAsExpression(e)||n.isParenthesizedExpression(e));)e=e.getExpression();return e},z=r=>{const e=r.getExportAssignments().find(a=>!a.isExportEquals());let t=c(e?.getExpression());return t!==void 0&&n.isIdentifier(t)&&(t=c(r.getVariableDeclaration(t.getText())?.getInitializer())),t!==void 0&&n.isObjectLiteralExpression(t)?t:void 0},g=(r,e)=>n.isPropertyAssignment(r)?r.getInitializer():e.getVariableDeclaration(d(r))?.getInitializer(),b=(r,e,t)=>{const a=c(r);if(a===void 0||!n.isObjectLiteralExpression(a))return{unreadable:!0};const i=a.getProperties(),s=i.filter(l=>n.isPropertyAssignment(l)&&!n.isComputedPropertyName(l.getNameNode())||n.isShorthandPropertyAssignment(l));if(s.length!==i.length)return{unreadable:!0};const o=s.findLast(l=>d(l)===t);if(o===void 0)return{absent:!0};const u=g(o,e);return u===void 0?{unreadable:!0}:{literal:u}},C=["exportName","file","reason","rule"],F=r=>{const e=c(r);if(e===void 0||!n.isObjectLiteralExpression(e))return;const t={};for(const u of e.getProperties()){if(!n.isPropertyAssignment(u)||n.isComputedPropertyName(u.getNameNode()))return;const l=d(u),m=c(u.getInitializer());if(!C.includes(l)||m===void 0||!n.isStringLiteral(m)&&!n.isNoSubstitutionTemplateLiteral(m))return;t[l]=m.getLiteralValue()}const{exportName:a,file:i,reason:s,rule:o}=t;return a?.trim()&&i?.trim()&&s?.trim()&&o?.trim()?{exportName:a,file:i,reason:s,rule:o}:void 0},I=(r,e)=>{const t=b(r,e,"accept");if("absent"in t)return{};const a="literal"in t?c(t.literal):void 0;if(a===void 0||!n.isArrayLiteralExpression(a))return{acceptUnreadable:!0};const i=[];for(const s of a.getElements()){const o=F(s);if(o===void 0)return{acceptUnreadable:!0};i.push(o)}return{accept:i}},V=(r,e)=>{const t=b(r,e,"minSeverity"),a=I(r,e);return"absent"in t?{advisor:a}:"literal"in t&&n.isStringLiteral(t.literal)?{advisor:{...a,minSeverity:t.literal.getLiteralValue()}}:{advisor:{...a,unreadable:!0}}},w=(r,e)=>{const t=b(r,e,"exclude");if("absent"in t)return{};if(!("literal"in t)||!n.isArrayLiteralExpression(t.literal))return{unreadable:!0};const a=[];for(const i of t.literal.getElements()){if(!n.isStringLiteral(i)&&!n.isNoSubstitutionTemplateLiteral(i)||i.getLiteralValue().startsWith("!"))return{unreadable:!0};a.push(i.getLiteralValue())}return{exclude:a}},D=(r,e,t)=>{const a=b(r,e,"lazyFunctions");if("absent"in a)return{};if("unreadable"in a)return r!==void 0&&(n.isIdentifier(r)||r.getText().includes("lazyFunctions")||t&&!n.isObjectLiteralExpression(r))?{lazyFunctionsUnreadable:!0}:{};const i="literal"in a?c(a.literal):void 0;return i!==void 0&&(n.isTrueLiteral(i)||n.isFalseLiteral(i))?{lazyFunctions:i.getLiteralValue()}:{lazyFunctionsUnreadable:!0}},T=(r,e)=>{const t=c(r),a=t!==void 0&&n.isIdentifier(t),i=t!==void 0&&n.isIdentifier(t)?e.getVariableDeclaration(t.getText()):void 0,s=i?.getVariableStatement()?.getDeclarationKind()===A.Const,o=i?.getNameNode(),l=i!==void 0&&s&&o!==void 0&&n.isIdentifier(o)&&o.findReferencesAsNodes().length===1?c(i.getInitializer())??t:t;return{codegen:{...w(l,e),...D(l,e,a)}}},M=(r,e)=>{const t=b(r,e,"merge");return"absent"in t?{durableObjects:{}}:"literal"in t&&(n.isTrueLiteral(t.literal)||n.isFalseLiteral(t.literal))?{durableObjects:{merge:t.literal.getLiteralValue()}}:{durableObjects:{unreadable:!0}}},k=(r,e)=>{const t=b(r,e,"companion");return"absent"in t?{studio:{}}:"literal"in t&&(n.isTrueLiteral(t.literal)||n.isFalseLiteral(t.literal))?{studio:{companion:t.literal.getLiteralValue()}}:{studio:{unreadable:!0}}},R=new Map([["durableObjects",M],["studio",k]]),U=new Map([["advisor",{advisor:{unreadable:!0}}],["codegen",{codegen:{lazyFunctionsUnreadable:!0,unreadable:!0}}],["durableObjects",{durableObjects:{unreadable:!0}}],["remote",{unreadable:!0}],["studio",{studio:{unreadable:!0}}],["target",{unreadable:!0}]]),j=(r,e)=>{const t=r.getProperty(e);if(t!==void 0)return(n.isPropertyAssignment(t)?t.getInitializer():void 0)??"unreadable"},v=(r,e)=>{const t=j(r,e);if(t!==void 0)return t!=="unreadable"&&(n.isStringLiteral(t)||n.isNoSubstitutionTemplateLiteral(t))?t.getLiteralValue():!1},_=r=>{const e=j(r,"rpc");if(e!==void 0)return e!=="unreadable"&&n.isFalseLiteral(e)?!1:"unreadable"},$=r=>{const e=c(r);if(e===void 0||!n.isObjectLiteralExpression(e))return{services:{unreadable:!0}};const t={};for(const a of e.getProperties()){if(!n.isPropertyAssignment(a)||n.isComputedPropertyName(a.getNameNode()))return{services:{unreadable:!0}};const i=c(a.getInitializer());if(i===void 0||!n.isObjectLiteralExpression(i)||i.getProperties().some(l=>!n.isPropertyAssignment(l)))return{services:{unreadable:!0}};const s=v(i,"dir"),o=v(i,"entrypoint"),u=_(i);if(typeof s!="string"||o===!1||u==="unreadable")return{services:{unreadable:!0}};t[d(a)]={dir:s,...o===void 0?{}:{entrypoint:o},...u===void 0?{}:{rpc:u}}}return{services:{declared:t}}},K=(r,e)=>n.isShorthandPropertyAssignment(r)?r.getNameNode():g(r,e),W=(r,e)=>{if(n.isGetAccessorDeclaration(r)||n.isMethodDeclaration(r))return U.get(d(r))??{};if(!n.isPropertyAssignment(r)&&!n.isShorthandPropertyAssignment(r))return{};const t=d(r);if(t==="advisor")return V(g(r,e),e);if(t==="services")return $(g(r,e));if(t==="codegen")return T(K(r,e),e);const a=R.get(t);if(a!==void 0)return a(g(r,e),e);if(t!=="target"&&t!=="remote")return{};const i=g(r,e);return i===void 0?{unreadable:!0}:t==="target"?n.isStringLiteral(i)?{target:i.getLiteralValue()}:{unreadable:!0}:n.isTrueLiteral(i)||n.isFalseLiteral(i)?{remote:i.getLiteralValue()}:n.isObjectLiteralExpression(i)?{remote:!0}:{unreadable:!0}},f=r=>{let e;try{e=h(r,"utf8")}catch{return{unreadable:!0}}const a=new x({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(N(r),e,{overwrite:!0}),i=z(a);if(i===void 0)return{unreadable:!0};if(i.getProperties().some(o=>n.isSpreadAssignment(o))){const o=u=>i.getProperties().some(l=>!n.isSpreadAssignment(l)&&d(l)===u);return{...o("advisor")?{advisor:{unreadable:!0}}:{},...o("codegen")?{codegen:{lazyFunctionsUnreadable:!0,unreadable:!0}}:{},...o("durableObjects")?{durableObjects:{unreadable:!0}}:{},...o("studio")?{studio:{unreadable:!0}}:{},...o("services")?{services:{unreadable:!0}}:{},unreadable:!0}}let s={};for(const o of i.getProperties())s={...s,...W(o,a)};return s},J=r=>{const e=S(r);return e===void 0?{}:f(e)},Z=r=>{const{durableObjects:e}=J(r);return e?.unreadable&&console.warn("@lunora/codegen: `durableObjects.merge` in lunora.config is not a boolean literal — the Durable Object classes stay separate."),e?.merge===!0};let y;const ee=r=>{const e=P(r),{codegen:t}=e===void 0?{}:f(e);if(t?.lazyFunctionsUnreadable){const a=e===void 0?void 0:E(e,{throwIfNoEntry:!1}),i=e===void 0||a===void 0?"":`${e}:${String(a.mtimeMs)}:${String(a.size)}`;i!==y&&(y=i,console.warn("@lunora/codegen: `codegen.lazyFunctions` in lunora.config is not a boolean literal, so the config does not turn the function registry lazy."))}return t?.lazyFunctions===!0},L=new Set,te=r=>{const e=P(r),{studio:t}=e===void 0?{}:f(e);return t?.unreadable&&e!==void 0&&!L.has(e)&&(L.add(e),console.warn("@lunora/codegen: `studio.companion` in lunora.config is not a boolean literal, so the companion Worker is not generated.")),t?.companion===!0};export{ie as PROJECT_CONFIG_FILENAMES,S as findProjectConfigFile,X as loadProjectConfig,Z as readMergeDurableObjects,J as readProjectConfigLiterals,ee as readProjectLazyFunctions,te as readProjectStudioCompanion};
@@ -1 +0,0 @@
1
- import{Node as i,SyntaxKind as a}from"ts-morph";const n=Symbol("not-literal"),p=e=>Number(e.getText().replaceAll("_","")),f=e=>i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e)?e.getLiteralValue():i.isNumericLiteral(e)?p(e):i.isPrefixUnaryExpression(e)&&e.getOperatorToken()===a.MinusToken&&i.isNumericLiteral(e.getOperand())?-p(e.getOperand()):i.isTrueLiteral(e)||i.isFalseLiteral(e)?e.getLiteralValue():i.isBinaryExpression(e)?m(e):i.isNullLiteral(e)?null:n,g={[a.AsteriskAsteriskToken]:(e,t)=>e**t,[a.AsteriskToken]:(e,t)=>e*t,[a.MinusToken]:(e,t)=>e-t,[a.PercentToken]:(e,t)=>e%t,[a.PlusToken]:(e,t)=>e+t,[a.SlashToken]:(e,t)=>e/t},m=e=>{const t=g[e.getOperatorToken().getKind()],[r,s]=[l(e.getLeft()),l(e.getRight())];return t!==void 0&&typeof r=="number"&&typeof s=="number"&&Number.isFinite(r)&&Number.isFinite(s)?t(r,s):n},l=e=>{if(i.isParenthesizedExpression(e)||i.isAsExpression(e)||i.isSatisfiesExpression(e))return l(e.getExpression());if(i.isArrayLiteralExpression(e)){const t=e.getElements().map(r=>l(r));return t.includes(n)?n:t}return i.isObjectLiteralExpression(e)?L(e):f(e)},L=e=>{const t=[];for(const r of e.getProperties()){const s=i.isPropertyAssignment(r)?r.getNameNode():void 0,o=i.isPropertyAssignment(r)?r.getInitializer():void 0,u=o===void 0?n:l(o);if(s===void 0||u===n||!(i.isIdentifier(s)||i.isStringLiteral(s)))return n;const c=i.isStringLiteral(s)?s.getLiteralValue():s.getText();if(c==="__proto__")return n;t.push([c,u])}return Object.fromEntries(t)};export{n as N,l};