@lunora/codegen 1.0.0-alpha.402 → 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 (59) hide show
  1. package/dist/index.d.mts +1 -1
  2. package/dist/index.d.ts +1 -1
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/{AGENTS_FILENAME-BiSJTXnu.mjs → AGENTS_FILENAME-D0Y0_UgB.mjs} +1 -1
  5. package/dist/packem_shared/{ALL_NOTIFY_CHANNELS-_xAn-jI3.mjs → ALL_NOTIFY_CHANNELS-CtrsBtZX.mjs} +1 -1
  6. package/dist/packem_shared/{CONTAINERS_FILENAME-Bj3hFBa-.mjs → CONTAINERS_FILENAME-J-e3Vanb.mjs} +1 -1
  7. package/dist/packem_shared/{DEFAULT_TARGET-BfJ7upI0.mjs → DEFAULT_TARGET-CVYzxQ0y.mjs} +1 -1
  8. package/dist/packem_shared/{FLAGS_FILENAME-BW7MzS9C.mjs → FLAGS_FILENAME-6RzszxVW.mjs} +1 -1
  9. package/dist/packem_shared/{MUTATORS_FILENAME-tPpN_a00.mjs → MUTATORS_FILENAME-C3OImAxC.mjs} +1 -1
  10. package/dist/packem_shared/{OPENRPC_VERSION-DI_G2H0Q.mjs → OPENRPC_VERSION-UNYmA7Ty.mjs} +1 -1
  11. package/dist/packem_shared/{QUEUES_FILENAME-Cpp-0QI9.mjs → QUEUES_FILENAME-Ba-sK5Ek.mjs} +1 -1
  12. package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-CoCuKo3b.mjs → SCHEMA_SNAPSHOT_FILENAME-Cuhl5Xbr.mjs} +15 -13
  13. package/dist/packem_shared/{SHAPES_FILENAME-cHL4n_Co.mjs → SHAPES_FILENAME-CH0KrAdb.mjs} +1 -1
  14. package/dist/packem_shared/{WORKFLOWS_FILENAME-BXjKKAmj.mjs → WORKFLOWS_FILENAME-DfVfBum_.mjs} +1 -1
  15. package/dist/packem_shared/{attribution-C6VQNs-V.mjs → attribution-BhGR_h0Z.mjs} +1 -1
  16. package/dist/packem_shared/{buildOpenApiDocument-aAAsKnsY.mjs → buildOpenApiDocument-B8KEeeRr.mjs} +1 -1
  17. package/dist/packem_shared/{capabilitiesUsedBy-t-UvdnZl.mjs → capabilitiesUsedBy-BwhaHK08.mjs} +1 -1
  18. package/dist/packem_shared/chain-CXiqZFUk.mjs +1 -0
  19. package/dist/packem_shared/{classify-procedure-call-DwWrpCoX.mjs → classify-procedure-call-BZ164dkJ.mjs} +1 -1
  20. package/dist/packem_shared/{companionServiceBinding-CnEUhH0Z.mjs → companionServiceBinding-BZjm486n.mjs} +1 -1
  21. package/dist/packem_shared/{context-property-calls-RsCkfFCU.mjs → context-property-calls-Ggrmu3UL.mjs} +1 -1
  22. package/dist/packem_shared/{context-root-CY5kkBER.mjs → context-root-DnvrQxae.mjs} +1 -1
  23. package/dist/packem_shared/{createCodegenProject-BC4GwdnG.mjs → createCodegenProject-Cfr1xHPC.mjs} +1 -1
  24. package/dist/packem_shared/{database-calls-HP2mxQAR.mjs → database-calls-BRI5W-Mp.mjs} +1 -1
  25. package/dist/packem_shared/{discoverAuthApiCalls-CHytF_NH.mjs → discoverAuthApiCalls-ENLGem4M.mjs} +1 -1
  26. package/dist/packem_shared/{discoverCrons-C6Y1u_kI.mjs → discoverCrons-DWVXmktw.mjs} +1 -1
  27. package/dist/packem_shared/discoverFunctions-mAWlAiuj.mjs +1 -0
  28. package/dist/packem_shared/{discoverHttpRoutes-BccPlGZb.mjs → discoverHttpRoutes-CAoEemno.mjs} +1 -1
  29. package/dist/packem_shared/discoverHyperdriveCalls-BaRayTZe.mjs +1 -0
  30. package/dist/packem_shared/{discoverInserts-z7jg8LD3.mjs → discoverInserts-DmSa4WKU.mjs} +1 -1
  31. package/dist/packem_shared/discoverMaskProcedures-CyjXtZgc.mjs +1 -0
  32. package/dist/packem_shared/{discoverMigrations-B6u2Do9_.mjs → discoverMigrations-Duh6HVG3.mjs} +1 -1
  33. package/dist/packem_shared/{discoverNondeterministicCalls-Dei7EUFX.mjs → discoverNondeterministicCalls-BoF6ob-B.mjs} +1 -1
  34. package/dist/packem_shared/{discoverQueries-D4mihML_.mjs → discoverQueries-spxu-wHR.mjs} +1 -1
  35. package/dist/packem_shared/discoverR2sqlCalls-CZjqFVi_.mjs +1 -0
  36. package/dist/packem_shared/{discoverRlsMetadata-CNn4cdfy.mjs → discoverRlsMetadata-Cc0zA-gZ.mjs} +1 -1
  37. package/dist/packem_shared/{discoverRlsProcedures-CsczAow2.mjs → discoverRlsProcedures-mjiA0I4S.mjs} +1 -1
  38. package/dist/packem_shared/{discoverSandboxUsage-EKZOCCPU.mjs → discoverSandboxUsage-Ccy9n7G1.mjs} +1 -1
  39. package/dist/packem_shared/{discoverSchema-BcyKCBIw.mjs → discoverSchema-ynieYB0n.mjs} +1 -1
  40. package/dist/packem_shared/{discoverStorageRulesMetadata-yCB6MdrA.mjs → discoverStorageRulesMetadata-CtE5trUR.mjs} +1 -1
  41. package/dist/packem_shared/{exported-procedure-chains-DiNvW1Wl.mjs → exported-procedure-chains-h8Y7xDjq.mjs} +1 -1
  42. package/dist/packem_shared/{fingerprintSchemaSources-Cpom_87X.mjs → fingerprintSchemaSources-C8H1wOcH.mjs} +1 -1
  43. package/dist/packem_shared/{handler-reference-BqSXtjJ6.mjs → handler-reference-DpIVI5BM.mjs} +1 -1
  44. package/dist/packem_shared/{index-BPg6e1oa.mjs → index-jtzAVdUp.mjs} +1 -1
  45. package/dist/packem_shared/{index-DgHhQfpm.mjs → index-mFEIaT45.mjs} +1 -1
  46. package/dist/packem_shared/{ip-reads-Bn9qvrMD.mjs → ip-reads-BPDWkzEu.mjs} +1 -1
  47. package/dist/packem_shared/{isTestPath-B357_sbh.mjs → isTestPath-DRIdZaij.mjs} +1 -1
  48. package/dist/packem_shared/loadProjectConfig-BXwH3_gn.mjs +1 -0
  49. package/dist/packem_shared/{modules-BgublqiK.mjs → modules-Qpm_zqz4.mjs} +1 -1
  50. package/dist/packem_shared/project-config-file-DR7xrrNB.mjs +1 -0
  51. package/dist/packem_shared/{unwrap-handler-return-zNStZJ4K.mjs → unwrap-handler-return-DUzluwPj.mjs} +1 -1
  52. package/package.json +1 -1
  53. package/dist/packem_shared/chain-BvRxehwv.mjs +0 -1
  54. package/dist/packem_shared/discoverFunctions-B-051l15.mjs +0 -1
  55. package/dist/packem_shared/discoverHyperdriveCalls-DmUuhUoL.mjs +0 -1
  56. package/dist/packem_shared/discoverMaskProcedures-CrkT80jO.mjs +0 -1
  57. package/dist/packem_shared/discoverR2sqlCalls-Ej8oRuVk.mjs +0 -1
  58. package/dist/packem_shared/loadProjectConfig-D4_s2UFp.mjs +0 -1
  59. package/dist/packem_shared/project-config-file-DBVmBpin.mjs +0 -1
