@lunora/codegen 1.0.0-alpha.274 → 1.0.0-alpha.276

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 (73) hide show
  1. package/dist/index.d.mts +78 -9
  2. package/dist/index.d.ts +78 -9
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/{AGENTS_FILENAME-lBe4g_sU.mjs → AGENTS_FILENAME-NQIB6wh3.mjs} +1 -1
  5. package/dist/packem_shared/{CONTAINERS_FILENAME-CY43AXXN.mjs → CONTAINERS_FILENAME-CK3xJGwm.mjs} +1 -1
  6. package/dist/packem_shared/DEFAULT_TARGET-GPPgJNTn.mjs +1 -0
  7. package/dist/packem_shared/{FLAGS_FILENAME-DXltN9DD.mjs → FLAGS_FILENAME-DYMd1xqw.mjs} +1 -1
  8. package/dist/packem_shared/GENERATED_HEADER-D-P7ii4H.mjs +1 -0
  9. package/dist/packem_shared/{MUTATORS_FILENAME-BxRrG_s-.mjs → MUTATORS_FILENAME-BrEGrcPU.mjs} +1 -1
  10. package/dist/packem_shared/{NOTIFY_FILENAME-J5MGAkca.mjs → NOTIFY_FILENAME-B42rW2NJ.mjs} +1 -1
  11. package/dist/packem_shared/{OPENRPC_VERSION-B8RT1JYn.mjs → OPENRPC_VERSION-BaD2A2YR.mjs} +1 -1
  12. package/dist/packem_shared/{QUEUES_FILENAME-DeJw5eqU.mjs → QUEUES_FILENAME-Dj5yK34Z.mjs} +1 -1
  13. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-CaONLqHU.mjs +11 -0
  14. package/dist/packem_shared/{SHAPES_FILENAME-CeBFuc8M.mjs → SHAPES_FILENAME-CVc2VCnS.mjs} +1 -1
  15. package/dist/packem_shared/{WORKFLOWS_FILENAME-B47AB5pc.mjs → WORKFLOWS_FILENAME-Ze98LsB3.mjs} +1 -1
  16. package/dist/packem_shared/{attribution-NRssTEkk.mjs → attribution-Dw35rOaJ.mjs} +1 -1
  17. package/dist/packem_shared/{buildOpenApiDocument-6VJGU6fU.mjs → buildOpenApiDocument-BjHdW7b2.mjs} +1 -1
  18. package/dist/packem_shared/{capabilitiesUsedBy-DARbl-4Z.mjs → capabilitiesUsedBy-FnnYmnSl.mjs} +1 -1
  19. package/dist/packem_shared/chain-nWiSr1yy.mjs +1 -0
  20. package/dist/packem_shared/{classify-procedure-call-BBKuBvKg.mjs → classify-procedure-call-DxuPQkJA.mjs} +1 -1
  21. package/dist/packem_shared/{context-property-calls-tlnXE-wv.mjs → context-property-calls-BLTVj9HH.mjs} +1 -1
  22. package/dist/packem_shared/{context-root-IuI71QkK.mjs → context-root-B04bYCE-.mjs} +1 -1
  23. package/dist/packem_shared/{database-calls-BFY_pIUf.mjs → database-calls-DWDtdDbS.mjs} +1 -1
  24. package/dist/packem_shared/{discoverAuthApiCalls-TA2a8bZI.mjs → discoverAuthApiCalls-XK_WCMDG.mjs} +1 -1
  25. package/dist/packem_shared/discoverCrons-B5bVCaNF.mjs +1 -0
  26. package/dist/packem_shared/{discoverFunctions-4sef11AC.mjs → discoverFunctions-Be-XuuSW.mjs} +1 -1
  27. package/dist/packem_shared/{discoverHttpRoutes-CLGXL19M.mjs → discoverHttpRoutes-CMOxt2Y9.mjs} +1 -1
  28. package/dist/packem_shared/discoverHyperdriveCalls-mrho5AnY.mjs +1 -0
  29. package/dist/packem_shared/{discoverInserts-CKEO1mZZ.mjs → discoverInserts-BhIpUWXN.mjs} +1 -1
  30. package/dist/packem_shared/discoverMaskProcedures-DCw165tP.mjs +1 -0
  31. package/dist/packem_shared/{discoverMigrations-DYQbnqow.mjs → discoverMigrations-dVVZtuJa.mjs} +1 -1
  32. package/dist/packem_shared/{discoverNondeterministicCalls-BfdM93-8.mjs → discoverNondeterministicCalls-Dtb1aoGV.mjs} +1 -1
  33. package/dist/packem_shared/{discoverQueries-DEkIMaBP.mjs → discoverQueries-BSOjEsk3.mjs} +1 -1
  34. package/dist/packem_shared/discoverR2sqlCalls-KONCqZr2.mjs +1 -0
  35. package/dist/packem_shared/{discoverRlsMetadata-rpiO4wSi.mjs → discoverRlsMetadata-9YDlDDoh.mjs} +1 -1
  36. package/dist/packem_shared/{discoverRlsProcedures-BtT8-r93.mjs → discoverRlsProcedures-c0DnIR4z.mjs} +1 -1
  37. package/dist/packem_shared/{discoverSandboxUsage-B8P9QjWZ.mjs → discoverSandboxUsage-CfEU2hM-.mjs} +1 -1
  38. package/dist/packem_shared/{discoverSchema-BdmC-kO2.mjs → discoverSchema-BTFFWy3i.mjs} +1 -1
  39. package/dist/packem_shared/{discoverStorageRulesMetadata-C2hYksmI.mjs → discoverStorageRulesMetadata-f89BWody.mjs} +1 -1
  40. package/dist/packem_shared/{emitAgents-CzxW-qj5.mjs → emitAgents-CG2R-Zz6.mjs} +1 -1
  41. package/dist/packem_shared/{emitApi-xDIHPRPH.mjs → emitApi-zY6egN77.mjs} +44 -63
  42. package/dist/packem_shared/{emitApp-BdVXkH7A.mjs → emitApp-DUGS6Ve2.mjs} +1 -1
  43. package/dist/packem_shared/{emitCrons-DKeoaeqU.mjs → emitCrons-B8TBAOZ4.mjs} +1 -1
  44. package/dist/packem_shared/{emitDataModel-DSk9AkJe.mjs → emitDataModel-B68T_eX6.mjs} +5 -5
  45. package/dist/packem_shared/{emitDrizzleSchema-DohtnI8c.mjs → emitDrizzleSchema-DLtfKTI4.mjs} +2 -2
  46. package/dist/packem_shared/{emitFunctions-evl8Mx1a.mjs → emitFunctions-DkkcTDqh.mjs} +39 -47
  47. package/dist/packem_shared/{emitServer-CYjqZ3W8.mjs → emitServer-BbjIwe2-.mjs} +1 -1
  48. package/dist/packem_shared/{emitShard-tQej36w1.mjs → emitShard-CSLqD-Hr.mjs} +1 -1
  49. package/dist/packem_shared/{exported-procedure-chains-DqU-ZCbG.mjs → exported-procedure-chains-C5VKkd9T.mjs} +1 -1
  50. package/dist/packem_shared/{fingerprintSchemaSources-ChYfrghz.mjs → fingerprintSchemaSources-BJSIxwhY.mjs} +1 -1
  51. package/dist/packem_shared/{handler-reference-B3coD2YR.mjs → handler-reference-2Hs4WKnz.mjs} +1 -1
  52. package/dist/packem_shared/{index-CRO3TRxd.mjs → index-CefI-Sba.mjs} +1 -1
  53. package/dist/packem_shared/isTestPath-CgyyLk8U.mjs +1 -0
  54. package/dist/packem_shared/{modules-6EEBTEDo.mjs → modules-BIpFLz3Z.mjs} +1 -1
  55. package/dist/packem_shared/paths-DwTjD7BU.mjs +1 -0
  56. package/dist/packem_shared/{qualifiers-Cw8dEDbh.mjs → qualifiers-COHdrghK.mjs} +1 -1
  57. package/dist/packem_shared/{server-dr22ile6.mjs → server-BmY5wwKY.mjs} +1 -1
  58. package/dist/packem_shared/{shard-C1ZGdOG1.mjs → shard-Dr5gMNyz.mjs} +1 -1
  59. package/dist/packem_shared/{shard-runtime-DGrBvQWg.mjs → shard-runtime-BI2SZ54Z.mjs} +1 -1
  60. package/dist/packem_shared/shared-Be3TGzxM.mjs +13 -0
  61. package/dist/packem_shared/{unwrap-handler-return-Dy8h5-I6.mjs → unwrap-handler-return-T5sJhEss.mjs} +1 -1
  62. package/package.json +7 -7
  63. package/dist/packem_shared/DEFAULT_TARGET-rlz3WdHe.mjs +0 -1
  64. package/dist/packem_shared/GENERATED_HEADER-dFyrHgQ0.mjs +0 -1
  65. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-UlgFl8hS.mjs +0 -11
  66. package/dist/packem_shared/chain-6qc9c0JF.mjs +0 -1
  67. package/dist/packem_shared/discoverCrons-PQeDYVPc.mjs +0 -1
  68. package/dist/packem_shared/discoverHyperdriveCalls-imtma-ic.mjs +0 -1
  69. package/dist/packem_shared/discoverMaskProcedures-Cr6hDinL.mjs +0 -1
  70. package/dist/packem_shared/discoverR2sqlCalls-BRIyb8Cl.mjs +0 -1
  71. package/dist/packem_shared/isTestPath-DCyIyPa7.mjs +0 -1
  72. package/dist/packem_shared/paths-C-9fwEgQ.mjs +0 -1
  73. package/dist/packem_shared/shared-BXUKWh7t.mjs +0 -9
