@lunora/codegen 1.0.0-alpha.413 → 1.0.0-alpha.414

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.
@@ -0,0 +1 @@
1
+ import{join as j,relative as Q,isAbsolute as Y,sep as $,dirname as ee}from"node:path";import{LunoraError as te}from"@lunora/errors";import{Node as a,SyntaxKind as N}from"ts-morph";import{diagnosticAt as d}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{findObjectProperty as m,lunoraRelativePath as ne,unwrapExpression as D,symbolConstInitializer as re,descendantsOfKind as se}from"./isTestPath-Uwb5a6Kq.mjs";import{createRequire as ie}from"node:module";import{fileURLToPath as oe}from"node:url";import{createJiti as ae}from"jiti";import{l as le,N as ce}from"./project-config-file-DR7xrrNB.mjs";import{r as de,p as fe}from"./parse-validator-BisfC8bR.mjs";import{R as ue}from"./reserved-words-CW1QFbTd.mjs";import{a as P}from"./property-name-7cBlgK_O.mjs";const ge=(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.`,me=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}},pe=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}:{}}),b=e=>{const t=e?._meta??{},n=e?.kind??"unknown",r={column:pe(t.column),kind:n,...t.sensitive===!0?{sensitive:!0}:{}};switch(n){case"array":case"optional":{r.inner=b(t.inner);break}case"from":break;case"id":{r.tableName=t.tableName;break}case"literal":{r.literalValue=me(t.value);break}case"object":{const i=t.shape??{};r.shape=Object.fromEntries(Object.entries(i).map(([o,l])=>[o,b(l)]));break}case"record":{r.valueType=b(t.valueValidator),t.keyValidator!==void 0&&(r.keyType=b(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=>b(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},he=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",be=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")}}},xe=(e,t)=>{const n=e.shape??{},r=(e.indexes??[]).map(i=>({fields:i.fields,name:i.name,...i.unique?{unique:!0}:{}})),s=he(e.shardMode);return{...e.aggregateIndexes&&e.aggregateIndexes.length>0?{aggregateIndexed:!0}:{},...e.commitOrderedMode===!0?{commitOrdered:!0}:{},...e.isExternallyManaged?{externallyManaged:!0}:{},...e.externalSource?{externalSource:be(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,b(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}))}},ye=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])=>xe(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}},ve=e=>{if(a.isIdentifier(e))return e.getText();if(a.isPropertyAccessExpression(e)){const t=e.getExpression();return a.isIdentifier(t)?t.getText():void 0}},Ee=e=>{const t=ve(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:[]}}},R=e=>a.isCallExpression(e)?e:a.isParenthesizedExpression(e)||a.isAsExpression(e)||a.isSatisfiesExpression(e)?R(e.getExpression()):void 0,Ie=(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()},Se=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:R(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=>le(u)),c=s.getReturnType().getProperty(e.getName())?.getTypeAtLocation(s).getNonNullableType();if(!(l.includes(ce)||c?.getProperty("tables")===void 0))for(const u of s.getSourceFile().getImportDeclarations()){const g=u.getModuleSpecifierValue();if(g.startsWith("."))continue;const h=Ie(u,i,o);if(h!==void 0)return{args:l,importedName:h,moduleSpecifier:g,propertyPath:[e.getName()]}}},F=(e,t)=>{let n=e;for(const r of t){if(typeof n!="object"||n===null)return;n=n[r]}return n},we=(e,t)=>F(e[t.importedName],t.propertyPath),C=(e,t)=>{const n=ae(j(t,"noop.js")).esmResolve(e);return ie(j(t,"noop.cjs"))(n.startsWith("file:")?oe(n):n)},Te=(e,t)=>{const n=Ee(e);if(n&&!n.moduleSpecifier.startsWith("."))return we(C(n.moduleSpecifier,t),n);const r=Se(e);if(!r)return;const s=C(r.moduleSpecifier,t)[r.importedName];return typeof s=="function"?F(s(...r.args),r.propertyPath):void 0},ke=(e,t)=>{try{const n=Te(e,t);return typeof n!="object"||n===null?void 0:ye(n)}catch{return}},Ne=new Set(["cosine","dot-product","euclidean"]),v=(e,t)=>{const n=m(e,t);if(n&&a.isPropertyAssignment(n))return n.getInitializer()},f=(e,t)=>{const n=v(e,t);if(n&&a.isStringLiteral(n))return n.getLiteralText()},I=(e,t)=>{const n=v(e,t);if(n&&a.isNumericLiteral(n))return Number(n.getLiteralText())},B=(e,t)=>{const n=v(e,t);if(n&&(a.isTrueLiteral(n)||a.isFalseLiteral(n)))return n.getLiteralValue()},S=(e,t)=>{const n=v(e,t);if(n&&a.isArrayLiteralExpression(n))return n.getElements().filter(r=>a.isStringLiteral(r)).map(r=>r.getLiteralText())},V=e=>e&&Ne.has(e)?e:void 0,w=e=>e&&a.isStringLiteral(e)?e.getLiteralText():"_unnamed_",Ae=(e,t)=>{const n=S(e,t);return n!==void 0&&n.length>0?n:void 0},q=(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}},Pe=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.`,Oe=/^(?:sqlite_|_cf_|__)/u,Le=/__(?:agg|rank|geo|fts)_/u,_e=e=>Oe.test(e)||Le.test(e),J=()=>{},je=e=>t=>{const n=t.getSourceFile().getFilePath(),r=Q(e,n);if(!(r===""||Y(r)||r.split($)[0]===".."||r.split($).includes("node_modules")))return{file:ne(e,n),line:t.getStartLineNumber()}},$e=new Set(["cascade","restrict","set null"]),De=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"]),U=/^[A-Za-z_$][\w$]*$/u,O=(e,t)=>{if(De.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(ue.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(!U.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(_e(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.`)},Ce=e=>e&&$e.has(e)?e:void 0,ze=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},Me=(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}}},Re=(e,t,n,r)=>{const s=r&&a.isObjectLiteralExpression(r)?r:void 0,i=e==="many"?s?.getProperty("through"):void 0;return i?Me(i,t,n):{field:(s&&f(s,"field"))??"_unknown_",kind:e,name:t,onDelete:e==="one"&&s?Ce(f(s,"onDelete")):void 0,references:(s&&f(s,"references"))??"_id",table:n}},Fe=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 Re(r,P(e),o,i)},Be=(e,t)=>{const n=ze(e);if(!n)return[];const r=[];for(const s of n.getProperties()){const i=Fe(s);if(i){const o=t(s);r.push(o===void 0?i:{...i,site:o})}}return r},Ve=(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})},qe=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)},Je=e=>{const[t,n,r]=e,s=qe(r),i=w(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)Ve(c,c.getLiteralText(),i);return{fields:l.map(c=>c.getLiteralText()),name:i,unique:s}},Ue=e=>{const[t,n]=e;let r="_unknown_",s,i,o,l;return n&&a.isObjectLiteralExpression(n)&&(r=f(n,"field")??r,s=S(n,"filterFields"),i=f(n,"language"),o=B(n,"staged"),l=f(n,"strategy")),{field:r,filterFields:s,language:i,name:w(t),staged:o,strategy:l}},Ke=e=>{const[t,n]=e;let r="_unknown_",s;return n&&a.isObjectLiteralExpression(n)&&(r=f(n,"field")??r,s=I(n,"precision")),{field:r,name:w(t),precision:s}},We=e=>{const[t,n]=e,r=t&&a.isStringLiteral(t)?t.getLiteralText():"_unknown_";let s;return n&&a.isObjectLiteralExpression(n)&&(s=I(n,"after")),{after:s,field:r}},He=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}},Xe=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=>He(l)).filter(l=>l!==void 0))}s=S(n,"partitionBy")}return{name:w(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:I(r,"dimensions"),field:s,metadata:S(r,"metadata"),metric:V(f(r,"metric")),name:f(r,"index")??"_unnamed_",table:t}},Ge=e=>{const t=e[0];return t&&a.isObjectLiteralExpression(t)&&f(t,"backend")==="hyperdrive"?"hyperdrive":"d1"},z=(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.")},Qe=e=>{const t=e[0];return!t||!a.isObjectLiteralExpression(t)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(t,"binding")??"",columns:Ae(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")}},x=(e,t)=>t===void 0?e:{...e,site:t},Ye=(e,t,n,r,s)=>{const i=e.locate(s);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(x(Ke(n),i));break}case"global":{e.shardMode="global",e.globalBackend=Ge(n);break}case"index":{e.indexes.unshift(x(Je(n),i));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(x(Xe(n),i));break}case"relations":{const o=n[0];o&&e.relations.push(...Be(o,e.locate));break}case"searchIndex":{e.searchIndexes.push(x(Ue(n),i));break}case"shardBy":{const o=n[0];e.shardMode={field:o&&a.isStringLiteral(o)?o.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:z(n[0],"deletedAt")};break}case"source":{e.externalSource=Qe(n),e.externallyManaged=!0;break}case"timestamps":{e.timestampsFields.push(z(n[0],"updatedAt"));break}case"ttl":{e.ttl=We(n);break}case"vectorize":{const o=Ze(n,r);o&&e.vectorIndexes.push(x(o,i));break}}},M=["__vocab","_config","_content","_data","_docsize","_idx"],et=(e,t,n)=>{const r=new Set(n.map(s=>s.name));for(const s of n)for(const i of M){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 ${M.join(", ")}.`)}},tt=(e,t,n)=>{if(n.ttl!==void 0&&n.shardMode==="global")throw d(e,Pe(t))},nt=(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}},k=4,rt=e=>{const t=e.getParent(),n=a.isShorthandPropertyAssignment(t)&&t.getNameNode()===e?t.getValueSymbol():e.getSymbol();return re(n?.isAlias()===!0?n.getAliasedSymbol():n)},A=(e,t)=>d(e,`table "${t}" is defined as ${JSON.stringify(e.getText())}, but codegen reads a table only from an inline defineTable(...) chain or one bound to a module-scope const. Inline the defineTable(...) call, or bind it to a const.`),st=(e,t,n)=>{const s=t.getParentIfKind(N.VariableDeclaration)?.getNameNode();if(!(s===void 0||!a.isIdentifier(s)))for(const i of s.findReferencesAsNodes()){const o=i.getParent();if(i!==e&&a.isPropertyAccessExpression(o)&&o.getExpression()===i&&a.isCallExpression(o.getParent())&&o.getParentIfKindOrThrow(N.CallExpression).getExpression()===o)throw d(i,`table "${n}" is built from "${s.getText()}", which also has .${o.getName()}(...) called on it outside the chain the schema uses. Table builder methods change the shared builder, so codegen cannot see that call. Chain every method in one expression.`)}},it=e=>{let t=0;return n=>{let r=D(n)??n;for(;a.isIdentifier(r);){if(t+=1,t>k)throw d(r,`table "${e}" is reached through more than ${String(k)} const bindings, and codegen follows at most ${String(k)}. Inline the defineTable(...) call.`);const s=rt(r);if(s===void 0)throw A(r,e);st(r,s,e),r=D(s)??s}return r}},ot=e=>e.getText()==="defineTable"?!0:e.getSymbol()?.getDeclarations().some(t=>a.isImportSpecifier(t)&&t.getName()==="defineTable")===!0,at=(e,t)=>{if(e===void 0)return{};if(a.isObjectLiteralExpression(e))return fe(e);throw d(e,`table "${t}" calls defineTable(${JSON.stringify(e.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.`)},K=(e,t,n=J)=>{const r={aggregateIndexed:!1,commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,locate:n,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",timestampsFields:[],vectorIndexes:[]};let s={};const i=it(t);let o=i(e),l=!1,c;for(;a.isCallExpression(o);){const g=o.getExpression(),h=o.getArguments();if(a.isPropertyAccessExpression(g))Ye(r,g.getName(),h,t,g.getNameNode()),o=i(g.getExpression());else if(a.isIdentifier(g)&&ot(g)){c=o,s=at(h[0],t),l=!0;break}else throw A(o,t)}if(!l)throw A(o,t);s=nt(e,s,r),et(e,t,r.searchIndexes),tt(e,t,r);const u=c===void 0?void 0:n(c);return{...r.aggregateIndexed?{aggregateIndexed:!0}:{},commitOrdered:r.commitOrdered,externallyManaged:r.externallyManaged,externalSource:r.externalSource,geoIndexes:r.geoIndexes,...u===void 0?{}:{site:u},globalBackend:r.shardMode==="global"?r.globalBackend??"d1":void 0,indexes:r.indexes,isPublic:r.isPublic,memory:r.memory,name:t,rankIndexes:r.rankIndexes,relations:r.relations,searchIndexes:r.searchIndexes,shape:s,shardMode:r.shardMode,softDelete:r.softDelete,ttl:r.ttl,vectorIndexes:r.vectorIndexes}},W=e=>a.isPropertyAssignment(e)?e.getInitializer():e.getNameNode(),H=(e,t=J,n=[],r=new Set,s=new Set)=>{s.add(e);for(const i of e.getProperties()){if(a.isSpreadAssignment(i)){const l=de(i.getExpression());l!==void 0&&!s.has(l)&&H(l,t,n,r,s);continue}if(!a.isPropertyAssignment(i)&&!a.isShorthandPropertyAssignment(i))continue;const o=W(i);if(o){const l=P(i);if(O(l,i.getNameNode()),r.has(l))throw d(i.getNameNode(),`defineSchema({...}): table "${l}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);r.add(l),n.push(K(o,l,t))}}return n},lt=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_"},ct=(e,t)=>{if(!a.isPropertyAssignment(e))return;const n=e.getInitializer();if(!n||!a.isCallExpression(n))return;const r=n.getExpression();if(!a.isIdentifier(r)||r.getText()!=="defineVectorIndex")return;const s=n.getArguments()[0];if(!s||!a.isObjectLiteralExpression(s))return;const i=e.getNameNode(),o=a.isStringLiteral(i)?i.getLiteralText():i.getText(),l=t(n);return{dimensions:I(s,"dimensions"),metric:V(f(s,"metric")),name:o,...l===void 0?{}:{site:l},table:lt(s)}},X=(e,t)=>{const n=[];for(const r of e.getProperties()){const s=ct(r,t);s&&n.push(s)}return n},L=(e,t)=>`${e}_${t}`,dt=(e,t)=>{if(!U.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.`)},y=(e,t,n)=>n.has(e)?L(t,e):e,E=(e,t)=>{const n=r=>r===void 0?void 0:E(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=>E(r,t))},...e.shape===void 0?{}:{shape:Object.fromEntries(Object.entries(e.shape).map(([r,s])=>[r,E(s,t)]))}}},ft=(e,t,n,r)=>{const s=L(t,e.name);return{...e,extensionKey:t,...r?{extensionFromPackage:!0}:{},name:s,shape:Object.fromEntries(Object.entries(e.shape).map(([i,o])=>[i,E(o,l=>y(l,t,n))])),relations:e.relations.map(i=>{const o=y(i.table,t,n);return i.through===void 0?{...i,table:o}:{...i,table:o,through:{...i.through,table:y(i.through.table,t,n)}}}),vectorIndexes:e.vectorIndexes.map(i=>({...i,table:y(i.table,t,n)}))}},ut=e=>{if(a.isVariableDeclaration(e)||a.isPropertyAssignment(e))return e.getInitializer();if(a.isShorthandPropertyAssignment(e))return e.getNameNode()},gt=e=>{if(!a.isCallExpression(e))return!1;const t=e.getExpression();return a.isIdentifier(t)&&t.getText()==="defineSchemaExtension"},mt=e=>{if(a.isIdentifier(e))return e;if(a.isPropertyAccessExpression(e)){const t=e.getExpression();return a.isIdentifier(t)?t:void 0}},pt=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}}},ht=(e,t)=>{const n=ut(e);if(n){if(a.isPropertyAccessExpression(t)){const r=pt(n);return r?v(r,t.getName()):void 0}return n}},bt=e=>{let t=e,n=0;for(;t&&n<32;){if(n+=1,gt(t))return t;const r=mt(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=ht(o,t)}},xt=e=>{const[t,n]=e.getArguments();if(!(!t||!a.isStringLiteral(t))&&!(!n||!a.isObjectLiteralExpression(n)))return{key:t.getLiteralText(),keyNode:t,options:n}},yt=(e,t)=>{const n=m(e,"tables");if(!n||!a.isPropertyAssignment(n))return[];const r=n.getInitializer();if(!r||!a.isObjectLiteralExpression(r))return[];const s=[];for(const i of r.getProperties()){if(!a.isPropertyAssignment(i)&&!a.isShorthandPropertyAssignment(i))continue;const o=W(i);if(!o)continue;const l=P(i);O(l,i.getNameNode()),s.push(K(o,l,t))}return s},vt=(e,t)=>{const n=m(e,"vectorIndexes");if(!n||!a.isPropertyAssignment(n))return[];const r=n.getInitializer();return!r||!a.isObjectLiteralExpression(r)?[]:X(r,t)},Z=(e,t,n,r,s)=>{dt(e,r);const i=new Set(t.map(c=>c.name)),o=t.map(c=>ft(c,e,i,s)),l=n.map(c=>({...c,name:L(e,c.name),table:y(c.table,e,i)}));return{tables:o,vectorIndexes:l}},Et=(e,t,n,r)=>Z(e,yt(n,r),vt(n,r),t,t.getSourceFile().getFilePath().includes("/node_modules/")),It=(e,t,n)=>{const r=e.getArguments()[0];if(!r)return;let s=r;for(;a.isParenthesizedExpression(s)||a.isAsExpression(s)||a.isSatisfiesExpression(s);)s=s.getExpression();const i=bt(s);if(!i){if(t!==void 0){const l=ke(s,t);if(l){for(const c of l.bareTables)O(c.name,s);return Z(l.key,l.bareTables,l.bareVectorIndexes,s,!0)}}console.warn(`@lunora/codegen: skipping \`.extend(${s.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 o=xt(i);if(!o){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return Et(o.key,o.keyNode,o.options,n)},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},wt=(e,t,n,r)=>{const s=new Set(t.map(o=>o.name)),i=[];for(const o of St(e)){const l=It(o,n,r);if(l){for(const c of l.tables){if(s.has(c.name))throw d(o,`defineSchema(...).extend(...): table "${c.name}" already exists — another extension with the same key already contributed it.`);s.add(c.name),t.push(c)}i.push(...l.vectorIndexes)}}return i},Tt=new Set(["eu","fedramp","us"]),kt=e=>q(e,"jurisdiction","jurisdiction",Tt,'"eu", "us", or "fedramp"'),Nt=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)&&B(s,"pinAuth")===!0}t=r}},At=new Set(["required"]),Pt=e=>q(e,"rls","rls mode",At,'"required"'),Ot=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},Lt=(e,t)=>{if(t===void 0)return;const n=Ot(t);for(const r of e)(n===void 0||n.has(r.name))&&(r.aggregateIndexed=!0)},Jt=(e,t,n)=>{const r=e.addSourceFileAtPath(t),s=se(r,N.CallExpression).find(p=>{const _=p.getExpression();return a.isIdentifier(_)&&_.getText()==="defineSchema"});if(!s)throw new te("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=je(ee(t)),l=H(i,o),c=s.getArguments()[1],u=c&&a.isObjectLiteralExpression(c)?X(c,o):[],g=wt(s,l,n,o);Lt(l,s.getArguments()[2]);const h=[...l.flatMap(p=>p.vectorIndexes),...u,...g],G=new Set(l.filter(p=>p.shardMode==="global").map(p=>p.name)),T=h.find(p=>G.has(p.table));if(T)throw d(s,ge(T.table,T.name));return{jurisdiction:kt(s),...Nt(s)?{jurisdictionPinsAuth:!0}:{},rlsMode:Pt(s),tables:l,vectorIndexes:h}};export{Jt as default};
@@ -0,0 +1,2 @@
1
+ import{runAdvisor as d}from"@lunora/advisor";const t=n=>n===void 0?{}:{file:n.file,line:n.line},m=n=>[...n.indexes.map(e=>({fields:e.fields,kind:"index",name:e.name,unique:e.unique,...t(e.site)})),...n.searchIndexes.map(e=>({fields:[e.field,...e.filterFields??[]],kind:"search",name:e.name,...t(e.site)})),...n.rankIndexes.map(e=>({fields:[...e.sortBy.map(r=>r.field),...e.partitionBy??[]],kind:"rank",name:e.name,...t(e.site)})),...n.vectorIndexes.filter(e=>e.field!==void 0).map(e=>({fields:[e.field],kind:"vector",name:e.name,...t(e.site)})),...(n.geoIndexes??[]).map(e=>({fields:[e.field],kind:"geo",name:e.name,...t(e.site)}))],c=n=>{const e={};for(const[r,s]of Object.entries(n.shape))e[r]=s.kind==="optional"?s.inner?.kind??"optional":s.kind;return e},u=n=>({rlsMode:n.rlsMode,tables:n.tables.map(e=>({externallyManaged:e.externallyManaged??!1,externalSource:e.externalSource?{hasReconcile:e.externalSource.hasReconcile??!1,hasSoftDelete:e.externalSource.hasSoftDelete??!1,hasTenantBy:e.externalSource.hasTenantBy,mode:e.externalSource.mode,unanalyzable:e.externalSource.unanalyzable}:void 0,...t(e.site),columnKinds:c(e),fields:Object.keys(e.shape),indexes:m(e),isPublic:e.isPublic??!1,name:e.name,relations:e.relations.map(r=>r.through!==void 0?{kind:"many",name:r.name,table:r.table,through:{...r.through},...t(r.site)}:{...t(r.site),field:r.field,kind:r.kind,name:r.name,onDelete:r.onDelete,references:r.references,table:r.table}),commitOrdered:e.commitOrdered,shardKind:typeof e.shardMode=="string"?e.shardMode:"shardBy",softDelete:e.softDelete,ttl:e.ttl}))}),f=n=>n.map(e=>({exportName:e.exportName,file:`lunora/${e.filePath}.ts`,line:e.line,table:e.table})),h=n=>n.map(e=>({exportName:e.exportName,file:e.filePath,line:e.line})),p=n=>n.map(e=>({exportName:e.exportName,file:`lunora/${e.filePath}.ts`,line:e.line,owner:e.owner})),v=n=>{const{argumentValidators:e,mutators:r,queries:s,schema:i,shapes:o,topics:a,...l}=n;return{...l,argValidators:e,mutators:r===void 0?void 0:p(r),queries:s??[],schema:u(i),shapes:o===void 0?void 0:f(o),topics:a===void 0?void 0:h(a)}},S=n=>d(v(n),{source:"static"}),x=n=>{if(n.length===0)return"";const e=`@lunora/codegen: ${String(n.length)} schema advisor finding${n.length===1?"":"s"}`,r=n.map(s=>` [${s.level}] ${s.name}: ${s.detail}`);return[e,...r].join(`
2
+ `)};export{x as formatAdvisories,S as lintSchema,v as toAdvisorContext};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.413",
3
+ "version": "1.0.0-alpha.414",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -50,7 +50,7 @@
50
50
  "access": "public"
51
51
  },
52
52
  "dependencies": {
53
- "@lunora/advisor": "^1.0.0-alpha.291",
53
+ "@lunora/advisor": "^1.0.0-alpha.292",
54
54
  "@lunora/agent": "^1.0.0-alpha.283",
55
55
  "@lunora/container": "1.0.0-alpha.108",
56
56
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
@@ -1 +0,0 @@
1
- import{existsSync as x}from"node:fs";import{join as f}from"node:path";import{LunoraError as b}from"@lunora/errors";import{queueDefaultName as q,queueBindingName as y}from"@lunora/queue";import{SyntaxKind as S,Node as u}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{lunoraRelativePath as g,findObjectProperty as l,declarationLineOf as w,stringPropertyFor as v}from"./isTestPath-Uwb5a6Kq.mjs";import{a as $}from"./attribution-Cwt30DDJ.mjs";import{r as F}from"./handler-reference-BkOkxxg8.mjs";import{d as P}from"./modules-DdOd-7Wp.mjs";const h="queues.ts",E=o=>{const e=t=>t==="defineQueue"||t==="defineSubscription"||t==="defineTopic",i=o.getSymbol();if(!i){const t=o.getText();return e(t)?t:void 0}for(const t of i.getDeclarations()){if(!u.isImportSpecifier(t))continue;if(t.getImportDeclaration().getModuleSpecifierValue()!=="@lunora/queue")return;const n=t.getNameNode().getText();return e(n)?n:void 0}},d=v("queue"),I=(o,e,i)=>{if(u.isNumericLiteral(o))return o.getLiteralValue();throw c(o,`queue "${e}": \`${i}\` must be a static numeric literal — it is deploy configuration codegen writes into wrangler.jsonc`)},A={maxBatchSize:{integer:!0,max:100,min:1},maxBatchTimeout:{integer:!1,max:60,min:0},maxConcurrency:{integer:!0,max:250,min:1},maxRetries:{integer:!0,max:100,min:0},retryDelay:{integer:!0,max:86400,min:0}},T=(o,e)=>{const i={};for(const[t,n]of Object.entries(A)){const r=l(o,t);if(r&&u.isPropertyAssignment(r)){const a=I(r.getInitializerOrThrow(),e,t);if(a<n.min||a>n.max||n.integer&&!Number.isInteger(a))throw c(r,`queue "${e}": \`${t}\` must be ${n.integer?"an integer":"a number"} from ${n.min.toString()} to ${n.max.toString()} (got ${a.toString()})`);i[t]=a}}return i},O=(o,e)=>{const i=l(o,"name");if(!i||!u.isPropertyAssignment(i))return;const t=d(i.getInitializerOrThrow(),e,"name");if(t.length===0)throw c(i,`queue "${e}": \`name\` must be a non-empty string when provided`);return t},N=(o,e,i,t)=>{const n=F(l(o,"handler"),t)?.site,r={bindingName:y(e),exportName:e,filePath:g(t,o.getSourceFile().getFilePath()),line:w(o),mode:"push",name:O(o,e)??q(e),...i===void 0?{}:{topic:i},...n===void 0?{}:{handlerSite:n},tuning:{}},a=l(o,"mode");if(a&&u.isPropertyAssignment(a)){if(i!==void 0)throw c(a,`subscription "${e}": \`mode\` is not allowed — a subscription is always a push consumer`);const m=d(a.getInitializerOrThrow(),e,"mode");if(m!=="push"&&m!=="pull")throw c(a,`queue "${e}": \`mode\` must be "push" or "pull" (got ${JSON.stringify(m)})`);r.mode=m}const s=l(o,"deadLetterQueue");return s&&u.isPropertyAssignment(s)&&(r.tuning.deadLetterQueue=d(s.getInitializerOrThrow(),e,"deadLetterQueue")),Object.assign(r.tuning,T(o,e)),r},Q=(o,e,i)=>{const t=o.getArguments()[0];if(!t||!u.isObjectLiteralExpression(t))throw c(o,`queue "${e}": defineQueue must be passed an inline object literal`);return N(t,e,void 0,i)},p=(o,e)=>`${o}:${e}`,L=o=>{const e=o.getSymbol(),i=(e?.isAlias()===!0?e.getAliasedSymbol():e)?.getDeclarations()[0];return i!==void 0&&u.isVariableDeclaration(i)?p(i.getSourceFile().getFilePath(),i.getName()):p(o.getSourceFile().getFilePath(),o.getText())},U=(o,e,i,t)=>{const[n,r]=o.getArguments(),a=n!==void 0&&u.isIdentifier(n)?i.get(L(n)):void 0;if(a===void 0)throw c(n??o,`subscription "${e}": the first argument must name a \`defineTopic()\` export of lunora/queues.ts or a module's queues.ts`);if(!r||!u.isObjectLiteralExpression(r))throw c(o,`subscription "${e}": defineSubscription must be passed an inline object literal`);return N(r,e,a,t)},C=o=>{const e=[];for(const i of o.getVariableDeclarations()){const t=i.getInitializer();if(t?.getKind()!==S.CallExpression)continue;const n=t,r=n.getExpression(),a=u.isIdentifier(r)?E(r):void 0;if(a===void 0)continue;const s=i.getNameNode();if(!u.isIdentifier(s)){if(i.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw c(s,`${a} exports must be plain named exports (no destructuring)`)}const m=$(i,"binding");m!==void 0&&e.push({call:n,exportName:m,factory:a,localName:s.getText()})}return e},M=(o,e)=>{const i=new Map;for(const t of o){const n=g(e,t.call.getSourceFile().getFilePath()),r=i.get(t.exportName);if(r!==void 0)throw c(t.call,`"${t.exportName}" is exported by both lunora/${r}.ts and lunora/${n}.ts — queue and topic export names must be unique across the app`);i.set(t.exportName,n)}},j=(o,e)=>{const i=o.flatMap(s=>C(s));M(i,e);const t=i.filter(s=>s.factory==="defineTopic"),n=new Map(t.map(s=>[p(s.call.getSourceFile().getFilePath(),s.localName),s.exportName])),r=[];for(const s of i)s.factory==="defineQueue"?r.push(Q(s.call,s.exportName,e)):s.factory==="defineSubscription"&&r.push(U(s.call,s.exportName,n,e));const a=t.map(s=>({exportName:s.exportName,filePath:g(e,s.call.getSourceFile().getFilePath())}));return{queues:r,topics:a}},z=(o,e)=>[f(e,h),...P(o,e).map(i=>f(e,i.name,h))].filter(i=>x(i)),D=o=>{const e=new Map,i=new Map;for(const t of o){const n=e.get(t.name);if(n!==void 0)throw new b("DUPLICATE_QUEUE_NAME",`Duplicate queue name "${t.name}": produced by both "${n}" and "${t.exportName}". Deployed queue names must be unique across the project.`,{status:500});e.set(t.name,t.exportName);const r=i.get(t.bindingName);if(r!==void 0)throw new b("DUPLICATE_QUEUE_BINDING",`Duplicate queue binding "${t.bindingName}": produced by both "${r}" and "${t.exportName}". Queue export names must yield unique binding names.`,{status:500});i.set(t.bindingName,t.exportName)}},B=(o,e)=>{const i=z(o,e).map(a=>o.getSourceFile(a)??o.addSourceFileAtPath(a)),{queues:t,topics:n}=j(i,e),r=t.toSorted((a,s)=>a.exportName.localeCompare(s.exportName));return D(r),{queues:r,topics:n.toSorted((a,s)=>a.exportName.localeCompare(s.exportName))}},Y=(o,e)=>B(o,e).queues;export{h as QUEUES_FILENAME,B as discoverQueueDeclarations,Y as discoverQueues};
@@ -1 +0,0 @@
1
- import{LunoraError as H}from"@lunora/errors";import{Node as a,SyntaxKind as k}from"ts-morph";import{diagnosticAt as d}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{findObjectProperty as g,unwrapExpression as L,symbolConstInitializer as X,descendantsOfKind as Z}from"./isTestPath-Uwb5a6Kq.mjs";import{createRequire as G}from"node:module";import{join as j}from"node:path";import{fileURLToPath as Q}from"node:url";import{createJiti as Y}from"jiti";import{l as ee,N as te}from"./project-config-file-DR7xrrNB.mjs";import{r as ne,p as re}from"./parse-validator-BisfC8bR.mjs";import{R as se}from"./reserved-words-CW1QFbTd.mjs";import{a as N}from"./property-name-7cBlgK_O.mjs";const ie=(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.`,oe=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}},ae=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:ae(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=oe(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},le=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",ce=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")}}},de=(e,t)=>{const n=e.shape??{},r=(e.indexes??[]).map(i=>({fields:i.fields,name:i.name,...i.unique?{unique:!0}:{}})),s=le(e.shardMode);return{...e.aggregateIndexes&&e.aggregateIndexes.length>0?{aggregateIndexed:!0}:{},...e.commitOrderedMode===!0?{commitOrdered:!0}:{},...e.isExternallyManaged?{externallyManaged:!0}:{},...e.externalSource?{externalSource:ce(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}))}},fe=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])=>de(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}},ue=e=>{if(a.isIdentifier(e))return e.getText();if(a.isPropertyAccessExpression(e)){const t=e.getExpression();return a.isIdentifier(t)?t.getText():void 0}},ge=e=>{const t=ue(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:[]}}},C=e=>a.isCallExpression(e)?e:a.isParenthesizedExpression(e)||a.isAsExpression(e)||a.isSatisfiesExpression(e)?C(e.getExpression()):void 0,me=(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()},pe=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:C(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=>ee(u)),c=s.getReturnType().getProperty(e.getName())?.getTypeAtLocation(s).getNonNullableType();if(!(l.includes(te)||c?.getProperty("tables")===void 0))for(const u of s.getSourceFile().getImportDeclarations()){const h=u.getModuleSpecifierValue();if(h.startsWith("."))continue;const y=me(u,i,o);if(y!==void 0)return{args:l,importedName:y,moduleSpecifier:h,propertyPath:[e.getName()]}}},M=(e,t)=>{let n=e;for(const r of t){if(typeof n!="object"||n===null)return;n=n[r]}return n},he=(e,t)=>M(e[t.importedName],t.propertyPath),$=(e,t)=>{const n=Y(j(t,"noop.js")).esmResolve(e);return G(j(t,"noop.cjs"))(n.startsWith("file:")?Q(n):n)},be=(e,t)=>{const n=ge(e);if(n&&!n.moduleSpecifier.startsWith("."))return he($(n.moduleSpecifier,t),n);const r=pe(e);if(!r)return;const s=$(r.moduleSpecifier,t)[r.importedName];return typeof s=="function"?M(s(...r.args),r.propertyPath):void 0},xe=(e,t)=>{try{const n=be(e,t);return typeof n!="object"||n===null?void 0:fe(n)}catch{return}},ye=new Set(["cosine","dot-product","euclidean"]),x=(e,t)=>{const n=g(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())},R=(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())},F=e=>e&&ye.has(e)?e:void 0,S=e=>e&&a.isStringLiteral(e)?e.getLiteralText():"_unnamed_",ve=(e,t)=>{const n=I(e,t);return n!==void 0&&n.length>0?n:void 0},B=(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}},Ee=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.`,Ie=/^(?:sqlite_|_cf_|__)/u,Se=/__(?:agg|rank|geo|fts)_/u,we=e=>Ie.test(e)||Se.test(e),Te=new Set(["cascade","restrict","set null"]),ke=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"]),V=/^[A-Za-z_$][\w$]*$/u,P=(e,t)=>{if(ke.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(se.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(!V.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(we(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.`)},Ae=e=>e&&Te.has(e)?e:void 0,Ne=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},Pe=(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}}},Oe=(e,t,n,r)=>{const s=r&&a.isObjectLiteralExpression(r)?r:void 0,i=e==="many"?s?.getProperty("through"):void 0;return i?Pe(i,t,n):{field:(s&&f(s,"field"))??"_unknown_",kind:e,name:t,onDelete:e==="one"&&s?Ae(f(s,"onDelete")):void 0,references:(s&&f(s,"references"))??"_id",table:n}},_e=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 Oe(r,N(e),o,i)},Le=e=>{const t=Ne(e);if(!t)return[];const n=[];for(const r of t.getProperties()){const s=_e(r);s&&n.push(s)}return n},je=(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})},$e=e=>{if(!e||!a.isObjectLiteralExpression(e))return!1;const t=g(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)},De=e=>{const[t,n,r]=e,s=$e(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)je(c,c.getLiteralText(),i);return{fields:l.map(c=>c.getLiteralText()),name:i,unique:s}},ze=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=R(n,"staged"),l=f(n,"strategy")),{field:r,filterFields:s,language:i,name:S(t),staged:o,strategy:l}},Ce=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}},Me=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}},Re=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}},Fe=e=>{const[t,n]=e;let r=[],s;if(n&&a.isObjectLiteralExpression(n)){const i=g(n,"sortBy");if(i&&a.isPropertyAssignment(i)){const o=i.getInitializer();o&&a.isArrayLiteralExpression(o)&&(r=o.getElements().map(l=>Re(l)).filter(l=>l!==void 0))}s=I(n,"partitionBy")}return{name:S(t),partitionBy:s,sortBy:r}},Be=(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:F(f(r,"metric")),name:f(r,"index")??"_unnamed_",table:t}},Ve=e=>{const t=e[0];return t&&a.isObjectLiteralExpression(t)&&f(t,"backend")==="hyperdrive"?"hyperdrive":"d1"},D=(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=g(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.")},qe=e=>{const t=e[0];return!t||!a.isObjectLiteralExpression(t)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(t,"binding")??"",columns:ve(t,"columns"),hasReconcile:g(t,"reconcileEveryMs")!==void 0,hasSoftDelete:g(t,"softDeleteColumn")!==void 0,hasTenantBy:g(t,"tenantBy")!==void 0,idColumn:f(t,"idColumn"),mode:f(t,"mode"),query:f(t,"query")}},Je=(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(Ce(n));break}case"global":{e.shardMode="global",e.globalBackend=Ve(n);break}case"index":{e.indexes.unshift(De(n));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(Fe(n));break}case"relations":{const s=n[0];s&&e.relations.push(...Le(s));break}case"searchIndex":{e.searchIndexes.push(ze(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:D(n[0],"deletedAt")};break}case"source":{e.externalSource=qe(n),e.externallyManaged=!0;break}case"timestamps":{e.timestampsFields.push(D(n[0],"updatedAt"));break}case"ttl":{e.ttl=Me(n);break}case"vectorize":{const s=Be(n,r);s&&e.vectorIndexes.push(s);break}}},z=["__vocab","_config","_content","_data","_docsize","_idx"],Ue=(e,t,n)=>{const r=new Set(n.map(s=>s.name));for(const s of n)for(const i of z){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 ${z.join(", ")}.`)}},Ke=(e,t,n)=>{if(n.ttl!==void 0&&n.shardMode==="global")throw d(e,Ee(t))},We=(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}},T=4,He=e=>{const t=e.getParent(),n=a.isShorthandPropertyAssignment(t)&&t.getNameNode()===e?t.getValueSymbol():e.getSymbol();return X(n?.isAlias()===!0?n.getAliasedSymbol():n)},A=(e,t)=>d(e,`table "${t}" is defined as ${JSON.stringify(e.getText())}, but codegen reads a table only from an inline defineTable(...) chain or one bound to a module-scope const. Inline the defineTable(...) call, or bind it to a const.`),Xe=(e,t,n)=>{const s=t.getParentIfKind(k.VariableDeclaration)?.getNameNode();if(!(s===void 0||!a.isIdentifier(s)))for(const i of s.findReferencesAsNodes()){const o=i.getParent();if(i!==e&&a.isPropertyAccessExpression(o)&&o.getExpression()===i&&a.isCallExpression(o.getParent())&&o.getParentIfKindOrThrow(k.CallExpression).getExpression()===o)throw d(i,`table "${n}" is built from "${s.getText()}", which also has .${o.getName()}(...) called on it outside the chain the schema uses. Table builder methods change the shared builder, so codegen cannot see that call. Chain every method in one expression.`)}},Ze=e=>{let t=0;return n=>{let r=L(n)??n;for(;a.isIdentifier(r);){if(t+=1,t>T)throw d(r,`table "${e}" is reached through more than ${String(T)} const bindings, and codegen follows at most ${String(T)}. Inline the defineTable(...) call.`);const s=He(r);if(s===void 0)throw A(r,e);Xe(r,s,e),r=L(s)??s}return r}},Ge=e=>e.getText()==="defineTable"?!0:e.getSymbol()?.getDeclarations().some(t=>a.isImportSpecifier(t)&&t.getName()==="defineTable")===!0,Qe=(e,t)=>{if(e===void 0)return{};if(a.isObjectLiteralExpression(e))return re(e);throw d(e,`table "${t}" calls defineTable(${JSON.stringify(e.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.`)},q=(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={};const s=Ze(t);let i=s(e),o=!1;for(;a.isCallExpression(i);){const l=i.getExpression(),c=i.getArguments();if(a.isPropertyAccessExpression(l))Je(n,l.getName(),c,t),i=s(l.getExpression());else if(a.isIdentifier(l)&&Ge(l)){r=Qe(c[0],t),o=!0;break}else throw A(i,t)}if(!o)throw A(i,t);return r=We(e,r,n),Ue(e,t,n.searchIndexes),Ke(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}},J=e=>a.isPropertyAssignment(e)?e.getInitializer():e.getNameNode(),U=(e,t=[],n=new Set,r=new Set)=>{r.add(e);for(const s of e.getProperties()){if(a.isSpreadAssignment(s)){const o=ne(s.getExpression());o!==void 0&&!r.has(o)&&U(o,t,n,r);continue}if(!a.isPropertyAssignment(s)&&!a.isShorthandPropertyAssignment(s))continue;const i=J(s);if(i){const o=N(s);if(P(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(q(i,o))}}return t},Ye=e=>{const t=g(e,"source");if(t&&a.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&a.isObjectLiteralExpression(n))return f(n,"table")??"_unknown_"}return"_unknown_"},et=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:F(f(r,"metric")),name:i,table:Ye(r)}},K=e=>{const t=[];for(const n of e.getProperties()){const r=et(n);r&&t.push(r)}return t},O=(e,t)=>`${e}_${t}`,tt=(e,t)=>{if(!V.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)?O(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)]))}}},nt=(e,t,n,r)=>{const s=O(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)}))}},rt=e=>{if(a.isVariableDeclaration(e)||a.isPropertyAssignment(e))return e.getInitializer();if(a.isShorthandPropertyAssignment(e))return e.getNameNode()},st=e=>{if(!a.isCallExpression(e))return!1;const t=e.getExpression();return a.isIdentifier(t)&&t.getText()==="defineSchemaExtension"},it=e=>{if(a.isIdentifier(e))return e;if(a.isPropertyAccessExpression(e)){const t=e.getExpression();return a.isIdentifier(t)?t:void 0}},ot=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}}},at=(e,t)=>{const n=rt(e);if(n){if(a.isPropertyAccessExpression(t)){const r=ot(n);return r?x(r,t.getName()):void 0}return n}},lt=e=>{let t=e,n=0;for(;t&&n<32;){if(n+=1,st(t))return t;const r=it(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=at(o,t)}},ct=e=>{const[t,n]=e.getArguments();if(!(!t||!a.isStringLiteral(t))&&!(!n||!a.isObjectLiteralExpression(n)))return{key:t.getLiteralText(),keyNode:t,options:n}},dt=e=>{const t=g(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)&&!a.isShorthandPropertyAssignment(s))continue;const i=J(s);if(!i)continue;const o=N(s);P(o,s.getNameNode()),r.push(q(i,o))}return r},ft=e=>{const t=g(e,"vectorIndexes");if(!t||!a.isPropertyAssignment(t))return[];const n=t.getInitializer();return!n||!a.isObjectLiteralExpression(n)?[]:K(n)},W=(e,t,n,r,s)=>{tt(e,r);const i=new Set(t.map(c=>c.name)),o=t.map(c=>nt(c,e,i,s)),l=n.map(c=>({...c,name:O(e,c.name),table:b(c.table,e,i)}));return{tables:o,vectorIndexes:l}},ut=(e,t,n)=>W(e,dt(n),ft(n),t,t.getSourceFile().getFilePath().includes("/node_modules/")),gt=(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=lt(r);if(!s){if(t!==void 0){const o=xe(r,t);if(o){for(const l of o.bareTables)P(l.name,r);return W(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=ct(s);if(!i){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return ut(i.key,i.keyNode,i.options)},mt=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},pt=(e,t,n)=>{const r=new Set(t.map(i=>i.name)),s=[];for(const i of mt(e)){const o=gt(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},ht=new Set(["eu","fedramp","us"]),bt=e=>B(e,"jurisdiction","jurisdiction",ht,'"eu", "us", or "fedramp"'),xt=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)&&R(s,"pinAuth")===!0}t=r}},yt=new Set(["required"]),vt=e=>B(e,"rls","rls mode",yt,'"required"'),Et=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},It=(e,t)=>{if(t===void 0)return;const n=Et(t);for(const r of e)(n===void 0||n.has(r.name))&&(r.aggregateIndexed=!0)},Dt=(e,t,n)=>{const r=e.addSourceFileAtPath(t),s=Z(r,k.CallExpression).find(m=>{const _=m.getExpression();return a.isIdentifier(_)&&_.getText()==="defineSchema"});if(!s)throw new H("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=U(i),l=s.getArguments()[1],c=l&&a.isObjectLiteralExpression(l)?K(l):[],u=pt(s,o,n);It(o,s.getArguments()[2]);const h=[...o.flatMap(m=>m.vectorIndexes),...c,...u],y=new Set(o.filter(m=>m.shardMode==="global").map(m=>m.name)),w=h.find(m=>y.has(m.table));if(w)throw d(s,ie(w.table,w.name));return{jurisdiction:bt(s),...xt(s)?{jurisdictionPinsAuth:!0}:{},rlsMode:vt(s),tables:o,vectorIndexes:h}};export{Dt as default};
@@ -1,2 +0,0 @@
1
- import{runAdvisor as i}from"@lunora/advisor";const d=n=>[...n.indexes.map(e=>({fields:e.fields,kind:"index",name:e.name,unique:e.unique})),...n.searchIndexes.map(e=>({fields:[e.field,...e.filterFields??[]],kind:"search",name:e.name})),...n.rankIndexes.map(e=>({fields:[...e.sortBy.map(r=>r.field),...e.partitionBy??[]],kind:"rank",name:e.name})),...n.vectorIndexes.filter(e=>e.field!==void 0).map(e=>({fields:[e.field],kind:"vector",name:e.name})),...(n.geoIndexes??[]).map(e=>({fields:[e.field],kind:"geo",name:e.name}))],l=n=>{const e={};for(const[r,s]of Object.entries(n.shape))e[r]=s.kind==="optional"?s.inner?.kind??"optional":s.kind;return e},m=n=>({rlsMode:n.rlsMode,tables:n.tables.map(e=>({externallyManaged:e.externallyManaged??!1,externalSource:e.externalSource?{hasReconcile:e.externalSource.hasReconcile??!1,hasSoftDelete:e.externalSource.hasSoftDelete??!1,hasTenantBy:e.externalSource.hasTenantBy,mode:e.externalSource.mode,unanalyzable:e.externalSource.unanalyzable}:void 0,columnKinds:l(e),fields:Object.keys(e.shape),indexes:d(e),isPublic:e.isPublic??!1,name:e.name,relations:e.relations.map(r=>r.through!==void 0?{kind:"many",name:r.name,table:r.table,through:{...r.through}}:{field:r.field,kind:r.kind,name:r.name,onDelete:r.onDelete,references:r.references,table:r.table}),commitOrdered:e.commitOrdered,shardKind:typeof e.shardMode=="string"?e.shardMode:"shardBy",softDelete:e.softDelete,ttl:e.ttl}))}),c=n=>n.map(e=>({exportName:e.exportName,file:`lunora/${e.filePath}.ts`,line:e.line,table:e.table})),u=n=>n.map(e=>({exportName:e.exportName,file:`lunora/${e.filePath}.ts`,line:e.line,owner:e.owner})),f=n=>{const{argumentValidators:e,mutators:r,queries:s,schema:t,shapes:o,...a}=n;return{...a,argValidators:e,mutators:r===void 0?void 0:u(r),queries:s??[],schema:m(t),shapes:o===void 0?void 0:c(o)}},p=n=>i(f(n),{source:"static"}),v=n=>{if(n.length===0)return"";const e=`@lunora/codegen: ${String(n.length)} schema advisor finding${n.length===1?"":"s"}`,r=n.map(s=>` [${s.level}] ${s.name}: ${s.detail}`);return[e,...r].join(`
2
- `)};export{v as formatAdvisories,p as lintSchema,f as toAdvisorContext};