@@ -1 +1 @@
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-B357_sbh.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"./project-config-file-DBVmBpin.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
+ 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-DRIdZaij.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"./project-config-file-DR7xrrNB.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 +1 @@
1
- import{Node as u}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as p,stringPropertyOf as l}from"./isTestPath-B357_sbh.mjs";import{w as d}from"./classify-procedure-call-DwWrpCoX.mjs";import{e as m}from"./exported-procedure-chains-DiNvW1Wl.mjs";const h=new Set(["delete","list","read","write"]),g=t=>d(t,"use","storageRules"),x=(t,s,n)=>{const e=t.getArguments()[0];if(!e||!u.isArrayLiteralExpression(e))return[];const i=[];for(const o of e.getElements()){if(!u.isObjectLiteralExpression(o))continue;const r=l(o,"on");if(r===void 0||!h.has(r))continue;const a=l(o,"prefix"),c={bucket:l(o,"bucket")??"",file:s,on:r,procedure:n};a!==void 0&&(c.prefix=a),i.push(c)}return i},A=(t,s)=>{const n=[];for(const e of f(s)){const i=t.getSourceFile(e)??t.addSourceFileAtPath(e),o=p(s,e);for(const{name:r,receiver:a}of m(i))for(const c of g(a))n.push(...x(c,o,r))}return{rules:n}};export{A as default};
1
+ import{Node as u}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as p,stringPropertyOf as l}from"./isTestPath-DRIdZaij.mjs";import{w as d}from"./classify-procedure-call-BZ164dkJ.mjs";import{e as m}from"./exported-procedure-chains-h8Y7xDjq.mjs";const h=new Set(["delete","list","read","write"]),g=t=>d(t,"use","storageRules"),x=(t,s,n)=>{const e=t.getArguments()[0];if(!e||!u.isArrayLiteralExpression(e))return[];const i=[];for(const o of e.getElements()){if(!u.isObjectLiteralExpression(o))continue;const r=l(o,"on");if(r===void 0||!h.has(r))continue;const a=l(o,"prefix"),c={bucket:l(o,"bucket")??"",file:s,on:r,procedure:n};a!==void 0&&(c.prefix=a),i.push(c)}return i},A=(t,s)=>{const n=[];for(const e of f(s)){const i=t.getSourceFile(e)??t.addSourceFileAtPath(e),o=p(s,e);for(const{name:r,receiver:a}of m(i))for(const c of g(a))n.push(...x(c,o,r))}return{rules:n}};export{A as default};
@@ -1 +1 @@
1
- import{Node as s}from"ts-morph";import{j as t,h as c}from"./attribution-C6VQNs-V.mjs";import{c as n}from"./classify-procedure-call-DwWrpCoX.mjs";const m=a=>{const i=[];for(const e of t(a)){const r=e.getInitializer(),o=r&&s.isCallExpression(r)?n(r):void 0;o?.receiver&&i.push({name:c(e)??e.getName(),receiver:o.receiver})}return i};export{m as e};
1
+ import{Node as s}from"ts-morph";import{j as t,h as c}from"./attribution-BhGR_h0Z.mjs";import{c as n}from"./classify-procedure-call-BZ164dkJ.mjs";const m=a=>{const i=[];for(const e of t(a)){const r=e.getInitializer(),o=r&&s.isCallExpression(r)?n(r):void 0;o?.receiver&&i.push({name:c(e)??e.getName(),receiver:o.receiver})}return i};export{m as e};
@@ -1 +1 @@
1
- import{createHash as i}from"node:crypto";import{existsSync as s,readFileSync as c}from"node:fs";import{join as u}from"node:path";import{listLunoraSourceFiles as h}from"./isTestPath-B357_sbh.mjs";const S=t=>{if(!s(t))return"unreadable";const e=h(t,{includeSkipped:!0}),o=u(t,"schema.ts");s(o)&&e.push(o);const r=i("sha256");for(const a of e.toSorted((n,p)=>n.localeCompare(p)))try{r.update(a).update("\0").update(c(a))}catch{}return r.digest("hex")};export{S as default};
1
+ import{createHash as i}from"node:crypto";import{existsSync as s,readFileSync as c}from"node:fs";import{join as u}from"node:path";import{listLunoraSourceFiles as h}from"./isTestPath-DRIdZaij.mjs";const S=t=>{if(!s(t))return"unreadable";const e=h(t,{includeSkipped:!0}),o=u(t,"schema.ts");s(o)&&e.push(o);const r=i("sha256");for(const a of e.toSorted((n,p)=>n.localeCompare(p)))try{r.update(a).update("\0").update(c(a))}catch{}return r.digest("hex")};export{S as default};
@@ -1 +1 @@
1
- import{dirname as F}from"node:path";import{Node as e}from"ts-morph";import{unwrapExpression as m,lunoraRelativePath as u}from"./isTestPath-B357_sbh.mjs";import{r as v,h}from"./attribution-C6VQNs-V.mjs";const b=i=>e.isPropertyAssignment(i)?m(i.getInitializer()):e.isShorthandPropertyAssignment(i)?i.getNameNode():void 0,A=(i,s)=>{const o=i===void 0?void 0:b(i);if(o===void 0||!e.isIdentifier(o))return;const a=v(o),g=a?.getAliasedSymbol()??a;for(const t of g?.getDeclarations()??[]){const n=e.isVariableDeclaration(t)?m(t.getInitializer()):t;if(!(e.isFunctionDeclaration(n)||e.isArrowFunction(n)||e.isFunctionExpression(n))||!(e.isFunctionDeclaration(t)||e.isVariableDeclaration(t)))continue;const r=t.getSourceFile(),c=u(s,r.getFilePath()),l=!c.startsWith("../"),d=l?c:u(F(s),r.getFilePath()),f=h(t);return{body:n,...r===o.getSourceFile()?{}:{file:d},...l&&f!==void 0?{site:{exportName:f,file:d}}:{}}}};export{A as r};
1
+ import{dirname as F}from"node:path";import{Node as e}from"ts-morph";import{unwrapExpression as m,lunoraRelativePath as u}from"./isTestPath-DRIdZaij.mjs";import{r as v,h}from"./attribution-BhGR_h0Z.mjs";const b=i=>e.isPropertyAssignment(i)?m(i.getInitializer()):e.isShorthandPropertyAssignment(i)?i.getNameNode():void 0,A=(i,s)=>{const o=i===void 0?void 0:b(i);if(o===void 0||!e.isIdentifier(o))return;const a=v(o),g=a?.getAliasedSymbol()??a;for(const t of g?.getDeclarations()??[]){const n=e.isVariableDeclaration(t)?m(t.getInitializer()):t;if(!(e.isFunctionDeclaration(n)||e.isArrowFunction(n)||e.isFunctionExpression(n))||!(e.isFunctionDeclaration(t)||e.isVariableDeclaration(t)))continue;const r=t.getSourceFile(),c=u(s,r.getFilePath()),l=!c.startsWith("../"),d=l?c:u(F(s),r.getFilePath()),f=h(t);return{body:n,...r===o.getSourceFile()?{}:{file:d},...l&&f!==void 0?{site:{exportName:f,file:d}}:{}}}};export{A as r};
@@ -1 +1 @@
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-B357_sbh.mjs";import{e as K,i as O}from"./attribution-C6VQNs-V.mjs";import{u as R,p as q,r as Y,c as w,a as G}from"./unwrap-handler-return-zNStZJ4K.mjs";import{m as J}from"./ip-reads-Bn9qvrMD.mjs";import{b as L,s as X,c as Q}from"./classify-procedure-call-DwWrpCoX.mjs";import{r as D,p as C,a as Z}from"./parse-validator-BisfC8bR.mjs";import{N as ee,l as te}from"./project-config-file-DBVmBpin.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
+ 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-DRIdZaij.mjs";import{e as K,i as O}from"./attribution-BhGR_h0Z.mjs";import{u as R,p as q,r as Y,c as w,a as G}from"./unwrap-handler-return-DUzluwPj.mjs";import{m as J}from"./ip-reads-BPDWkzEu.mjs";import{b as L,s as X,c as Q}from"./classify-procedure-call-BZ164dkJ.mjs";import{r as D,p as C,a as Z}from"./parse-validator-BisfC8bR.mjs";import{N as ee,l as te}from"./project-config-file-DR7xrrNB.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 +1 @@
1
- import{Node as r}from"ts-morph";import{listLunoraSourceFiles as u,lunoraRelativePath as f}from"./isTestPath-B357_sbh.mjs";import{j as m,h as p}from"./attribution-C6VQNs-V.mjs";import{t as d}from"./database-calls-HP2mxQAR.mjs";import{w as g,c as h}from"./classify-procedure-call-DwWrpCoX.mjs";import{a as k}from"./property-name-7cBlgK_O.mjs";const l=e=>{if(!(!r.isPropertyAssignment(e)&&!r.isShorthandPropertyAssignment(e)&&!r.isMethodDeclaration(e)&&!r.isGetAccessorDeclaration(e)))return k(e)},v=e=>g(e,"use","mask"),D=e=>{if(r.isPropertyAssignment(e)){const s=e.getInitializer();if(s&&r.isStringLiteral(s)){const t=s.getLiteralText();if(t==="redact"||t==="hash")return t}}return"custom"},P=e=>{const s=e.getArguments()[0];if(!s||!r.isObjectLiteralExpression(s))return[];const t=[];for(const i of s.getProperties()){const o=l(i);if(o===void 0||!r.isPropertyAssignment(i))continue;const n=i.getInitializer();if(!(!n||!r.isObjectLiteralExpression(n)))for(const a of n.getProperties()){const c=l(a);c!==void 0&&t.push({column:c,table:o})}}return t},y=e=>{const s=v(e);return{maskColumns:s.flatMap(t=>P(t)),usesMask:s.length>0}},C=new Set(["explain","findFirst","findFirstOrThrow","findMany","get","query"]),M=new Set(["delete","insert","patch","replace"]),x=(e,s)=>{if(!r.isVariableDeclaration(e))return;const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const i=h(t);if(!i)return;const o=i.receiver?y(i.receiver):{maskColumns:[],usesMask:!1},{tablesRead:n,tablesWritten:a}=d(e,C,M);return{exportName:p(e)??e.getName(),file:s,maskColumns:o.maskColumns,tablesRead:n,tablesWritten:a,usesMask:o.usesMask,visibility:i.visibility}},E=(e,s)=>{const t=[];for(const i of u(s)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i),n=f(s,i);for(const a of m(o)){const c=x(a,n);c&&t.push(c)}}return t};export{l as a,E as d,v as m,D as s};
1
+ import{Node as r}from"ts-morph";import{listLunoraSourceFiles as u,lunoraRelativePath as f}from"./isTestPath-DRIdZaij.mjs";import{j as m,h as p}from"./attribution-BhGR_h0Z.mjs";import{t as d}from"./database-calls-BRI5W-Mp.mjs";import{w as g,c as h}from"./classify-procedure-call-BZ164dkJ.mjs";import{a as k}from"./property-name-7cBlgK_O.mjs";const l=e=>{if(!(!r.isPropertyAssignment(e)&&!r.isShorthandPropertyAssignment(e)&&!r.isMethodDeclaration(e)&&!r.isGetAccessorDeclaration(e)))return k(e)},v=e=>g(e,"use","mask"),D=e=>{if(r.isPropertyAssignment(e)){const s=e.getInitializer();if(s&&r.isStringLiteral(s)){const t=s.getLiteralText();if(t==="redact"||t==="hash")return t}}return"custom"},P=e=>{const s=e.getArguments()[0];if(!s||!r.isObjectLiteralExpression(s))return[];const t=[];for(const i of s.getProperties()){const o=l(i);if(o===void 0||!r.isPropertyAssignment(i))continue;const n=i.getInitializer();if(!(!n||!r.isObjectLiteralExpression(n)))for(const a of n.getProperties()){const c=l(a);c!==void 0&&t.push({column:c,table:o})}}return t},y=e=>{const s=v(e);return{maskColumns:s.flatMap(t=>P(t)),usesMask:s.length>0}},C=new Set(["explain","findFirst","findFirstOrThrow","findMany","get","query"]),M=new Set(["delete","insert","patch","replace"]),x=(e,s)=>{if(!r.isVariableDeclaration(e))return;const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const i=h(t);if(!i)return;const o=i.receiver?y(i.receiver):{maskColumns:[],usesMask:!1},{tablesRead:n,tablesWritten:a}=d(e,C,M);return{exportName:p(e)??e.getName(),file:s,maskColumns:o.maskColumns,tablesRead:n,tablesWritten:a,usesMask:o.usesMask,visibility:i.visibility}},E=(e,s)=>{const t=[];for(const i of u(s)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i),n=f(s,i);for(const a of m(o)){const c=x(a,n);c&&t.push(c)}}return t};export{l as a,E as d,v as m,D as s};
@@ -1 +1 @@
1
- import{Node as s,SyntaxKind as i}from"ts-morph";import{i as n}from"./context-root-CY5kkBER.mjs";const o=/rate|limit|\bip\b|geo|throttle/iu,a=/^run[A-Z]/u,l=t=>s.isIdentifier(t)?(t.getSymbol()?.getDeclarations()??[]).some(r=>r.getFirstAncestorByKind(i.ImportDeclaration)?.getModuleSpecifierValue().startsWith("@lunora/")===!0):!1,c=t=>{const e=s.isCallExpression(t)?t.getExpression():t;let r;return s.isIdentifier(e)?r=e:s.isPropertyAccessExpression(e)&&(r=e.getNameNode()),r!==void 0&&l(s.isPropertyAccessExpression(e)?e.getExpression():r)&&!o.test(r.getText())},p=t=>{const e=s.isCallExpression(t)?t.getExpression():void 0;if(s.isElementAccessExpression(e)){const r=e.getArgumentExpression();return(s.isStringLiteral(r)||s.isNoSubstitutionTemplateLiteral(r))&&r.getLiteralText()==="use"}return s.isPropertyAccessExpression(e)&&e.getName()==="use"},g=t=>{const e=t.getParent();return s.isPropertyAccessExpression(e)&&e.getExpression()===t?!a.test(e.getName()):s.isElementAccessExpression(e)&&e.getExpression()===t?s.isStringLiteral(e.getArgumentExpression())||s.isNoSubstitutionTemplateLiteral(e.getArgumentExpression()):s.isVariableDeclaration(e)&&e.getInitializer()?.getText()===t.getText()},u=t=>{if(s.isPropertyAccessExpression(t))return t.getName()==="ip";if(s.isElementAccessExpression(t)){const e=t.getArgumentExpression();return(s.isStringLiteral(e)||s.isNoSubstitutionTemplateLiteral(e))&&e.getLiteralText()==="ip"}return s.isBindingElement(t)?t.getDotDotDotToken()!==void 0||(t.getPropertyNameNode()?.getText()??t.getName())==="ip":s.isShorthandPropertyAssignment(t)&&t.getName()==="ip"},A=t=>{for(const e of t.getDescendants()){if(u(e)||p(e)&&!c(e.getArguments()[0]))return!0;if(s.isIdentifier(e)&&n(e)&&!g(e)){const r=e.getParent();if(!(s.isParameterDeclaration(r)||s.isBindingElement(r)||s.isVariableDeclaration(r)))return!0}}return!1};export{A as m};
1
+ import{Node as s,SyntaxKind as i}from"ts-morph";import{i as n}from"./context-root-DnvrQxae.mjs";const o=/rate|limit|\bip\b|geo|throttle/iu,a=/^run[A-Z]/u,l=t=>s.isIdentifier(t)?(t.getSymbol()?.getDeclarations()??[]).some(r=>r.getFirstAncestorByKind(i.ImportDeclaration)?.getModuleSpecifierValue().startsWith("@lunora/")===!0):!1,c=t=>{const e=s.isCallExpression(t)?t.getExpression():t;let r;return s.isIdentifier(e)?r=e:s.isPropertyAccessExpression(e)&&(r=e.getNameNode()),r!==void 0&&l(s.isPropertyAccessExpression(e)?e.getExpression():r)&&!o.test(r.getText())},p=t=>{const e=s.isCallExpression(t)?t.getExpression():void 0;if(s.isElementAccessExpression(e)){const r=e.getArgumentExpression();return(s.isStringLiteral(r)||s.isNoSubstitutionTemplateLiteral(r))&&r.getLiteralText()==="use"}return s.isPropertyAccessExpression(e)&&e.getName()==="use"},g=t=>{const e=t.getParent();return s.isPropertyAccessExpression(e)&&e.getExpression()===t?!a.test(e.getName()):s.isElementAccessExpression(e)&&e.getExpression()===t?s.isStringLiteral(e.getArgumentExpression())||s.isNoSubstitutionTemplateLiteral(e.getArgumentExpression()):s.isVariableDeclaration(e)&&e.getInitializer()?.getText()===t.getText()},u=t=>{if(s.isPropertyAccessExpression(t))return t.getName()==="ip";if(s.isElementAccessExpression(t)){const e=t.getArgumentExpression();return(s.isStringLiteral(e)||s.isNoSubstitutionTemplateLiteral(e))&&e.getLiteralText()==="ip"}return s.isBindingElement(t)?t.getDotDotDotToken()!==void 0||(t.getPropertyNameNode()?.getText()??t.getName())==="ip":s.isShorthandPropertyAssignment(t)&&t.getName()==="ip"},A=t=>{for(const e of t.getDescendants()){if(u(e)||p(e)&&!c(e.getArguments()[0]))return!0;if(s.isIdentifier(e)&&n(e)&&!g(e)){const r=e.getParent();if(!(s.isParameterDeclaration(r)||s.isBindingElement(r)||s.isVariableDeclaration(r)))return!0}}return!1};export{A as m};
@@ -1 +1 @@
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{r as K}from"./project-config-file-DBVmBpin.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
+ 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{r as K}from"./project-config-file-DR7xrrNB.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};
@@ -0,0 +1 @@
1
+ import{b as a,p as t,e as i,r as s,c,d,a as n}from"./project-config-file-DR7xrrNB.mjs";import"./property-name-7cBlgK_O.mjs";import{PROJECT_CONFIG_FILENAMES as P,findProjectConfigFile as f}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";export{P as PROJECT_CONFIG_FILENAMES,f as findProjectConfigFile,a as loadProjectConfig,t as projectConfigProblems,i as readMergeDurableObjects,s as readProjectConfigLiterals,c as readProjectLazyFunctions,d as readProjectSecurityHeaders,n as readProjectStudioCompanion};
@@ -1 +1 @@
1
- import{basename as b}from"node:path";import{Node as d}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{listLunoraSourceFiles as $,lunoraRelativePath as v,unwrapToCallExpression as E,defaultExportExpression as S,findObjectProperty as M}from"./isTestPath-B357_sbh.mjs";import{s as g}from"./dispatch-namespace-DwTjD7BU.mjs";const h=(e,o)=>e.find(t=>t.ownsFolder!==!1&&o.startsWith(`${t.name}/`))?.name,F="module.ts",w=(e,o,t)=>{if(d.isStringLiteral(e)||d.isNoSubstitutionTemplateLiteral(e))return e.getLiteralValue();throw c(e,`module "${o}": \`${t}\` must be a static string literal — codegen reads it without running the file`)},L=(e,o,t)=>{if(!d.isArrayLiteralExpression(e))throw c(e,`module "${o}": \`${t}\` must be an inline array of table names`);return e.getElements().map(n=>w(n,o,t))},p=(e,o,t)=>{const n=M(e,o);if(n!==void 0){if(!d.isPropertyAssignment(n))throw c(n,`module "${t}": write \`${o}\` inline as \`${o}: …\` — codegen reads it without running the file`);return n.getInitializerOrThrow()}},A=(e,o,t)=>{const n=e.getSourceFile(o)??e.addSourceFileAtPath(o),s=E(S(n)),a=s?.getExpression();if(!s||!a||!d.isIdentifier(a)||a.getText()!=="defineModule")return;if(t==="")throw c(s,"defineModule: lunora/module.ts would make the whole app one module — move it into the folder it describes (lunora/<module>/module.ts)");const i=s.getArguments()[0],m={name:t,tables:[]};if(i===void 0)return m;if(!d.isObjectLiteralExpression(i))throw c(i,`module "${t}": defineModule must be passed an inline object literal`);const r=p(i,"description",t);r!==void 0&&(m.description=w(r,t,"description"));const l=p(i,"tables",t);return l!==void 0&&(m.tables=L(l,t,"tables")),m},k=(e,o)=>{const t=[];for(const n of $(o)){if(b(n)!==F)continue;const s=v(o,n),a=A(e,n,s==="module"?"":s.slice(0,-7));a&&t.push(a)}return t.toSorted((n,s)=>n.name.localeCompare(s.name))},T=(e,o)=>{const t=new Set(e.map(r=>r.name)),n=new Set(e.flatMap(r=>r.tables)),s=o.tables.filter(r=>r.extensionKey!==void 0&&!n.has(r.name)),a=Map.groupBy(s,r=>String(r.extensionKey)),i=e.map(r=>{const l=a.get(r.name);return l===void 0?r:{...r,tables:[...r.tables,...l.map(u=>u.name)]}}),m=[...a].filter(([r])=>!t.has(r)).map(([r,l])=>{const u=l.every(f=>f.extensionFromPackage===!0);return{installed:!0,name:r,...u?{ownsFolder:!1}:{},tables:l.map(f=>f.name)}});return[...i,...m].toSorted((r,l)=>r.name.localeCompare(l.name))},x=e=>{for(const o of e){const t=e.find(n=>n.name.startsWith(`${o.name}/`));if(t)throw new Error(`@lunora/codegen: module "${t.name}" is nested inside ${o.installed===!0?"installed component":"module"} "${o.name}" — a file can belong to one module only, so move one of the two`)}},y=(e,o)=>{const t=new Set(o.tables.map(s=>s.name)),n=new Map;for(const s of e)for(const a of s.tables){if(!t.has(a))throw new Error(`@lunora/codegen: module "${s.name}" declares table "${a}", which lunora/schema.ts does not define`);const i=n.get(a);if(i!==void 0)throw new Error(`@lunora/codegen: table "${a}" is claimed by both module "${i}" and module "${s.name}" — a table has one owner`);n.set(a,s.name)}},C=(e,o,t)=>{if(e.length===0)return;const n=new Set(o.map(s=>s.name));for(const s of t){const a=g(s);if(h(o,s)===void 0&&n.has(a))throw new Error(`@lunora/codegen: lunora/${s}.ts sits beside module "${a}" and shares its name — move it into lunora/${a}/ or rename one of them`)}},z=(e,o,t)=>{const n=T(e,o);return x(n),y(n,o),C(e,n,t),n},K=(e,o)=>h(e,o)??g(o);export{h as a,k as d,K as m,z as r};
1
+ import{basename as b}from"node:path";import{Node as d}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{listLunoraSourceFiles as $,lunoraRelativePath as v,unwrapToCallExpression as E,defaultExportExpression as S,findObjectProperty as M}from"./isTestPath-DRIdZaij.mjs";import{s as g}from"./dispatch-namespace-DwTjD7BU.mjs";const h=(e,o)=>e.find(t=>t.ownsFolder!==!1&&o.startsWith(`${t.name}/`))?.name,F="module.ts",w=(e,o,t)=>{if(d.isStringLiteral(e)||d.isNoSubstitutionTemplateLiteral(e))return e.getLiteralValue();throw c(e,`module "${o}": \`${t}\` must be a static string literal — codegen reads it without running the file`)},L=(e,o,t)=>{if(!d.isArrayLiteralExpression(e))throw c(e,`module "${o}": \`${t}\` must be an inline array of table names`);return e.getElements().map(n=>w(n,o,t))},p=(e,o,t)=>{const n=M(e,o);if(n!==void 0){if(!d.isPropertyAssignment(n))throw c(n,`module "${t}": write \`${o}\` inline as \`${o}: …\` — codegen reads it without running the file`);return n.getInitializerOrThrow()}},A=(e,o,t)=>{const n=e.getSourceFile(o)??e.addSourceFileAtPath(o),s=E(S(n)),a=s?.getExpression();if(!s||!a||!d.isIdentifier(a)||a.getText()!=="defineModule")return;if(t==="")throw c(s,"defineModule: lunora/module.ts would make the whole app one module — move it into the folder it describes (lunora/<module>/module.ts)");const i=s.getArguments()[0],m={name:t,tables:[]};if(i===void 0)return m;if(!d.isObjectLiteralExpression(i))throw c(i,`module "${t}": defineModule must be passed an inline object literal`);const r=p(i,"description",t);r!==void 0&&(m.description=w(r,t,"description"));const l=p(i,"tables",t);return l!==void 0&&(m.tables=L(l,t,"tables")),m},k=(e,o)=>{const t=[];for(const n of $(o)){if(b(n)!==F)continue;const s=v(o,n),a=A(e,n,s==="module"?"":s.slice(0,-7));a&&t.push(a)}return t.toSorted((n,s)=>n.name.localeCompare(s.name))},T=(e,o)=>{const t=new Set(e.map(r=>r.name)),n=new Set(e.flatMap(r=>r.tables)),s=o.tables.filter(r=>r.extensionKey!==void 0&&!n.has(r.name)),a=Map.groupBy(s,r=>String(r.extensionKey)),i=e.map(r=>{const l=a.get(r.name);return l===void 0?r:{...r,tables:[...r.tables,...l.map(u=>u.name)]}}),m=[...a].filter(([r])=>!t.has(r)).map(([r,l])=>{const u=l.every(f=>f.extensionFromPackage===!0);return{installed:!0,name:r,...u?{ownsFolder:!1}:{},tables:l.map(f=>f.name)}});return[...i,...m].toSorted((r,l)=>r.name.localeCompare(l.name))},x=e=>{for(const o of e){const t=e.find(n=>n.name.startsWith(`${o.name}/`));if(t)throw new Error(`@lunora/codegen: module "${t.name}" is nested inside ${o.installed===!0?"installed component":"module"} "${o.name}" — a file can belong to one module only, so move one of the two`)}},y=(e,o)=>{const t=new Set(o.tables.map(s=>s.name)),n=new Map;for(const s of e)for(const a of s.tables){if(!t.has(a))throw new Error(`@lunora/codegen: module "${s.name}" declares table "${a}", which lunora/schema.ts does not define`);const i=n.get(a);if(i!==void 0)throw new Error(`@lunora/codegen: table "${a}" is claimed by both module "${i}" and module "${s.name}" — a table has one owner`);n.set(a,s.name)}},C=(e,o,t)=>{if(e.length===0)return;const n=new Set(o.map(s=>s.name));for(const s of t){const a=g(s);if(h(o,s)===void 0&&n.has(a))throw new Error(`@lunora/codegen: lunora/${s}.ts sits beside module "${a}" and shares its name — move it into lunora/${a}/ or rename one of them`)}},z=(e,o,t)=>{const n=T(e,o);return x(n),y(n,o),C(e,n,t),n},K=(e,o)=>h(e,o)??g(o);export{h as a,k as d,K as m,z as r};
@@ -0,0 +1 @@
1
+ import{statSync as B,readFileSync as se}from"node:fs";import{basename as j}from"node:path";import{createJiti as ie}from"jiti";import{Node as s,SyntaxKind as p,VariableDeclarationKind as J,Project as oe}from"ts-morph";import{s as ae,a as h}from"./property-name-7cBlgK_O.mjs";import{findProjectConfigFile as W,findCodegenConfigFile as w}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";const q=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},ce=/^[a-z][\d+.a-z-]*:\/\/(?:\*\.)?[\d.a-z-]+(?::\d{1,5})?$/iu,Q=e=>[...e].every(t=>t===" "||t>=" "&&t!==""&&t<="ÿ"),le=["same-origin","same-origin-allow-popups","unsafe-none"],ue=["DENY","SAMEORIGIN"],$=["includeSubDomains","maxAge","preload"],X=["csp","permissionsPolicy","referrerPolicy"],I=[...X,"crossOriginOpenerPolicy","frameAncestors","frameOptions","hsts"],M=e=>e.map(t=>JSON.stringify(t)).join(", "),de=(e,t)=>{if(typeof e=="boolean")return e;if(!q(e)){t.push("security.headers.hsts must be a boolean or an object { maxAge?, includeSubDomains?, preload? }");return}for(const o of Object.keys(e).filter(a=>!$.includes(a)))t.push(`security.headers.hsts.${o} is not an option (expected ${M($)})`);const{includeSubDomains:r,maxAge:n,preload:i}=e;n!==void 0&&!(typeof n=="number"&&Number.isSafeInteger(n)&&n>=0)&&t.push(`security.headers.hsts.maxAge must be a whole number of seconds (got ${JSON.stringify(n)})`);for(const[o,a]of[["includeSubDomains",r],["preload",i]])a!==void 0&&typeof a!="boolean"&&t.push(`security.headers.hsts.${o} must be a boolean`);return{...r===void 0?{}:{includeSubDomains:r},...n===void 0?{}:{maxAge:n},...i===void 0?{}:{preload:i}}},V=(e,t,r,n)=>{if(t===void 0||t===!1||r.includes(t))return t;n.push(`security.headers.${e} must be one of ${M(r)} or false (got ${JSON.stringify(t)})`)},fe=(e,t)=>{if(e!==void 0){if(!Array.isArray(e)){t.push('security.headers.frameAncestors must be an array of origins like ["https://partner.example"]');return}for(const r of e)(typeof r!="string"||!ce.test(r)||!Q(r))&&t.push(`security.headers.frameAncestors entry ${JSON.stringify(r)} is not an origin like "https://partner.example"`);return[...e]}},pe=e=>{if(e===void 0||typeof e=="boolean")return{ok:!0,value:e};if(!q(e))return{ok:!1,problems:[`security.headers must be a boolean or an object (got ${Array.isArray(e)?"an array":JSON.stringify(e)})`]};const t=Object.keys(e).filter(n=>!I.includes(n)).map(n=>`security.headers.${n} is not an option (expected ${M(I)})`),r={};for(const n of X){const i=e[n];i===void 0||i===!1?r[n]=i:typeof i!="string"?t.push(`security.headers.${n} must be a string or false`):Q(i)?r[n]=i:t.push(`security.headers.${n} contains a line break or control character`)}return r.crossOriginOpenerPolicy=V("crossOriginOpenerPolicy",e.crossOriginOpenerPolicy,le,t),r.frameOptions=V("frameOptions",e.frameOptions,ue,t),r.frameAncestors=fe(e.frameAncestors,t),r.hsts=e.hsts===void 0?void 0:de(e.hsts,t),r.frameAncestors!==void 0&&typeof r.csp=="string"&&t.push("security.headers.frameAncestors cannot be combined with a csp string: put the frame-ancestors directive in the csp"),r.frameAncestors!==void 0&&r.frameOptions==="DENY"&&t.push('security.headers.frameAncestors cannot be combined with frameOptions: "DENY"'),r.frameAncestors!==void 0&&r.csp===!1&&t.push("security.headers.frameAncestors needs the Content-Security-Policy that carries it; it cannot be combined with csp: false"),t.length>0?{ok:!1,problems:t}:{ok:!0,value:Object.fromEntries(Object.entries(r).filter(([,n])=>n!==void 0))}},ge=(e,t)=>{const r=Array.from({length:t.length+1},(n,i)=>i);for(let n=1;n<=e.length;n+=1){let i=r[0]??0;r[0]=n;for(let o=1;o<=t.length;o+=1){const a=r[o]??0,l=e[n-1]===t[o-1]?0:1;r[o]=Math.min((r[o-1]??0)+1,a+1,i+l),i=a}}return r[t.length]??0},me=(e,t)=>{let r,n=Number.POSITIVE_INFINITY;for(const o of t){const a=ge(e,o);a<n&&(n=a,r=o)}const i=Math.max(2,Math.ceil(e.length/3));return r!==void 0&&n<=i?r:void 0},g=Symbol("not-literal"),C=e=>Number(e.getText().replaceAll("_","")),b=e=>s.isTrueLiteral(e)||s.isFalseLiteral(e)?e.getLiteralValue():s.isPrefixUnaryExpression(e)&&e.getOperatorToken()===p.ExclamationToken&&s.isNumericLiteral(e.getOperand())?C(e.getOperand())===0:void 0,be=e=>{if(s.isStringLiteral(e)||s.isNoSubstitutionTemplateLiteral(e))return e.getLiteralValue();if(s.isNumericLiteral(e))return C(e);if(s.isPrefixUnaryExpression(e)&&e.getOperatorToken()===p.MinusToken&&s.isNumericLiteral(e.getOperand()))return-C(e.getOperand());const t=b(e);return t!==void 0?t:s.isBinaryExpression(e)?ve(e):s.isNullLiteral(e)?null:g},ye={[p.AsteriskAsteriskToken]:(e,t)=>e**t,[p.AsteriskToken]:(e,t)=>e*t,[p.MinusToken]:(e,t)=>e-t,[p.PercentToken]:(e,t)=>e%t,[p.PlusToken]:(e,t)=>e+t,[p.SlashToken]:(e,t)=>e/t},ve=e=>{const t=ye[e.getOperatorToken().getKind()],[r,n]=[S(e.getLeft()),S(e.getRight())];return t!==void 0&&typeof r=="number"&&typeof n=="number"&&Number.isFinite(r)&&Number.isFinite(n)?t(r,n):g},S=e=>{if(s.isParenthesizedExpression(e)||s.isAsExpression(e)||s.isSatisfiesExpression(e))return S(e.getExpression());if(s.isArrayLiteralExpression(e)){const t=e.getElements().map(r=>S(r));return t.includes(g)?g:t}return s.isObjectLiteralExpression(e)?he(e):be(e)},he=e=>{const t=[];for(const r of e.getProperties()){const n=s.isPropertyAssignment(r)?r.getNameNode():void 0,i=s.isPropertyAssignment(r)?r.getInitializer():void 0,o=i===void 0?g:S(i);if(n===void 0||o===g||!(s.isIdentifier(n)||s.isStringLiteral(n)))return g;const a=s.isStringLiteral(n)?n.getLiteralValue():n.getText();if(a==="__proto__")return g;t.push([a,o])}return Object.fromEntries(t)},N={accepts:["boolean"],expected:"a boolean"},xe={accepts:["function"],expected:"a function"},Oe={accepts:["number"],expected:"a number"},E={accepts:["string"],expected:"a string"},D={accepts:["array"],expected:"an array of strings",items:E},L={accepts:["boolean","string"],expected:"a string or `false`",literal:!1},v=(e,t)=>({accepts:["object"],expected:"an object",keys:e,...t===void 0?{}:{required:t}}),Ee={crossOriginOpenerPolicy:L,csp:L,frameAncestors:D,frameOptions:L,hsts:{accepts:["boolean","object"],expected:"a boolean or an object",keys:Object.fromEntries($.map(e=>[e,e==="maxAge"?Oe:N]))},permissionsPolicy:L,referrerPolicy:L},Se={accepts:["boolean","object"],expected:"a boolean or an object",keys:Object.fromEntries(I.toSorted((e,t)=>e.localeCompare(t)).map(e=>[e,Ee[e]]))},u=e=>{let t=e;for(;t!==void 0&&(s.isSatisfiesExpression(t)||s.isAsExpression(t)||s.isParenthesizedExpression(t));)t=t.getExpression();return t},Le=(e,t)=>e.getDescendants().some(r=>{if(s.isBinaryExpression(r)){const n=r.getOperatorToken().getKind(),i=r.getLeft();return n>=p.FirstAssignment&&n<=p.LastAssignment&&s.isIdentifier(i)&&i.getText()===t}return(s.isPrefixUnaryExpression(r)||s.isPostfixUnaryExpression(r))&&(r.getOperatorToken()===p.PlusPlusToken||r.getOperatorToken()===p.MinusMinusToken)&&r.getOperand().getText()===t}),T=(e,t)=>{const r=e.getVariableDeclaration(t);return r===void 0?void 0:r.getVariableStatement()?.getDeclarationKind()===J.Const||!Le(e,t)?r.getInitializer():void 0},Z=(e,t)=>{const r=u(e);return r!==void 0&&s.isIdentifier(r)?u(T(t,r.getText())):r},Ae=e=>{if(e!==void 0)return s.isStringLiteral(e)||s.isNoSubstitutionTemplateLiteral(e)||s.isTemplateExpression(e)?"string":b(e)!==void 0?"boolean":s.isBigIntLiteral(e)||s.isPrefixUnaryExpression(e)&&s.isBigIntLiteral(e.getOperand())?"bigint":s.isNumericLiteral(e)||s.isPrefixUnaryExpression(e)&&s.isNumericLiteral(e.getOperand())?"number":s.isNullLiteral(e)?"null":s.isObjectLiteralExpression(e)?"object":s.isArrayLiteralExpression(e)?"array":s.isArrowFunction(e)||s.isFunctionExpression(e)||s.isMethodDeclaration(e)?"function":void 0},Ne={array:"an array",bigint:"a bigint",boolean:"a boolean",function:"a function",null:"null",number:"a number",object:"an object",string:"a string"},_=e=>s.isPropertyAssignment(e)?e.getInitializer():s.isShorthandPropertyAssignment(e)?e.getNameNode():s.isMethodDeclaration(e)?e:void 0,je=(e,t,r)=>{const n=l=>t===""?l:`${t}.${l}`,i=me(e,r),o=i===void 0?"":` Did you mean \`${n(i)}\`?`,a=t===""?"":` of \`${t}\``;return`unknown key \`${n(e)}\`.${o} Valid keys${a}: ${r.join(", ")}.`},ee=(e,t,r,n)=>{const i=Z(e,n),o=Ae(i);if(i===void 0||o===void 0)return[];const a=i.getText(),l=a.length>40?`${a.slice(0,37)}...`:a;if(!t.accepts.includes(o))return[`\`${r}\` must be ${t.expected}, got ${Ne[o]} (${l}).`];if(t.literal!==void 0&&o==="boolean"&&b(i)!==t.literal)return[`\`${r}\` must be ${t.expected}, got \`${a}\`.${t.hint===void 0?"":` ${t.hint}`}`];if(t.items!==void 0&&s.isArrayLiteralExpression(i)){const{items:c}=t,d=i.getElements(),f=d.findIndex(O=>s.isSpreadElement(O));return(f===-1?d:d.slice(0,f)).flatMap((O,ne)=>ee(O,c,`${r}[${String(ne)}]`,n))}return s.isObjectLiteralExpression(i)&&(t.keys!==void 0||t.entries!==void 0)?R(i,t,r,n):[]},Pe=(e,t,r)=>{const n=(e.required??[]).filter(i=>!t.has(i));return n.length===0?[]:[`\`${r}\` is missing ${n.map(i=>`\`${i}\``).join(", ")}.`]},R=(e,t,r,n,i=!1)=>{const o=e.getProperties(),a=f=>s.isSpreadAssignment(f)?void 0:ae(f.getNameNode()),l=!i&&o.every(f=>a(f)!==void 0),c=[],d=new Map(o.map(f=>[a(f),f]));for(const f of o){const y=a(f);if(y===void 0)continue;const O=t.entries??(t.keys!==void 0&&Object.hasOwn(t.keys,y)?t.keys[y]:void 0);O===void 0?c.push(je(y,r,Object.keys(t.keys??{}))):c.push(...Te(f,O,r===""?y:`${r}.${y}`,n,l&&d.get(y)===f))}return l?[...c,...Pe(t,d,r)]:c},Te=(e,t,r,n,i)=>{if(s.isGetAccessorDeclaration(e)||s.isSetAccessorDeclaration(e))return[];if(i)return ee(_(e),t,r,n);const o=Z(_(e),n);return o!==void 0&&s.isObjectLiteralExpression(o)&&(t.keys!==void 0||t.entries!==void 0)?R(o,t,r,n,!0):[]},ke=e=>s.isInterfaceDeclaration(e)||s.isTypeAliasDeclaration(e)||s.isExportSpecifier(e)&&(e.isTypeOnly()||e.getExportDeclaration().isTypeOnly()),$e=e=>e.getExportSymbols().filter(t=>{const r=t.getDeclarations();return r.length===0||!r.every(n=>ke(n))}).map(t=>t.getName()),Ie=(e,t,r)=>{if(t.getExportSymbols().some(c=>c.getName()==="default"))return;const n=$e(t),i=t.getExportDeclarations().filter(c=>c.isNamespaceExport()&&c.getNamespaceExport()===void 0&&!c.isTypeOnly()).map(c=>c.getModuleSpecifierValue()).filter(c=>c!==void 0);if(n.length===0&&i.length===0)return;if(n.length===0)return`${e} has no default export, so none of its settings are read (it only re-exports ${i.map(c=>`\`${c}\``).join(", ")} with \`export *\`, which never forwards a default). Lunora reads only the default export, and codegen reads its settings from this file without loading the modules it imports: move them here as \`export default { … } satisfies LunoraConfig\`.`;const o=n.filter(c=>r.has(c)),a=n.filter(c=>{const d=u(T(t,c));return!r.has(c)&&d!==void 0&&s.isObjectLiteralExpression(d)});let l="`export default { … } satisfies LunoraConfig`";return o.length>0?l=`\`export default { ${o.join(", ")} } satisfies LunoraConfig\``:a.length===1&&(l=`\`export default ${String(a[0])};\` in place of the named export`),`${e} has no default export, so none of its settings are read (it exports ${n.map(c=>`\`${c}\``).join(", ")}). Lunora reads only the default export: ${l}.`},te=e=>{const t=e.getExportAssignments().find(i=>!i.isExportEquals()),r=e.getExportDeclarations().filter(i=>!i.hasModuleSpecifier()&&!i.isTypeOnly()).flatMap(i=>i.getNamedExports()).find(i=>(i.getAliasNode()?.getText()??i.getName())==="default"),n=t===void 0&&r!==void 0?r.getNameNode():u(t?.getExpression());return n!==void 0&&s.isIdentifier(n)?u(T(e,n.getText())):n},Ce=e=>{const t=te(e);return t!==void 0&&s.isObjectLiteralExpression(t)?t:void 0},De=e=>{const t=te(e);if(t!==void 0)return s.isArrayLiteralExpression(t)?"an array":s.isStringLiteral(t)||s.isNoSubstitutionTemplateLiteral(t)||s.isTemplateExpression(t)?"a string":s.isNumericLiteral(t)?"a number":b(t)!==void 0?"a boolean":s.isNullLiteral(t)?"null":void 0},m=(e,t)=>s.isPropertyAssignment(e)?e.getInitializer():T(t,h(e)),x=(e,t,r)=>{const n=u(e);if(n===void 0||!s.isObjectLiteralExpression(n))return{unreadable:!0};const i=n.getProperties(),o=i.filter(c=>s.isPropertyAssignment(c)&&!s.isComputedPropertyName(c.getNameNode())||s.isShorthandPropertyAssignment(c));if(o.length!==i.length)return{unreadable:!0};const a=o.findLast(c=>h(c)===r);if(a===void 0)return{absent:!0};const l=m(a,t);return l===void 0?{unreadable:!0}:{literal:l}},z=["exportName","file","reason","rule"],ze=e=>{const t=u(e);if(t===void 0||!s.isObjectLiteralExpression(t))return;const r={};for(const l of t.getProperties()){if(!s.isPropertyAssignment(l)||s.isComputedPropertyName(l.getNameNode()))return;const c=h(l),d=u(l.getInitializer());if(!z.includes(c)||d===void 0||!s.isStringLiteral(d)&&!s.isNoSubstitutionTemplateLiteral(d))return;r[c]=d.getLiteralValue()}const{exportName:n,file:i,reason:o,rule:a}=r;return n?.trim()&&i?.trim()&&o?.trim()&&a?.trim()?{exportName:n,file:i,reason:o,rule:a}:void 0},we=(e,t)=>{const r=x(e,t,"accept");if("absent"in r)return{};const n="literal"in r?u(r.literal):void 0;if(n===void 0||!s.isArrayLiteralExpression(n))return{acceptUnreadable:!0};const i=[];for(const o of n.getElements()){const a=ze(o);if(a===void 0)return{acceptUnreadable:!0};i.push(a)}return{accept:i}},Me=(e,t)=>{const r=x(e,t,"minSeverity"),n=we(e,t);return"absent"in r?{advisor:n}:"literal"in r&&s.isStringLiteral(r.literal)?{advisor:{...n,minSeverity:r.literal.getLiteralValue()}}:{advisor:{...n,unreadable:!0}}},Re=(e,t)=>{const r=x(e,t,"exclude");if("absent"in r)return{};if(!("literal"in r)||!s.isArrayLiteralExpression(r.literal))return{unreadable:!0};const n=[];for(const i of r.literal.getElements()){if(!s.isStringLiteral(i)&&!s.isNoSubstitutionTemplateLiteral(i)||i.getLiteralValue().startsWith("!"))return{unreadable:!0};n.push(i.getLiteralValue())}return{exclude:n}},Ve=(e,t,r)=>{const n=x(e,t,"lazyFunctions");if("absent"in n)return{};if("unreadable"in n)return e!==void 0&&(s.isIdentifier(e)||e.getText().includes("lazyFunctions")||r&&!s.isObjectLiteralExpression(e))?{lazyFunctionsUnreadable:!0}:{};const i="literal"in n?u(n.literal):void 0,o=i===void 0?void 0:b(i);return o===void 0?{lazyFunctionsUnreadable:!0}:{lazyFunctions:o}},_e=(e,t)=>{const r=u(e),n=r!==void 0&&s.isIdentifier(r),i=r!==void 0&&s.isIdentifier(r)?t.getVariableDeclaration(r.getText()):void 0,o=i?.getVariableStatement()?.getDeclarationKind()===J.Const,a=i?.getNameNode(),c=i!==void 0&&o&&a!==void 0&&s.isIdentifier(a)&&a.findReferencesAsNodes().length===1?u(i.getInitializer())??r:r;return{codegen:{...Re(c,t),...Ve(c,t,n)}}},Ue=(e,t)=>{const r=x(e,t,"merge");if("absent"in r)return{durableObjects:{}};const n="literal"in r?b(r.literal):void 0;return n===void 0?{durableObjects:{unreadable:!0}}:{durableObjects:{merge:n}}},Fe=(e,t)=>{const r=x(e,t,"companion");if("absent"in r)return{studio:{}};const n="literal"in r?b(r.literal):void 0;return n===void 0?{studio:{unreadable:!0}}:{studio:{companion:n}}},Ke=(e,t)=>{const r=x(e,t,"headers");if("absent"in r)return{security:{}};const n="literal"in r?S(r.literal):g;return n===g?{security:{unreadable:!0}}:{security:{headers:n}}},re=(e,t)=>{const r=e.getProperty(t);if(r!==void 0)return(s.isPropertyAssignment(r)?r.getInitializer():void 0)??"unreadable"},U=(e,t)=>{const r=re(e,t);if(r!==void 0)return r!=="unreadable"&&(s.isStringLiteral(r)||s.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():!1},Ye=e=>{const t=re(e,"rpc");if(t!==void 0)return t!=="unreadable"&&b(t)===!1?!1:"unreadable"},He=e=>{const t=u(e);if(t===void 0||!s.isObjectLiteralExpression(t))return{services:{unreadable:!0}};const r={};for(const n of t.getProperties()){if(!s.isPropertyAssignment(n)||s.isComputedPropertyName(n.getNameNode()))return{services:{unreadable:!0}};const i=u(n.getInitializer());if(i===void 0||!s.isObjectLiteralExpression(i)||i.getProperties().some(c=>!s.isPropertyAssignment(c)))return{services:{unreadable:!0}};const o=U(i,"dir"),a=U(i,"entrypoint"),l=Ye(i);if(typeof o!="string"||a===!1||l==="unreadable")return{services:{unreadable:!0}};r[h(n)]={dir:o,...a===void 0?{}:{entrypoint:a},...l===void 0?{}:{rpc:l}}}return{services:{declared:r}}},Ge=(e,t)=>s.isShorthandPropertyAssignment(e)?e.getNameNode():m(e,t),Be=(e,t)=>{const r=m(e,t);return r!==void 0&&s.isStringLiteral(r)?{target:r.getLiteralValue()}:{unreadable:!0}},Je=(e,t)=>{const r=u(m(e,t)),n=r===void 0?void 0:b(r);return n!==void 0?{remote:n}:r!==void 0&&s.isNullLiteral(r)?{}:r!==void 0&&s.isObjectLiteralExpression(r)?{remote:!0}:{unreadable:!0}},A=new Map([["advisor",{read:(e,t)=>Me(m(e,t),t),shape:v({accept:{...D,expected:"an array of objects",items:v(Object.fromEntries(z.map(e=>[e,E])),z)},minSeverity:E}),unreadable:{advisor:{unreadable:!0}}}],["app",{read:()=>({}),shape:xe,unreadable:{}}],["codegen",{read:(e,t)=>_e(Ge(e,t),t),shape:v({exclude:D,lazyFunctions:N}),unreadable:{codegen:{lazyFunctionsUnreadable:!0,unreadable:!0}}}],["durableObjects",{read:(e,t)=>Ue(m(e,t),t),shape:v({merge:N}),unreadable:{durableObjects:{unreadable:!0}}}],["remote",{read:Je,shape:{accepts:["boolean","null","object"],expected:"a boolean"},unreadable:{unreadable:!0}}],["security",{read:(e,t)=>Ke(m(e,t),t),shape:v({headers:Se}),unreadable:{security:{unreadable:!0}}}],["services",{read:(e,t)=>He(m(e,t)),shape:{accepts:["object"],entries:v({dir:E,entrypoint:E,rpc:{accepts:["boolean"],expected:"`false`",hint:"Leave it out for an RPC binding.",literal:!1}},["dir"]),expected:"an object"},unreadable:{services:{unreadable:!0}}}],["studio",{read:(e,t)=>Fe(m(e,t),t),shape:v({companion:N}),unreadable:{studio:{unreadable:!0}}}],["target",{read:Be,shape:E,unreadable:{unreadable:!0}}]]),We=(e,t)=>s.isGetAccessorDeclaration(e)||s.isMethodDeclaration(e)?A.get(h(e))?.unreadable??{}:!s.isPropertyAssignment(e)&&!s.isShorthandPropertyAssignment(e)?{}:A.get(h(e))?.read(e,t)??{},qe=(e,t)=>new oe({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(j(e),t,{overwrite:!0}),Qe=(e,t)=>{if(e.getProperties().some(n=>s.isSpreadAssignment(n))){const n=o=>e.getProperties().some(a=>!s.isSpreadAssignment(a)&&h(a)===o);let i={unreadable:!0};for(const[o,a]of A)n(o)&&(i={...i,...a.unreadable});return i}let r={};for(const n of e.getProperties())r={...r,...We(n,t)};return r},Xe=(e,t)=>{const r=qe(e,t),n=Ce(r);if(n===void 0){const o=De(r),a=o===void 0?Ie(j(e),r,A):`${j(e)} exports ${o} as its default, so none of its settings are read. Lunora reads an object: \`export default { … } satisfies LunoraConfig\`.`;return{literals:{unreadable:!0},...o===void 0?{namedOnly:a}:{notObject:a},problems:a===void 0?[]:[a]}}const i=v(Object.fromEntries([...A].map(([o,a])=>[o,a.shape])));return{literals:Qe(n,r),problems:R(n,i,"",r)}},F=new Map,P=e=>{let t;try{t=se(e,"utf8")}catch{return{literals:{unreadable:!0},problems:[]}}const r=F.get(e);if(r?.source===t)return r.value;const n=Xe(e,t);return F.set(e,{source:t,value:n}),n},K=new Map,at=async e=>{const t=W(e);if(t===void 0)return{};let r;try{const o=B(t);r=`${String(o.mtimeMs)}:${String(o.size)}`}catch{return{}}const n=K.get(t);if(n?.key===r)return n.value;const i=(async()=>{try{const a=(await ie(t,{interopDefault:!1,moduleCache:!1}).import(t))?.default,l=a===void 0?P(t).namedOnly:void 0;return l!==void 0?{error:l}:a!==void 0&&(a===null||typeof a!="object"||Array.isArray(a))?{error:P(t).notObject??`${j(t)}'s default export is not an object, so none of its settings are read. Lunora reads an object: \`export default { … } satisfies LunoraConfig\`.`}:{config:a}}catch(o){return{error:o instanceof Error?o.message:String(o)}}})();return K.set(t,{key:r,value:i}),i},k=e=>P(e).literals,ct=e=>P(e).problems,Ze=e=>{const t=W(e);return t===void 0?{}:k(t)},lt=e=>{const{durableObjects:t}=Ze(e);return t?.unreadable&&console.warn("@lunora/codegen: `durableObjects.merge` in lunora.config is not a boolean literal — the Durable Object classes stay separate."),t?.merge===!0};let Y;const ut=e=>{const t=w(e),{codegen:r}=t===void 0?{}:k(t);if(r?.lazyFunctionsUnreadable){const n=t===void 0?void 0:B(t,{throwIfNoEntry:!1}),i=t===void 0||n===void 0?"":`${t}:${String(n.mtimeMs)}:${String(n.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 r?.lazyFunctions===!0},H=new Set,dt=e=>{const t=w(e),{studio:r}=t===void 0?{}:k(t);return r?.unreadable&&t!==void 0&&!H.has(t)&&(H.add(t),console.warn("@lunora/codegen: `studio.companion` in lunora.config is not a boolean literal, so the companion Worker is not generated.")),r?.companion===!0},G=new Set,et=(e,t,r)=>{let n;r!==void 0?{problems:n}=r:t.unreadable&&t.security===void 0?n=["is not an object literal codegen can read, so `security.headers` cannot be read either"]:n=["`security.headers` is not built from literals"];const i=`${e??""}:${n.join(";")}`;return G.has(i)||(G.add(i),console.warn(`@lunora/codegen: lunora.config ${n.join("; ")}, so the default security headers apply.`)),!0},ft=e=>{const t=w(e),r=t===void 0?{}:k(t),{security:n}=r,o=n?.unreadable===!0||r.unreadable===!0&&n===void 0?void 0:pe(n?.headers);return o?.ok?o.value:et(t,r,o)};export{g as N,dt as a,at as b,ut as c,ft as d,lt as e,S as l,ct as p,Ze as r};
@@ -1 +1 @@
1
- import{posix as w,dirname as h,join as F}from"node:path";import{Node as l,SyntaxKind as g,DiagnosticCategory as K}from"ts-morph";import{lunoraRelativePath as B}from"./isTestPath-B357_sbh.mjs";let S,v;const Oe=e=>{const t=S,n=[];S=n;try{return{erased:n,value:e()}}finally{S=t}},Ue=e=>{S?.push(...e)},V=e=>{for(const t of e.getAncestors())if(l.isVariableDeclaration(t))return t.getName()},y=(e,t)=>{S?.push({exportName:V(e),filePath:e.getSourceFile().getFilePath(),line:e.getStartLineNumber(),rendered:t})},Pe=e=>{v!==void 0&&y(v,e)},Le=(e,t)=>{const n=v;v=e;try{return t()}finally{v=n}},W=(e,t)=>{const n=e.exportName??`line ${e.line.toString()}`;return{cacheKey:`procedure_return_type_erased:${t}:${n}`,categories:["SCHEMA"],description:"Codegen renders a procedure's return type into `_generated/`, where only names that resolve from that directory may appear. A type it can neither name nor reproduce structurally — a class instance, a call or index signature, a recursive or very deeply nested shape — is emitted as `unknown` instead, so callers lose the shape while the runtime still returns it.",detail:`\`${n}\` in \`${t}\` (line ${e.line.toString()}) returns \`${e.rendered}\`, which codegen could not reproduce — its generated type is \`unknown\`.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,filePath:t,line:e.line,rendered:e.rendered},name:"procedure_return_type_erased",remediation:"Declare the shape explicitly with `.output(...)`, or export the type from the module that declares it so codegen can name it. A class instance cannot cross the wire at all — return a plain object.",title:"Procedure return type is missing from the generated type"}},Fe=(e,t)=>{const n=new Map;for(const r of e){const s=W(r,B(t,r.filePath));n.set(s.cacheKey,s)}return[...n.values()].toSorted((r,s)=>r.cacheKey.localeCompare(s.cacheKey))},q=/\bany\b(?!\s*(?:\?\s*)?:)/u,G=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,X=e=>q.test(e.replaceAll(G,"")),H="/_generated/",J=e=>{const t=[e.getSymbol(),e.getAliasSymbol()].flatMap(n=>n?.getDeclarations()??[]);return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},Y=/^(?<quote>["'])(?<specifier>.*)\k<quote>$/su,x=e=>{for(const t of e.getAncestors())if(l.isModuleDeclaration(t)){const n=Y.exec(t.getName());if(n?.groups?.specifier!==void 0)return n.groups.specifier}},M=new WeakMap,z=(e,t)=>{const n=e.getSymbol();if(n===void 0)return;let r=M.get(n.compilerSymbol);return r===void 0&&(r=new Map,M.set(n.compilerSymbol,r)),r.has(t)||r.set(t,n.getExport(t)??e.getExportSymbols().find(s=>s.getName()===t)),r.get(t)},C=(e,t)=>e.getNamespaceImport()!==void 0||e.getNamedImports().some(n=>n.getName()===t),Q=(e,t,n)=>e.getModuleSpecifierValue()===t&&C(e,n)?n:void 0,Z=(e,t)=>{const n=e.getDefaultImport();if(n===void 0)return;const r=n.getSymbol();return(r?.getAliasedSymbol()??r)?.getDeclarations().includes(t)===!0?"default":void 0},ee=(e,t,n)=>{if(!C(e,n))return;const r=e.getModuleSpecifierSourceFile(),s=r===void 0?void 0:z(r,n);return(s?.getAliasedSymbol()??s)?.getDeclarations().includes(t)===!0?n:void 0},te=/^\.\.?(?:$|\/)/u,ne=new Map([[".cjs",".cjs"],[".cts",".cjs"],[".d.ts",".js"],[".js",".js"],[".jsx",".jsx"],[".mjs",".mjs"],[".mts",".mjs"],[".ts",".js"],[".tsx",".js"]]),re=(e,t)=>{const n=t.getModuleSpecifierValue();if(!te.test(n))return;const r=t.getModuleSpecifierSourceFile(),s=r===void 0?void 0:ne.get(r.getExtension());if(r===void 0||s===void 0)return;const i=`${w.join(r.getDirectoryPath(),r.getBaseNameWithoutExtension())}${s}`,o=w.relative(e.getDirectoryPath(),i);return o.startsWith(".")?o:`./${o}`},se=(e,t,n)=>{const r=x(t);for(const s of e.getImportDeclarations()){const i=r===void 0?Z(s,t)??ee(s,t,n):Q(s,r,n);if(i!==void 0)return{exportName:i,specifier:re(e,s)??s.getModuleSpecifierValue()}}},oe=(e,t)=>Object.keys(t.getProject().getCompilerOptions().paths??{}).some(n=>{const r=n.indexOf("*");return r===-1?e===n:e.startsWith(n.slice(0,r))&&e.endsWith(n.slice(r+1))}),f={kind:"verbatim"},p={kind:"expand"},ie=new Set([g.ClassDeclaration,g.EnumDeclaration,g.EnumMember,g.InterfaceDeclaration,g.TypeAliasDeclaration]),ae=e=>x(e)!==void 0||l.isExportable(e)&&e.isExported(),ce=(e,t)=>new RegExp(String.raw`(?<![$\w])${t.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`)}(?![$\w])`,"u").test(e),O=(e,t,n,r)=>{const s=e.getSourceFile();if(s.getSymbol()===void 0&&x(e)===void 0||!ie.has(e.getKind()))return f;const i=s.getFilePath();if(i.includes(H))return f;if(i===n)return p;const o=l.isEnumMember(e)?e.getParent():e;if(!l.hasName(o))return p;const c=se(t.getSourceFile(),o,o.getName());return c===void 0?ae(o)||!ce(r(),o.getName())?f:p:oe(c.specifier,t)?p:{kind:"qualify",qualified:c}},ue=new Set([g.ClassDeclaration,g.EnumDeclaration,g.FunctionDeclaration,g.ModuleDeclaration]),_=e=>{const t=e?.getDeclarations()??[];return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},le=e=>{for(const t of e.getDeclarations()){const n=t.getFirstChildByKind(g.ComputedPropertyName);if(n!==void 0){let r=n.getExpression();for(;l.isPropertyAccessExpression(r);)r=r.getExpression();return r}}},ge=(e,t)=>{if(e.getProperties().some(s=>{if(!s.getName().startsWith("__@"))return!1;const i=le(s);return i===void 0||!_(i.getSymbol())}))return!0;const r=e.getSymbol();return r!==void 0&&r.getDeclarations().some(s=>ue.has(s.getKind()))&&!_(r)&&t().startsWith("typeof ")},U=(e,t,n)=>{const r=e.getAliasSymbol(),s=e.getSymbol(),i=new Set((r??s)?.getDeclarations());let o=!1,c;const a=()=>(c??=e.getText(t),c);for(const u of[s,r].flatMap(d=>d?.getDeclarations()??[])){const d=O(u,t,n,a);if(d.kind==="qualify"&&i.has(u))return d;o||=d.kind!=="verbatim"}return o||ge(e,a)?p:f},de=(e,t,n)=>{const r=l.isPropertySignature(e)||l.isPropertyDeclaration(e)?e.getTypeNode():void 0;if(r===void 0)return f;let s=!1;for(const i of[r,...r.getDescendantsOfKind(g.TypeReference)].filter(o=>l.isTypeReference(o))){const o=i.getTypeName().getSymbol();for(const c of(o?.getAliasedSymbol()??o)?.getDeclarations()??[]){const a=O(c,t,n,()=>i.getText());if(a.kind==="qualify")return a;s||=a.kind!=="verbatim"}}return s?p:f},fe=/^[A-Za-z_$][\w$]*$/u,me=e=>fe.test(e)?e:JSON.stringify(e),P=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},A=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0&&!e.getProperties().some(t=>t.getName().startsWith("__@")),T=(e,t,n,r=new Set)=>r.has(e)?!1:(r.add(e),U(e,t,n).kind!=="verbatim"||P(e).some(s=>T(s,t,n,r))?!0:A(e)?e.getProperties().some(s=>s.getDeclarations().some(i=>de(i,t,n).kind!=="verbatim")?!0:T(s.getTypeAtLocation(t),t,n,r)):!1),pe=(e,t)=>{const n=e.getValueDeclaration()??e.getDeclarations()[0];return n&&(l.isPropertySignature(n)||l.isPropertyDeclaration(n))&&n.hasQuestionToken()?!0:t.isUnion()&&t.getUnionTypes().some(r=>r.isUndefined())},L=(e,t)=>e!==void 0&&(A(e)||e.isString()||e.isNumber()||e.isBigInt()||e.isBoolean()||e.isLiteral()||e.isBooleanLiteral()||e.isEnumLiteral()||e.isTemplateLiteral()||e.isNull()||e.isUndefined()||e.isAny()||e.isUnknown()||e.isNever()||e.isVoid())?t:`(${t})`,Se=32,ve=8,ye=(e,t,n,r,s,i)=>{const o=e.getArrayElementType(),c=o?i(o,t,n,r,s):void 0;if(c!==void 0)return`${L(o,c)}[]`},Ee=(e,t,n,r,s,i)=>{const o=[];for(const c of e.getUnionTypes()){const a=i(c,t,n,r,s);if(a===void 0)return;o.push(a)}return[...new Set(o)].join(" | ")},be=(e,t,n,r,s,i)=>{const o=[];for(const c of e.getIntersectionTypes()){const a=i(c,t,n,r,s);if(a===void 0)return;o.push(L(c,a))}return o.join(" & ")},Te=(e,t,n,r,s,i)=>{if(!A(e))return;const o=[];for(const c of e.getProperties()){const a=c.getTypeAtLocation(t),u=pe(c,a),d=u&&a.isUnion()?a.getUnionTypes().filter(N=>!N.isUndefined()):[a],D=[];for(const N of d){const I=i(N,t,n,r+1,s);if(I===void 0)return;D.push(I)}o.push(`${me(c.getName())}${u?"?":""}: ${D.join(" | ")}`)}return o.length>0?`{ ${o.join("; ")} }`:"{}"},Ae=e=>{const t=e.getLiteralValue();return typeof t=="string"?JSON.stringify(t):typeof t=="number"?String(t):void 0},Ne=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isClassDeclaration(t)||l.isClassExpression(t)),E=(e,t,n,r,s=new Set)=>{if(r.has(e)||s.has(e))return!1;if(n>Se)return!0;const i=new Set(r).add(e);if(P(e).some(u=>E(u,t,n+1,i,s)))return!0;const o=e.getArrayElementType();if(o!==void 0)return E(o,t,n+1,i,s);if(J(e))return s.add(e),!1;if(e.getCallSignatures().length>0||e.getConstructSignatures().length>0||[e.getSymbol(),e.getAliasSymbol()].flatMap(u=>u?.getDeclarations()??[]).some(u=>l.isClassDeclaration(u)||l.isClassExpression(u)))return!0;const a=A(e)&&e.getProperties().some(u=>E(u.getTypeAtLocation(t),t,n+1,i,s));return a||s.add(e),a},xe=(e,t,n,r,s,i,o)=>{const c=[];for(const a of t.getAliasSymbol()===void 0?t.getTypeArguments():t.getAliasTypeArguments()){const u=o(a,n,r,s+1,i);if(u===void 0)return;c.push(u)}return`import("${e.specifier}").${e.exportName}${c.length>0?`<${c.join(", ")}>`:""}`},De=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isEnumDeclaration(t)||l.isEnumMember(t)),m=(e,t,n,r,s)=>{if(r>ve||s.has(e))return;const i=U(e,t,n);if(i.kind==="verbatim"&&!T(e,t,n))return e.getText(t);const o=new Set(s).add(e);if(!Ne(e)){if(e.isEnumLiteral())return Ae(e);if(i.kind==="qualify"&&!De(e)){const c=xe(i.qualified,e,t,n,r,o,m);if(c!==void 0)return c}return e.isArray()?ye(e,t,n,r,o,m):e.isUnion()?Ee(e,t,n,r,o,m):e.isIntersection()?be(e,t,n,r,o,m):Te(e,t,n,r,o,m)}},R=new WeakMap,Ie=e=>{const t=R.get(e.compilerNode);if(t)return t;const n=e.getPreEmitDiagnostics().filter(r=>r.getCategory()===K.Error);return R.set(e.compilerNode,n),n},b=e=>{const t=e.getMessageText();return typeof t=="string"?t:t.getMessageText()},we=/is of type 'unknown'|on type '\{\}'/,he=e=>we.test(e),Me=/has no exported member '([^']+)'/,_e=(e,t,n,r)=>{const s=e.getSourceFile();for(const i of e.getDescendantsOfKind(g.Identifier))for(const o of i.getSymbol()?.getDeclarations()??[]){const c=o.getStart();if(o.getSourceFile()!==s||c>=n&&c<=r)continue;const a=t.find(u=>{const d=u.getStart();return d!==void 0&&d>=o.getStart()&&d<=o.getEnd()});if(a!==void 0)return b(a)}},$=e=>{const t=e.getStart(),n=e.getEnd(),r=Ie(e.getSourceFile()),s=r.find(a=>{const u=a.getStart();return u!==void 0&&u>=t&&u<=n});if(s===void 0){const a=_e(e,r,t,n);return a===void 0?void 0:{derivative:!0,message:a}}const i=b(s);if(!he(i))return{derivative:!1,message:i};const o=new Set(e.getDescendantsOfKind(g.Identifier).map(a=>a.getText())),c=r.find(a=>{const u=Me.exec(b(a))?.[1];return u!==void 0&&o.has(u)});return{derivative:!0,message:c?`${i}; caused by: ${b(c)}`:i}},Re=e=>{const t=e.getProject().getFileSystem();let n=h(e.getFilePath());for(;;){const r=F(n,"package.json");if(t.fileExistsSync(r)){let i;try{i=JSON.parse(t.readFileSync(r))}catch{return}const o=typeof i=="object"&&i!==null?i.name:void 0;return typeof o=="string"?o:void 0}const s=h(n);if(s===n)return;n=s}},k=e=>{const t=e.getSymbol()??e.getAliasSymbol(),n=t?.getName()==="SseEvent"?t.getDeclarations()[0]:void 0;return n!==void 0&&Re(n.getSourceFile())==="@lunora/server"},$e=e=>{const t=e.isUnion()?e.getUnionTypes():[e];if(t.some(n=>k(n)))return t.flatMap(n=>{const r=k(n)?n.getTypeArguments()[0]??n:n;return r.isUnion()?r.getUnionTypes():[r]})},j=(e,t)=>{const n=e.getText(t);if(!n||n==="any"||n==="never"||n==="unknown"){const s=$(t);return s!==void 0&&(n!=="unknown"||s.derivative)&&y(t,`${n||"any"} (${s.message})`),"unknown"}if(X(n)){const s=$(t);return s!==void 0&&y(t,`${n} (${s.message})`),"unknown"}if(E(e,t,0,new Set))return"unknown";const r=t.getSourceFile().getFilePath();if(T(e,t,r)){const s=m(e,t,r,0,new Set);return s===void 0&&y(t,n),s??"unknown"}return n},Ke=(e,t=!1)=>{const n=e.getType().getCallSignatures()[0];if(!n)return"unknown";let r=n.getReturnType();const i=(r.getSymbol()??r.getAliasSymbol())?.getName();if(i==="Promise"||i==="AsyncIterable"||i==="AsyncIterableIterator"||i==="AsyncGenerator"){const a=r.getTypeArguments()[0];a&&(r=a)}const o=t?$e(r):void 0;if(o===void 0)return j(r,e);const c=o.map(a=>j(a,e));return c.includes("unknown")?"unknown":[...new Set(c)].join(" | ")};export{Ue as a,T as b,Oe as c,Pe as d,m as e,Fe as f,X as i,Le as p,j as r,Ke as u};
1
+ import{posix as w,dirname as h,join as F}from"node:path";import{Node as l,SyntaxKind as g,DiagnosticCategory as K}from"ts-morph";import{lunoraRelativePath as B}from"./isTestPath-DRIdZaij.mjs";let S,v;const Oe=e=>{const t=S,n=[];S=n;try{return{erased:n,value:e()}}finally{S=t}},Ue=e=>{S?.push(...e)},V=e=>{for(const t of e.getAncestors())if(l.isVariableDeclaration(t))return t.getName()},y=(e,t)=>{S?.push({exportName:V(e),filePath:e.getSourceFile().getFilePath(),line:e.getStartLineNumber(),rendered:t})},Pe=e=>{v!==void 0&&y(v,e)},Le=(e,t)=>{const n=v;v=e;try{return t()}finally{v=n}},W=(e,t)=>{const n=e.exportName??`line ${e.line.toString()}`;return{cacheKey:`procedure_return_type_erased:${t}:${n}`,categories:["SCHEMA"],description:"Codegen renders a procedure's return type into `_generated/`, where only names that resolve from that directory may appear. A type it can neither name nor reproduce structurally — a class instance, a call or index signature, a recursive or very deeply nested shape — is emitted as `unknown` instead, so callers lose the shape while the runtime still returns it.",detail:`\`${n}\` in \`${t}\` (line ${e.line.toString()}) returns \`${e.rendered}\`, which codegen could not reproduce — its generated type is \`unknown\`.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,filePath:t,line:e.line,rendered:e.rendered},name:"procedure_return_type_erased",remediation:"Declare the shape explicitly with `.output(...)`, or export the type from the module that declares it so codegen can name it. A class instance cannot cross the wire at all — return a plain object.",title:"Procedure return type is missing from the generated type"}},Fe=(e,t)=>{const n=new Map;for(const r of e){const s=W(r,B(t,r.filePath));n.set(s.cacheKey,s)}return[...n.values()].toSorted((r,s)=>r.cacheKey.localeCompare(s.cacheKey))},q=/\bany\b(?!\s*(?:\?\s*)?:)/u,G=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,X=e=>q.test(e.replaceAll(G,"")),H="/_generated/",J=e=>{const t=[e.getSymbol(),e.getAliasSymbol()].flatMap(n=>n?.getDeclarations()??[]);return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},Y=/^(?<quote>["'])(?<specifier>.*)\k<quote>$/su,x=e=>{for(const t of e.getAncestors())if(l.isModuleDeclaration(t)){const n=Y.exec(t.getName());if(n?.groups?.specifier!==void 0)return n.groups.specifier}},M=new WeakMap,z=(e,t)=>{const n=e.getSymbol();if(n===void 0)return;let r=M.get(n.compilerSymbol);return r===void 0&&(r=new Map,M.set(n.compilerSymbol,r)),r.has(t)||r.set(t,n.getExport(t)??e.getExportSymbols().find(s=>s.getName()===t)),r.get(t)},C=(e,t)=>e.getNamespaceImport()!==void 0||e.getNamedImports().some(n=>n.getName()===t),Q=(e,t,n)=>e.getModuleSpecifierValue()===t&&C(e,n)?n:void 0,Z=(e,t)=>{const n=e.getDefaultImport();if(n===void 0)return;const r=n.getSymbol();return(r?.getAliasedSymbol()??r)?.getDeclarations().includes(t)===!0?"default":void 0},ee=(e,t,n)=>{if(!C(e,n))return;const r=e.getModuleSpecifierSourceFile(),s=r===void 0?void 0:z(r,n);return(s?.getAliasedSymbol()??s)?.getDeclarations().includes(t)===!0?n:void 0},te=/^\.\.?(?:$|\/)/u,ne=new Map([[".cjs",".cjs"],[".cts",".cjs"],[".d.ts",".js"],[".js",".js"],[".jsx",".jsx"],[".mjs",".mjs"],[".mts",".mjs"],[".ts",".js"],[".tsx",".js"]]),re=(e,t)=>{const n=t.getModuleSpecifierValue();if(!te.test(n))return;const r=t.getModuleSpecifierSourceFile(),s=r===void 0?void 0:ne.get(r.getExtension());if(r===void 0||s===void 0)return;const i=`${w.join(r.getDirectoryPath(),r.getBaseNameWithoutExtension())}${s}`,o=w.relative(e.getDirectoryPath(),i);return o.startsWith(".")?o:`./${o}`},se=(e,t,n)=>{const r=x(t);for(const s of e.getImportDeclarations()){const i=r===void 0?Z(s,t)??ee(s,t,n):Q(s,r,n);if(i!==void 0)return{exportName:i,specifier:re(e,s)??s.getModuleSpecifierValue()}}},oe=(e,t)=>Object.keys(t.getProject().getCompilerOptions().paths??{}).some(n=>{const r=n.indexOf("*");return r===-1?e===n:e.startsWith(n.slice(0,r))&&e.endsWith(n.slice(r+1))}),f={kind:"verbatim"},p={kind:"expand"},ie=new Set([g.ClassDeclaration,g.EnumDeclaration,g.EnumMember,g.InterfaceDeclaration,g.TypeAliasDeclaration]),ae=e=>x(e)!==void 0||l.isExportable(e)&&e.isExported(),ce=(e,t)=>new RegExp(String.raw`(?<![$\w])${t.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`)}(?![$\w])`,"u").test(e),O=(e,t,n,r)=>{const s=e.getSourceFile();if(s.getSymbol()===void 0&&x(e)===void 0||!ie.has(e.getKind()))return f;const i=s.getFilePath();if(i.includes(H))return f;if(i===n)return p;const o=l.isEnumMember(e)?e.getParent():e;if(!l.hasName(o))return p;const c=se(t.getSourceFile(),o,o.getName());return c===void 0?ae(o)||!ce(r(),o.getName())?f:p:oe(c.specifier,t)?p:{kind:"qualify",qualified:c}},ue=new Set([g.ClassDeclaration,g.EnumDeclaration,g.FunctionDeclaration,g.ModuleDeclaration]),_=e=>{const t=e?.getDeclarations()??[];return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},le=e=>{for(const t of e.getDeclarations()){const n=t.getFirstChildByKind(g.ComputedPropertyName);if(n!==void 0){let r=n.getExpression();for(;l.isPropertyAccessExpression(r);)r=r.getExpression();return r}}},ge=(e,t)=>{if(e.getProperties().some(s=>{if(!s.getName().startsWith("__@"))return!1;const i=le(s);return i===void 0||!_(i.getSymbol())}))return!0;const r=e.getSymbol();return r!==void 0&&r.getDeclarations().some(s=>ue.has(s.getKind()))&&!_(r)&&t().startsWith("typeof ")},U=(e,t,n)=>{const r=e.getAliasSymbol(),s=e.getSymbol(),i=new Set((r??s)?.getDeclarations());let o=!1,c;const a=()=>(c??=e.getText(t),c);for(const u of[s,r].flatMap(d=>d?.getDeclarations()??[])){const d=O(u,t,n,a);if(d.kind==="qualify"&&i.has(u))return d;o||=d.kind!=="verbatim"}return o||ge(e,a)?p:f},de=(e,t,n)=>{const r=l.isPropertySignature(e)||l.isPropertyDeclaration(e)?e.getTypeNode():void 0;if(r===void 0)return f;let s=!1;for(const i of[r,...r.getDescendantsOfKind(g.TypeReference)].filter(o=>l.isTypeReference(o))){const o=i.getTypeName().getSymbol();for(const c of(o?.getAliasedSymbol()??o)?.getDeclarations()??[]){const a=O(c,t,n,()=>i.getText());if(a.kind==="qualify")return a;s||=a.kind!=="verbatim"}}return s?p:f},fe=/^[A-Za-z_$][\w$]*$/u,me=e=>fe.test(e)?e:JSON.stringify(e),P=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},A=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0&&!e.getProperties().some(t=>t.getName().startsWith("__@")),T=(e,t,n,r=new Set)=>r.has(e)?!1:(r.add(e),U(e,t,n).kind!=="verbatim"||P(e).some(s=>T(s,t,n,r))?!0:A(e)?e.getProperties().some(s=>s.getDeclarations().some(i=>de(i,t,n).kind!=="verbatim")?!0:T(s.getTypeAtLocation(t),t,n,r)):!1),pe=(e,t)=>{const n=e.getValueDeclaration()??e.getDeclarations()[0];return n&&(l.isPropertySignature(n)||l.isPropertyDeclaration(n))&&n.hasQuestionToken()?!0:t.isUnion()&&t.getUnionTypes().some(r=>r.isUndefined())},L=(e,t)=>e!==void 0&&(A(e)||e.isString()||e.isNumber()||e.isBigInt()||e.isBoolean()||e.isLiteral()||e.isBooleanLiteral()||e.isEnumLiteral()||e.isTemplateLiteral()||e.isNull()||e.isUndefined()||e.isAny()||e.isUnknown()||e.isNever()||e.isVoid())?t:`(${t})`,Se=32,ve=8,ye=(e,t,n,r,s,i)=>{const o=e.getArrayElementType(),c=o?i(o,t,n,r,s):void 0;if(c!==void 0)return`${L(o,c)}[]`},Ee=(e,t,n,r,s,i)=>{const o=[];for(const c of e.getUnionTypes()){const a=i(c,t,n,r,s);if(a===void 0)return;o.push(a)}return[...new Set(o)].join(" | ")},be=(e,t,n,r,s,i)=>{const o=[];for(const c of e.getIntersectionTypes()){const a=i(c,t,n,r,s);if(a===void 0)return;o.push(L(c,a))}return o.join(" & ")},Te=(e,t,n,r,s,i)=>{if(!A(e))return;const o=[];for(const c of e.getProperties()){const a=c.getTypeAtLocation(t),u=pe(c,a),d=u&&a.isUnion()?a.getUnionTypes().filter(N=>!N.isUndefined()):[a],D=[];for(const N of d){const I=i(N,t,n,r+1,s);if(I===void 0)return;D.push(I)}o.push(`${me(c.getName())}${u?"?":""}: ${D.join(" | ")}`)}return o.length>0?`{ ${o.join("; ")} }`:"{}"},Ae=e=>{const t=e.getLiteralValue();return typeof t=="string"?JSON.stringify(t):typeof t=="number"?String(t):void 0},Ne=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isClassDeclaration(t)||l.isClassExpression(t)),E=(e,t,n,r,s=new Set)=>{if(r.has(e)||s.has(e))return!1;if(n>Se)return!0;const i=new Set(r).add(e);if(P(e).some(u=>E(u,t,n+1,i,s)))return!0;const o=e.getArrayElementType();if(o!==void 0)return E(o,t,n+1,i,s);if(J(e))return s.add(e),!1;if(e.getCallSignatures().length>0||e.getConstructSignatures().length>0||[e.getSymbol(),e.getAliasSymbol()].flatMap(u=>u?.getDeclarations()??[]).some(u=>l.isClassDeclaration(u)||l.isClassExpression(u)))return!0;const a=A(e)&&e.getProperties().some(u=>E(u.getTypeAtLocation(t),t,n+1,i,s));return a||s.add(e),a},xe=(e,t,n,r,s,i,o)=>{const c=[];for(const a of t.getAliasSymbol()===void 0?t.getTypeArguments():t.getAliasTypeArguments()){const u=o(a,n,r,s+1,i);if(u===void 0)return;c.push(u)}return`import("${e.specifier}").${e.exportName}${c.length>0?`<${c.join(", ")}>`:""}`},De=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isEnumDeclaration(t)||l.isEnumMember(t)),m=(e,t,n,r,s)=>{if(r>ve||s.has(e))return;const i=U(e,t,n);if(i.kind==="verbatim"&&!T(e,t,n))return e.getText(t);const o=new Set(s).add(e);if(!Ne(e)){if(e.isEnumLiteral())return Ae(e);if(i.kind==="qualify"&&!De(e)){const c=xe(i.qualified,e,t,n,r,o,m);if(c!==void 0)return c}return e.isArray()?ye(e,t,n,r,o,m):e.isUnion()?Ee(e,t,n,r,o,m):e.isIntersection()?be(e,t,n,r,o,m):Te(e,t,n,r,o,m)}},R=new WeakMap,Ie=e=>{const t=R.get(e.compilerNode);if(t)return t;const n=e.getPreEmitDiagnostics().filter(r=>r.getCategory()===K.Error);return R.set(e.compilerNode,n),n},b=e=>{const t=e.getMessageText();return typeof t=="string"?t:t.getMessageText()},we=/is of type 'unknown'|on type '\{\}'/,he=e=>we.test(e),Me=/has no exported member '([^']+)'/,_e=(e,t,n,r)=>{const s=e.getSourceFile();for(const i of e.getDescendantsOfKind(g.Identifier))for(const o of i.getSymbol()?.getDeclarations()??[]){const c=o.getStart();if(o.getSourceFile()!==s||c>=n&&c<=r)continue;const a=t.find(u=>{const d=u.getStart();return d!==void 0&&d>=o.getStart()&&d<=o.getEnd()});if(a!==void 0)return b(a)}},$=e=>{const t=e.getStart(),n=e.getEnd(),r=Ie(e.getSourceFile()),s=r.find(a=>{const u=a.getStart();return u!==void 0&&u>=t&&u<=n});if(s===void 0){const a=_e(e,r,t,n);return a===void 0?void 0:{derivative:!0,message:a}}const i=b(s);if(!he(i))return{derivative:!1,message:i};const o=new Set(e.getDescendantsOfKind(g.Identifier).map(a=>a.getText())),c=r.find(a=>{const u=Me.exec(b(a))?.[1];return u!==void 0&&o.has(u)});return{derivative:!0,message:c?`${i}; caused by: ${b(c)}`:i}},Re=e=>{const t=e.getProject().getFileSystem();let n=h(e.getFilePath());for(;;){const r=F(n,"package.json");if(t.fileExistsSync(r)){let i;try{i=JSON.parse(t.readFileSync(r))}catch{return}const o=typeof i=="object"&&i!==null?i.name:void 0;return typeof o=="string"?o:void 0}const s=h(n);if(s===n)return;n=s}},k=e=>{const t=e.getSymbol()??e.getAliasSymbol(),n=t?.getName()==="SseEvent"?t.getDeclarations()[0]:void 0;return n!==void 0&&Re(n.getSourceFile())==="@lunora/server"},$e=e=>{const t=e.isUnion()?e.getUnionTypes():[e];if(t.some(n=>k(n)))return t.flatMap(n=>{const r=k(n)?n.getTypeArguments()[0]??n:n;return r.isUnion()?r.getUnionTypes():[r]})},j=(e,t)=>{const n=e.getText(t);if(!n||n==="any"||n==="never"||n==="unknown"){const s=$(t);return s!==void 0&&(n!=="unknown"||s.derivative)&&y(t,`${n||"any"} (${s.message})`),"unknown"}if(X(n)){const s=$(t);return s!==void 0&&y(t,`${n} (${s.message})`),"unknown"}if(E(e,t,0,new Set))return"unknown";const r=t.getSourceFile().getFilePath();if(T(e,t,r)){const s=m(e,t,r,0,new Set);return s===void 0&&y(t,n),s??"unknown"}return n},Ke=(e,t=!1)=>{const n=e.getType().getCallSignatures()[0];if(!n)return"unknown";let r=n.getReturnType();const i=(r.getSymbol()??r.getAliasSymbol())?.getName();if(i==="Promise"||i==="AsyncIterable"||i==="AsyncIterableIterator"||i==="AsyncGenerator"){const a=r.getTypeArguments()[0];a&&(r=a)}const o=t?$e(r):void 0;if(o===void 0)return j(r,e);const c=o.map(a=>j(a,e));return c.includes("unknown")?"unknown":[...new Set(c)].join(" | ")};export{Ue as a,T as b,Oe as c,Pe as d,m as e,Fe as f,X as i,Le as p,j as r,Ke as u};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.402",
3
+ "version": "1.0.0-alpha.403",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -1 +0,0 @@
1
- import{w as a}from"./classify-procedure-call-DwWrpCoX.mjs";const l=s=>a(s,"use","rls");export{l as r};
@@ -1 +0,0 @@
1
- import"./declared-output-Iaar469J.mjs";import"./isTestPath-B357_sbh.mjs";import"./attribution-C6VQNs-V.mjs";import"./unwrap-handler-return-zNStZJ4K.mjs";import"./ip-reads-Bn9qvrMD.mjs";import"./classify-procedure-call-DwWrpCoX.mjs";import{d as f}from"./index-BPg6e1oa.mjs";import"./dispatch-namespace-DwTjD7BU.mjs";export{f as default};
@@ -1 +0,0 @@
1
- import{d as o}from"./context-property-calls-RsCkfFCU.mjs";const t=(r,e)=>o(r,e,"sql");export{t as default};
@@ -1 +0,0 @@
1
- import"./isTestPath-B357_sbh.mjs";import"./attribution-C6VQNs-V.mjs";import"./database-calls-HP2mxQAR.mjs";import"./classify-procedure-call-DwWrpCoX.mjs";import{d as a}from"./index-DgHhQfpm.mjs";export{a as default};
@@ -1 +0,0 @@
1
- import{d as r}from"./context-property-calls-RsCkfFCU.mjs";const t=(s,o)=>r(s,o,"r2sql");export{t as default};
@@ -1 +0,0 @@
1
- import{b as a,e as t,r as i,c,d,a as s}from"./project-config-file-DBVmBpin.mjs";import"./property-name-7cBlgK_O.mjs";import{PROJECT_CONFIG_FILENAMES as j,findProjectConfigFile as P}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";export{j as PROJECT_CONFIG_FILENAMES,P as findProjectConfigFile,a as loadProjectConfig,t as readMergeDurableObjects,i as readProjectConfigLiterals,c as readProjectLazyFunctions,d as readProjectSecurityHeaders,s as readProjectStudioCompanion};
@@ -1 +0,0 @@
1
- import{statSync as z,readFileSync as $}from"node:fs";import{basename as D}from"node:path";import{createJiti as M}from"jiti";import{Node as n,SyntaxKind as p,Project as _,VariableDeclarationKind as R}from"ts-morph";import{a as b}from"./property-name-7cBlgK_O.mjs";import{findProjectConfigFile as I,findCodegenConfigFile as O}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";const F=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},U=/^[a-z][\d+.a-z-]*:\/\/(?:\*\.)?[\d.a-z-]+(?::\d{1,5})?$/iu,C=e=>[...e].every(t=>t===" "||t>=" "&&t!==""&&t<="ÿ"),K=["same-origin","same-origin-allow-popups","unsafe-none"],H=["DENY","SAMEORIGIN"],L=["includeSubDomains","maxAge","preload"],w=["csp","permissionsPolicy","referrerPolicy"],A=[...w,"crossOriginOpenerPolicy","frameAncestors","frameOptions","hsts"],S=e=>e.map(t=>JSON.stringify(t)).join(", "),J=(e,t)=>{if(typeof e=="boolean")return e;if(!F(e)){t.push("security.headers.hsts must be a boolean or an object { maxAge?, includeSubDomains?, preload? }");return}for(const o of Object.keys(e).filter(a=>!L.includes(a)))t.push(`security.headers.hsts.${o} is not an option (expected ${S(L)})`);const{includeSubDomains:r,maxAge:i,preload:s}=e;i!==void 0&&!(typeof i=="number"&&Number.isSafeInteger(i)&&i>=0)&&t.push(`security.headers.hsts.maxAge must be a whole number of seconds (got ${JSON.stringify(i)})`);for(const[o,a]of[["includeSubDomains",r],["preload",s]])a!==void 0&&typeof a!="boolean"&&t.push(`security.headers.hsts.${o} must be a boolean`);return{...r===void 0?{}:{includeSubDomains:r},...i===void 0?{}:{maxAge:i},...s===void 0?{}:{preload:s}}},P=(e,t,r,i)=>{if(t===void 0||t===!1||r.includes(t))return t;i.push(`security.headers.${e} must be one of ${S(r)} or false (got ${JSON.stringify(t)})`)},Y=(e,t)=>{if(e!==void 0){if(!Array.isArray(e)){t.push('security.headers.frameAncestors must be an array of origins like ["https://partner.example"]');return}for(const r of e)(typeof r!="string"||!U.test(r)||!C(r))&&t.push(`security.headers.frameAncestors entry ${JSON.stringify(r)} is not an origin like "https://partner.example"`);return[...e]}},W=e=>{if(e===void 0||typeof e=="boolean")return{ok:!0,value:e};if(!F(e))return{ok:!1,problems:[`security.headers must be a boolean or an object (got ${Array.isArray(e)?"an array":JSON.stringify(e)})`]};const t=Object.keys(e).filter(i=>!A.includes(i)).map(i=>`security.headers.${i} is not an option (expected ${S(A)})`),r={};for(const i of w){const s=e[i];s===void 0||s===!1?r[i]=s:typeof s!="string"?t.push(`security.headers.${i} must be a string or false`):C(s)?r[i]=s:t.push(`security.headers.${i} contains a line break or control character`)}return r.crossOriginOpenerPolicy=P("crossOriginOpenerPolicy",e.crossOriginOpenerPolicy,K,t),r.frameOptions=P("frameOptions",e.frameOptions,H,t),r.frameAncestors=Y(e.frameAncestors,t),r.hsts=e.hsts===void 0?void 0:J(e.hsts,t),r.frameAncestors!==void 0&&typeof r.csp=="string"&&t.push("security.headers.frameAncestors cannot be combined with a csp string: put the frame-ancestors directive in the csp"),r.frameAncestors!==void 0&&r.frameOptions==="DENY"&&t.push('security.headers.frameAncestors cannot be combined with frameOptions: "DENY"'),r.frameAncestors!==void 0&&r.csp===!1&&t.push("security.headers.frameAncestors needs the Content-Security-Policy that carries it; it cannot be combined with csp: false"),t.length>0?{ok:!1,problems:t}:{ok:!0,value:Object.fromEntries(Object.entries(r).filter(([,i])=>i!==void 0))}},d=Symbol("not-literal"),N=e=>Number(e.getText().replaceAll("_","")),G=e=>n.isStringLiteral(e)||n.isNoSubstitutionTemplateLiteral(e)?e.getLiteralValue():n.isNumericLiteral(e)?N(e):n.isPrefixUnaryExpression(e)&&e.getOperatorToken()===p.MinusToken&&n.isNumericLiteral(e.getOperand())?-N(e.getOperand()):n.isTrueLiteral(e)||n.isFalseLiteral(e)?e.getLiteralValue():n.isBinaryExpression(e)?B(e):n.isNullLiteral(e)?null:d,q={[p.AsteriskAsteriskToken]:(e,t)=>e**t,[p.AsteriskToken]:(e,t)=>e*t,[p.MinusToken]:(e,t)=>e-t,[p.PercentToken]:(e,t)=>e%t,[p.PlusToken]:(e,t)=>e+t,[p.SlashToken]:(e,t)=>e/t},B=e=>{const t=q[e.getOperatorToken().getKind()],[r,i]=[y(e.getLeft()),y(e.getRight())];return t!==void 0&&typeof r=="number"&&typeof i=="number"&&Number.isFinite(r)&&Number.isFinite(i)?t(r,i):d},y=e=>{if(n.isParenthesizedExpression(e)||n.isAsExpression(e)||n.isSatisfiesExpression(e))return y(e.getExpression());if(n.isArrayLiteralExpression(e)){const t=e.getElements().map(r=>y(r));return t.includes(d)?d:t}return n.isObjectLiteralExpression(e)?Q(e):G(e)},Q=e=>{const t=[];for(const r of e.getProperties()){const i=n.isPropertyAssignment(r)?r.getNameNode():void 0,s=n.isPropertyAssignment(r)?r.getInitializer():void 0,o=s===void 0?d:y(s);if(i===void 0||o===d||!(n.isIdentifier(i)||n.isStringLiteral(i)))return d;const a=n.isStringLiteral(i)?i.getLiteralValue():i.getText();if(a==="__proto__")return d;t.push([a,o])}return Object.fromEntries(t)},E=new Map,Ae=async e=>{const t=I(e);if(t===void 0)return{};let r;try{const o=z(t);r=`${String(o.mtimeMs)}:${String(o.size)}`}catch{return{}}const i=E.get(t);if(i?.key===r)return i.value;const s=(async()=>{try{const a=(await M(t,{interopDefault:!1,moduleCache:!1}).import(t))?.default;return{config:a!==null&&typeof a=="object"?a:void 0}}catch(o){return{error:o instanceof Error?o.message:String(o)}}})();return E.set(t,{key:r,value:s}),s},u=e=>{let t=e;for(;t!==void 0&&(n.isSatisfiesExpression(t)||n.isAsExpression(t)||n.isParenthesizedExpression(t));)t=t.getExpression();return t},X=e=>{const t=e.getExportAssignments().find(i=>!i.isExportEquals());let r=u(t?.getExpression());return r!==void 0&&n.isIdentifier(r)&&(r=u(e.getVariableDeclaration(r.getText())?.getInitializer())),r!==void 0&&n.isObjectLiteralExpression(r)?r:void 0},m=(e,t)=>n.isPropertyAssignment(e)?e.getInitializer():t.getVariableDeclaration(b(e))?.getInitializer(),g=(e,t,r)=>{const i=u(e);if(i===void 0||!n.isObjectLiteralExpression(i))return{unreadable:!0};const s=i.getProperties(),o=s.filter(l=>n.isPropertyAssignment(l)&&!n.isComputedPropertyName(l.getNameNode())||n.isShorthandPropertyAssignment(l));if(o.length!==s.length)return{unreadable:!0};const a=o.findLast(l=>b(l)===r);if(a===void 0)return{absent:!0};const c=m(a,t);return c===void 0?{unreadable:!0}:{literal:c}},Z=["exportName","file","reason","rule"],ee=e=>{const t=u(e);if(t===void 0||!n.isObjectLiteralExpression(t))return;const r={};for(const c of t.getProperties()){if(!n.isPropertyAssignment(c)||n.isComputedPropertyName(c.getNameNode()))return;const l=b(c),f=u(c.getInitializer());if(!Z.includes(l)||f===void 0||!n.isStringLiteral(f)&&!n.isNoSubstitutionTemplateLiteral(f))return;r[l]=f.getLiteralValue()}const{exportName:i,file:s,reason:o,rule:a}=r;return i?.trim()&&s?.trim()&&o?.trim()&&a?.trim()?{exportName:i,file:s,reason:o,rule:a}:void 0},te=(e,t)=>{const r=g(e,t,"accept");if("absent"in r)return{};const i="literal"in r?u(r.literal):void 0;if(i===void 0||!n.isArrayLiteralExpression(i))return{acceptUnreadable:!0};const s=[];for(const o of i.getElements()){const a=ee(o);if(a===void 0)return{acceptUnreadable:!0};s.push(a)}return{accept:s}},re=(e,t)=>{const r=g(e,t,"minSeverity"),i=te(e,t);return"absent"in r?{advisor:i}:"literal"in r&&n.isStringLiteral(r.literal)?{advisor:{...i,minSeverity:r.literal.getLiteralValue()}}:{advisor:{...i,unreadable:!0}}},ie=(e,t)=>{const r=g(e,t,"exclude");if("absent"in r)return{};if(!("literal"in r)||!n.isArrayLiteralExpression(r.literal))return{unreadable:!0};const i=[];for(const s of r.literal.getElements()){if(!n.isStringLiteral(s)&&!n.isNoSubstitutionTemplateLiteral(s)||s.getLiteralValue().startsWith("!"))return{unreadable:!0};i.push(s.getLiteralValue())}return{exclude:i}},ne=(e,t,r)=>{const i=g(e,t,"lazyFunctions");if("absent"in i)return{};if("unreadable"in i)return e!==void 0&&(n.isIdentifier(e)||e.getText().includes("lazyFunctions")||r&&!n.isObjectLiteralExpression(e))?{lazyFunctionsUnreadable:!0}:{};const s="literal"in i?u(i.literal):void 0;return s!==void 0&&(n.isTrueLiteral(s)||n.isFalseLiteral(s))?{lazyFunctions:s.getLiteralValue()}:{lazyFunctionsUnreadable:!0}},se=(e,t)=>{const r=u(e),i=r!==void 0&&n.isIdentifier(r),s=r!==void 0&&n.isIdentifier(r)?t.getVariableDeclaration(r.getText()):void 0,o=s?.getVariableStatement()?.getDeclarationKind()===R.Const,a=s?.getNameNode(),l=s!==void 0&&o&&a!==void 0&&n.isIdentifier(a)&&a.findReferencesAsNodes().length===1?u(s.getInitializer())??r:r;return{codegen:{...ie(l,t),...ne(l,t,i)}}},oe=(e,t)=>{const r=g(e,t,"merge");return"absent"in r?{durableObjects:{}}:"literal"in r&&(n.isTrueLiteral(r.literal)||n.isFalseLiteral(r.literal))?{durableObjects:{merge:r.literal.getLiteralValue()}}:{durableObjects:{unreadable:!0}}},ae=(e,t)=>{const r=g(e,t,"companion");return"absent"in r?{studio:{}}:"literal"in r&&(n.isTrueLiteral(r.literal)||n.isFalseLiteral(r.literal))?{studio:{companion:r.literal.getLiteralValue()}}:{studio:{unreadable:!0}}},le=(e,t)=>{const r=g(e,t,"headers");if("absent"in r)return{security:{}};const i="literal"in r?y(r.literal):d;return i===d?{security:{unreadable:!0}}:{security:{headers:i}}},V=(e,t)=>{const r=e.getProperty(t);if(r!==void 0)return(n.isPropertyAssignment(r)?r.getInitializer():void 0)??"unreadable"},x=(e,t)=>{const r=V(e,t);if(r!==void 0)return r!=="unreadable"&&(n.isStringLiteral(r)||n.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():!1},ce=e=>{const t=V(e,"rpc");if(t!==void 0)return t!=="unreadable"&&n.isFalseLiteral(t)?!1:"unreadable"},ue=e=>{const t=u(e);if(t===void 0||!n.isObjectLiteralExpression(t))return{services:{unreadable:!0}};const r={};for(const i of t.getProperties()){if(!n.isPropertyAssignment(i)||n.isComputedPropertyName(i.getNameNode()))return{services:{unreadable:!0}};const s=u(i.getInitializer());if(s===void 0||!n.isObjectLiteralExpression(s)||s.getProperties().some(l=>!n.isPropertyAssignment(l)))return{services:{unreadable:!0}};const o=x(s,"dir"),a=x(s,"entrypoint"),c=ce(s);if(typeof o!="string"||a===!1||c==="unreadable")return{services:{unreadable:!0}};r[b(i)]={dir:o,...a===void 0?{}:{entrypoint:a},...c===void 0?{}:{rpc:c}}}return{services:{declared:r}}},de=(e,t)=>n.isShorthandPropertyAssignment(e)?e.getNameNode():m(e,t),fe=(e,t)=>{const r=m(e,t);return r!==void 0&&n.isStringLiteral(r)?{target:r.getLiteralValue()}:{unreadable:!0}},me=(e,t)=>{const r=m(e,t);return r!==void 0&&(n.isTrueLiteral(r)||n.isFalseLiteral(r))?{remote:r.getLiteralValue()}:r!==void 0&&n.isObjectLiteralExpression(r)?{remote:!0}:{unreadable:!0}},h=new Map([["advisor",{read:(e,t)=>re(m(e,t),t),unreadable:{advisor:{unreadable:!0}}}],["codegen",{read:(e,t)=>se(de(e,t),t),unreadable:{codegen:{lazyFunctionsUnreadable:!0,unreadable:!0}}}],["durableObjects",{read:(e,t)=>oe(m(e,t),t),unreadable:{durableObjects:{unreadable:!0}}}],["remote",{read:me,unreadable:{unreadable:!0}}],["security",{read:(e,t)=>le(m(e,t),t),unreadable:{security:{unreadable:!0}}}],["services",{read:(e,t)=>ue(m(e,t)),unreadable:{services:{unreadable:!0}}}],["studio",{read:(e,t)=>ae(m(e,t),t),unreadable:{studio:{unreadable:!0}}}],["target",{read:fe,unreadable:{unreadable:!0}}]]),pe=(e,t)=>n.isGetAccessorDeclaration(e)||n.isMethodDeclaration(e)?h.get(b(e))?.unreadable??{}:!n.isPropertyAssignment(e)&&!n.isShorthandPropertyAssignment(e)?{}:h.get(b(e))?.read(e,t)??{},v=e=>{let t;try{t=$(e,"utf8")}catch{return{unreadable:!0}}const i=new _({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(D(e),t,{overwrite:!0}),s=X(i);if(s===void 0)return{unreadable:!0};if(s.getProperties().some(a=>n.isSpreadAssignment(a))){const a=l=>s.getProperties().some(f=>!n.isSpreadAssignment(f)&&b(f)===l);let c={unreadable:!0};for(const[l,f]of h)a(l)&&(c={...c,...f.unreadable});return c}let o={};for(const a of s.getProperties())o={...o,...pe(a,i)};return o},be=e=>{const t=I(e);return t===void 0?{}:v(t)},Pe=e=>{const{durableObjects:t}=be(e);return t?.unreadable&&console.warn("@lunora/codegen: `durableObjects.merge` in lunora.config is not a boolean literal — the Durable Object classes stay separate."),t?.merge===!0};let j;const Ne=e=>{const t=O(e),{codegen:r}=t===void 0?{}:v(t);if(r?.lazyFunctionsUnreadable){const i=t===void 0?void 0:z(t,{throwIfNoEntry:!1}),s=t===void 0||i===void 0?"":`${t}:${String(i.mtimeMs)}:${String(i.size)}`;s!==j&&(j=s,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 r?.lazyFunctions===!0},k=new Set,Ee=e=>{const t=O(e),{studio:r}=t===void 0?{}:v(t);return r?.unreadable&&t!==void 0&&!k.has(t)&&(k.add(t),console.warn("@lunora/codegen: `studio.companion` in lunora.config is not a boolean literal, so the companion Worker is not generated.")),r?.companion===!0},T=new Set,ge=(e,t,r)=>{let i;r!==void 0?{problems:i}=r:t.unreadable&&t.security===void 0?i=["is not an object literal codegen can read, so `security.headers` cannot be read either"]:i=["`security.headers` is not built from literals"];const s=`${e??""}:${i.join(";")}`;return T.has(s)||(T.add(s),console.warn(`@lunora/codegen: lunora.config ${i.join("; ")}, so the default security headers apply.`)),!0},xe=e=>{const t=O(e),r=t===void 0?{}:v(t),{security:i}=r,o=i?.unreadable===!0||r.unreadable===!0&&i===void 0?void 0:W(i?.headers);return o?.ok?o.value:ge(t,r,o)};export{d as N,Ee as a,Ae as b,Ne as c,xe as d,Pe as e,y as l,be as r};