@@ -1 +1 @@
1
- import{d as P}from"./declared-output-Iaar469J.mjs";import{s as b}from"./paths-C-9fwEgQ.mjs";import{findObjectProperty as c,bindingKeyName as N,listLunoraSourceFiles as A,lunoraRelativePath as F}from"./isTestPath-DCyIyPa7.mjs";import{e as O,i as z}from"./attribution-NRssTEkk.mjs";import{u as y,p as C,c as g,r as S}from"./unwrap-handler-return-Dy8h5-I6.mjs";import{b as d,c as L}from"./classify-procedure-call-BBKuBvKg.mjs";import{Node as n,SyntaxKind as k}from"ts-morph";import{r as h,p as x,a as I}from"./parse-validator-DYdT7Hyf.mjs";const T=i=>{const e=i.getArguments()[0];if(!e||!n.isObjectLiteralExpression(e))return"unknown";const t=c(e,"handler");if(!t||!n.isPropertyAssignment(t))return"unknown";const r=t.getInitializer();return!r||!(n.isArrowFunction(r)||n.isFunctionExpression(r))?"unknown":y(r)},w=i=>{const e=i.getArguments()[0];return!e||!(n.isArrowFunction(e)||n.isFunctionExpression(e))?"unknown":y(e)},V=i=>{let e={};for(const t of d(i)){if(t.name!=="input")continue;const r=t.call.getArguments()[0],s=r!==void 0&&n.isExpression(r)?h(r):void 0;s!==void 0&&(e={...x(s),...e})}return e},D=i=>{const e=d(i).find(r=>r.name==="output");if(!e)return;const t=e.call.getArguments()[0];return t&&n.isExpression(t)?C(e.call,()=>I(t)):void 0},p=(i,e)=>{const t=c(i,e);if(t===void 0||!n.isPropertyAssignment(t))return;const r=t.getInitializer();return r!==void 0&&n.isStringLiteral(r)?r.getLiteralValue():void 0},v=(i,e)=>{const t=c(i,e);if(t===void 0||!n.isPropertyAssignment(t))return;const r=t.getInitializer();return r!==void 0&&n.isNumericLiteral(r)?r.getLiteralValue():void 0},j=i=>{const e=c(i,"cache");if(e===void 0||!n.isPropertyAssignment(e))return;const t=e.getInitializer();if(t===void 0||!n.isObjectLiteralExpression(t))return;const r=p(t,"scope"),s=v(t,"maxAge"),o=v(t,"staleWhileRevalidate"),a=p(t,"tag"),l=p(t,"vary"),m={...s===void 0?{}:{maxAge:s},...r==="private"||r==="public"?{scope:r}:{},...o===void 0?{}:{staleWhileRevalidate:o},...a===void 0?{}:{tag:a},...l===void 0?{}:{vary:l}};return Object.keys(m).length===0?void 0:m},B=i=>{if(i===void 0||!n.isObjectLiteralExpression(i))return{};const e=j(i),t=c(i,"rest");return t!==void 0&&n.isPropertyAssignment(t)?{...e===void 0?{}:{cache:e},rest:t.getInitializer()?.getText()==="true"}:e===void 0?{}:{cache:e}},R=i=>{const e=d(i).find(t=>t.name==="expose");return e?B(e.call.getArguments()[0]):void 0},M=i=>{const e=i.getArguments()[0];if(!e||!n.isObjectLiteralExpression(e))return{};const t=c(e,"args");if(!t||!n.isPropertyAssignment(t))return{};const r=t.getInitializer(),s=r===void 0?void 0:h(r);return s===void 0?{}:x(s)},$=8,u=(i,e=0)=>{if(e>$)return;if(n.isCallExpression(i))return i;if(n.isParenthesizedExpression(i)||n.isAsExpression(i)||n.isSatisfiesExpression(i)||n.isNonNullExpression(i))return u(i.getExpression(),e+1);if(!n.isIdentifier(i)&&!n.isPropertyAccessExpression(i))return;const t=i.getSymbol()?.getValueDeclaration();return t?f(t,e+1):void 0},f=(i,e)=>{if(n.isVariableDeclaration(i)||n.isPropertyAssignment(i)){const t=i.getInitializer();return t?u(t,e):void 0}if(n.isShorthandPropertyAssignment(i)){const t=i.getValueSymbol()?.getValueDeclaration();return t?f(t,e+1):void 0}if(n.isBindingElement(i)){const t=N(i),o=i.getFirstAncestorByKind(k.VariableDeclaration)?.getInitializer()?.getType().getProperty(t)?.getValueDeclaration();return o?f(o,e+1):void 0}},W=(i,e=()=>!0)=>{const t=i.getNameNode();if(n.isObjectBindingPattern(t)){const o=[];for(const a of t.getElements().filter(l=>e(l.getName()))){const l=u(a.getNameNode());l&&o.push([a.getName(),l])}return o}if(!e(i.getName()))return[];const r=i.getInitializer(),s=r&&(n.isCallExpression(r)?r:u(r));return s?[[i.getName(),s]]:[]},_=i=>{const e=L(i);if(!e)return;const{receiver:t}=e;if(t){const r=R(t),s=g(()=>D(t)),o=g(()=>w(i)),a=P({kind:e.kind,output:s.value});return S(a?s.erased:o.erased),{args:V(t),...r?{expose:r}:{},kind:e.kind,...s.value?{output:s.value}:{},returnType:o.value,visibility:e.visibility}}return e.lifecycle?{args:{},kind:e.kind,lifecycle:e.lifecycle,returnType:"void",visibility:e.visibility}:{args:M(i),kind:e.kind,returnType:T(i),visibility:e.visibility}},E=(i,e,t)=>{const r=_(i);if(r)return{args:r.args,exportName:e,filePath:t,kind:r.kind,returnType:r.returnType,...r.output?{output:r.output}:{},visibility:r.visibility,...r.expose?{expose:r.expose}:{},...r.lifecycle?{lifecycle:r.lifecycle}:{}}},H=(i,e)=>{const t=[];for(const r of i.getExportAssignments()){if(r.isExportEquals())continue;const s=u(r.getExpression()),o=s?E(s,"default",e):void 0;o&&t.push(o)}return t},K=(i,e)=>{const t=O(i),r=i.getVariableStatements().flatMap(o=>o.getDeclarations()).flatMap(o=>W(o,a=>t.has(a))).flatMap(([o,a])=>(t.get(o)??[]).filter(l=>z(l)).flatMap(l=>E(a,l,e)??[])),s=new Set(r.map(o=>o.exportName));return r.push(...H(i,e).filter(o=>!s.has(o.exportName))),r},q=i=>{const e=new Map;for(const t of i){const r=b(t.filePath),s=e.get(r);if(s&&s!==t.filePath)throw Object.assign(new Error(`Namespace collision: "${s}" and "${t.filePath}" both resolve to "${r}". Rename one of the files so the JS-identifier-sanitized names differ. (note: case-insensitive filesystems may also cause this — \`foo\` and \`FOO\` map to the same identifier)`),{code:"NAMESPACE_COLLISION",name:"LunoraError",paths:[s,t.filePath],status:500});e.set(r,t.filePath)}},te=(i,e)=>{const t=A(e),r=[];for(const s of t){const o=i.getSourceFile(s)??i.addSourceFileAtPath(s),a=F(e,s);r.push(...K(o,a))}return r.sort((s,o)=>`${s.filePath}:${s.exportName}`.localeCompare(`${o.filePath}:${o.exportName}`)),q(r),r};export{te as default};
1
+ import{d as P}from"./declared-output-Iaar469J.mjs";import{s as b}from"./paths-DwTjD7BU.mjs";import{findObjectProperty as c,bindingKeyName as N,listLunoraSourceFiles as A,lunoraRelativePath as F}from"./isTestPath-CgyyLk8U.mjs";import{e as O,i as z}from"./attribution-Dw35rOaJ.mjs";import{u as y,p as C,c as g,r as S}from"./unwrap-handler-return-T5sJhEss.mjs";import{b as d,c as L}from"./classify-procedure-call-DxuPQkJA.mjs";import{Node as n,SyntaxKind as k}from"ts-morph";import{r as h,p as x,a as I}from"./parse-validator-DYdT7Hyf.mjs";const T=i=>{const e=i.getArguments()[0];if(!e||!n.isObjectLiteralExpression(e))return"unknown";const t=c(e,"handler");if(!t||!n.isPropertyAssignment(t))return"unknown";const r=t.getInitializer();return!r||!(n.isArrowFunction(r)||n.isFunctionExpression(r))?"unknown":y(r)},w=i=>{const e=i.getArguments()[0];return!e||!(n.isArrowFunction(e)||n.isFunctionExpression(e))?"unknown":y(e)},V=i=>{let e={};for(const t of d(i)){if(t.name!=="input")continue;const r=t.call.getArguments()[0],s=r!==void 0&&n.isExpression(r)?h(r):void 0;s!==void 0&&(e={...x(s),...e})}return e},D=i=>{const e=d(i).find(r=>r.name==="output");if(!e)return;const t=e.call.getArguments()[0];return t&&n.isExpression(t)?C(e.call,()=>I(t)):void 0},p=(i,e)=>{const t=c(i,e);if(t===void 0||!n.isPropertyAssignment(t))return;const r=t.getInitializer();return r!==void 0&&n.isStringLiteral(r)?r.getLiteralValue():void 0},v=(i,e)=>{const t=c(i,e);if(t===void 0||!n.isPropertyAssignment(t))return;const r=t.getInitializer();return r!==void 0&&n.isNumericLiteral(r)?r.getLiteralValue():void 0},j=i=>{const e=c(i,"cache");if(e===void 0||!n.isPropertyAssignment(e))return;const t=e.getInitializer();if(t===void 0||!n.isObjectLiteralExpression(t))return;const r=p(t,"scope"),s=v(t,"maxAge"),o=v(t,"staleWhileRevalidate"),a=p(t,"tag"),l=p(t,"vary"),m={...s===void 0?{}:{maxAge:s},...r==="private"||r==="public"?{scope:r}:{},...o===void 0?{}:{staleWhileRevalidate:o},...a===void 0?{}:{tag:a},...l===void 0?{}:{vary:l}};return Object.keys(m).length===0?void 0:m},B=i=>{if(i===void 0||!n.isObjectLiteralExpression(i))return{};const e=j(i),t=c(i,"rest");return t!==void 0&&n.isPropertyAssignment(t)?{...e===void 0?{}:{cache:e},rest:t.getInitializer()?.getText()==="true"}:e===void 0?{}:{cache:e}},R=i=>{const e=d(i).find(t=>t.name==="expose");return e?B(e.call.getArguments()[0]):void 0},M=i=>{const e=i.getArguments()[0];if(!e||!n.isObjectLiteralExpression(e))return{};const t=c(e,"args");if(!t||!n.isPropertyAssignment(t))return{};const r=t.getInitializer(),s=r===void 0?void 0:h(r);return s===void 0?{}:x(s)},$=8,u=(i,e=0)=>{if(e>$)return;if(n.isCallExpression(i))return i;if(n.isParenthesizedExpression(i)||n.isAsExpression(i)||n.isSatisfiesExpression(i)||n.isNonNullExpression(i))return u(i.getExpression(),e+1);if(!n.isIdentifier(i)&&!n.isPropertyAccessExpression(i))return;const t=i.getSymbol()?.getValueDeclaration();return t?f(t,e+1):void 0},f=(i,e)=>{if(n.isVariableDeclaration(i)||n.isPropertyAssignment(i)){const t=i.getInitializer();return t?u(t,e):void 0}if(n.isShorthandPropertyAssignment(i)){const t=i.getValueSymbol()?.getValueDeclaration();return t?f(t,e+1):void 0}if(n.isBindingElement(i)){const t=N(i),o=i.getFirstAncestorByKind(k.VariableDeclaration)?.getInitializer()?.getType().getProperty(t)?.getValueDeclaration();return o?f(o,e+1):void 0}},W=(i,e=()=>!0)=>{const t=i.getNameNode();if(n.isObjectBindingPattern(t)){const o=[];for(const a of t.getElements().filter(l=>e(l.getName()))){const l=u(a.getNameNode());l&&o.push([a.getName(),l])}return o}if(!e(i.getName()))return[];const r=i.getInitializer(),s=r&&(n.isCallExpression(r)?r:u(r));return s?[[i.getName(),s]]:[]},_=i=>{const e=L(i);if(!e)return;const{receiver:t}=e;if(t){const r=R(t),s=g(()=>D(t)),o=g(()=>w(i)),a=P({kind:e.kind,output:s.value});return S(a?s.erased:o.erased),{args:V(t),...r?{expose:r}:{},kind:e.kind,...s.value?{output:s.value}:{},returnType:o.value,visibility:e.visibility}}return e.lifecycle?{args:{},kind:e.kind,lifecycle:e.lifecycle,returnType:"void",visibility:e.visibility}:{args:M(i),kind:e.kind,returnType:T(i),visibility:e.visibility}},E=(i,e,t)=>{const r=_(i);if(r)return{args:r.args,exportName:e,filePath:t,kind:r.kind,returnType:r.returnType,...r.output?{output:r.output}:{},visibility:r.visibility,...r.expose?{expose:r.expose}:{},...r.lifecycle?{lifecycle:r.lifecycle}:{}}},H=(i,e)=>{const t=[];for(const r of i.getExportAssignments()){if(r.isExportEquals())continue;const s=u(r.getExpression()),o=s?E(s,"default",e):void 0;o&&t.push(o)}return t},K=(i,e)=>{const t=O(i),r=i.getVariableStatements().flatMap(o=>o.getDeclarations()).flatMap(o=>W(o,a=>t.has(a))).flatMap(([o,a])=>(t.get(o)??[]).filter(l=>z(l)).flatMap(l=>E(a,l,e)??[])),s=new Set(r.map(o=>o.exportName));return r.push(...H(i,e).filter(o=>!s.has(o.exportName))),r},q=i=>{const e=new Map;for(const t of i){const r=b(t.filePath),s=e.get(r);if(s&&s!==t.filePath)throw Object.assign(new Error(`Namespace collision: "${s}" and "${t.filePath}" both resolve to "${r}". Rename one of the files so the JS-identifier-sanitized names differ. (note: case-insensitive filesystems may also cause this — \`foo\` and \`FOO\` map to the same identifier)`),{code:"NAMESPACE_COLLISION",name:"LunoraError",paths:[s,t.filePath],status:500});e.set(r,t.filePath)}},te=(i,e)=>{const t=A(e),r=[];for(const s of t){const o=i.getSourceFile(s)??i.addSourceFileAtPath(s),a=F(e,s);r.push(...K(o,a))}return r.sort((s,o)=>`${s.filePath}:${s.exportName}`.localeCompare(`${o.filePath}:${o.exportName}`)),q(r),r};export{te as default};
@@ -1 +1 @@
1
- import{Node as n}from"ts-morph";import{a as m,p as l}from"./parse-validator-DYdT7Hyf.mjs";import{listLunoraSourceFiles as d,lunoraRelativePath as h}from"./isTestPath-DCyIyPa7.mjs";import{b as f,d as g}from"./attribution-NRssTEkk.mjs";import{u as x}from"./unwrap-handler-return-Dy8h5-I6.mjs";const u=new Set(["delete","get","head","options","patch","post","put"]),E=new Set(["body","params","searchParams"]),v=new Set(["handler","stream"]),P=s=>{const e=s.getArguments()[0];if(e&&n.isStringLiteral(e))return e.getLiteralValue()},S=s=>{const e=s.getArguments()[0];return e&&n.isObjectLiteralExpression(e)?l(e):{}},A=s=>{if(!n.isCallExpression(s))return;const e=s.getExpression();if(!n.isPropertyAccessExpression(e))return;const o=e.getName();if(!u.has(o))return;const a=e.getExpression();if(!n.isIdentifier(a)||a.getText()!=="httpRoute")return;const t=P(s);return t===void 0?void 0:{method:o.toUpperCase(),path:t}},b=(s,e)=>{const o={body:{},params:{},searchParams:{},stream:e==="stream"},a=s.getExpression();if(!n.isPropertyAccessExpression(a))return;let t=a.getExpression();for(;n.isCallExpression(t);){const i=t.getExpression();if(!n.isPropertyAccessExpression(i))break;const c=i.getName();if(u.has(c))break;if(E.has(c)){const p=S(t);o[c]={...p,...o[c]}}else if(c==="output"&&o.output===void 0){const p=t.getArguments()[0];p&&n.isExpression(p)&&(o.output=m(p))}t=i.getExpression()}const r=A(t);if(r)return o.method=r.method,o.path=r.path,o},T=s=>{const e=s.getArguments()[0];return!e||!(n.isArrowFunction(e)||n.isFunctionExpression(e))?"unknown":x(e)},y=(s,e,o,a)=>{const t=e.getName();if(!v.has(t))return;const r=b(s,t);if(!(r?.method===void 0||r.path===void 0))return{body:r.body,exportName:o,filePath:a,method:r.method,params:r.params,path:r.path,searchParams:r.searchParams,stream:r.stream,...r.stream?{chunkType:T(s)}:{},...r.output?{output:r.output}:{}}},R=(s,e)=>{const o=[];for(const a of f(s)){const t=a.getInitializer();if(!t||!n.isCallExpression(t))continue;const r=t.getExpression();if(!n.isPropertyAccessExpression(r))continue;const i=y(t,r,g(a)??a.getName(),e);i&&o.push(i)}return o},L=(s,e)=>{const o=d(e),a=[];for(const t of o){const r=s.getSourceFile(t)??s.addSourceFileAtPath(t),i=h(e,t);a.push(...R(r,i))}return a.sort((t,r)=>`${t.method} ${t.path}`.localeCompare(`${r.method} ${r.path}`)||t.filePath.localeCompare(r.filePath)),a};export{L as default};
1
+ import{Node as n}from"ts-morph";import{a as m,p as l}from"./parse-validator-DYdT7Hyf.mjs";import{listLunoraSourceFiles as d,lunoraRelativePath as h}from"./isTestPath-CgyyLk8U.mjs";import{b as f,d as g}from"./attribution-Dw35rOaJ.mjs";import{u as x}from"./unwrap-handler-return-T5sJhEss.mjs";const u=new Set(["delete","get","head","options","patch","post","put"]),E=new Set(["body","params","searchParams"]),v=new Set(["handler","stream"]),P=s=>{const e=s.getArguments()[0];if(e&&n.isStringLiteral(e))return e.getLiteralValue()},S=s=>{const e=s.getArguments()[0];return e&&n.isObjectLiteralExpression(e)?l(e):{}},A=s=>{if(!n.isCallExpression(s))return;const e=s.getExpression();if(!n.isPropertyAccessExpression(e))return;const o=e.getName();if(!u.has(o))return;const a=e.getExpression();if(!n.isIdentifier(a)||a.getText()!=="httpRoute")return;const t=P(s);return t===void 0?void 0:{method:o.toUpperCase(),path:t}},b=(s,e)=>{const o={body:{},params:{},searchParams:{},stream:e==="stream"},a=s.getExpression();if(!n.isPropertyAccessExpression(a))return;let t=a.getExpression();for(;n.isCallExpression(t);){const i=t.getExpression();if(!n.isPropertyAccessExpression(i))break;const c=i.getName();if(u.has(c))break;if(E.has(c)){const p=S(t);o[c]={...p,...o[c]}}else if(c==="output"&&o.output===void 0){const p=t.getArguments()[0];p&&n.isExpression(p)&&(o.output=m(p))}t=i.getExpression()}const r=A(t);if(r)return o.method=r.method,o.path=r.path,o},T=s=>{const e=s.getArguments()[0];return!e||!(n.isArrowFunction(e)||n.isFunctionExpression(e))?"unknown":x(e)},y=(s,e,o,a)=>{const t=e.getName();if(!v.has(t))return;const r=b(s,t);if(!(r?.method===void 0||r.path===void 0))return{body:r.body,exportName:o,filePath:a,method:r.method,params:r.params,path:r.path,searchParams:r.searchParams,stream:r.stream,...r.stream?{chunkType:T(s)}:{},...r.output?{output:r.output}:{}}},R=(s,e)=>{const o=[];for(const a of f(s)){const t=a.getInitializer();if(!t||!n.isCallExpression(t))continue;const r=t.getExpression();if(!n.isPropertyAccessExpression(r))continue;const i=y(t,r,g(a)??a.getName(),e);i&&o.push(i)}return o},L=(s,e)=>{const o=d(e),a=[];for(const t of o){const r=s.getSourceFile(t)??s.addSourceFileAtPath(t),i=h(e,t);a.push(...R(r,i))}return a.sort((t,r)=>`${t.method} ${t.path}`.localeCompare(`${r.method} ${r.path}`)||t.filePath.localeCompare(r.filePath)),a};export{L as default};
@@ -0,0 +1 @@
1
+ import{d as o}from"./context-property-calls-BLTVj9HH.mjs";const t=(r,e)=>o(r,e,"sql");export{t as default};
@@ -1 +1 @@
1
- import{Node as i}from"ts-morph";import{collectCallRows as n}from"./isTestPath-DCyIyPa7.mjs";import{c as a}from"./attribution-NRssTEkk.mjs";import{i as c}from"./database-calls-BFY_pIUf.mjs";const l=t=>{const e=t.getExpression();if(!i.isPropertyAccessExpression(e)||e.getName()!=="insert")return!1;const r=e.getExpression();return c(r)},g=t=>{if(!i.isIdentifier(t))return;const e=t.getSymbol(),r=e?.getAliasedSymbol()?.getDeclarations()??e?.getDeclarations()??[];for(const s of r)if(i.isVariableDeclaration(s)){const o=s.getInitializer();if(o&&i.isStringLiteral(o))return o.getLiteralText()}},f=t=>{const e=t.getArguments()[0];return e?i.isStringLiteral(e)?e.getLiteralText():g(e)??"":""},d=(t,e)=>n(t,e,(r,s)=>l(r)?{file:s,line:r.getStartLineNumber(),scope:a(r),table:f(r)}:void 0);export{d as default};
1
+ import{Node as i}from"ts-morph";import{collectCallRows as n}from"./isTestPath-CgyyLk8U.mjs";import{c as a}from"./attribution-Dw35rOaJ.mjs";import{i as c}from"./database-calls-DWDtdDbS.mjs";const l=t=>{const e=t.getExpression();if(!i.isPropertyAccessExpression(e)||e.getName()!=="insert")return!1;const r=e.getExpression();return c(r)},g=t=>{if(!i.isIdentifier(t))return;const e=t.getSymbol(),r=e?.getAliasedSymbol()?.getDeclarations()??e?.getDeclarations()??[];for(const s of r)if(i.isVariableDeclaration(s)){const o=s.getInitializer();if(o&&i.isStringLiteral(o))return o.getLiteralText()}},f=t=>{const e=t.getArguments()[0];return e?i.isStringLiteral(e)?e.getLiteralText():g(e)??"":""},d=(t,e)=>n(t,e,(r,s)=>l(r)?{file:s,line:r.getStartLineNumber(),scope:a(r),table:f(r)}:void 0);export{d as default};
@@ -0,0 +1 @@
1
+ import"./isTestPath-CgyyLk8U.mjs";import"./attribution-Dw35rOaJ.mjs";import"./database-calls-DWDtdDbS.mjs";import"./classify-procedure-call-DxuPQkJA.mjs";import{d as a}from"./index-CefI-Sba.mjs";export{a as default};
@@ -1 +1 @@
1
- import{SyntaxKind as f,Node as s}from"ts-morph";import{diagnosticAt as g}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as u}from"./module-specifiers-WF8iAydP.mjs";import{listLunoraSourceFiles as m,lunoraRelativePath as p,findObjectProperty as h}from"./isTestPath-DCyIyPa7.mjs";import{b as I,a as b}from"./attribution-NRssTEkk.mjs";const P=r=>{const i=r.getSymbol();if(!i)return r.getText()==="defineMigration";for(const t of i.getDeclarations())if(s.isImportSpecifier(t))return u(t.getImportDeclaration().getModuleSpecifierValue())?t.getNameNode().getText()==="defineMigration":!1;return!1},d=(r,i)=>{const t=h(r,i);if(!t||!s.isPropertyAssignment(t))return;const e=t.getInitializer();return e&&s.isStringLiteral(e)?e.getLiteralValue():void 0},v=(r,i)=>{const t=r.getInitializer();if(t?.getKind()!==f.CallExpression)return;const e=t.getExpression();if(!s.isIdentifier(e)||!P(e))return;const o=t.getArguments()[0];if(!o||!s.isObjectLiteralExpression(o))return;const n=d(o,"id"),a=b(r,"member");if(a!==void 0){if(n===void 0||n.trim()==="")throw g(o,`Migration "${a}" in "${i}" must declare \`id\` as a non-empty string literal so codegen can key the registry.`,{code:"MIGRATION_ID_NOT_STATIC",name:"LunoraError",status:500});return{exportName:a,filePath:i,id:n,table:d(o,"table")??""}}},M=r=>{const i=new Map;for(const t of r){const e=i.get(t.id);if(e!==void 0)throw Object.assign(new Error(`Duplicate migration id "${t.id}": declared in both "${e}" and "${t.filePath}". Migration ids must be unique across the project.`),{code:"DUPLICATE_MIGRATION_ID",id:t.id,name:"LunoraError",paths:[e,t.filePath],status:500});i.set(t.id,t.filePath)}},E=(r,i)=>{const t=m(i),e=[];for(const o of t){const n=r.getSourceFile(o)??r.addSourceFileAtPath(o),a=p(i,o);for(const l of I(n)){const c=v(l,a);c&&e.push(c)}}return e.sort((o,n)=>o.id.localeCompare(n.id)),M(e),e};export{E as default};
1
+ import{SyntaxKind as f,Node as s}from"ts-morph";import{diagnosticAt as g}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as u}from"./module-specifiers-WF8iAydP.mjs";import{listLunoraSourceFiles as m,lunoraRelativePath as p,findObjectProperty as h}from"./isTestPath-CgyyLk8U.mjs";import{b as I,a as b}from"./attribution-Dw35rOaJ.mjs";const P=r=>{const i=r.getSymbol();if(!i)return r.getText()==="defineMigration";for(const t of i.getDeclarations())if(s.isImportSpecifier(t))return u(t.getImportDeclaration().getModuleSpecifierValue())?t.getNameNode().getText()==="defineMigration":!1;return!1},d=(r,i)=>{const t=h(r,i);if(!t||!s.isPropertyAssignment(t))return;const e=t.getInitializer();return e&&s.isStringLiteral(e)?e.getLiteralValue():void 0},v=(r,i)=>{const t=r.getInitializer();if(t?.getKind()!==f.CallExpression)return;const e=t.getExpression();if(!s.isIdentifier(e)||!P(e))return;const o=t.getArguments()[0];if(!o||!s.isObjectLiteralExpression(o))return;const n=d(o,"id"),a=b(r,"member");if(a!==void 0){if(n===void 0||n.trim()==="")throw g(o,`Migration "${a}" in "${i}" must declare \`id\` as a non-empty string literal so codegen can key the registry.`,{code:"MIGRATION_ID_NOT_STATIC",name:"LunoraError",status:500});return{exportName:a,filePath:i,id:n,table:d(o,"table")??""}}},M=r=>{const i=new Map;for(const t of r){const e=i.get(t.id);if(e!==void 0)throw Object.assign(new Error(`Duplicate migration id "${t.id}": declared in both "${e}" and "${t.filePath}". Migration ids must be unique across the project.`),{code:"DUPLICATE_MIGRATION_ID",id:t.id,name:"LunoraError",paths:[e,t.filePath],status:500});i.set(t.id,t.filePath)}},E=(r,i)=>{const t=m(i),e=[];for(const o of t){const n=r.getSourceFile(o)??r.addSourceFileAtPath(o),a=p(i,o);for(const l of I(n)){const c=v(l,a);c&&e.push(c)}}return e.sort((o,n)=>o.id.localeCompare(n.id)),M(e),e};export{E as default};
@@ -1 +1 @@
1
- import{Node as s,SyntaxKind as r}from"ts-morph";import{listLunoraSourceFiles as a,lunoraRelativePath as l,handlerOf as c}from"./isTestPath-DCyIyPa7.mjs";import{b as d,d as f}from"./attribution-NRssTEkk.mjs";import{c as u}from"./classify-procedure-call-BBKuBvKg.mjs";const m={"crypto.getRandomValues":"crypto.getRandomValues","crypto.randomUUID":"crypto.randomUUID","Date.now":"Date.now","Math.random":"Math.random"},p=new Set(["globalThis","self"]),g=new Set(["globalThis","self","window"]),h=e=>{if(s.isIdentifier(e))return e.getText();if(s.isPropertyAccessExpression(e)){const t=e.getExpression();if(s.isIdentifier(t)&&g.has(t.getText()))return e.getName()}},x=e=>{const t=e.getExpression();if(s.isIdentifier(t)){const i=t.getText();return i==="fetch"||i==="Date"?i:void 0}if(!s.isPropertyAccessExpression(t))return;const n=t.getName(),o=h(t.getExpression());if(o!==void 0)return n==="fetch"&&p.has(o)?"fetch":m[`${o}.${n}`]},N=e=>{const t=e.getExpression();if(!s.isIdentifier(t)||t.getText()!=="Date")return;const n=e.getArguments(),o=n.every(i=>s.isNumericLiteral(i)||s.isStringLiteral(i)||s.isNoSubstitutionTemplateLiteral(i));return n.length>0&&o?void 0:"new Date"},E=e=>{const t=e.getInitializer();if(!t||!s.isCallExpression(t))return;const n=u(t);if(!n||n.kind!=="query"&&n.kind!=="mutation")return;const o=c(t,n.receiver);return o?{exportName:f(e)??e.getName(),handler:o,kind:n.kind}:void 0},S=(e,t)=>{const n=[];for(const o of e.handler.getDescendantsOfKind(r.CallExpression)){const i=x(o);i!==void 0&&n.push({callee:i,exportName:e.exportName,file:t,kind:e.kind,line:o.getStartLineNumber()})}for(const o of e.handler.getDescendantsOfKind(r.NewExpression)){const i=N(o);i!==void 0&&n.push({callee:i,exportName:e.exportName,file:t,kind:e.kind,line:o.getStartLineNumber()})}return n},v=(e,t)=>{const n=[];for(const o of d(e)){const i=E(o);i&&n.push(...S(i,t))}return n},T=(e,t)=>{const n=[];for(const o of a(t)){const i=e.getSourceFile(o)??e.addSourceFileAtPath(o);n.push(...v(i,l(t,o)))}return n};export{T as default};
1
+ import{Node as s,SyntaxKind as r}from"ts-morph";import{listLunoraSourceFiles as a,lunoraRelativePath as l,handlerOf as c}from"./isTestPath-CgyyLk8U.mjs";import{b as d,d as f}from"./attribution-Dw35rOaJ.mjs";import{c as u}from"./classify-procedure-call-DxuPQkJA.mjs";const m={"crypto.getRandomValues":"crypto.getRandomValues","crypto.randomUUID":"crypto.randomUUID","Date.now":"Date.now","Math.random":"Math.random"},p=new Set(["globalThis","self"]),g=new Set(["globalThis","self","window"]),h=e=>{if(s.isIdentifier(e))return e.getText();if(s.isPropertyAccessExpression(e)){const t=e.getExpression();if(s.isIdentifier(t)&&g.has(t.getText()))return e.getName()}},x=e=>{const t=e.getExpression();if(s.isIdentifier(t)){const i=t.getText();return i==="fetch"||i==="Date"?i:void 0}if(!s.isPropertyAccessExpression(t))return;const n=t.getName(),o=h(t.getExpression());if(o!==void 0)return n==="fetch"&&p.has(o)?"fetch":m[`${o}.${n}`]},N=e=>{const t=e.getExpression();if(!s.isIdentifier(t)||t.getText()!=="Date")return;const n=e.getArguments(),o=n.every(i=>s.isNumericLiteral(i)||s.isStringLiteral(i)||s.isNoSubstitutionTemplateLiteral(i));return n.length>0&&o?void 0:"new Date"},E=e=>{const t=e.getInitializer();if(!t||!s.isCallExpression(t))return;const n=u(t);if(!n||n.kind!=="query"&&n.kind!=="mutation")return;const o=c(t,n.receiver);return o?{exportName:f(e)??e.getName(),handler:o,kind:n.kind}:void 0},S=(e,t)=>{const n=[];for(const o of e.handler.getDescendantsOfKind(r.CallExpression)){const i=x(o);i!==void 0&&n.push({callee:i,exportName:e.exportName,file:t,kind:e.kind,line:o.getStartLineNumber()})}for(const o of e.handler.getDescendantsOfKind(r.NewExpression)){const i=N(o);i!==void 0&&n.push({callee:i,exportName:e.exportName,file:t,kind:e.kind,line:o.getStartLineNumber()})}return n},v=(e,t)=>{const n=[];for(const o of d(e)){const i=E(o);i&&n.push(...S(i,t))}return n},T=(e,t)=>{const n=[];for(const o of a(t)){const i=e.getSourceFile(o)??e.addSourceFileAtPath(o);n.push(...v(i,l(t,o)))}return n};export{T as default};
@@ -1 +1 @@
1
- import{Node as i}from"ts-morph";import{collectCallRows as c}from"./isTestPath-DCyIyPa7.mjs";import{c as l}from"./attribution-NRssTEkk.mjs";import{i as f}from"./database-calls-BFY_pIUf.mjs";const u=new Set(["withGeoIndex","withIndex","withSearchIndex"]),p=new Set(["collect","collectWithScores","first","paginate","take","unique"]),m=n=>{const t=n.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="query")return!1;const e=t.getExpression();return f(e)},g=n=>{const t=[];let e=n;for(;;){const r=e.getParent();if(!r||!i.isPropertyAccessExpression(r))break;const s=r.getParent();if(!s||!i.isCallExpression(s))break;t.push(r.getName()),e=s}return t},d=/\b[A-Za-z_$][\w$]*\._id\s*===?[^=]/u,E=n=>{let t=n;for(;;){const e=t.getParent();if(!e||!i.isPropertyAccessExpression(e))return!1;const r=e.getParent();if(!r||!i.isCallExpression(r))return!1;if(e.getName()==="filter"){const s=r.getArguments()[0];if(s&&d.test(s.getText()))return!0}t=r}},h=n=>{const t=n.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},y=(n,t)=>c(n,t,(e,r)=>{if(!m(e))return;const s=g(e),a=s.includes("filter");return{file:r,filtersPrimaryKey:a&&E(e),hasFilter:a,hasIndex:s.some(o=>u.has(o)),line:e.getStartLineNumber(),scope:l(e),table:h(e),terminal:s.findLast(o=>p.has(o))}});export{y as default};
1
+ import{Node as i}from"ts-morph";import{collectCallRows as c}from"./isTestPath-CgyyLk8U.mjs";import{c as l}from"./attribution-Dw35rOaJ.mjs";import{i as f}from"./database-calls-DWDtdDbS.mjs";const u=new Set(["withGeoIndex","withIndex","withSearchIndex"]),p=new Set(["collect","collectWithScores","first","paginate","take","unique"]),m=n=>{const t=n.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="query")return!1;const e=t.getExpression();return f(e)},g=n=>{const t=[];let e=n;for(;;){const r=e.getParent();if(!r||!i.isPropertyAccessExpression(r))break;const s=r.getParent();if(!s||!i.isCallExpression(s))break;t.push(r.getName()),e=s}return t},d=/\b[A-Za-z_$][\w$]*\._id\s*===?[^=]/u,E=n=>{let t=n;for(;;){const e=t.getParent();if(!e||!i.isPropertyAccessExpression(e))return!1;const r=e.getParent();if(!r||!i.isCallExpression(r))return!1;if(e.getName()==="filter"){const s=r.getArguments()[0];if(s&&d.test(s.getText()))return!0}t=r}},h=n=>{const t=n.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},y=(n,t)=>c(n,t,(e,r)=>{if(!m(e))return;const s=g(e),a=s.includes("filter");return{file:r,filtersPrimaryKey:a&&E(e),hasFilter:a,hasIndex:s.some(o=>u.has(o)),line:e.getStartLineNumber(),scope:l(e),table:h(e),terminal:s.findLast(o=>p.has(o))}});export{y as default};
@@ -0,0 +1 @@
1
+ import{d as r}from"./context-property-calls-BLTVj9HH.mjs";const t=(s,o)=>r(s,o,"r2sql");export{t as default};
@@ -1 +1 @@
1
- import{Node as o}from"ts-morph";import{listLunoraSourceFiles as x,lunoraRelativePath as h,findObjectProperty as m,stringPropertyOf as c}from"./isTestPath-DCyIyPa7.mjs";import{e as A}from"./exported-procedure-chains-DqU-ZCbG.mjs";import{r as L}from"./chain-6qc9c0JF.mjs";const E=new Set(["delete","insert","read","update"]),P=(e,t,i)=>{const r=e.getArguments()[0];if(!r||!o.isArrayLiteralExpression(r))return[];const s=[];for(const n of r.getElements()){if(!o.isObjectLiteralExpression(n))continue;const a=c(n,"on");a===void 0||!E.has(a)||s.push({file:t,on:a,procedure:i,table:c(n,"table")??""})}return s},u=e=>{if(!o.isObjectLiteralExpression(e))return[];const t=m(e,"permissions");if(!t||!o.isPropertyAssignment(t))return[];const i=t.getInitializer();if(!i||!o.isArrayLiteralExpression(i))return[];const r=[];for(const s of i.getElements()){if(o.isStringLiteral(s)){r.push(s.getLiteralText());continue}if(o.isCallExpression(s)){const n=s.getArguments()[0];n&&o.isStringLiteral(n)&&r.push(n.getLiteralText())}}return r},f=(e,t)=>t===void 0?e:{...e,description:t},v=e=>{if(o.isCallExpression(e)){const t=e.getArguments()[0];if(!t||!o.isStringLiteral(t))return;const i=e.getArguments()[1],r=i?c(i,"description"):void 0,s=i?u(i):[];return f({name:t.getLiteralText(),permissions:s},r)}if(o.isObjectLiteralExpression(e)){const t=c(e,"name");return t===void 0?void 0:f({name:t,permissions:u(e)},c(e,"description"))}},y=e=>{const t=e.getArguments()[1];if(!t||!o.isObjectLiteralExpression(t))return[];const i=m(t,"roles");if(!i||!o.isPropertyAssignment(i))return[];const r=i.getInitializer();if(!r||!o.isArrayLiteralExpression(r))return[];const s=[];for(const n of r.getElements()){const a=v(n);a&&s.push(a)}return s},O=(e,t,i)=>{const r=L(e);return{policies:r.flatMap(s=>P(s,t,i)),roles:r.flatMap(s=>y(s))}},I=(e,t)=>{const i=[],r=new Map;for(const s of x(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),a=h(t,s);for(const{name:g,receiver:d}of A(n)){const p=O(d,a,g);i.push(...p.policies);for(const l of p.roles)r.has(l.name)||r.set(l.name,l)}}return{policies:i,roles:[...r.values()]}};export{I as default};
1
+ import{Node as o}from"ts-morph";import{listLunoraSourceFiles as x,lunoraRelativePath as h,findObjectProperty as m,stringPropertyOf as c}from"./isTestPath-CgyyLk8U.mjs";import{e as A}from"./exported-procedure-chains-C5VKkd9T.mjs";import{r as L}from"./chain-nWiSr1yy.mjs";const E=new Set(["delete","insert","read","update"]),P=(e,t,i)=>{const r=e.getArguments()[0];if(!r||!o.isArrayLiteralExpression(r))return[];const s=[];for(const n of r.getElements()){if(!o.isObjectLiteralExpression(n))continue;const a=c(n,"on");a===void 0||!E.has(a)||s.push({file:t,on:a,procedure:i,table:c(n,"table")??""})}return s},u=e=>{if(!o.isObjectLiteralExpression(e))return[];const t=m(e,"permissions");if(!t||!o.isPropertyAssignment(t))return[];const i=t.getInitializer();if(!i||!o.isArrayLiteralExpression(i))return[];const r=[];for(const s of i.getElements()){if(o.isStringLiteral(s)){r.push(s.getLiteralText());continue}if(o.isCallExpression(s)){const n=s.getArguments()[0];n&&o.isStringLiteral(n)&&r.push(n.getLiteralText())}}return r},f=(e,t)=>t===void 0?e:{...e,description:t},v=e=>{if(o.isCallExpression(e)){const t=e.getArguments()[0];if(!t||!o.isStringLiteral(t))return;const i=e.getArguments()[1],r=i?c(i,"description"):void 0,s=i?u(i):[];return f({name:t.getLiteralText(),permissions:s},r)}if(o.isObjectLiteralExpression(e)){const t=c(e,"name");return t===void 0?void 0:f({name:t,permissions:u(e)},c(e,"description"))}},y=e=>{const t=e.getArguments()[1];if(!t||!o.isObjectLiteralExpression(t))return[];const i=m(t,"roles");if(!i||!o.isPropertyAssignment(i))return[];const r=i.getInitializer();if(!r||!o.isArrayLiteralExpression(r))return[];const s=[];for(const n of r.getElements()){const a=v(n);a&&s.push(a)}return s},O=(e,t,i)=>{const r=L(e);return{policies:r.flatMap(s=>P(s,t,i)),roles:r.flatMap(s=>y(s))}},I=(e,t)=>{const i=[],r=new Map;for(const s of x(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),a=h(t,s);for(const{name:g,receiver:d}of A(n)){const p=O(d,a,g);i.push(...p.policies);for(const l of p.roles)r.has(l.name)||r.set(l.name,l)}}return{policies:i,roles:[...r.values()]}};export{I as default};
@@ -1 +1 @@
1
- import{Node as o}from"ts-morph";import{listLunoraSourceFiles as c,lunoraRelativePath as f,findObjectProperty as u}from"./isTestPath-DCyIyPa7.mjs";import{b as p,d}from"./attribution-NRssTEkk.mjs";import{t as m}from"./database-calls-BFY_pIUf.mjs";import{c as b}from"./classify-procedure-call-BBKuBvKg.mjs";import{r as g}from"./chain-6qc9c0JF.mjs";const h=e=>{const t=e.getArguments()[0];if(!t||!o.isArrayLiteralExpression(t))return[];const r=[];for(const s of t.getElements()){if(!o.isObjectLiteralExpression(s))continue;const i=u(s,"table");if(!i||!o.isPropertyAssignment(i))continue;const n=i.getInitializer();n&&o.isStringLiteral(n)&&r.push(n.getLiteralText())}return r},y=e=>{const t=g(e);return{rlsTables:t.flatMap(r=>h(r)),usesRls:t.length>0}},v=new Set(["findFirst","findFirstOrThrow","findMany","get","query"]),P=new Set(["delete","deleteMany","insert","insertMany","patch","patchMany","replace"]),T=(e,t)=>{if(!o.isVariableDeclaration(e))return;const r=e.getInitializer();if(!r||!o.isCallExpression(r))return;const s=b(r);if(!s)return;const i=s.receiver?y(s.receiver):{rlsTables:[],usesRls:!1},{tablesRead:n,tablesWritten:a}=m(e,v,P);return{exportName:d(e)??e.getName(),file:t,rlsTables:i.rlsTables,tablesRead:n,tablesWritten:a,usesRls:i.usesRls,visibility:s.visibility}},O=(e,t)=>{const r=[];for(const s of c(t)){const i=e.getSourceFile(s)??e.addSourceFileAtPath(s),n=f(t,s);for(const a of p(i)){const l=T(a,n);l&&r.push(l)}}return r};export{O as default};
1
+ import{Node as o}from"ts-morph";import{listLunoraSourceFiles as c,lunoraRelativePath as f,findObjectProperty as u}from"./isTestPath-CgyyLk8U.mjs";import{b as p,d}from"./attribution-Dw35rOaJ.mjs";import{t as m}from"./database-calls-DWDtdDbS.mjs";import{c as b}from"./classify-procedure-call-DxuPQkJA.mjs";import{r as g}from"./chain-nWiSr1yy.mjs";const h=e=>{const t=e.getArguments()[0];if(!t||!o.isArrayLiteralExpression(t))return[];const r=[];for(const s of t.getElements()){if(!o.isObjectLiteralExpression(s))continue;const i=u(s,"table");if(!i||!o.isPropertyAssignment(i))continue;const n=i.getInitializer();n&&o.isStringLiteral(n)&&r.push(n.getLiteralText())}return r},y=e=>{const t=g(e);return{rlsTables:t.flatMap(r=>h(r)),usesRls:t.length>0}},v=new Set(["findFirst","findFirstOrThrow","findMany","get","query"]),P=new Set(["delete","deleteMany","insert","insertMany","patch","patchMany","replace"]),T=(e,t)=>{if(!o.isVariableDeclaration(e))return;const r=e.getInitializer();if(!r||!o.isCallExpression(r))return;const s=b(r);if(!s)return;const i=s.receiver?y(s.receiver):{rlsTables:[],usesRls:!1},{tablesRead:n,tablesWritten:a}=m(e,v,P);return{exportName:d(e)??e.getName(),file:t,rlsTables:i.rlsTables,tablesRead:n,tablesWritten:a,usesRls:i.usesRls,visibility:s.visibility}},O=(e,t)=>{const r=[];for(const s of c(t)){const i=e.getSourceFile(s)??e.addSourceFileAtPath(s),n=f(t,s);for(const a of p(i)){const l=T(a,n);l&&r.push(l)}}return r};export{O as default};
@@ -1 +1 @@
1
- import{listLunoraSourceFiles as d}from"./isTestPath-DCyIyPa7.mjs";const f=new Set(["@lunora/agent","@lunora/agent/sandbox"]),t={browserTool:"usesSandboxBrowser",containerFsTool:"usesSandboxContainer",containerTool:"usesSandboxContainer",fsTool:"usesSandboxFs",jsCodeTool:"usesSandboxLoader"},u=()=>({usesSandboxBrowser:!1,usesSandboxContainer:!1,usesSandboxFs:!1,usesSandboxLoader:!1}),i=o=>{const s=u();if(!f.has(o.getModuleSpecifierValue())||o.isTypeOnly())return s;for(const e of o.getNamedImports()){if(e.isTypeOnly())continue;const n=t[e.getNameNode().getText()];n!==void 0&&(s[n]=!0)}return s},b=(o,s)=>{const e=u();for(const n of d(s)){const c=o.getSourceFile(n)??o.addSourceFileAtPath(n);for(const a of c.getImportDeclarations()){const l=i(a);for(const r of Object.values(t))e[r]||=l[r]}if(Object.values(t).every(a=>e[a]))break}return e};export{b as discoverSandboxUsage,u as noSandboxUsage,i as scanImportDeclaration};
1
+ import{listLunoraSourceFiles as d}from"./isTestPath-CgyyLk8U.mjs";const f=new Set(["@lunora/agent","@lunora/agent/sandbox"]),t={browserTool:"usesSandboxBrowser",containerFsTool:"usesSandboxContainer",containerTool:"usesSandboxContainer",fsTool:"usesSandboxFs",jsCodeTool:"usesSandboxLoader"},u=()=>({usesSandboxBrowser:!1,usesSandboxContainer:!1,usesSandboxFs:!1,usesSandboxLoader:!1}),i=o=>{const s=u();if(!f.has(o.getModuleSpecifierValue())||o.isTypeOnly())return s;for(const e of o.getNamedImports()){if(e.isTypeOnly())continue;const n=t[e.getNameNode().getText()];n!==void 0&&(s[n]=!0)}return s},b=(o,s)=>{const e=u();for(const n of d(s)){const c=o.getSourceFile(n)??o.addSourceFileAtPath(n);for(const a of c.getImportDeclarations()){const l=i(a);for(const r of Object.values(t))e[r]||=l[r]}if(Object.values(t).every(a=>e[a]))break}return e};export{b as discoverSandboxUsage,u as noSandboxUsage,i as scanImportDeclaration};
@@ -1 +1 @@
1
- import{LunoraError as R}from"@lunora/errors";import{Node as i,SyntaxKind as F}from"ts-morph";import{diagnosticAt as d}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{createRequire as C}from"node:module";import{join as _}from"node:path";import{fileURLToPath as B}from"node:url";import{createJiti as V}from"jiti";import{findObjectProperty as u}from"./isTestPath-DCyIyPa7.mjs";import{r as q,p as J}from"./parse-validator-DYdT7Hyf.mjs";import{R as U}from"./reserved-words-CW1QFbTd.mjs";import{a as I}from"./project-config-file-Bv2l-Kmm.mjs";const K=(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.`,W=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}},Z=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}:{}}),m=e=>{const t=e?._meta??{},n=e?.kind??"unknown",s={column:Z(t.column),kind:n};switch(n){case"array":case"optional":{s.inner=m(t.inner);break}case"from":break;case"id":{s.tableName=t.tableName;break}case"literal":{s.literalValue=W(t.value);break}case"object":{const r=t.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([o,a])=>[o,m(a)]));break}case"record":{s.valueType=m(t.valueValidator),t.keyValidator!==void 0&&(s.keyType=m(t.keyValidator));break}case"storage":{typeof t.bucket=="string"&&(s.bucket=t.bucket);break}case"union":{const r=t.members??[];s.members=r.map(o=>m(o));break}}return s},G=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",X=(e,t)=>{const n=[];e.relationMap&&Object.keys(e.relationMap).length>0&&n.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&n.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&n.push("vector indexes"),n.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${t}" declares ${n.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},H=(e,t)=>{const n=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return X(e,t),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:t,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(r=>({field:r.field,...r.filterFields?{filterFields:r.filterFields}:{},...r.language===void 0?{}:{language:r.language},...r.staged===void 0?{}:{staged:r.staged},...r.strategy===void 0?{}:{strategy:r.strategy},name:r.name})),shape:Object.fromEntries(Object.entries(n).map(([r,o])=>[r,m(o)])),shardMode:G(e.shardMode),vectorIndexes:[]}},Q=e=>{const{key:t,tables:n}=e;if(typeof t!="string"||typeof n!="object"||n===null)return;const s=Object.entries(n).map(([a,l])=>H(l,a)),r=e.vectorIndexes??{},o=Object.entries(r??{}).map(([a,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:a,table:l.table??""}));return{bareTables:s,bareVectorIndexes:o,key:t}},Y=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0}},ee=e=>{const t=Y(e);if(t===void 0)return;const n=i.isPropertyAccessExpression(e)?e.getName():void 0,s=n===void 0?[]:[n];for(const r of e.getSourceFile().getImportDeclarations()){const o=r.getModuleSpecifierValue();for(const a of r.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===t)return{importedName:a.getName(),moduleSpecifier:o,propertyPath:s};if(r.getDefaultImport()?.getText()===t)return{importedName:"default",moduleSpecifier:o,propertyPath:s};if(r.getNamespaceImport()?.getText()===t&&n!==void 0)return{importedName:n,moduleSpecifier:o,propertyPath:[]}}},te=(e,t)=>{let n=e[t.importedName];for(const s of t.propertyPath){if(typeof n!="object"||n===null)return;n=n[s]}return n},ne=(e,t)=>{const n=ee(e);if(n)try{const s=V(_(t,"noop.js")).esmResolve(n.moduleSpecifier),r=C(_(t,"noop.cjs"))(s.startsWith("file:")?B(s):s),o=te(r,n);return typeof o!="object"||o===null?void 0:Q(o)}catch{return}},re=new Set(["cosine","dot-product","euclidean"]),b=(e,t)=>{const n=u(e,t);if(n&&i.isPropertyAssignment(n))return n.getInitializer()},f=(e,t)=>{const n=b(e,t);if(n&&i.isStringLiteral(n))return n.getLiteralText()},x=(e,t)=>{const n=b(e,t);if(n&&i.isNumericLiteral(n))return Number(n.getLiteralText())},O=(e,t)=>{const n=b(e,t);if(n&&(i.isTrueLiteral(n)||i.isFalseLiteral(n)))return n.getLiteralValue()},h=(e,t)=>{const n=b(e,t);if(n&&i.isArrayLiteralExpression(n))return n.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},A=e=>e&&re.has(e)?e:void 0,y=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",se=(e,t)=>{const n=h(e,t);return n!==void 0&&n.length>0?n:void 0},N=(e,t,n,s,r)=>{let o=e;for(;;){const a=o.getParent();if(!a||!i.isPropertyAccessExpression(a))break;const l=a.getParent();if(!l||!i.isCallExpression(l))break;if(a.getName()===t){const c=l.getArguments()[0];if(!c||!i.isStringLiteral(c))throw d(l,`\`.${t}(...)\` expects a string literal (${r})`);const g=c.getLiteralText();if(!s.has(g))throw d(c,`unknown ${n} ${JSON.stringify(g)} — expected ${r}`);return g}o=l}},ie=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,ae=/__(?:agg|rank|geo|fts)_/u,le=e=>oe.test(e)||ae.test(e),ce=new Set(["cascade","restrict","set null"]),de=new Set(["aggregate","asId","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteWhere","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","lookupById","normalizeId","patch","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","replace","restore","system","wipeShard"]),P=/^[A-Za-z_$][\w$]*$/u,S=(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(U.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(!P.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(le(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.`)},fe=e=>e&&ce.has(e)?e:void 0,ue=e=>{if(!i.isArrowFunction(e))return;let t=e.getBody();if(i.isParenthesizedExpression(t))t=t.getExpression();else if(i.isBlock(t)){const n=t.getStatements().find(s=>i.isReturnStatement(s));t=n&&i.isReturnStatement(n)?n.getExpression()??t:t}return i.isObjectLiteralExpression(t)?t:void 0},pe=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isPropertyAccessExpression(n))return;const s=n.getName();if(s!=="one"&&s!=="many")return;const[r,o]=t.getArguments();if(!r||!i.isStringLiteral(r))throw d(r??t,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${r?r.getText():"no argument"}.`);const a=r.getLiteralText();let l="_unknown_",c="_id",g;return o&&i.isObjectLiteralExpression(o)&&(l=f(o,"field")??l,c=f(o,"references")??c,g=s==="one"?fe(f(o,"onDelete")):void 0),{field:l,kind:s,name:I(e),onDelete:g,references:c,table:a}},ge=e=>{const t=ue(e);if(!t)return[];const n=[];for(const s of t.getProperties()){const r=pe(s);r&&n.push(r)}return n},me=(e,t,n)=>{if(!t.includes("."))return;const[s="",...r]=t.split("."),o=`${s}${r.map(a=>a.charAt(0).toUpperCase()+a.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. \`${o}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`)},be=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=u(e,"unique");if(!t||!i.isPropertyAssignment(t))return!1;const n=t.getInitializer();if(n===void 0)return!1;if(!i.isTrueLiteral(n)&&!i.isFalseLiteral(n))throw d(n,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(n.getText())}`);return i.isTrueLiteral(n)},xe=e=>{const[t,n,s]=e,r=be(s),o=y(t),a=n&&i.isArrayLiteralExpression(n)?n.getElements():[];for(const c of a)if(!i.isStringLiteral(c))throw d(c,`index "${o}" lists a non-literal field (${JSON.stringify(c.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=a.filter(c=>i.isStringLiteral(c));for(const c of l)me(c,c.getLiteralText(),o);return{fields:l.map(c=>c.getLiteralText()),name:o,unique:r}},he=e=>{const[t,n]=e;let s="_unknown_",r,o,a,l;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=h(n,"filterFields"),o=f(n,"language"),a=O(n,"staged"),l=f(n,"strategy")),{field:s,filterFields:r,language:o,name:y(t),staged:a,strategy:l}},ye=e=>{const[t,n]=e;let s="_unknown_",r;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=x(n,"precision")),{field:s,name:y(t),precision:r}},ve=e=>{const[t,n]=e,s=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";let r;return n&&i.isObjectLiteralExpression(n)&&(r=x(n,"after")),{after:r,field:s}},Ee=e=>{if(!i.isObjectLiteralExpression(e))return;const t=f(e,"field");return t===void 0?void 0:{direction:f(e,"direction")==="desc"?"desc":"asc",field:t}},Ie=e=>{const[t,n]=e;let s=[],r;if(n&&i.isObjectLiteralExpression(n)){const o=u(n,"sortBy");if(o&&i.isPropertyAssignment(o)){const a=o.getInitializer();a&&i.isArrayLiteralExpression(a)&&(s=a.getElements().map(l=>Ee(l)).filter(l=>l!==void 0))}r=h(n,"partitionBy")}return{name:y(t),partitionBy:r,sortBy:s}},Se=(e,t)=>{const[n,s]=e,r=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:x(s,"dimensions"),field:r,metadata:h(s,"metadata"),metric:A(f(s,"metric")),name:f(s,"index")??"_unnamed_",table:t}},ke=e=>{const t=e[0];return t&&i.isObjectLiteralExpression(t)&&f(t,"backend")==="hyperdrive"?"hyperdrive":"d1"},we=e=>{if(e&&i.isObjectLiteralExpression(e)){const t=u(e,"field");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isStringLiteral(n))return n.getLiteralText()}}return"deletedAt"},Te=e=>{const t=e[0];return!t||!i.isObjectLiteralExpression(t)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(t,"binding")??"",columns:se(t,"columns"),hasReconcile:u(t,"reconcileEveryMs")!==void 0,hasSoftDelete:u(t,"softDeleteColumn")!==void 0,hasTenantBy:u(t,"tenantBy")!==void 0,idColumn:f(t,"idColumn"),mode:f(t,"mode"),query:f(t,"query")}},_e=(e,t,n,s)=>{switch(t){case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(ye(n));break}case"global":{e.shardMode="global",e.globalBackend=ke(n);break}case"index":{e.indexes.push(xe(n));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(Ie(n));break}case"relations":{const r=n[0];r&&e.relations.push(...ge(r));break}case"searchIndex":{e.searchIndexes.push(he(n));break}case"shardBy":{const r=n[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:we(n[0])};break}case"source":{e.externalSource=Te(n),e.externallyManaged=!0;break}case"ttl":{e.ttl=ve(n);break}case"vectorize":{const r=Se(n,s);r&&e.vectorIndexes.push(r);break}}},L=["__vocab","_config","_content","_data","_docsize","_idx"],Le=(e,t,n)=>{const s=new Set(n.map(r=>r.name));for(const r of n)for(const o of L){const a=`${r.name}${o}`;if(!s.has(a))continue;const l=o==="__vocab"?`the \`fts5vocab\` companion for "${a}" is created \`IF NOT EXISTS\`, so it silently resolves to "${r.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${a}" 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 "${r.name}" and "${a}", whose generated FTS5 tables collide: "${r.name}" already owns "${t}__fts_${a}" as its "${o}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${L.join(", ")}.`)}},Oe=(e,t,n)=>{if(n.ttl!==void 0&&n.shardMode==="global")throw d(e,ie(t))},$=(e,t)=>{const n={commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",vectorIndexes:[]};let s={},r=e;for(;i.isCallExpression(r);){const o=r.getExpression(),a=r.getArguments();if(i.isPropertyAccessExpression(o))_e(n,o.getName(),a,t),r=o.getExpression();else if(i.isIdentifier(o)&&o.getText()==="defineTable"){const l=a[0];if(l&&i.isObjectLiteralExpression(l))s=J(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 n.softDelete&&!(n.softDelete.field in s)&&(s={...s,[n.softDelete.field]:{inner:{column:{notNull:!1},kind:"number"},kind:"optional"}}),Le(e,t,n.searchIndexes),Oe(e,t,n),{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:s,shardMode:n.shardMode,softDelete:n.softDelete,ttl:n.ttl,vectorIndexes:n.vectorIndexes}},j=(e,t=[],n=new Set,s=new Set)=>{s.add(e);for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){const a=q(r.getExpression());a!==void 0&&!s.has(a)&&j(a,t,n,s);continue}if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(o){const a=I(r);if(S(a,r.getNameNode()),n.has(a))throw d(r.getNameNode(),`defineSchema({...}): table "${a}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);n.add(a),t.push($(o,a))}}return t},Ae=e=>{const t=u(e,"source");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isObjectLiteralExpression(n))return f(n,"table")??"_unknown_"}return"_unknown_"},Ne=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isIdentifier(n)||n.getText()!=="defineVectorIndex")return;const s=t.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),o=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:x(s,"dimensions"),metric:A(f(s,"metric")),name:o,table:Ae(s)}},D=e=>{const t=[];for(const n of e.getProperties()){const s=Ne(n);s&&t.push(s)}return t},k=(e,t)=>`${e}_${t}`,Pe=(e,t)=>{if(!P.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.`)},E=(e,t,n)=>n.has(e)?k(t,e):e,$e=(e,t,n,s)=>{const r=k(t,e.name);return{...e,extensionKey:t,...s?{extensionFromPackage:!0}:{},name:r,relations:e.relations.map(o=>({...o,table:E(o.table,t,n)})),vectorIndexes:e.vectorIndexes.map(o=>({...o,table:E(o.table,t,n)}))}},je=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},De=e=>{if(!i.isCallExpression(e))return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="defineSchemaExtension"},ze=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t:void 0}},Me=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const t=e.getExpression();let n;if(i.isIdentifier(t)?n=t.getText():i.isPropertyAccessExpression(t)&&(n=t.getName()),n==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},Re=(e,t)=>{const n=je(e);if(n){if(i.isPropertyAccessExpression(t)){const s=Me(n);return s?b(s,t.getName()):void 0}return n}},Fe=e=>{let t=e,n=0;for(;t&&n<32;){if(n+=1,De(t))return t;const s=ze(t),r=s&&i.isIdentifier(s)?s.getSymbol():void 0,a=(r?.getAliasedSymbol()?.getDeclarations()??r?.getDeclarations()??[])[0];if(!a)return;const l=a.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;t=Re(a,t)}},Ce=e=>{const[t,n]=e.getArguments();if(!(!t||!i.isStringLiteral(t))&&!(!n||!i.isObjectLiteralExpression(n)))return{key:t.getLiteralText(),keyNode:t,options:n}},Be=e=>{const t=u(e,"tables");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();if(!n||!i.isObjectLiteralExpression(n))return[];const s=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=I(r);S(a,r.getNameNode()),s.push($(o,a))}return s},Ve=e=>{const t=u(e,"vectorIndexes");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();return!n||!i.isObjectLiteralExpression(n)?[]:D(n)},z=(e,t,n,s,r)=>{Pe(e,s);const o=new Set(t.map(c=>c.name)),a=t.map(c=>$e(c,e,o,r)),l=n.map(c=>({...c,name:k(e,c.name),table:E(c.table,e,o)}));return{tables:a,vectorIndexes:l}},qe=(e,t,n)=>z(e,Be(n),Ve(n),t,t.getSourceFile().getFilePath().includes("/node_modules/")),Je=(e,t)=>{const n=e.getArguments()[0];if(!n)return;const s=Fe(n);if(!s){if(t!==void 0){const o=ne(n,t);if(o){for(const a of o.bareTables)S(a.name,n);return z(o.key,o.bareTables,o.bareVectorIndexes,n,!0)}}console.warn(`@lunora/codegen: skipping \`.extend(${n.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.`);return}const r=Ce(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return qe(r.key,r.keyNode,r.options)},Ue=e=>{const t=[];let n=e;for(;;){const s=n.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&t.push(r),n=r}return t},Ke=(e,t,n)=>{const s=new Set(t.map(o=>o.name)),r=[];for(const o of Ue(e)){const a=Je(o,n);if(a){for(const l of a.tables){if(s.has(l.name))throw d(o,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),t.push(l)}r.push(...a.vectorIndexes)}}return r},We=new Set(["eu","fedramp","us"]),Ze=e=>N(e,"jurisdiction","jurisdiction",We,'"eu", "us", or "fedramp"'),Ge=e=>{let t=e;for(;;){const n=t.getParent(),s=n?.getParent();if(!n||!i.isPropertyAccessExpression(n)||!s||!i.isCallExpression(s))return!1;if(n.getName()==="jurisdiction"){const r=s.getArguments()[1];return r!==void 0&&i.isObjectLiteralExpression(r)&&O(r,"pinAuth")===!0}t=s}},Xe=new Set(["required"]),He=e=>N(e,"rls","rls mode",Xe,'"required"'),ct=(e,t,n)=>{const r=e.addSourceFileAtPath(t).getDescendantsOfKind(F.CallExpression).find(p=>{const T=p.getExpression();return i.isIdentifier(T)&&T.getText()==="defineSchema"});if(!r)throw new R("INTERNAL",`defineSchema() not found in ${t}`);const o=r.getArguments()[0];if(!o||!i.isObjectLiteralExpression(o))throw d(r,"defineSchema() expects an object literal");const a=j(o),l=r.getArguments()[1],c=l&&i.isObjectLiteralExpression(l)?D(l):[],g=Ke(r,a,n),w=[...a.flatMap(p=>p.vectorIndexes),...c,...g],M=new Set(a.filter(p=>p.shardMode==="global").map(p=>p.name)),v=w.find(p=>M.has(p.table));if(v)throw d(r,K(v.table,v.name));return{jurisdiction:Ze(r),...Ge(r)?{jurisdictionPinsAuth:!0}:{},rlsMode:He(r),tables:a,vectorIndexes:w}};export{ct as default};
1
+ import{LunoraError as R}from"@lunora/errors";import{Node as i,SyntaxKind as F}from"ts-morph";import{diagnosticAt as d}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{createRequire as C}from"node:module";import{join as _}from"node:path";import{fileURLToPath as B}from"node:url";import{createJiti as V}from"jiti";import{findObjectProperty as u}from"./isTestPath-CgyyLk8U.mjs";import{r as q,p as J}from"./parse-validator-DYdT7Hyf.mjs";import{R as U}from"./reserved-words-CW1QFbTd.mjs";import{a as I}from"./project-config-file-Bv2l-Kmm.mjs";const K=(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.`,W=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}},Z=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}:{}}),m=e=>{const t=e?._meta??{},n=e?.kind??"unknown",s={column:Z(t.column),kind:n};switch(n){case"array":case"optional":{s.inner=m(t.inner);break}case"from":break;case"id":{s.tableName=t.tableName;break}case"literal":{s.literalValue=W(t.value);break}case"object":{const r=t.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([o,a])=>[o,m(a)]));break}case"record":{s.valueType=m(t.valueValidator),t.keyValidator!==void 0&&(s.keyType=m(t.keyValidator));break}case"storage":{typeof t.bucket=="string"&&(s.bucket=t.bucket);break}case"union":{const r=t.members??[];s.members=r.map(o=>m(o));break}}return s},G=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",X=(e,t)=>{const n=[];e.relationMap&&Object.keys(e.relationMap).length>0&&n.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&n.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&n.push("vector indexes"),n.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${t}" declares ${n.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},H=(e,t)=>{const n=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return X(e,t),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:t,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(r=>({field:r.field,...r.filterFields?{filterFields:r.filterFields}:{},...r.language===void 0?{}:{language:r.language},...r.staged===void 0?{}:{staged:r.staged},...r.strategy===void 0?{}:{strategy:r.strategy},name:r.name})),shape:Object.fromEntries(Object.entries(n).map(([r,o])=>[r,m(o)])),shardMode:G(e.shardMode),vectorIndexes:[]}},Q=e=>{const{key:t,tables:n}=e;if(typeof t!="string"||typeof n!="object"||n===null)return;const s=Object.entries(n).map(([a,l])=>H(l,a)),r=e.vectorIndexes??{},o=Object.entries(r??{}).map(([a,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:a,table:l.table??""}));return{bareTables:s,bareVectorIndexes:o,key:t}},Y=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0}},ee=e=>{const t=Y(e);if(t===void 0)return;const n=i.isPropertyAccessExpression(e)?e.getName():void 0,s=n===void 0?[]:[n];for(const r of e.getSourceFile().getImportDeclarations()){const o=r.getModuleSpecifierValue();for(const a of r.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===t)return{importedName:a.getName(),moduleSpecifier:o,propertyPath:s};if(r.getDefaultImport()?.getText()===t)return{importedName:"default",moduleSpecifier:o,propertyPath:s};if(r.getNamespaceImport()?.getText()===t&&n!==void 0)return{importedName:n,moduleSpecifier:o,propertyPath:[]}}},te=(e,t)=>{let n=e[t.importedName];for(const s of t.propertyPath){if(typeof n!="object"||n===null)return;n=n[s]}return n},ne=(e,t)=>{const n=ee(e);if(n)try{const s=V(_(t,"noop.js")).esmResolve(n.moduleSpecifier),r=C(_(t,"noop.cjs"))(s.startsWith("file:")?B(s):s),o=te(r,n);return typeof o!="object"||o===null?void 0:Q(o)}catch{return}},re=new Set(["cosine","dot-product","euclidean"]),b=(e,t)=>{const n=u(e,t);if(n&&i.isPropertyAssignment(n))return n.getInitializer()},f=(e,t)=>{const n=b(e,t);if(n&&i.isStringLiteral(n))return n.getLiteralText()},x=(e,t)=>{const n=b(e,t);if(n&&i.isNumericLiteral(n))return Number(n.getLiteralText())},O=(e,t)=>{const n=b(e,t);if(n&&(i.isTrueLiteral(n)||i.isFalseLiteral(n)))return n.getLiteralValue()},h=(e,t)=>{const n=b(e,t);if(n&&i.isArrayLiteralExpression(n))return n.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},A=e=>e&&re.has(e)?e:void 0,y=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",se=(e,t)=>{const n=h(e,t);return n!==void 0&&n.length>0?n:void 0},N=(e,t,n,s,r)=>{let o=e;for(;;){const a=o.getParent();if(!a||!i.isPropertyAccessExpression(a))break;const l=a.getParent();if(!l||!i.isCallExpression(l))break;if(a.getName()===t){const c=l.getArguments()[0];if(!c||!i.isStringLiteral(c))throw d(l,`\`.${t}(...)\` expects a string literal (${r})`);const g=c.getLiteralText();if(!s.has(g))throw d(c,`unknown ${n} ${JSON.stringify(g)} — expected ${r}`);return g}o=l}},ie=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,ae=/__(?:agg|rank|geo|fts)_/u,le=e=>oe.test(e)||ae.test(e),ce=new Set(["cascade","restrict","set null"]),de=new Set(["aggregate","asId","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteWhere","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","lookupById","normalizeId","patch","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","replace","restore","system","wipeShard"]),P=/^[A-Za-z_$][\w$]*$/u,S=(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(U.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(!P.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(le(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.`)},fe=e=>e&&ce.has(e)?e:void 0,ue=e=>{if(!i.isArrowFunction(e))return;let t=e.getBody();if(i.isParenthesizedExpression(t))t=t.getExpression();else if(i.isBlock(t)){const n=t.getStatements().find(s=>i.isReturnStatement(s));t=n&&i.isReturnStatement(n)?n.getExpression()??t:t}return i.isObjectLiteralExpression(t)?t:void 0},pe=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isPropertyAccessExpression(n))return;const s=n.getName();if(s!=="one"&&s!=="many")return;const[r,o]=t.getArguments();if(!r||!i.isStringLiteral(r))throw d(r??t,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${r?r.getText():"no argument"}.`);const a=r.getLiteralText();let l="_unknown_",c="_id",g;return o&&i.isObjectLiteralExpression(o)&&(l=f(o,"field")??l,c=f(o,"references")??c,g=s==="one"?fe(f(o,"onDelete")):void 0),{field:l,kind:s,name:I(e),onDelete:g,references:c,table:a}},ge=e=>{const t=ue(e);if(!t)return[];const n=[];for(const s of t.getProperties()){const r=pe(s);r&&n.push(r)}return n},me=(e,t,n)=>{if(!t.includes("."))return;const[s="",...r]=t.split("."),o=`${s}${r.map(a=>a.charAt(0).toUpperCase()+a.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. \`${o}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`)},be=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=u(e,"unique");if(!t||!i.isPropertyAssignment(t))return!1;const n=t.getInitializer();if(n===void 0)return!1;if(!i.isTrueLiteral(n)&&!i.isFalseLiteral(n))throw d(n,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(n.getText())}`);return i.isTrueLiteral(n)},xe=e=>{const[t,n,s]=e,r=be(s),o=y(t),a=n&&i.isArrayLiteralExpression(n)?n.getElements():[];for(const c of a)if(!i.isStringLiteral(c))throw d(c,`index "${o}" lists a non-literal field (${JSON.stringify(c.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=a.filter(c=>i.isStringLiteral(c));for(const c of l)me(c,c.getLiteralText(),o);return{fields:l.map(c=>c.getLiteralText()),name:o,unique:r}},he=e=>{const[t,n]=e;let s="_unknown_",r,o,a,l;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=h(n,"filterFields"),o=f(n,"language"),a=O(n,"staged"),l=f(n,"strategy")),{field:s,filterFields:r,language:o,name:y(t),staged:a,strategy:l}},ye=e=>{const[t,n]=e;let s="_unknown_",r;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=x(n,"precision")),{field:s,name:y(t),precision:r}},ve=e=>{const[t,n]=e,s=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";let r;return n&&i.isObjectLiteralExpression(n)&&(r=x(n,"after")),{after:r,field:s}},Ee=e=>{if(!i.isObjectLiteralExpression(e))return;const t=f(e,"field");return t===void 0?void 0:{direction:f(e,"direction")==="desc"?"desc":"asc",field:t}},Ie=e=>{const[t,n]=e;let s=[],r;if(n&&i.isObjectLiteralExpression(n)){const o=u(n,"sortBy");if(o&&i.isPropertyAssignment(o)){const a=o.getInitializer();a&&i.isArrayLiteralExpression(a)&&(s=a.getElements().map(l=>Ee(l)).filter(l=>l!==void 0))}r=h(n,"partitionBy")}return{name:y(t),partitionBy:r,sortBy:s}},Se=(e,t)=>{const[n,s]=e,r=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:x(s,"dimensions"),field:r,metadata:h(s,"metadata"),metric:A(f(s,"metric")),name:f(s,"index")??"_unnamed_",table:t}},ke=e=>{const t=e[0];return t&&i.isObjectLiteralExpression(t)&&f(t,"backend")==="hyperdrive"?"hyperdrive":"d1"},we=e=>{if(e&&i.isObjectLiteralExpression(e)){const t=u(e,"field");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isStringLiteral(n))return n.getLiteralText()}}return"deletedAt"},Te=e=>{const t=e[0];return!t||!i.isObjectLiteralExpression(t)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(t,"binding")??"",columns:se(t,"columns"),hasReconcile:u(t,"reconcileEveryMs")!==void 0,hasSoftDelete:u(t,"softDeleteColumn")!==void 0,hasTenantBy:u(t,"tenantBy")!==void 0,idColumn:f(t,"idColumn"),mode:f(t,"mode"),query:f(t,"query")}},_e=(e,t,n,s)=>{switch(t){case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(ye(n));break}case"global":{e.shardMode="global",e.globalBackend=ke(n);break}case"index":{e.indexes.push(xe(n));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(Ie(n));break}case"relations":{const r=n[0];r&&e.relations.push(...ge(r));break}case"searchIndex":{e.searchIndexes.push(he(n));break}case"shardBy":{const r=n[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:we(n[0])};break}case"source":{e.externalSource=Te(n),e.externallyManaged=!0;break}case"ttl":{e.ttl=ve(n);break}case"vectorize":{const r=Se(n,s);r&&e.vectorIndexes.push(r);break}}},L=["__vocab","_config","_content","_data","_docsize","_idx"],Le=(e,t,n)=>{const s=new Set(n.map(r=>r.name));for(const r of n)for(const o of L){const a=`${r.name}${o}`;if(!s.has(a))continue;const l=o==="__vocab"?`the \`fts5vocab\` companion for "${a}" is created \`IF NOT EXISTS\`, so it silently resolves to "${r.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${a}" 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 "${r.name}" and "${a}", whose generated FTS5 tables collide: "${r.name}" already owns "${t}__fts_${a}" as its "${o}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${L.join(", ")}.`)}},Oe=(e,t,n)=>{if(n.ttl!==void 0&&n.shardMode==="global")throw d(e,ie(t))},$=(e,t)=>{const n={commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",vectorIndexes:[]};let s={},r=e;for(;i.isCallExpression(r);){const o=r.getExpression(),a=r.getArguments();if(i.isPropertyAccessExpression(o))_e(n,o.getName(),a,t),r=o.getExpression();else if(i.isIdentifier(o)&&o.getText()==="defineTable"){const l=a[0];if(l&&i.isObjectLiteralExpression(l))s=J(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 n.softDelete&&!(n.softDelete.field in s)&&(s={...s,[n.softDelete.field]:{inner:{column:{notNull:!1},kind:"number"},kind:"optional"}}),Le(e,t,n.searchIndexes),Oe(e,t,n),{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:s,shardMode:n.shardMode,softDelete:n.softDelete,ttl:n.ttl,vectorIndexes:n.vectorIndexes}},j=(e,t=[],n=new Set,s=new Set)=>{s.add(e);for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){const a=q(r.getExpression());a!==void 0&&!s.has(a)&&j(a,t,n,s);continue}if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(o){const a=I(r);if(S(a,r.getNameNode()),n.has(a))throw d(r.getNameNode(),`defineSchema({...}): table "${a}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);n.add(a),t.push($(o,a))}}return t},Ae=e=>{const t=u(e,"source");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isObjectLiteralExpression(n))return f(n,"table")??"_unknown_"}return"_unknown_"},Ne=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isIdentifier(n)||n.getText()!=="defineVectorIndex")return;const s=t.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),o=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:x(s,"dimensions"),metric:A(f(s,"metric")),name:o,table:Ae(s)}},D=e=>{const t=[];for(const n of e.getProperties()){const s=Ne(n);s&&t.push(s)}return t},k=(e,t)=>`${e}_${t}`,Pe=(e,t)=>{if(!P.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.`)},E=(e,t,n)=>n.has(e)?k(t,e):e,$e=(e,t,n,s)=>{const r=k(t,e.name);return{...e,extensionKey:t,...s?{extensionFromPackage:!0}:{},name:r,relations:e.relations.map(o=>({...o,table:E(o.table,t,n)})),vectorIndexes:e.vectorIndexes.map(o=>({...o,table:E(o.table,t,n)}))}},je=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},De=e=>{if(!i.isCallExpression(e))return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="defineSchemaExtension"},ze=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t:void 0}},Me=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const t=e.getExpression();let n;if(i.isIdentifier(t)?n=t.getText():i.isPropertyAccessExpression(t)&&(n=t.getName()),n==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},Re=(e,t)=>{const n=je(e);if(n){if(i.isPropertyAccessExpression(t)){const s=Me(n);return s?b(s,t.getName()):void 0}return n}},Fe=e=>{let t=e,n=0;for(;t&&n<32;){if(n+=1,De(t))return t;const s=ze(t),r=s&&i.isIdentifier(s)?s.getSymbol():void 0,a=(r?.getAliasedSymbol()?.getDeclarations()??r?.getDeclarations()??[])[0];if(!a)return;const l=a.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;t=Re(a,t)}},Ce=e=>{const[t,n]=e.getArguments();if(!(!t||!i.isStringLiteral(t))&&!(!n||!i.isObjectLiteralExpression(n)))return{key:t.getLiteralText(),keyNode:t,options:n}},Be=e=>{const t=u(e,"tables");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();if(!n||!i.isObjectLiteralExpression(n))return[];const s=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=I(r);S(a,r.getNameNode()),s.push($(o,a))}return s},Ve=e=>{const t=u(e,"vectorIndexes");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();return!n||!i.isObjectLiteralExpression(n)?[]:D(n)},z=(e,t,n,s,r)=>{Pe(e,s);const o=new Set(t.map(c=>c.name)),a=t.map(c=>$e(c,e,o,r)),l=n.map(c=>({...c,name:k(e,c.name),table:E(c.table,e,o)}));return{tables:a,vectorIndexes:l}},qe=(e,t,n)=>z(e,Be(n),Ve(n),t,t.getSourceFile().getFilePath().includes("/node_modules/")),Je=(e,t)=>{const n=e.getArguments()[0];if(!n)return;const s=Fe(n);if(!s){if(t!==void 0){const o=ne(n,t);if(o){for(const a of o.bareTables)S(a.name,n);return z(o.key,o.bareTables,o.bareVectorIndexes,n,!0)}}console.warn(`@lunora/codegen: skipping \`.extend(${n.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.`);return}const r=Ce(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return qe(r.key,r.keyNode,r.options)},Ue=e=>{const t=[];let n=e;for(;;){const s=n.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&t.push(r),n=r}return t},Ke=(e,t,n)=>{const s=new Set(t.map(o=>o.name)),r=[];for(const o of Ue(e)){const a=Je(o,n);if(a){for(const l of a.tables){if(s.has(l.name))throw d(o,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),t.push(l)}r.push(...a.vectorIndexes)}}return r},We=new Set(["eu","fedramp","us"]),Ze=e=>N(e,"jurisdiction","jurisdiction",We,'"eu", "us", or "fedramp"'),Ge=e=>{let t=e;for(;;){const n=t.getParent(),s=n?.getParent();if(!n||!i.isPropertyAccessExpression(n)||!s||!i.isCallExpression(s))return!1;if(n.getName()==="jurisdiction"){const r=s.getArguments()[1];return r!==void 0&&i.isObjectLiteralExpression(r)&&O(r,"pinAuth")===!0}t=s}},Xe=new Set(["required"]),He=e=>N(e,"rls","rls mode",Xe,'"required"'),ct=(e,t,n)=>{const r=e.addSourceFileAtPath(t).getDescendantsOfKind(F.CallExpression).find(p=>{const T=p.getExpression();return i.isIdentifier(T)&&T.getText()==="defineSchema"});if(!r)throw new R("INTERNAL",`defineSchema() not found in ${t}`);const o=r.getArguments()[0];if(!o||!i.isObjectLiteralExpression(o))throw d(r,"defineSchema() expects an object literal");const a=j(o),l=r.getArguments()[1],c=l&&i.isObjectLiteralExpression(l)?D(l):[],g=Ke(r,a,n),w=[...a.flatMap(p=>p.vectorIndexes),...c,...g],M=new Set(a.filter(p=>p.shardMode==="global").map(p=>p.name)),v=w.find(p=>M.has(p.table));if(v)throw d(r,K(v.table,v.name));return{jurisdiction:Ze(r),...Ge(r)?{jurisdictionPinsAuth:!0}:{},rlsMode:He(r),tables:a,vectorIndexes:w}};export{ct as default};
@@ -1 +1 @@
1
- import{Node as u}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as p,stringPropertyOf as l}from"./isTestPath-DCyIyPa7.mjs";import{w as d}from"./classify-procedure-call-BBKuBvKg.mjs";import{e as m}from"./exported-procedure-chains-DqU-ZCbG.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-CgyyLk8U.mjs";import{w as d}from"./classify-procedure-call-DxuPQkJA.mjs";import{e as m}from"./exported-procedure-chains-C5VKkd9T.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"./ir-DBSvhNa-.mjs";import"./json-data-Chfs2Cz5.mjs";import{o as i,j as r,s as o,h as n,t as g,k as F,d as u,v as p,m as f,g as l,f as d,i as k,u as w,l as Q}from"./shard-runtime-DGrBvQWg.mjs";import"./shared-BXUKWh7t.mjs";export{i as buildDoTypeImports,r as emitAgentFragments,o as emitAgents,n as emitContainerFragments,g as emitContainers,F as emitPaymentFragments,u as emitQueueFragments,p as emitQueues,f as emitQueuesMetadataFragments,l as emitServiceFragments,d as emitTopicFragments,k as emitWorkflowFragments,w as emitWorkflows,Q as emitWorkflowsMetadataFragments};
1
+ import"./ir-DBSvhNa-.mjs";import"./json-data-Chfs2Cz5.mjs";import{o as i,j as r,s as o,h as n,t as g,k as F,d as u,v as p,m as f,g as l,f as d,i as k,u as w,l as Q}from"./shard-runtime-BI2SZ54Z.mjs";import"./shared-Be3TGzxM.mjs";export{i as buildDoTypeImports,r as emitAgentFragments,o as emitAgents,n as emitContainerFragments,g as emitContainers,F as emitPaymentFragments,u as emitQueueFragments,p as emitQueues,f as emitQueuesMetadataFragments,l as emitServiceFragments,d as emitTopicFragments,k as emitWorkflowFragments,w as emitWorkflows,Q as emitWorkflowsMetadataFragments};
@@ -1,8 +1,4 @@
1
- import{agentComponent as T}from"@lunora/agent/component";import{LunoraError as P}from"@lunora/errors";import{s as u}from"./paths-C-9fwEgQ.mjs";import{r as j,a as K,b as h,c as E}from"./qualifiers-Cw8dEDbh.mjs";import{G as w,a as B,r as g,p as $,b as x,c as y,d as v}from"./shared-BXUKWh7t.mjs";const A=t=>{const r=new Map;for(const o of t){const e=r.get(o.filePath)??[];e.push(o),r.set(o.filePath,e)}return[...r.entries()].toSorted(([o],[e])=>o.localeCompare(e))},C=t=>{const r=([o,e])=>{const c=e.toSorted((a,i)=>a.exportName.localeCompare(i.exportName)).map(a=>{const i=h(g(a.args),a.filePath),n=h(E(a),a.filePath);return` ${a.exportName}: FunctionReference<"${a.kind}", ${i}, ${n}>;`}).join(`
2
- `);return` ${x(u(o))}: {
3
- ${c}
4
- };`};return A(t).map(o=>r(o)).join(`
5
- `)},W=(t,r)=>{if(t.length===0&&r.length===0)return{block:"",importLine:""};const o=[];let e="";if(t.length>0&&(e+="\n/** Params type carried by a `defineWorkflow` definition (its phantom `__params`). */\ntype WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params } ? (unknown extends Params ? Record<string, unknown> : Params) : Record<string, unknown>;\n"),e+=`
1
+ import{agentComponent as N}from"@lunora/agent/component";import{LunoraError as w}from"@lunora/errors";import{s as f}from"./paths-DwTjD7BU.mjs";import{r as d,a as R,b as v,c as P}from"./qualifiers-COHdrghK.mjs";import{a as O,r as g,p as $,G as x,b as y,c as b,d as S,e as L}from"./shared-Be3TGzxM.mjs";const j=t=>y(t,e=>{const a=d(g(e.args),e.filePath),n=d(P(e),e.filePath);return`${e.exportName}: FunctionReference<"${e.kind}", ${a}, ${n}>;`},"type"),A=(t,e)=>{if(t.length===0&&e.length===0)return{block:"",importLine:""};const a=[];let n="";if(t.length>0&&(n+="\n/** Params type carried by a `defineWorkflow` definition (its phantom `__params`). */\ntype WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params } ? (unknown extends Params ? Record<string, unknown> : Params) : Record<string, unknown>;\n"),n+=`
6
2
  /** A typed reference to a durable workflow, addressable for \`cronJobs()\` targets. Mirrors \`@lunora/scheduler\`'s \`WorkflowReference\` structurally. */
7
3
  export interface WorkflowReference<Params = Record<string, unknown>> {
8
4
  readonly isLunoraWorkflow: true;
@@ -10,32 +6,32 @@ export interface WorkflowReference<Params = Record<string, unknown>> {
10
6
  readonly className: string;
11
7
  readonly name: string;
12
8
  }
13
- `,t.length>0){const c=[...t].toSorted((n,s)=>n.exportName.localeCompare(s.exportName)),a=c.map(n=>` ${n.exportName}: WorkflowReference<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${n.exportName}>>;`).join(`
14
- `),i=c.map(n=>` ${y(n.exportName)}: { isLunoraWorkflow: true, className: ${JSON.stringify(n.className)}, name: ${JSON.stringify(n.exportName)} },`).join(`
15
- `);e+=`
9
+ `,t.length>0){const i=[...t].toSorted((o,s)=>o.exportName.localeCompare(s.exportName)),r=i.map(o=>` ${o.exportName}: WorkflowReference<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${o.exportName}>>;`).join(`
10
+ `),l=i.map(o=>` ${b(o.exportName)}: { isLunoraWorkflow: true, className: ${JSON.stringify(o.className)}, name: ${JSON.stringify(o.exportName)} },`).join(`
11
+ `);n+=`
16
12
  /** This project's durable workflows, addressable as typed references (e.g. \`crons.daily("digest", …, workflows.digestPipeline, params)\`). */
17
13
  export interface WorkflowsRef {
18
- ${a}
14
+ ${r}
19
15
  }
20
16
 
21
17
  export const workflows: WorkflowsRef = {
22
- ${i}
18
+ ${l}
23
19
  };
24
- `,o.push(`import type * as lunoraWorkflowDefinitions from "../workflows.js";
25
- `)}if(r.length>0){const c=[...r].toSorted((n,s)=>n.exportName.localeCompare(s.exportName)),a=c.map(n=>` ${n.exportName}: WorkflowReference<AgentRunInput>;`).join(`
26
- `),i=c.map(n=>` ${y(n.exportName)}: { isLunoraWorkflow: true, className: ${JSON.stringify(n.className)}, name: ${JSON.stringify(n.name)} },`).join(`
27
- `);e+=`
20
+ `,a.push(`import type * as lunoraWorkflowDefinitions from "../workflows.js";
21
+ `)}if(e.length>0){const i=[...e].toSorted((o,s)=>o.exportName.localeCompare(s.exportName)),r=i.map(o=>` ${o.exportName}: WorkflowReference<AgentRunInput>;`).join(`
22
+ `),l=i.map(o=>` ${b(o.exportName)}: { isLunoraWorkflow: true, className: ${JSON.stringify(o.className)}, name: ${JSON.stringify(o.name)} },`).join(`
23
+ `);n+=`
28
24
  /** This project's durable agents, addressable as typed references for \`cronJobs()\` — each fire starts a fresh agent run (e.g. \`crons.daily("sweep", …, agents.support, { input, threadKey })\`). */
29
25
  export interface AgentsRef {
30
- ${a}
26
+ ${r}
31
27
  }
32
28
 
33
29
  export const agents: AgentsRef = {
34
- ${i}
30
+ ${l}
35
31
  };
36
- `,o.push(`import type { AgentRunInput } from "@lunora/agent";
37
- `)}return{block:e,importLine:o.join("")}},D=()=>Object.keys(T().functions).toSorted((t,r)=>t.localeCompare(r)),O=t=>new Set(t.filter(r=>u(r.filePath)==="agents").map(r=>r.exportName)),J=()=>new Set(Object.entries(T().functions).filter(([,t])=>t.visibility==="internal").map(([t])=>t)),X=(t,r)=>{const o={importLine:"",lines:"",prelude:""};if(t.length===0)return o;const e=O(r),c=J(),a=r.find(n=>u(n.filePath)==="agents"&&c.has(n.exportName));if(a)throw new P("INTERNAL",`@lunora/codegen: "agents:${a.exportName}" is reserved for the durable agent loop's internal dispatch — rename the "${a.exportName}" export in ${a.filePath}`);const i=D().filter(n=>!e.has(n));return i.length===0?o:{importLine:`import { agentComponent } from "@lunora/agent/component";
38
- `,lines:i.map(n=>` "agents:${n}": lunoraAgentRuntimeFunctions.${n} as unknown as RegisteredLunoraFunction,`).join(`
32
+ `,a.push(`import type { AgentRunInput } from "@lunora/agent";
33
+ `)}return{block:n,importLine:a.join("")}},I=()=>Object.keys(N().functions).toSorted((t,e)=>t.localeCompare(e)),C=t=>new Set(t.filter(e=>f(e.filePath)==="agents").map(e=>e.exportName)),M=()=>new Set(Object.entries(N().functions).filter(([,t])=>t.visibility==="internal").map(([t])=>t)),q=(t,e)=>{const a={importLine:"",lines:"",prelude:""};if(t.length===0)return a;const n=C(e),i=M(),r=e.find(o=>f(o.filePath)==="agents"&&i.has(o.exportName));if(r)throw new w("INTERNAL",`@lunora/codegen: "agents:${r.exportName}" is reserved for the durable agent loop's internal dispatch — rename the "${r.exportName}" export in ${r.filePath}`);const l=I().filter(o=>!n.has(o));return l.length===0?a:{importLine:`import { agentComponent } from "@lunora/agent/component";
34
+ `,lines:l.map(o=>` "agents:${o}": lunoraAgentRuntimeFunctions.${o} as unknown as RegisteredLunoraFunction,`).join(`
39
35
  `),prelude:`
40
36
  /**
41
37
  * The \`@lunora/agent\` runtime component — auto-registered because \`lunora/agents.ts\`
@@ -43,44 +39,29 @@ ${i}
43
39
  * subscribe to the public queries (\`agents:agentMessages\` is the live thread view).
44
40
  */
45
41
  const lunoraAgentRuntimeFunctions = agentComponent().functions;
46
- `}},Y=(t,r)=>{if(!t)return{importLine:"",lines:"",prelude:""};const o=r.find(e=>u(e.filePath)==="sandbox"&&e.exportName==="invoke");if(o)throw new P("INTERNAL",`@lunora/codegen: "sandbox:invoke" is reserved for the batteries-included sandbox tool dispatcher (browserTool/containerTool) — rename the "invoke" export in ${o.filePath}`);return{importLine:`import { sandboxComponent } from "@lunora/agent/component";
47
- `,lines:' "sandbox:invoke": lunoraSandbox.invoke as unknown as RegisteredLunoraFunction,',prelude:"\n/**\n * The `@lunora/agent` sandbox dispatcher — auto-registered because `lunora/`\n * imports a sandbox tool (`browserTool`/`containerTool`). The batteries-included\n * tools dispatch to this internal action, which runs on an action ctx carrying\n * `ctx.browser` + `ctx.containers` (the durable tool step itself has neither).\n */\nconst lunoraSandbox = sandboxComponent();\n"}},H=(t,r)=>{if(t.length===0)return[];const o=O(r),e=[{args:{key:{kind:"string"},limit:{inner:{kind:"number"},kind:"optional"}},exportName:"agentMessages",filePath:"agents",kind:"query",returnType:"Record<string, unknown>[]"},{args:{decision:{kind:"union",members:[{kind:"literal",literalValue:'"approve"'},{kind:"literal",literalValue:'"reject"'}]},instanceId:{kind:"string"},note:{inner:{kind:"string"},kind:"optional"},threadKey:{kind:"string"},toolCallId:{kind:"string"}},exportName:"agentResolveApproval",filePath:"agents",kind:"mutation",returnType:"{ resolved: boolean }"},{args:{agent:{kind:"string"},input:{kind:"string"},threadKey:{kind:"string"},title:{inner:{kind:"string"},kind:"optional"}},exportName:"agentRun",filePath:"agents",kind:"mutation",returnType:"{ id: string; threadKey: string }"},{args:{key:{kind:"string"}},exportName:"agentState",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"},{args:{key:{kind:"string"}},exportName:"agentThread",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"}];for(const c of t)c.voice&&e.push({args:{threadKey:{kind:"string"}},exportName:`${c.exportName}Voice`,filePath:"agents",kind:"stream",returnType:"Record<string, unknown>"});return e.filter(c=>!o.has(c.exportName))},_=(t,r)=>{if(t.length===0)return[];const o=new Set(r.filter(e=>u(e.filePath)==="mutators").map(e=>e.exportName));return t.filter(e=>!o.has(e.exportName)).map(e=>({args:e.args,exportName:e.exportName,filePath:e.filePath,kind:"mutation",returnType:e.returnType}))},q=t=>{const r=t.filter(i=>i.stream);if(r.length===0)return{block:"",body:""};const o=A(r),e=o.map(([i,n])=>{const s=n.map(l=>{const p=h(l.chunkType??"unknown",l.filePath),d=h(g(l.searchParams),l.filePath),m=h(g(l.params),l.filePath);return` ${x(l.exportName)}: HttpStreamRef<${p}, ${d}, ${m}>;`}).join(`
48
- `);return` ${x(u(i))}: {
49
- ${s}
50
- };`}).join(`
51
- `),c=o.map(([i,n])=>{const s=n.map(l=>` ${y(l.exportName)}: { method: ${JSON.stringify(l.method)}, path: ${JSON.stringify(l.path)} },`).join(`
52
- `);return` ${y(u(i))}: {
53
- ${s}
54
- },`}).join(`
55
- `);return{block:`
42
+ `}},U=(t,e)=>{if(!t)return{importLine:"",lines:"",prelude:""};const a=e.find(n=>f(n.filePath)==="sandbox"&&n.exportName==="invoke");if(a)throw new w("INTERNAL",`@lunora/codegen: "sandbox:invoke" is reserved for the batteries-included sandbox tool dispatcher (browserTool/containerTool) — rename the "invoke" export in ${a.filePath}`);return{importLine:`import { sandboxComponent } from "@lunora/agent/component";
43
+ `,lines:' "sandbox:invoke": lunoraSandbox.invoke as unknown as RegisteredLunoraFunction,',prelude:"\n/**\n * The `@lunora/agent` sandbox dispatcher — auto-registered because `lunora/`\n * imports a sandbox tool (`browserTool`/`containerTool`). The batteries-included\n * tools dispatch to this internal action, which runs on an action ctx carrying\n * `ctx.browser` + `ctx.containers` (the durable tool step itself has neither).\n */\nconst lunoraSandbox = sandboxComponent();\n"}},K=(t,e)=>{if(t.length===0)return[];const a=C(e),n=[{args:{key:{kind:"string"},limit:{inner:{kind:"number"},kind:"optional"}},exportName:"agentMessages",filePath:"agents",kind:"query",returnType:"Record<string, unknown>[]"},{args:{decision:{kind:"union",members:[{kind:"literal",literalValue:'"approve"'},{kind:"literal",literalValue:'"reject"'}]},instanceId:{kind:"string"},note:{inner:{kind:"string"},kind:"optional"},threadKey:{kind:"string"},toolCallId:{kind:"string"}},exportName:"agentResolveApproval",filePath:"agents",kind:"mutation",returnType:"{ resolved: boolean }"},{args:{agent:{kind:"string"},input:{kind:"string"},threadKey:{kind:"string"},title:{inner:{kind:"string"},kind:"optional"}},exportName:"agentRun",filePath:"agents",kind:"mutation",returnType:"{ id: string; threadKey: string }"},{args:{key:{kind:"string"}},exportName:"agentState",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"},{args:{key:{kind:"string"}},exportName:"agentThread",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"}];for(const i of t)i.voice&&n.push({args:{threadKey:{kind:"string"}},exportName:`${i.exportName}Voice`,filePath:"agents",kind:"stream",returnType:"Record<string, unknown>"});return n.filter(i=>!a.has(i.exportName))},E=(t,e)=>{if(t.length===0)return[];const a=new Set(e.filter(n=>f(n.filePath)==="mutators").map(n=>n.exportName));return t.filter(n=>!a.has(n.exportName)).map(n=>({args:n.args,exportName:n.exportName,filePath:n.filePath,kind:"mutation",returnType:n.returnType}))},F=t=>{const e=t.filter(r=>r.stream);if(e.length===0)return{block:"",body:""};const a=y(e,r=>{const l=d(r.chunkType??"unknown",r.filePath),o=d(g(r.searchParams),r.filePath),s=d(g(r.params),r.filePath);return`${L(r.exportName)}: HttpStreamRef<${l}, ${o}, ${s}>;`},"type"),n=y(e,r=>`${b(r.exportName)}: { method: ${JSON.stringify(r.method)}, path: ${JSON.stringify(r.path)} },`,"value");return{block:`
56
44
  /** This project's HTTP-SSE stream routes (\`httpRoute.<verb>(path).stream()\`), addressable as typed references for \`client.httpStream\` / \`useHttpStream\`. */
57
45
  export interface HttpStreamsRef {
58
- ${e}
46
+ ${a}
59
47
  }
60
48
 
61
49
  export const httpStreams: HttpStreamsRef = {
62
- ${c}
50
+ ${n}
63
51
  };
64
- `,body:e}},Z=t=>{const{agents:r=[],functions:o,httpRoutes:e=[],mutators:c=[],useUmbrella:a=!1,workflows:i=[]}=t,n=v(a),s=[...o.filter(k=>k.visibility!=="internal"),...H(r,o),..._(c,o)],l=o.filter(k=>k.visibility==="internal"),p=C(s),d=C(l),m=q(e),b=`${p}
65
- ${d}
66
- ${m.body}`,f=j(b),L=f.length>0?`
67
- import type { ${f.join(", ")} } from "./dataModel.js";
68
- `:"",I=p?`
69
- ${p}
70
- `:"",M=d?`
71
- ${d}
72
- `:"",N=W(i,r),R=`export interface ApiTypes {${I}}
73
-
74
- export const api = anyApi as unknown as ApiTypes;
75
-
76
- /** Internal functions — callable only server-side via \`ctx.run*\`, never from a client. */
77
- export interface InternalApiTypes {${M}}
52
+ `,body:a}},W=t=>y(t,e=>`${b(e.exportName)}: { __lunoraRef: ${JSON.stringify(`${f(e.filePath)}:${e.exportName}`)} },`,"value"),T=t=>{const{block:e="",constName:a,docComment:n="",functions:i,importLine:r="",typeName:l,typesBody:o="",useUmbrella:s}=t,c=j(i),p=W(i),m=R(`${c}
53
+ ${o}`),k=m.length>0?`
54
+ import type { ${m.join(", ")} } from "./dataModel.js";
55
+ `:"",h=[...c===""?[]:["FunctionReference"],...t.clientImports??[]],u=h.length>0?`import type { ${h.join(", ")} } from "${S(s).client}";
56
+ `:"";return v(`${x}${u}${r}${k}
57
+ ${n}export interface ${l} {${c?`
58
+ ${c}
59
+ `:""}}
78
60
 
79
- export const internal = anyApi as unknown as InternalApiTypes;
80
- ${N.block}${m.block}`,S=[...R.includes("FunctionReference<")?["FunctionReference"]:[],...m.block===""?[]:["HttpStreamRef"]],F=S.length>0?`import type { ${S.join(", ")} } from "${n.client}";
81
- `:"";return K(`${w}import { anyApi } from "${n.client}";
82
- ${F}${N.importLine}${L}
83
- ${R}`,a)},ee=t=>t?`${w}import { createSeedClient as createSeedClientBase } from "@lunora/seed";
61
+ export const ${a}: ${l} = {${p?`
62
+ ${p}
63
+ `:""}};
64
+ ${e}`,s)},V=t=>{const{agents:e=[],functions:a,httpRoutes:n=[],mutators:i=[],useUmbrella:r=!1,workflows:l=[]}=t,o=F(n),s=A(l,e);return T({block:`${s.block}${o.block}`,clientImports:o.block===""?[]:["HttpStreamRef"],constName:"api",functions:[...a.filter(c=>c.visibility!=="internal"),...K(e,a),...E(i,a)],importLine:s.importLine,typeName:"ApiTypes",typesBody:o.body,useUmbrella:r})},z=t=>T({constName:"internal",docComment:"/** Internal functions — callable only server-side via `ctx.run*`, never from a client. */\n",functions:t.functions.filter(e=>e.visibility==="internal"),typeName:"InternalApiTypes",useUmbrella:t.useUmbrella??!1}),G=t=>t?`${x}import { createSeedClient as createSeedClientBase } from "@lunora/seed";
84
65
  import type { SeedClient, SeedClientOptions } from "@lunora/seed";
85
66
 
86
67
  import schema from "../schema.js";
@@ -97,9 +78,9 @@ import type { InsertModel } from "./dataModel.js";
97
78
  * const { posts } = await seed.posts((x) => x([10, 20]));
98
79
  */
99
80
  export const createSeedClient = (options?: SeedClientOptions): SeedClient<InsertModel> => createSeedClientBase<InsertModel>(schema, options);
100
- `:"",te=(t,r,o=!1)=>{if(t.length===0||!r)return"";const e=v(o),c=s=>s.table===void 0?"Row":`Doc<${JSON.stringify(s.table)}> & Row`,a=t.map(s=>{B(s.exportName,"shape export name");const l=c(s),p=h(g(s.args),s.filePath),d=Object.keys(s.args).length>0,m=d?` args: ${p};`:` args?: ${p};`,b=d?`(args: ${p}) => void`:`(args?: ${p}) => void`,f=`${s.exportName}CollectionOptions`;return`/** Options for the \`${s.exportName}\` shape binding. */
101
- export interface ${$(f)} {
102
- ${m}
81
+ `:"",Q=(t,e,a=!1)=>{if(t.length===0||!e)return"";const n=S(a),i=s=>s.table===void 0?"Row":`Doc<${JSON.stringify(s.table)}> & Row`,r=t.map(s=>{O(s.exportName,"shape export name");const c=i(s),p=d(g(s.args),s.filePath),m=Object.keys(s.args).length>0,k=m?` args: ${p};`:` args?: ${p};`,h=m?`(args: ${p}) => void`:`(args?: ${p}) => void`,u=`${s.exportName}CollectionOptions`;return`/** Options for the \`${s.exportName}\` shape binding. */
82
+ export interface ${$(u)} {
83
+ ${k}
103
84
  /**
104
85
  * Share the optimistic-overlay gate with other collections + mutators on this
105
86
  * shard. Defaults to the shared per-shard registry, which is almost always what
@@ -109,7 +90,7 @@ ${m}
109
90
  /** The Lunora client to subscribe through. */
110
91
  client: LunoraClient;
111
92
  /** Row key extractor — defaults to \`row._id\`. Override when the app keys rows by a natural column. */
112
- getKey?: (row: ${l}) => string;
93
+ getKey?: (row: ${c}) => string;
113
94
  /** \`"eager"\` starts syncing at creation; \`"lazy"\` (default) on the first subscriber. */
114
95
  load?: "eager" | "lazy";
115
96
  /** Notified when the underlying subscription errors; the collection always leaves \`loading\`. */
@@ -123,8 +104,8 @@ ${m}
123
104
  * \`createCollection\`, plus the \`checkpoints\` registry to hand \`bindMutators\` and
124
105
  * \`scope\` to re-point the subscription.
125
106
  */
126
- export const ${s.exportName}CollectionOptions = (options: ${$(f)}): LunoraCollectionOptions<${l}> =>
127
- lunoraCollectionOptions<${l}>({
107
+ export const ${s.exportName}CollectionOptions = (options: ${$(u)}): LunoraCollectionOptions<${c}> =>
108
+ lunoraCollectionOptions<${c}>({
128
109
  client: options.client,
129
110
  ...(options.checkpoints === undefined ? {} : { checkpoints: options.checkpoints }),
130
111
  ...(options.getKey === undefined ? {} : { getKey: options.getKey }),
@@ -136,19 +117,19 @@ export const ${s.exportName}CollectionOptions = (options: ${$(f)}): LunoraCollec
136
117
 
137
118
  /** Live collection for the \`${s.exportName}\` shape, with its sync controls. */
138
119
  export const ${s.exportName}Collection = (
139
- options: ${$(f)},
140
- ): { checkpoints: CheckpointRegistry; collection: Collection<${l}, string>; scope: ${b} } => {
120
+ options: ${$(u)},
121
+ ): { checkpoints: CheckpointRegistry; collection: Collection<${c}, string>; scope: ${h} } => {
141
122
  const { checkpoints, config, scope } = ${s.exportName}CollectionOptions(options);
142
123
 
143
124
  return { checkpoints, collection: createCollection(config), scope };
144
125
  };`}).join(`
145
126
 
146
- `),i=j(a),n=i.length>0?`import type { ${i.join(", ")} } from "./dataModel.js";
147
- `:"";return`${w}import type { LunoraClient, SubscriptionError } from "${e.client}";
127
+ `),l=R(r),o=l.length>0?`import type { ${l.join(", ")} } from "./dataModel.js";
128
+ `:"";return`${x}import type { LunoraClient, SubscriptionError } from "${n.client}";
148
129
  import { lunoraCollectionOptions } from "@lunora/db/collections";
149
130
  import type { CheckpointRegistry, LunoraCollectionOptions, Row } from "@lunora/db";
150
131
  import type { Collection } from "@tanstack/db";
151
132
  import { createCollection } from "@tanstack/db";
152
- ${n}
153
- ${a}
154
- `};export{Z as emitApi,te as emitCollections,ee as emitSeed,A as groupByFileSorted,X as renderAgentFunctionRegistry,Y as renderSandboxFunctionRegistry};
133
+ ${o}
134
+ ${r}
135
+ `};export{V as emitApi,Q as emitCollections,z as emitInternalApi,G as emitSeed,q as renderAgentFunctionRegistry,U as renderSandboxFunctionRegistry};
@@ -1,4 +1,4 @@
1
- import{APP_METHOD_CAPABILITIES as k}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{i as S}from"./ir-DBSvhNa-.mjs";import{G as E}from"./shared-BXUKWh7t.mjs";const D={configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},g=e=>[...k.filter(({key:r})=>e.capabilities.has(r)).map(({appMethod:r})=>r),...e.hasVectors?[D]:[]],m=e=>g(e).length>0,v=e=>(e.emailAgents?.length??0)>0,d=e=>e.tables.some(r=>S(r)),R=e=>e.hasScheduler?`
1
+ import{APP_METHOD_CAPABILITIES as k}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{i as S}from"./ir-DBSvhNa-.mjs";import{G as E}from"./shared-Be3TGzxM.mjs";const D={configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},g=e=>[...k.filter(({key:r})=>e.capabilities.has(r)).map(({appMethod:r})=>r),...e.hasVectors?[D]:[]],m=e=>g(e).length>0,v=e=>(e.emailAgents?.length??0)>0,d=e=>e.tables.some(r=>S(r)),R=e=>e.hasScheduler?`
2
2
  /** Resolve the \`SchedulerDO\`-backed scheduler for this env; \`undefined\` until the namespace is wired. */
3
3
  private resolveScheduler(env: Env): ReturnType<typeof createScheduler> | undefined {
4
4
  const namespace = this.schedulerDeclaration?.namespace(env);
@@ -1,4 +1,4 @@
1
- import{i as m}from"./ir-DBSvhNa-.mjs";import{G as i,d as c}from"./shared-BXUKWh7t.mjs";const u=r=>r?`${i}/**
1
+ import{i as m}from"./ir-DBSvhNa-.mjs";import{G as i,d as c}from"./shared-Be3TGzxM.mjs";const u=r=>r?`${i}/**
2
2
  * The \`SchedulerDO\` Durable Object class, re-exported so a worker entry can
3
3
  * forward it — wrangler binds only what the entry exports:
4
4
  *
@@ -1,4 +1,4 @@
1
- import{b as k}from"./qualifiers-Cw8dEDbh.mjs";import{a as s,b as i,v as d,e as v,G as M}from"./shared-BXUKWh7t.mjs";const D="schema",w=a=>{for(const e of a.tables)s(e.name,"table name");const l=a.tables.map(e=>`"${e.name}"`).join(" | ")||"never",m=a.tables.filter(e=>e.extensionKey===void 0).map(e=>`"${e.name}"`).join(" | ")||"never",p=a.tables.map(e=>{const t=Object.entries(e.shape).map(([h,r])=>{const o=i(h);if(r.kind==="optional"){const g=r.inner?d(r.inner):"unknown";return` ${o}?: ${g};`}return` ${o}: ${d(r)};`}).join(`
1
+ import{r as k}from"./qualifiers-COHdrghK.mjs";import{a as s,e as i,v as d,f as v,G as M}from"./shared-Be3TGzxM.mjs";const D="schema",w=a=>{for(const e of a.tables)s(e.name,"table name");const l=a.tables.map(e=>`"${e.name}"`).join(" | ")||"never",m=a.tables.filter(e=>e.extensionKey===void 0).map(e=>`"${e.name}"`).join(" | ")||"never",p=a.tables.map(e=>{const t=Object.entries(e.shape).map(([h,r])=>{const o=i(h);if(r.kind==="optional"){const g=r.inner?d(r.inner):"unknown";return` ${o}?: ${g};`}return` ${o}: ${d(r)};`}).join(`
2
2
  `),n=t?`
3
3
  ${t}
4
4
  `:"",N=e.commitOrdered===!0?`
@@ -10,8 +10,8 @@ ${t}
10
10
  `),y=a.tables.map(e=>{const t=e.indexes.map(n=>JSON.stringify(n.name)).join(" | ");return` ${e.name}: ${t||"never"};`}).join(`
11
11
  `),x=a.tables.map(e=>{const t=e.searchIndexes.map(n=>JSON.stringify(n.name)).join(" | ");return` ${e.name}: ${t||"never"};`}).join(`
12
12
  `),b=a.tables.map(e=>{const t=e.rankIndexes.map(n=>JSON.stringify(n.name)).join(" | ");return` ${e.name}: ${t||"never"};`}).join(`
13
- `),T=a.tables.map(e=>{const t=e.shardMode==="global"?"":(e.geoIndexes??[]).map(n=>JSON.stringify(n.name)).join(" | ");return` ${e.name}: ${t||"never"};`}).join(`
14
- `),f=a.vectorIndexes.map(e=>JSON.stringify(e.name)).join(" | ")||"never",$=a.tables.map(e=>v(e)).join(`
13
+ `),f=a.tables.map(e=>{const t=e.shardMode==="global"?"":(e.geoIndexes??[]).map(n=>JSON.stringify(n.name)).join(" | ");return` ${e.name}: ${t||"never"};`}).join(`
14
+ `),T=a.vectorIndexes.map(e=>JSON.stringify(e.name)).join(" | ")||"never",$=a.tables.map(e=>v(e)).join(`
15
15
 
16
16
  `),u=a.tables.map(e=>` ${e.name}: Insert_${e.name};`).join(`
17
17
  `),I=a.tables.map(e=>{const t=e.relations.map(n=>(s(n.table,"relation target table"),` ${i(n.name)}: ${n.kind==="one"?"OneRelation":"ManyRelation"}<"${n.table}">;`)).join(`
@@ -73,13 +73,13 @@ export type RankIndexName<T extends keyof DataModel> = RankIndexNamesByTable[T];
73
73
 
74
74
  /** Per-table geo-index name union. \`never\` for tables without a geoIndex. */
75
75
  export interface GeoIndexNamesByTable {
76
- ${T}
76
+ ${f}
77
77
  }
78
78
 
79
79
  export type GeoIndexName<T extends keyof DataModel> = GeoIndexNamesByTable[T];
80
80
 
81
81
  /** Union of declared vector index names. \`never\` when none are declared. */
82
- export type VectorIndexName = ${f};
82
+ export type VectorIndexName = ${T};
83
83
 
84
84
  ${$}
85
85
 
@@ -1,11 +1,11 @@
1
- import{SCHEMA_MODULE_PATH as c}from"./emitDataModel-DSk9AkJe.mjs";import{b as m}from"./qualifiers-Cw8dEDbh.mjs";import{G as b,a as g,d as T,v as f,u as A,f as x,c as h}from"./shared-BXUKWh7t.mjs";const d=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:f(e)};case"bigint":return{builder:"blob",mode:"bigint",notNull:!0};case"boolean":return{builder:"integer",mode:"boolean",notNull:!0};case"bytes":return{builder:"blob",mode:"buffer",notNull:!0};case"date":case"timestamp":return{builder:"integer",notNull:!0};case"from":return{builder:"text",notNull:!0,typeAnnotation:f(e)};case"id":return{builder:"text",notNull:!0};case"literal":{const t=e.literalValue??"";return t.startsWith('"')||t.startsWith("'")?{builder:"text",notNull:!0}:t==="true"||t==="false"?{builder:"integer",mode:"boolean",notNull:!0}:t==="null"?{builder:"text",notNull:!0}:{builder:"real",notNull:!0}}case"null":return{builder:"text",notNull:!0};case"number":return{builder:"real",notNull:!0};case"optional":return{...e.inner?d(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},N=(e,t)=>{const r=A(e);return r.kind==="id"&&r.tableName!==void 0&&t.has(r.tableName)?r.tableName:void 0},j=(e,t,r)=>{x(e,"drizzle column name");const n=d(t),o=n.mode?`, { mode: "${n.mode}" }`:"";let l=`${n.builder}("${e}"${o})`;n.typeAnnotation&&(l+=`.$type<${n.typeAnnotation}>()`);const s=N(t,r);return s!==void 0&&(l+=`.references((): AnySQLiteColumn => ${s}._id)`),n.notNull&&t.column?.notNull!==!1&&(l+=".notNull()"),l},I=e=>{const t=e.unique?"uniqueIndex":"index",r=e.fields.map(n=>(x(n,"drizzle index field"),`t.${n}`)).join(", ");return` ${h(e.name)}: ${t}(${JSON.stringify(e.name)}).on(${r}),`},S=(e,t)=>{g(e.name,"table name");const r=[' _id: text("_id").primaryKey(),',' _creationTime: integer("_creationTime").notNull(),',...Object.entries(e.shape).map(([o,l])=>` ${o}: ${j(o,l,t)},`)].join(`
1
+ import{SCHEMA_MODULE_PATH as c}from"./emitDataModel-B68T_eX6.mjs";import{r as m}from"./qualifiers-COHdrghK.mjs";import{G as b,a as z,d as T,v as f,u as A,g as x,c as h}from"./shared-Be3TGzxM.mjs";const d=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:f(e)};case"bigint":return{builder:"blob",mode:"bigint",notNull:!0};case"boolean":return{builder:"integer",mode:"boolean",notNull:!0};case"bytes":return{builder:"blob",mode:"buffer",notNull:!0};case"date":case"timestamp":return{builder:"integer",notNull:!0};case"from":return{builder:"text",notNull:!0,typeAnnotation:f(e)};case"id":return{builder:"text",notNull:!0};case"literal":{const t=e.literalValue??"";return t.startsWith('"')||t.startsWith("'")?{builder:"text",notNull:!0}:t==="true"||t==="false"?{builder:"integer",mode:"boolean",notNull:!0}:t==="null"?{builder:"text",notNull:!0}:{builder:"real",notNull:!0}}case"null":return{builder:"text",notNull:!0};case"number":return{builder:"real",notNull:!0};case"optional":return{...e.inner?d(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},N=(e,t)=>{const r=A(e);return r.kind==="id"&&r.tableName!==void 0&&t.has(r.tableName)?r.tableName:void 0},j=(e,t,r)=>{x(e,"drizzle column name");const n=d(t),o=n.mode?`, { mode: "${n.mode}" }`:"";let l=`${n.builder}("${e}"${o})`;n.typeAnnotation&&(l+=`.$type<${n.typeAnnotation}>()`);const s=N(t,r);return s!==void 0&&(l+=`.references((): AnySQLiteColumn => ${s}._id)`),n.notNull&&t.column?.notNull!==!1&&(l+=".notNull()"),l},I=e=>{const t=e.unique?"uniqueIndex":"index",r=e.fields.map(n=>(x(n,"drizzle index field"),`t.${n}`)).join(", ");return` ${h(e.name)}: ${t}(${JSON.stringify(e.name)}).on(${r}),`},S=(e,t)=>{z(e.name,"table name");const r=[' _id: text("_id").primaryKey(),',' _creationTime: integer("_creationTime").notNull(),',...Object.entries(e.shape).map(([o,l])=>` ${o}: ${j(o,l,t)},`)].join(`
2
2
  `),n=e.indexes.length>0?`, (t) => ({
3
3
  ${e.indexes.map(o=>I(o)).join(`
4
4
  `)}
5
5
  })`:"";return`export const ${e.name} = sqliteTable("${e.name}", {
6
6
  ${r}
7
7
  }${n});`},C=e=>e.typeAnnotation?.includes('Id<"')??!1,D=(e,t)=>{const r=new Set(["integer","sqliteTable","text"]),n=new Set;let o=!1,l=!1;for(const s of e){for(const i of Object.values(s.shape)){const a=d(i);r.add(a.builder),l=l||C(a),o=o||N(i,t)!==void 0}for(const i of s.indexes)n.add(i.unique?"uniqueIndex":"index")}return{columns:[...r].toSorted((s,i)=>s.localeCompare(i)),indexes:[...n].toSorted((s,i)=>s.localeCompare(i)),needsAnyColumn:o,needsId:l}},p=(e,t=!1)=>{if(e.length===0)return`${b}export {};
8
- `;const r=T(t),n=new Set(e.map(u=>u.name)),{columns:o,indexes:l,needsAnyColumn:s,needsId:i}=D(e,n),a=[...l,...o].toSorted((u,z)=>u.localeCompare(z)),$=e.map(u=>S(u,n)).join(`
8
+ `;const r=T(t),n=new Set(e.map(u=>u.name)),{columns:o,indexes:l,needsAnyColumn:s,needsId:i}=D(e,n),a=[...l,...o].toSorted((u,g)=>u.localeCompare(g)),$=e.map(u=>S(u,n)).join(`
9
9
 
10
10
  `),y=[s?`import type { AnySQLiteColumn } from "${r.serverDrizzle}";
11
11
  `:"",i?`import type { Id } from "./dataModel.js";