@lunora/codegen 1.0.0-alpha.41 → 1.0.0-alpha.410

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 (130) hide show
  1. package/LICENSE.md +201 -104
  2. package/README.md +4 -4
  3. package/dist/index.d.mts +4513 -2048
  4. package/dist/index.d.ts +4513 -2048
  5. package/dist/index.mjs +1 -35
  6. package/dist/packem_shared/AGENTS_FILENAME-D0Y0_UgB.mjs +1 -0
  7. package/dist/packem_shared/ALL_NOTIFY_CHANNELS-D1LVGz6_.mjs +1 -0
  8. package/dist/packem_shared/CAPABILITY_PROBES-BuNEmlCO.mjs +25 -0
  9. package/dist/packem_shared/COMPANION_BINDING-Da_v9XpC.mjs +1 -0
  10. package/dist/packem_shared/CONTAINERS_FILENAME-J-e3Vanb.mjs +1 -0
  11. package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
  12. package/dist/packem_shared/DEFAULT_TARGET-CVYzxQ0y.mjs +1 -0
  13. package/dist/packem_shared/ENV_FILENAME-COPIfgzp.mjs +1 -0
  14. package/dist/packem_shared/FLAGS_FILENAME-6RzszxVW.mjs +1 -0
  15. package/dist/packem_shared/GENERATED_HEADER-DgrhC3Iv.mjs +1 -0
  16. package/dist/packem_shared/LUNORA_ERROR_CODES-D7AVT7qF.mjs +1 -0
  17. package/dist/packem_shared/MUTATORS_FILENAME-C3OImAxC.mjs +1 -0
  18. package/dist/packem_shared/OPENRPC_VERSION-UNYmA7Ty.mjs +3 -0
  19. package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs +1 -0
  20. package/dist/packem_shared/QUEUES_FILENAME-Ba-sK5Ek.mjs +1 -0
  21. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-CbyXHjvE.mjs +54 -0
  22. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs +2 -0
  23. package/dist/packem_shared/SHAPES_FILENAME-BYnZ1Xw-.mjs +1 -0
  24. package/dist/packem_shared/SchemaSnapshotParseError-CV7mmuPi.mjs +17 -0
  25. package/dist/packem_shared/WORKFLOWS_FILENAME-DfVfBum_.mjs +1 -0
  26. package/dist/packem_shared/attribution-BhGR_h0Z.mjs +1 -0
  27. package/dist/packem_shared/buildOpenApiDocument-B8KEeeRr.mjs +3 -0
  28. package/dist/packem_shared/capabilitiesUsedBy-BwhaHK08.mjs +1 -0
  29. package/dist/packem_shared/chain-CONXUmWW.mjs +1 -0
  30. package/dist/packem_shared/classify-procedure-call-n9urVsqb.mjs +1 -0
  31. package/dist/packem_shared/companionServiceBinding-BZjm486n.mjs +1 -0
  32. package/dist/packem_shared/context-property-calls-DXzNVV1P.mjs +1 -0
  33. package/dist/packem_shared/context-root-DP9WbBI_.mjs +1 -0
  34. package/dist/packem_shared/createCodegenProject-Cfr1xHPC.mjs +1 -0
  35. package/dist/packem_shared/database-calls-Do0YbPCL.mjs +1 -0
  36. package/dist/packem_shared/declared-output-Iaar469J.mjs +1 -0
  37. package/dist/packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs +1 -0
  38. package/dist/packem_shared/discoverAuthApiCalls-ENLGem4M.mjs +1 -0
  39. package/dist/packem_shared/discoverCrons-DWVXmktw.mjs +1 -0
  40. package/dist/packem_shared/discoverFunctions-CeHY4_ii.mjs +1 -0
  41. package/dist/packem_shared/discoverHttpRoutes-CAoEemno.mjs +1 -0
  42. package/dist/packem_shared/discoverHyperdriveCalls-W96s1VgA.mjs +1 -0
  43. package/dist/packem_shared/discoverInserts-BtyJbg8A.mjs +1 -0
  44. package/dist/packem_shared/discoverMaskProcedures-BFm9rkZ7.mjs +1 -0
  45. package/dist/packem_shared/discoverMigrations-Duh6HVG3.mjs +1 -0
  46. package/dist/packem_shared/discoverNondeterministicCalls-DR0S5Xb4.mjs +1 -0
  47. package/dist/packem_shared/discoverQueries-BLyL2qzX.mjs +1 -0
  48. package/dist/packem_shared/discoverR2sqlCalls-Cb4AmcY8.mjs +1 -0
  49. package/dist/packem_shared/discoverRlsMetadata-Cf4gZvxW.mjs +1 -0
  50. package/dist/packem_shared/discoverRlsProcedures-_Dh3Xb9Z.mjs +1 -0
  51. package/dist/packem_shared/discoverSandboxUsage-Ccy9n7G1.mjs +1 -0
  52. package/dist/packem_shared/discoverSchema-ynieYB0n.mjs +1 -0
  53. package/dist/packem_shared/discoverStorageRulesMetadata-ZKW6DInk.mjs +1 -0
  54. package/dist/packem_shared/dispatch-namespace-DwTjD7BU.mjs +1 -0
  55. package/dist/packem_shared/emitAgents-E9U99TB1.mjs +1 -0
  56. package/dist/packem_shared/emitApi-lwadq5G7.mjs +147 -0
  57. package/dist/packem_shared/emitApp-pPxkJ2Z-.mjs +1164 -0
  58. package/dist/packem_shared/emitCrons-CCRKs482.mjs +138 -0
  59. package/dist/packem_shared/emitDataModel-BvCZS4Yq.mjs +114 -0
  60. package/dist/packem_shared/emitDrizzleSchema-BzOChEYW.mjs +15 -0
  61. package/dist/packem_shared/emitFunctions-ppMX7E3X.mjs +528 -0
  62. package/dist/packem_shared/emitServer-CbcZN_Ug.mjs +1 -0
  63. package/dist/packem_shared/emitShard-B0i9dfOt.mjs +1 -0
  64. package/dist/packem_shared/exported-procedure-chains-DomRzs5_.mjs +1 -0
  65. package/dist/packem_shared/fingerprintSchemaSources-C8H1wOcH.mjs +1 -0
  66. package/dist/packem_shared/formatAdvisories-BCVASH7N.mjs +2 -0
  67. package/dist/packem_shared/handler-reference-DpIVI5BM.mjs +1 -0
  68. package/dist/packem_shared/index-BH3e-J44.mjs +1 -0
  69. package/dist/packem_shared/index-D03C6Kao.mjs +1 -0
  70. package/dist/packem_shared/ip-reads-ByzaRhd2.mjs +1 -0
  71. package/dist/packem_shared/isD1GlobalTable-udvHAAzD.mjs +1 -0
  72. package/dist/packem_shared/isTestPath-DRIdZaij.mjs +1 -0
  73. package/dist/packem_shared/isTypedSchema-CDv3pJB6.mjs +4 -0
  74. package/dist/packem_shared/json-data-Chfs2Cz5.mjs +1 -0
  75. package/dist/packem_shared/loadProjectConfig-BXwH3_gn.mjs +1 -0
  76. package/dist/packem_shared/module-specifiers-BctA0m_p.mjs +1 -0
  77. package/dist/packem_shared/modules-Qpm_zqz4.mjs +1 -0
  78. package/dist/packem_shared/parse-validator-BisfC8bR.mjs +1 -0
  79. package/dist/packem_shared/platform-8oj7iXQy.mjs +1 -0
  80. package/dist/packem_shared/project-config-file-DR7xrrNB.mjs +1 -0
  81. package/dist/packem_shared/property-name-7cBlgK_O.mjs +1 -0
  82. package/dist/packem_shared/qualifiers-qqH8fRTo.mjs +1 -0
  83. package/dist/packem_shared/readPackageDependencies-RHhGiz0k.mjs +1 -0
  84. package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
  85. package/dist/packem_shared/reserved-words-CW1QFbTd.mjs +1 -0
  86. package/dist/packem_shared/schema-BgM8A3XV.mjs +1 -0
  87. package/dist/packem_shared/schemaFromIr-CByOxuZb.mjs +1 -0
  88. package/dist/packem_shared/server-5ph4hltf.mjs +377 -0
  89. package/dist/packem_shared/shard-CgzAeeHn.mjs +1897 -0
  90. package/dist/packem_shared/shard-runtime-DsYnnWSe.mjs +351 -0
  91. package/dist/packem_shared/shared-Cn7dMQ_u.mjs +13 -0
  92. package/dist/packem_shared/unwrap-handler-return-DUzluwPj.mjs +1 -0
  93. package/dist/sdk/index.d.mts +288 -0
  94. package/dist/sdk/index.d.ts +288 -0
  95. package/dist/sdk/index.mjs +394 -0
  96. package/package.json +22 -9
  97. package/dist/packem_shared/CONTAINERS_FILENAME-DjpXMqhp.mjs +0 -224
  98. package/dist/packem_shared/CodegenDiagnosticError-DyQ5FwkM.mjs +0 -24
  99. package/dist/packem_shared/FLAGS_FILENAME-fEZtzWXi.mjs +0 -139
  100. package/dist/packem_shared/GENERATED_HEADER-cUyu5VOU.mjs +0 -3
  101. package/dist/packem_shared/LUNORA_ERROR_CODES-DvTLozCu.mjs +0 -68
  102. package/dist/packem_shared/MUTATORS_FILENAME-BZOfUhlY.mjs +0 -81
  103. package/dist/packem_shared/OPENRPC_VERSION-DxbqafcJ.mjs +0 -60
  104. package/dist/packem_shared/QUEUES_FILENAME-Xv6Vy-Ku.mjs +0 -145
  105. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-C1yHg38Z.mjs +0 -3438
  106. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-D0ARY6rL.mjs +0 -249
  107. package/dist/packem_shared/SHAPES_FILENAME-DOhPGi-6.mjs +0 -94
  108. package/dist/packem_shared/WORKFLOWS_FILENAME-B2By8S4s.mjs +0 -152
  109. package/dist/packem_shared/buildOpenApiDocument-_mwWOc2N.mjs +0 -183
  110. package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
  111. package/dist/packem_shared/discoverAuthApiCalls-WMx8L2FG.mjs +0 -62
  112. package/dist/packem_shared/discoverCrons-D-jrpm97.mjs +0 -256
  113. package/dist/packem_shared/discoverFunctions-CZ91aenA.mjs +0 -518
  114. package/dist/packem_shared/discoverHttpRoutes-DNZLDCmm.mjs +0 -131
  115. package/dist/packem_shared/discoverInserts-DFRJhmCv.mjs +0 -61
  116. package/dist/packem_shared/discoverMaskProcedures-B5iFnZ-X.mjs +0 -273
  117. package/dist/packem_shared/discoverMigrations-CdKtMlBc.mjs +0 -97
  118. package/dist/packem_shared/discoverNondeterministicCalls-C_PrQPkA.mjs +0 -122
  119. package/dist/packem_shared/discoverQueries-B8W9UPrt.mjs +0 -62
  120. package/dist/packem_shared/discoverR2sqlCalls-Bm7Rfnf4.mjs +0 -80
  121. package/dist/packem_shared/discoverRlsMetadata-B4GL4ZKm.mjs +0 -280
  122. package/dist/packem_shared/discoverSchema-DFWVgU5o.mjs +0 -874
  123. package/dist/packem_shared/discoverStorageRulesMetadata-nosjYcvN.mjs +0 -97
  124. package/dist/packem_shared/emit-CFz-9dcD.mjs +0 -3473
  125. package/dist/packem_shared/emitApp-D8rVuM__.mjs +0 -668
  126. package/dist/packem_shared/formatAdvisories-DRhEiJUz.mjs +0 -114
  127. package/dist/packem_shared/parse-validator-BSJo1HGP.mjs +0 -144
  128. package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
  129. package/dist/packem_shared/redact-oTmsol5A.mjs +0 -33
  130. package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
@@ -0,0 +1 @@
1
+ import{statSync as A,readdirSync as P,realpathSync as D,lstatSync as I}from"node:fs";import{dirname as w,join as x,relative as F,sep as N,extname as O,basename as k}from"node:path";import{matcher as z}from"@visulima/fs";import{SyntaxKind as p,Node as s,VariableDeclarationKind as j}from"ts-morph";import{diagnosticAt as M}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{r as K}from"./project-config-file-DR7xrrNB.mjs";import{findProjectConfigFile as $,findCodegenConfigFile as V}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{p as B,a as U}from"./property-name-7cBlgK_O.mjs";const W=/\.ts$/u,g=(e,t)=>F(e,t).split(N).join("/").replace(W,""),H=new Set(["_generated","node_modules"]),L=new Set(["__fixtures__","__mocks__","__snapshots__","__tests__"]),_=/\.(?:bench|e2e|e2e-spec|spec|spec-d|test|test-d)(?:\.tsx?)?$/u,ve=e=>{const t=e.split("/");return _.test(t.at(-1)??"")||t.slice(0,-1).some(i=>L.has(i))},d=(e,t,i)=>t?H.has(e)||!i&&L.has(e):!i&&_.test(e),v=new Map,E=()=>!1;let f;const X=e=>{const t=V(e),i=t===void 0?void 0:A(t,{throwIfNoEntry:!1});if(t===void 0||i===void 0)return E;const n=`${String(i.mtimeMs)}:${String(i.size)}`,r=v.get(t);if(r?.key===n)return r.isExcluded;const{codegen:o}=K(w(t));o?.unreadable&&console.warn("@lunora/codegen: `codegen.exclude` in lunora.config is not an array of string literals without `!` negations — ignoring it.");const c=o?.exclude?.length?z(o.exclude):E;return v.set(t,{isExcluded:c,key:n}),c},G=(e,t,i)=>e==="schema.ts"&&t===i,Y=e=>{try{return A(e)}catch{console.warn(`@lunora/codegen: skipping ${e} — it is a symlink that does not resolve (or vanished mid-scan).`);return}},R=(e,t,i,n,r)=>{let o,c;try{o=P(e),c=D(e)}catch{return t}if(n.has(c))return t;n.add(c);for(const l of o){const u=x(e,l),a=Y(u);a===void 0||r(l,F(i,u).split(N).join("/"),a.isDirectory())||(a.isDirectory()?R(u,t,i,n,r):a.isFile()&&O(l)===".ts"&&!G(l,e,i)&&t.push(u))}return t},C=(e,t={})=>{const i=t.includeSkipped??!1,n=`${String(i)}\0${e}`,r=f?.get(n);if(r!==void 0)return[...r];const o=i?E:X(e),c=R(e,[],e,new Set,(l,u,a)=>d(l,a,i)||o(u));return f?.set(n,c),[...c]},he=e=>{if(f!==void 0)return e();f=new Map;try{return e()}finally{f=void 0}},q=["src/server","src/index.ts","src/worker.ts"],Q=new Set([".ts",".tsx"]),T=(e,t=[])=>{let i;try{i=I(e)}catch{return t}if(i.isFile())return Q.has(O(e))&&!d(k(e),!1,!1)&&t.push(e),t;if(!i.isDirectory())return t;for(const n of P(e))d(n,!0,!1)||T(x(e,n),t);return t},J=e=>{const t=w(e),i=C(e).map(o=>({displayPath:g(e,o),filePath:o})),n=new Set(i.map(o=>o.filePath)),r=$(t);for(const o of[...q.flatMap(c=>T(x(t,c))),...r===void 0?[]:[r]])n.has(o)||(n.add(o),i.push({displayPath:g(t,o),filePath:o}));return i},Z=e=>Array.isArray(e),h=new WeakMap,ee=(e,t)=>{let i=h.get(e.compilerNode);i===void 0&&(i=new Map,h.set(e.compilerNode,i));let n=i.get(t);return n===void 0&&(n=e.getDescendantsOfKind(t),i.set(t,n)),n},b=(e,t,i,n)=>{const r=[];for(const{displayPath:o,filePath:c}of t){const l=e.getSourceFile(c)??e.addSourceFileAtPath(c);for(const u of ee(l,i)){const a=n(u,o);Z(a)?r.push(...a):a!==void 0&&r.push(a)}}return r},te=e=>C(e).map(t=>({displayPath:g(e,t),filePath:t})),ie=(e,t,i,n)=>b(e,te(t),i,n),ye=(e,t,i)=>ie(e,t,p.CallExpression,i),Ae=(e,t,i)=>b(e,J(t),p.CallExpression,i),Pe=e=>B(e.getPropertyNameNode()??e.getNameNode()),S=(e,t)=>e?.getProperties().find(i=>!s.isSpreadAssignment(i)&&U(i)===t),we=(e,t)=>{if(t){const o=e.getArguments()[0];return o&&(s.isArrowFunction(o)||s.isFunctionExpression(o))?o:void 0}const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return;const n=S(i,"handler");if(!n||!s.isPropertyAssignment(n))return;const r=n.getInitializer();return r&&(s.isArrowFunction(r)||s.isFunctionExpression(r))?r:void 0},Fe=(e,t)=>{if(!e||!s.isObjectLiteralExpression(e))return;const i=S(e,t);return i&&s.isPropertyAssignment(i)?i.getInitializer():void 0},se=e=>{const t=e?.getParent();return s.isVariableDeclaration(e)&&s.isVariableDeclarationList(t)&&t.getDeclarationKind()===j.Const},ne=e=>{let t=e,i=t.getParent();for(;i!==void 0&&(s.isParenthesizedExpression(i)||s.isAsExpression(i)||s.isSatisfiesExpression(i)||s.isTypeAssertion(i)||s.isNonNullExpression(i));)t=i,i=t.getParent();return t},y=e=>{const t=ne(e),i=t.getParent();if(i===void 0)return!1;if(s.isBinaryExpression(i)){const r=i.getOperatorToken().getKind();return i.getLeft()===t&&r>=p.FirstAssignment&&r<=p.LastAssignment}if(s.isPrefixUnaryExpression(i)||s.isPostfixUnaryExpression(i)){const r=i.getOperatorToken();return r===p.PlusPlusToken||r===p.MinusMinusToken}return s.isDeleteExpression(i)?!0:s.isForOfStatement(i)||s.isForInStatement(i)?i.getInitializer()===t:s.isPropertyAssignment(i)?i.getInitializer()===t&&y(i):(s.isShorthandPropertyAssignment(i)||s.isSpreadAssignment(i)||s.isSpreadElement(i)||s.isObjectLiteralExpression(i)||s.isArrayLiteralExpression(i))&&y(i)},re=e=>{const t=e?.getDeclarations().find(n=>s.isVariableDeclaration(n));if(!se(t))return;const i=t.getParent().getParent();return s.isVariableStatement(i)&&s.isSourceFile(i.getParent())?t.getInitializer():void 0},oe=e=>re(e.getSymbol()),Ne=e=>{if(!e)return;if(s.isObjectLiteralExpression(e))return e;if(!s.isIdentifier(e))return;const t=oe(e);return t!==void 0&&s.isObjectLiteralExpression(t)?t:void 0},m=e=>{let t=e;for(;t&&(s.isAsExpression(t)||s.isSatisfiesExpression(t)||s.isParenthesizedExpression(t)||s.isNonNullExpression(t));)t=t.getExpression();return t},ce=(e,t)=>{let i=m(e);for(;s.isAwaitExpression(i)||s.isPropertyAccessExpression(i)||s.isElementAccessExpression(i)||s.isCallExpression(i);){const n=s.isCallExpression(i)?t?.(i):void 0;if(n!==void 0)return{verdict:n};i=m(i.getExpression())}return{root:i}},Oe=e=>ce(e).root,Le=e=>s.isArrowFunction(e)||s.isConstructorDeclaration(e)||s.isFunctionDeclaration(e)||s.isFunctionExpression(e)||s.isGetAccessorDeclaration(e)||s.isMethodDeclaration(e)||s.isSetAccessorDeclaration(e),_e=(e,t)=>e?.compilerNode===t.compilerNode,Re=e=>{if(s.isPropertyAccessExpression(e))return{member:e.getName(),object:e.getExpression()};const t=s.isElementAccessExpression(e)?e.getArgumentExpression():void 0;return s.isElementAccessExpression(e)&&s.isStringLiteral(t)?{member:t.getLiteralValue(),object:e.getExpression()}:void 0},Ce=e=>{const t=e.getParent();return s.isReturnStatement(t)||s.isArrowFunction(t)&&t.getBody()===e?e.getFirstAncestor(n=>s.isFunctionLikeDeclaration(n)||s.isArrowFunction(n)):void 0},Te=e=>{const t=m(e);return t&&s.isCallExpression(t)?t:void 0},be=e=>{const t=e.getExportAssignment(r=>!r.isExportEquals());if(!t)return;const i=t.getExpression();if(!s.isIdentifier(i))return i;const n=i.getSymbol()?.getValueDeclaration();return n&&s.isVariableDeclaration(n)?n.getInitializer():i},De=e=>{const t=e.getArguments()[1];return t&&s.isStringLiteral(t)?t.getLiteralValue():""},Ie=(e,t)=>{if(!s.isObjectLiteralExpression(e))return;const i=S(e,t);if(!i||!s.isPropertyAssignment(i))return;const n=i.getInitializer();return n&&s.isStringLiteral(n)?n.getLiteralText():void 0},ae=e=>{const t=e.getStatements(),[i]=t;if(t.length!==1||i===void 0||!s.isReturnStatement(i))return;const n=i.getExpression();return n!==void 0&&s.isObjectLiteralExpression(n)?n:void 0},ke=e=>{if(s.isObjectLiteralExpression(e))return e;if(s.isParenthesizedExpression(e)){const t=e.getExpression();return s.isObjectLiteralExpression(t)?t:void 0}return s.isBlock(e)?ae(e):void 0},ze=e=>(t,i,n)=>{if(s.isStringLiteral(t)||s.isNoSubstitutionTemplateLiteral(t))return t.getLiteralValue();throw M(t,`${e} "${i}": \`${n}\` must be a static string literal — it is deploy configuration codegen writes into wrangler.jsonc`)},le=new Set(["api","internal"]),je=new Set(["run","runAction","runMutation","runQuery"]),ue=e=>{if(e===void 0||!s.isPropertyAccessExpression(e))return;const t=[];let i=e;for(;s.isPropertyAccessExpression(i);)t.unshift(i.getName()),i=i.getExpression();return s.isIdentifier(i)&&le.has(i.getText())&&t.length>=2?t:void 0},Me=e=>{const t=ue(e);return t===void 0?void 0:`${t.slice(0,-1).join("_")}:${String(t.at(-1))}`};export{je as RUN_METHODS,W as TS_EXTENSION_RE,Pe as bindingKeyName,Oe as chainRootOf,ye as collectCallRows,ie as collectNodeRows,Ae as collectSecurityCallRows,be as defaultExportExpression,ee as descendantsOfKind,S as findObjectProperty,Me as functionKeyOf,ue as functionReferenceSegments,we as handlerOf,se as isConstDeclaration,Le as isFunctionLike,_e as isSameNode,ve as isTestPath,y as isWriteTarget,De as limitNameOf,C as listLunoraSourceFiles,J as listSecurityScanFiles,g as lunoraRelativePath,Re as memberAccessOf,ke as objectLiteralFromCallbackBody,Ne as optionsObjectLiteral,ne as outermostValueWrapper,Fe as propertyInitializer,U as propertyKeyName,B as propertyNameText,Ce as returningFunctionOf,ze as stringPropertyFor,Ie as stringPropertyOf,re as symbolConstInitializer,m as unwrapExpression,Te as unwrapToCallExpression,ce as walkChain,he as withSourceListMemo};
@@ -0,0 +1,4 @@
1
+ const h=t=>t.methods.filter(e=>e["x-lunora-function-kind"]!=="stream"),b=/[^a-zA-Z0-9]+/gu,j=/([a-z0-9])([A-Z])/gu,p=t=>t.split(b).filter(e=>e.length>0).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),I=t=>t.replaceAll(j,"$1_$2").replaceAll(b,"_").toLowerCase(),d=t=>t===void 0?!1:["$ref","allOf","anyOf","enum","items","oneOf","properties","type"].some(e=>e in t),E=t=>t==="query"?"query":t==="action"?"action":"mutation",l=(t,e=0)=>{if(e>32||t===null||typeof t!="object")return!1;if(Array.isArray(t))return t.some(o=>l(o,e+1));const n=t;if(n.format==="int64"&&(n.type===void 0||n.type==="string")||n.type==="string"&&n.contentEncoding==="base64")return!0;const{properties:r}=n;return r!==null&&typeof r=="object"&&Object.values(r).some(o=>l(o,e+1))?!0:["additionalProperties","allOf","anyOf","items","oneOf"].some(o=>l(n[o],e+1))},x=t=>t.replaceAll(/[\n\r\u2028\u2029]+/gu," ").replaceAll("*/","* /").replaceAll('"""','" ""'),C=t=>t.replaceAll("\\","\\\\").replaceAll('"','\\"').replaceAll(`
2
+ `,"\\n").replaceAll("\r","\\r"),N=["$","{","'","$","'","}"].join(""),z=t=>C(t).split("$").join(N),H=(t,e)=>t.argsType!==void 0?e.typed(t.argsType):t.takesArgs?e.untyped:e.none,f=32,A=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return!1;const n=t;return n.type==="null"||Array.isArray(n.type)&&n.type.includes("null")?!0:["anyOf","oneOf"].some(r=>{const o=n[r];return Array.isArray(o)&&o.some(s=>A(s,e+1))})},P=(t,e,n)=>e.length===0?n===0?[]:[t]:e.map(r=>({properties:{...t.properties,...r.properties},required:new Set([...t.required,...r.required])})),k=t=>{const{properties:e}=t;if(e===null||typeof e!="object")return[];const n=t.required;return[{properties:e,required:new Set(Array.isArray(n)?n.filter(r=>typeof r=="string"):[])}]},m=(t,e,n)=>{const r=t[e];return Array.isArray(r)?r.flatMap(o=>w(o,n+1)):[]},w=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return[];const n=t,r=[...k(n),...m(n,"allOf",e)],o={properties:Object.assign({},...r.map(a=>a.properties)),required:new Set(r.flatMap(a=>[...a.required]))},s=[...m(n,"anyOf",e),...m(n,"oneOf",e)];return P(o,s,r.length)},$=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return[];const n=t,r=[n];for(const o of["anyOf","oneOf","allOf"]){const s=n[o];if(Array.isArray(s))for(const a of s)r.push(...$(a,e+1))}return r},y=(t,e,n,r=0)=>{if(r>f||t===null||typeof t!="object")return;const o=w(t),s=[...new Set(o.flatMap(a=>Object.keys(a.properties)))].toSorted((a,c)=>a.localeCompare(c));for(const a of s){const c=[...e,a],u=o.every(i=>i.required.has(a)),g=o.map(i=>i.properties[a]).filter(i=>i!==void 0);u?g.some(i=>A(i))&&n.nullable.push(c):n.optional.push(c);for(const i of g)y(i,c,n,r+1)}for(const a of $(t))for(const c of["additionalProperties","items"]){const u=a[c];u!==null&&typeof u=="object"&&y(u,[...e,"*"],n,r+1)}},q=(t,e)=>t.join("\0").localeCompare(e.join("\0")),L=t=>{const e={nullable:[],optional:[]};y(t,[],e);const n=r=>[...new Map(r.map(o=>[o.join("\0"),o])).values()].toSorted(q);return{nullable:n(e.nullable),optional:n(e.optional)}},S=t=>{const[e="",n=""]=t.name.split(":"),r=`${p(e)}${p(n)}`,o=t.params?.[0]?.schema,s=t.result?.schema;return{argsNullPaths:L(o),argsType:d(o)&&!l(o)?`${r}Args`:void 0,takesArgs:d(o),functionName:n,functionPath:t.name,namespace:e,resultType:d(s)&&!l(s)?`${r}Result`:void 0,summary:t.summary??t.name,verb:E(t["x-lunora-function-kind"])}},U=t=>{const e=new Map;for(const n of h(t)){const r=S(n),o=e.get(r.namespace);o===void 0?e.set(r.namespace,[r]):o.push(r)}return[...e.entries()].toSorted(([n],[r])=>n.localeCompare(r)).map(([n,r])=>({methods:r.toSorted((o,s)=>o.functionName.localeCompare(s.functionName)),name:n}))},W=t=>h(t).flatMap(e=>{const n=S(e);return[{name:n.argsType,schema:e.params?.[0]?.schema},{name:n.resultType,schema:e.result?.schema}]}).filter(e=>e.name!==void 0&&e.schema!==void 0).toSorted((e,n)=>e.name.localeCompare(n.name)),D=/^[A-Za-z][A-Za-z0-9]*$/u,M=t=>D.test(t),_=t=>{const e=new Map;for(const n of t.methods){const r=p(n.functionName);if(!M(r))throw new Error(`sdk: function "${n.functionPath}" produces the invalid identifier "${r}" — rename the export so it starts with a letter.`);const o=n.verb==="query"?[r,`Subscribe${r}`,`Watch${r}`]:[r];for(const s of o){const a=e.get(s);if(a!==void 0){const c=s.startsWith("Watch")?' (the Dart target emits a "watch" Stream member for every query)':"";throw new Error(`sdk: functions "${a}" and "${n.functionPath}" both generate "${s}"${c} — rename one so the generated methods stay distinct.`)}e.set(s,n.functionPath)}}},Z=t=>{const e=new Map;for(const n of t){const r=p(n.name);if(!M(r))throw new Error(`sdk: namespace "${n.name}" produces the invalid identifier "${r}" — rename the file so it starts with a letter.`);const o=e.get(r);if(o!==void 0)throw new Error(`sdk: namespaces "${o}" and "${n.name}" both generate "${r}" — rename one so the generated types stay distinct.`);e.set(r,n.name),_(n)}},F=(t,e,n)=>{for(const r of t){const o=new Map;for(const s of r.methods)for(const a of n(s)){const c=o.get(a);if(c!==void 0&&c!==s.functionPath)throw new Error(`sdk: functions "${c}" and "${s.functionPath}" both generate the ${e} member "${a}" — rename one so the generated methods stay distinct.`);o.set(a,s.functionPath)}}},v=t=>t.flatMap(e=>e.methods),G=t=>[`GENERATED by \`lunora sdk generate --lang ${t}\` — do not edit.`,"Run the command again to regenerate."],R=/^\s*(?:#|\/\/|\/\*|\*)/u,O=t=>t.split(`
3
+ `).filter(e=>!R.test(e)).join(`
4
+ `),T=(t,e)=>new RegExp(String.raw`\b${e}\b`,"u").test(t),B=(t,e)=>{const n=O(e),r=o=>o!==void 0&&T(n,o)?o:void 0;return t.map(o=>({methods:o.methods.map(s=>({...s,argsType:r(s.argsType),resultType:r(s.resultType)})),name:o.name}))},V=t=>h(t).filter(e=>l(e.params?.[0]?.schema)||l(e.result?.schema)).map(e=>e.name).toSorted((e,n)=>e.localeCompare(n)),K=(t,e)=>{const n=O(e);return[...new Set(v(t).flatMap(r=>[r.argsType,r.resultType]).filter(r=>r!==void 0&&!T(n,r)))].toSorted((r,o)=>r.localeCompare(o))},X=t=>[...new Set(v(t).flatMap(e=>[e.argsType,e.resultType]).filter(e=>e!==void 0))].toSorted((e,n)=>e.localeCompare(n));export{v as allMethods,H as argsChoice,F as assertDistinctMembers,Z as assertGeneratable,x as commentText,G as generatedHeaderLines,l as hasUnrepresentableWireType,d as isTypedSchema,z as kotlinLiteral,W as modelSources,L as nullPathsOf,S as parseMethod,U as parseSpec,X as referencedModels,C as stringLiteral,p as toPascalCase,I as toSnakeCase,K as undeclaredModels,V as unrepresentableFunctions,E as verbForKind,B as withDeclaredModels};
@@ -0,0 +1 @@
1
+ const a=(r,s)=>`JSON.parse(${JSON.stringify(JSON.stringify(r))}) as ${s}`;export{a as r};
@@ -0,0 +1 @@
1
+ import{b as a,p as t,e as i,r as s,c,d,a as n}from"./project-config-file-DR7xrrNB.mjs";import"./property-name-7cBlgK_O.mjs";import{PROJECT_CONFIG_FILENAMES as P,findProjectConfigFile as f}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";export{P as PROJECT_CONFIG_FILENAMES,f as findProjectConfigFile,a as loadProjectConfig,t as projectConfigProblems,i as readMergeDurableObjects,s as readProjectConfigLiterals,c as readProjectLazyFunctions,d as readProjectSecurityHeaders,n as readProjectStudioCompanion};
@@ -0,0 +1 @@
1
+ const r=/(?:^|\/)_generated\/server(?:\.js)?$/u,s=new Set(["@lunora/server","lunorash/server"]),o=e=>s.has(e),n=e=>r.test(e),t=e=>o(e)||n(e),a=new Set(["@lunora/scheduler",...s]),E=e=>a.has(e);export{o as a,t as b,E as i};
@@ -0,0 +1 @@
1
+ import{basename as b}from"node:path";import{Node as d}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{listLunoraSourceFiles as $,lunoraRelativePath as v,unwrapToCallExpression as E,defaultExportExpression as S,findObjectProperty as M}from"./isTestPath-DRIdZaij.mjs";import{s as g}from"./dispatch-namespace-DwTjD7BU.mjs";const h=(e,o)=>e.find(t=>t.ownsFolder!==!1&&o.startsWith(`${t.name}/`))?.name,F="module.ts",w=(e,o,t)=>{if(d.isStringLiteral(e)||d.isNoSubstitutionTemplateLiteral(e))return e.getLiteralValue();throw c(e,`module "${o}": \`${t}\` must be a static string literal — codegen reads it without running the file`)},L=(e,o,t)=>{if(!d.isArrayLiteralExpression(e))throw c(e,`module "${o}": \`${t}\` must be an inline array of table names`);return e.getElements().map(n=>w(n,o,t))},p=(e,o,t)=>{const n=M(e,o);if(n!==void 0){if(!d.isPropertyAssignment(n))throw c(n,`module "${t}": write \`${o}\` inline as \`${o}: …\` — codegen reads it without running the file`);return n.getInitializerOrThrow()}},A=(e,o,t)=>{const n=e.getSourceFile(o)??e.addSourceFileAtPath(o),s=E(S(n)),a=s?.getExpression();if(!s||!a||!d.isIdentifier(a)||a.getText()!=="defineModule")return;if(t==="")throw c(s,"defineModule: lunora/module.ts would make the whole app one module — move it into the folder it describes (lunora/<module>/module.ts)");const i=s.getArguments()[0],m={name:t,tables:[]};if(i===void 0)return m;if(!d.isObjectLiteralExpression(i))throw c(i,`module "${t}": defineModule must be passed an inline object literal`);const r=p(i,"description",t);r!==void 0&&(m.description=w(r,t,"description"));const l=p(i,"tables",t);return l!==void 0&&(m.tables=L(l,t,"tables")),m},k=(e,o)=>{const t=[];for(const n of $(o)){if(b(n)!==F)continue;const s=v(o,n),a=A(e,n,s==="module"?"":s.slice(0,-7));a&&t.push(a)}return t.toSorted((n,s)=>n.name.localeCompare(s.name))},T=(e,o)=>{const t=new Set(e.map(r=>r.name)),n=new Set(e.flatMap(r=>r.tables)),s=o.tables.filter(r=>r.extensionKey!==void 0&&!n.has(r.name)),a=Map.groupBy(s,r=>String(r.extensionKey)),i=e.map(r=>{const l=a.get(r.name);return l===void 0?r:{...r,tables:[...r.tables,...l.map(u=>u.name)]}}),m=[...a].filter(([r])=>!t.has(r)).map(([r,l])=>{const u=l.every(f=>f.extensionFromPackage===!0);return{installed:!0,name:r,...u?{ownsFolder:!1}:{},tables:l.map(f=>f.name)}});return[...i,...m].toSorted((r,l)=>r.name.localeCompare(l.name))},x=e=>{for(const o of e){const t=e.find(n=>n.name.startsWith(`${o.name}/`));if(t)throw new Error(`@lunora/codegen: module "${t.name}" is nested inside ${o.installed===!0?"installed component":"module"} "${o.name}" — a file can belong to one module only, so move one of the two`)}},y=(e,o)=>{const t=new Set(o.tables.map(s=>s.name)),n=new Map;for(const s of e)for(const a of s.tables){if(!t.has(a))throw new Error(`@lunora/codegen: module "${s.name}" declares table "${a}", which lunora/schema.ts does not define`);const i=n.get(a);if(i!==void 0)throw new Error(`@lunora/codegen: table "${a}" is claimed by both module "${i}" and module "${s.name}" — a table has one owner`);n.set(a,s.name)}},C=(e,o,t)=>{if(e.length===0)return;const n=new Set(o.map(s=>s.name));for(const s of t){const a=g(s);if(h(o,s)===void 0&&n.has(a))throw new Error(`@lunora/codegen: lunora/${s}.ts sits beside module "${a}" and shares its name — move it into lunora/${a}/ or rename one of them`)}},z=(e,o,t)=>{const n=T(e,o);return x(n),y(n,o),C(e,n,t),n},K=(e,o)=>h(e,o)??g(o);export{h as a,k as d,K as m,z as r};
@@ -0,0 +1 @@
1
+ import{LunoraError as y}from"@lunora/errors";import{Node as i,VariableDeclarationKind as E}from"ts-morph";import{diagnosticAt as h}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{s as A}from"./property-name-7cBlgK_O.mjs";let g;const q=e=>{g=e},k=/^[A-Za-z_$][\w$]*$/u,p=new Set(["$defaultFn","$onUpdateFn","$type","default","defaultNow","nullable","serverDefault","unique"]),N=(e,t)=>{const r={notNull:!0,...e.column};switch(t){case"$defaultFn":case"default":case"defaultNow":case"serverDefault":{r.hasDefault=!0;break}case"$onUpdateFn":{r.hasOnUpdate=!0;break}case"$type":break;case"nullable":{r.notNull=!1;break}case"unique":{r.unique=!0;break}}return{...e,column:r}},T=new Set(["any","bigint","boolean","bytes","date","geoPoint","null","number","string","timestamp"]),m=new Set(["check","email","int","length","max","min","pattern","positive","url"]),I=new Set(["meta"]),L=new Set(["strip"]),l=new Set,f=new Set,v=e=>{const t=e.getSymbol();let r=(t?.getAliasedSymbol()??t)?.getValueDeclaration();if(r!==void 0&&i.isShorthandPropertyAssignment(r)){const n=r.getValueSymbol();r=(n?.getAliasedSymbol()??n)?.getValueDeclaration()}if(!(r===void 0||!i.isVariableDeclaration(r)))return r.getInitializer()},w=e=>{const t=e.getParent();return!i.isVariableDeclaration(t)||t.getVariableStatement()?.getDeclarationKind()===E.Const},u=e=>{if(i.isParenthesizedExpression(e)||i.isAsExpression(e)||i.isSatisfiesExpression(e))return u(e.getExpression());if(i.isObjectLiteralExpression(e))return e;if(i.isPropertyAccessExpression(e)){const r=e.getSymbol()?.getValueDeclaration(),n=r!==void 0&&i.isPropertyAssignment(r)?r.getInitializer():void 0;return n===void 0?void 0:u(n)}if(!i.isIdentifier(e)||l.has(e))return;const t=v(e);if(!(t===void 0||!w(t))){l.add(e);try{return u(t)}finally{l.delete(e)}}},D="v",R=e=>{if(i.isIdentifier(e))return!0;let t=e;for(;i.isCallExpression(t);){const r=t.getExpression();if(!i.isPropertyAccessExpression(r))return!1;t=r.getExpression()}return i.isIdentifier(t)&&t.getText()===D},d=e=>{if(i.isIdentifier(e)&&!l.has(e)){const t=v(e);if(t!==void 0&&R(t)){l.add(e);try{return d(t)}finally{l.delete(e)}}}return i.isCallExpression(e)?C(e):{kind:"any",sourceText:e.getText()}},S=e=>{const t=u(e);if(t===void 0||f.has(t))return{};f.add(t);try{return x(t)}finally{f.delete(t)}},b=(e,t=new Set)=>{const r=u(e);if(r===void 0||t.has(r))return!1;t.add(r);try{return r.getProperties().every(n=>i.isSpreadAssignment(n)?b(n.getExpression(),t):i.isPropertyAssignment(n)||i.isShorthandPropertyAssignment(n))}finally{t.delete(r)}},P=e=>{if(e===void 0||!i.isExpression(e))return{kind:"object",shape:{},unresolvedShape:!0};const t=S(e);return b(e)?{kind:"object",shape:t}:{kind:"object",shape:t,unresolvedShape:!0}},V=e=>{throw h(e,`computed property name ${e.getText()} must be a string literal — codegen resolves object keys statically.`)},x=e=>{const t={};for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){Object.assign(t,S(r.getExpression()));continue}const n=i.isShorthandPropertyAssignment(r);if(!n&&!i.isPropertyAssignment(r))continue;const a=n?r.getNameNode():r.getInitializer();if(!a)continue;const s=r.getNameNode(),o=A(s)??V(s);if(!k.test(o))throw new y("INTERNAL",`@lunora/codegen: field name is not a valid JS identifier: ${JSON.stringify(o)}`);t[o]=d(a)}return t},c=(e,t)=>e&&i.isExpression(e)?d(e):t,O=e=>e.sensitive===!0?!0:[e.inner,e.keyType,e.valueType,...e.members??[],...Object.values(e.shape??{})].some(r=>r!==void 0&&O(r)),M=e=>e===void 0?"undefined":i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e)?JSON.stringify(e.getLiteralValue()):e.getText(),$=e=>{const t=e&&g?g(e):void 0;return t===void 0?{kind:"from"}:{kind:"from",tsType:t}},F=(e,t,r)=>{if(T.has(e))return{kind:e};const[n,a]=t;switch(e){case"array":return{inner:c(n,{kind:"any"}),kind:"array"};case"from":return $(n);case"id":{if(!n||!i.isStringLiteral(n))throw h(n??r,`v.id(...) target table must be a string literal — codegen resolves foreign-key targets statically. Got ${n?n.getText():"no argument"}.`);return{kind:"id",tableName:n.getLiteralText()}}case"literal":return{kind:"literal",literalValue:M(n)};case"object":return P(n);case"optional":return{inner:c(n,{kind:"any"}),kind:"optional"};case"record":return{keyType:c(n,{kind:"string"}),kind:"record",valueType:c(a,{kind:"any"})};case"sensitive":return{...c(n,{kind:"any"}),sensitive:!0};case"storage":return n&&i.isStringLiteral(n)?{bucket:n.getLiteralText(),kind:"storage"}:{kind:"storage"};case"union":return{kind:"union",members:t.filter(s=>i.isExpression(s)).map(s=>d(s))};default:throw new y("INTERNAL",`Unsupported validator kind: ${e}`)}},j=e=>{const[t]=e;if(e.length!==1||t===void 0||!i.isNumericLiteral(t))return;const r=Number(t.getText().replaceAll("_",""));return Number.isSafeInteger(r)&&r>=0?r:void 0},C=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return{kind:"any",sourceText:e.getText()};const r=t.getName(),n=e.getArguments();if(p.has(r)||m.has(r)||I.has(r)||L.has(r)){const a=t.getExpression(),s=i.isExpression(a)?d(a):{kind:"any"};if(p.has(r))return N(s,r);if(!m.has(r))return s;const o=r==="max"&&s.kind==="string"?j(n):void 0;return o!==void 0?{...s,hasRefinement:!0,stringMaxLength:Math.min(s.stringMaxLength??o,o)}:{...s,hasRefinement:!0,unmodelledRefinement:!0}}return F(r,n,e)};export{d as a,x as p,u as r,q as s,O as v};
@@ -0,0 +1 @@
1
+ const o=s=>s.filter(i=>i.topic===void 0),p=(s,i)=>s.filter(t=>t.topic===i);export{o as p,p as s};
@@ -0,0 +1 @@
1
+ import{statSync as B,readFileSync as se}from"node:fs";import{basename as j}from"node:path";import{createJiti as ie}from"jiti";import{Node as s,SyntaxKind as p,VariableDeclarationKind as J,Project as oe}from"ts-morph";import{s as ae,a as h}from"./property-name-7cBlgK_O.mjs";import{findProjectConfigFile as W,findCodegenConfigFile as w}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";const q=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},ce=/^[a-z][\d+.a-z-]*:\/\/(?:\*\.)?[\d.a-z-]+(?::\d{1,5})?$/iu,Q=e=>[...e].every(t=>t===" "||t>=" "&&t!==""&&t<="ÿ"),le=["same-origin","same-origin-allow-popups","unsafe-none"],ue=["DENY","SAMEORIGIN"],$=["includeSubDomains","maxAge","preload"],X=["csp","permissionsPolicy","referrerPolicy"],I=[...X,"crossOriginOpenerPolicy","frameAncestors","frameOptions","hsts"],M=e=>e.map(t=>JSON.stringify(t)).join(", "),de=(e,t)=>{if(typeof e=="boolean")return e;if(!q(e)){t.push("security.headers.hsts must be a boolean or an object { maxAge?, includeSubDomains?, preload? }");return}for(const o of Object.keys(e).filter(a=>!$.includes(a)))t.push(`security.headers.hsts.${o} is not an option (expected ${M($)})`);const{includeSubDomains:r,maxAge:n,preload:i}=e;n!==void 0&&!(typeof n=="number"&&Number.isSafeInteger(n)&&n>=0)&&t.push(`security.headers.hsts.maxAge must be a whole number of seconds (got ${JSON.stringify(n)})`);for(const[o,a]of[["includeSubDomains",r],["preload",i]])a!==void 0&&typeof a!="boolean"&&t.push(`security.headers.hsts.${o} must be a boolean`);return{...r===void 0?{}:{includeSubDomains:r},...n===void 0?{}:{maxAge:n},...i===void 0?{}:{preload:i}}},V=(e,t,r,n)=>{if(t===void 0||t===!1||r.includes(t))return t;n.push(`security.headers.${e} must be one of ${M(r)} or false (got ${JSON.stringify(t)})`)},fe=(e,t)=>{if(e!==void 0){if(!Array.isArray(e)){t.push('security.headers.frameAncestors must be an array of origins like ["https://partner.example"]');return}for(const r of e)(typeof r!="string"||!ce.test(r)||!Q(r))&&t.push(`security.headers.frameAncestors entry ${JSON.stringify(r)} is not an origin like "https://partner.example"`);return[...e]}},pe=e=>{if(e===void 0||typeof e=="boolean")return{ok:!0,value:e};if(!q(e))return{ok:!1,problems:[`security.headers must be a boolean or an object (got ${Array.isArray(e)?"an array":JSON.stringify(e)})`]};const t=Object.keys(e).filter(n=>!I.includes(n)).map(n=>`security.headers.${n} is not an option (expected ${M(I)})`),r={};for(const n of X){const i=e[n];i===void 0||i===!1?r[n]=i:typeof i!="string"?t.push(`security.headers.${n} must be a string or false`):Q(i)?r[n]=i:t.push(`security.headers.${n} contains a line break or control character`)}return r.crossOriginOpenerPolicy=V("crossOriginOpenerPolicy",e.crossOriginOpenerPolicy,le,t),r.frameOptions=V("frameOptions",e.frameOptions,ue,t),r.frameAncestors=fe(e.frameAncestors,t),r.hsts=e.hsts===void 0?void 0:de(e.hsts,t),r.frameAncestors!==void 0&&typeof r.csp=="string"&&t.push("security.headers.frameAncestors cannot be combined with a csp string: put the frame-ancestors directive in the csp"),r.frameAncestors!==void 0&&r.frameOptions==="DENY"&&t.push('security.headers.frameAncestors cannot be combined with frameOptions: "DENY"'),r.frameAncestors!==void 0&&r.csp===!1&&t.push("security.headers.frameAncestors needs the Content-Security-Policy that carries it; it cannot be combined with csp: false"),t.length>0?{ok:!1,problems:t}:{ok:!0,value:Object.fromEntries(Object.entries(r).filter(([,n])=>n!==void 0))}},ge=(e,t)=>{const r=Array.from({length:t.length+1},(n,i)=>i);for(let n=1;n<=e.length;n+=1){let i=r[0]??0;r[0]=n;for(let o=1;o<=t.length;o+=1){const a=r[o]??0,l=e[n-1]===t[o-1]?0:1;r[o]=Math.min((r[o-1]??0)+1,a+1,i+l),i=a}}return r[t.length]??0},me=(e,t)=>{let r,n=Number.POSITIVE_INFINITY;for(const o of t){const a=ge(e,o);a<n&&(n=a,r=o)}const i=Math.max(2,Math.ceil(e.length/3));return r!==void 0&&n<=i?r:void 0},g=Symbol("not-literal"),C=e=>Number(e.getText().replaceAll("_","")),b=e=>s.isTrueLiteral(e)||s.isFalseLiteral(e)?e.getLiteralValue():s.isPrefixUnaryExpression(e)&&e.getOperatorToken()===p.ExclamationToken&&s.isNumericLiteral(e.getOperand())?C(e.getOperand())===0:void 0,be=e=>{if(s.isStringLiteral(e)||s.isNoSubstitutionTemplateLiteral(e))return e.getLiteralValue();if(s.isNumericLiteral(e))return C(e);if(s.isPrefixUnaryExpression(e)&&e.getOperatorToken()===p.MinusToken&&s.isNumericLiteral(e.getOperand()))return-C(e.getOperand());const t=b(e);return t!==void 0?t:s.isBinaryExpression(e)?ve(e):s.isNullLiteral(e)?null:g},ye={[p.AsteriskAsteriskToken]:(e,t)=>e**t,[p.AsteriskToken]:(e,t)=>e*t,[p.MinusToken]:(e,t)=>e-t,[p.PercentToken]:(e,t)=>e%t,[p.PlusToken]:(e,t)=>e+t,[p.SlashToken]:(e,t)=>e/t},ve=e=>{const t=ye[e.getOperatorToken().getKind()],[r,n]=[S(e.getLeft()),S(e.getRight())];return t!==void 0&&typeof r=="number"&&typeof n=="number"&&Number.isFinite(r)&&Number.isFinite(n)?t(r,n):g},S=e=>{if(s.isParenthesizedExpression(e)||s.isAsExpression(e)||s.isSatisfiesExpression(e))return S(e.getExpression());if(s.isArrayLiteralExpression(e)){const t=e.getElements().map(r=>S(r));return t.includes(g)?g:t}return s.isObjectLiteralExpression(e)?he(e):be(e)},he=e=>{const t=[];for(const r of e.getProperties()){const n=s.isPropertyAssignment(r)?r.getNameNode():void 0,i=s.isPropertyAssignment(r)?r.getInitializer():void 0,o=i===void 0?g:S(i);if(n===void 0||o===g||!(s.isIdentifier(n)||s.isStringLiteral(n)))return g;const a=s.isStringLiteral(n)?n.getLiteralValue():n.getText();if(a==="__proto__")return g;t.push([a,o])}return Object.fromEntries(t)},N={accepts:["boolean"],expected:"a boolean"},xe={accepts:["function"],expected:"a function"},Oe={accepts:["number"],expected:"a number"},E={accepts:["string"],expected:"a string"},D={accepts:["array"],expected:"an array of strings",items:E},L={accepts:["boolean","string"],expected:"a string or `false`",literal:!1},v=(e,t)=>({accepts:["object"],expected:"an object",keys:e,...t===void 0?{}:{required:t}}),Ee={crossOriginOpenerPolicy:L,csp:L,frameAncestors:D,frameOptions:L,hsts:{accepts:["boolean","object"],expected:"a boolean or an object",keys:Object.fromEntries($.map(e=>[e,e==="maxAge"?Oe:N]))},permissionsPolicy:L,referrerPolicy:L},Se={accepts:["boolean","object"],expected:"a boolean or an object",keys:Object.fromEntries(I.toSorted((e,t)=>e.localeCompare(t)).map(e=>[e,Ee[e]]))},u=e=>{let t=e;for(;t!==void 0&&(s.isSatisfiesExpression(t)||s.isAsExpression(t)||s.isParenthesizedExpression(t));)t=t.getExpression();return t},Le=(e,t)=>e.getDescendants().some(r=>{if(s.isBinaryExpression(r)){const n=r.getOperatorToken().getKind(),i=r.getLeft();return n>=p.FirstAssignment&&n<=p.LastAssignment&&s.isIdentifier(i)&&i.getText()===t}return(s.isPrefixUnaryExpression(r)||s.isPostfixUnaryExpression(r))&&(r.getOperatorToken()===p.PlusPlusToken||r.getOperatorToken()===p.MinusMinusToken)&&r.getOperand().getText()===t}),T=(e,t)=>{const r=e.getVariableDeclaration(t);return r===void 0?void 0:r.getVariableStatement()?.getDeclarationKind()===J.Const||!Le(e,t)?r.getInitializer():void 0},Z=(e,t)=>{const r=u(e);return r!==void 0&&s.isIdentifier(r)?u(T(t,r.getText())):r},Ae=e=>{if(e!==void 0)return s.isStringLiteral(e)||s.isNoSubstitutionTemplateLiteral(e)||s.isTemplateExpression(e)?"string":b(e)!==void 0?"boolean":s.isBigIntLiteral(e)||s.isPrefixUnaryExpression(e)&&s.isBigIntLiteral(e.getOperand())?"bigint":s.isNumericLiteral(e)||s.isPrefixUnaryExpression(e)&&s.isNumericLiteral(e.getOperand())?"number":s.isNullLiteral(e)?"null":s.isObjectLiteralExpression(e)?"object":s.isArrayLiteralExpression(e)?"array":s.isArrowFunction(e)||s.isFunctionExpression(e)||s.isMethodDeclaration(e)?"function":void 0},Ne={array:"an array",bigint:"a bigint",boolean:"a boolean",function:"a function",null:"null",number:"a number",object:"an object",string:"a string"},_=e=>s.isPropertyAssignment(e)?e.getInitializer():s.isShorthandPropertyAssignment(e)?e.getNameNode():s.isMethodDeclaration(e)?e:void 0,je=(e,t,r)=>{const n=l=>t===""?l:`${t}.${l}`,i=me(e,r),o=i===void 0?"":` Did you mean \`${n(i)}\`?`,a=t===""?"":` of \`${t}\``;return`unknown key \`${n(e)}\`.${o} Valid keys${a}: ${r.join(", ")}.`},ee=(e,t,r,n)=>{const i=Z(e,n),o=Ae(i);if(i===void 0||o===void 0)return[];const a=i.getText(),l=a.length>40?`${a.slice(0,37)}...`:a;if(!t.accepts.includes(o))return[`\`${r}\` must be ${t.expected}, got ${Ne[o]} (${l}).`];if(t.literal!==void 0&&o==="boolean"&&b(i)!==t.literal)return[`\`${r}\` must be ${t.expected}, got \`${a}\`.${t.hint===void 0?"":` ${t.hint}`}`];if(t.items!==void 0&&s.isArrayLiteralExpression(i)){const{items:c}=t,d=i.getElements(),f=d.findIndex(O=>s.isSpreadElement(O));return(f===-1?d:d.slice(0,f)).flatMap((O,ne)=>ee(O,c,`${r}[${String(ne)}]`,n))}return s.isObjectLiteralExpression(i)&&(t.keys!==void 0||t.entries!==void 0)?R(i,t,r,n):[]},Pe=(e,t,r)=>{const n=(e.required??[]).filter(i=>!t.has(i));return n.length===0?[]:[`\`${r}\` is missing ${n.map(i=>`\`${i}\``).join(", ")}.`]},R=(e,t,r,n,i=!1)=>{const o=e.getProperties(),a=f=>s.isSpreadAssignment(f)?void 0:ae(f.getNameNode()),l=!i&&o.every(f=>a(f)!==void 0),c=[],d=new Map(o.map(f=>[a(f),f]));for(const f of o){const y=a(f);if(y===void 0)continue;const O=t.entries??(t.keys!==void 0&&Object.hasOwn(t.keys,y)?t.keys[y]:void 0);O===void 0?c.push(je(y,r,Object.keys(t.keys??{}))):c.push(...Te(f,O,r===""?y:`${r}.${y}`,n,l&&d.get(y)===f))}return l?[...c,...Pe(t,d,r)]:c},Te=(e,t,r,n,i)=>{if(s.isGetAccessorDeclaration(e)||s.isSetAccessorDeclaration(e))return[];if(i)return ee(_(e),t,r,n);const o=Z(_(e),n);return o!==void 0&&s.isObjectLiteralExpression(o)&&(t.keys!==void 0||t.entries!==void 0)?R(o,t,r,n,!0):[]},ke=e=>s.isInterfaceDeclaration(e)||s.isTypeAliasDeclaration(e)||s.isExportSpecifier(e)&&(e.isTypeOnly()||e.getExportDeclaration().isTypeOnly()),$e=e=>e.getExportSymbols().filter(t=>{const r=t.getDeclarations();return r.length===0||!r.every(n=>ke(n))}).map(t=>t.getName()),Ie=(e,t,r)=>{if(t.getExportSymbols().some(c=>c.getName()==="default"))return;const n=$e(t),i=t.getExportDeclarations().filter(c=>c.isNamespaceExport()&&c.getNamespaceExport()===void 0&&!c.isTypeOnly()).map(c=>c.getModuleSpecifierValue()).filter(c=>c!==void 0);if(n.length===0&&i.length===0)return;if(n.length===0)return`${e} has no default export, so none of its settings are read (it only re-exports ${i.map(c=>`\`${c}\``).join(", ")} with \`export *\`, which never forwards a default). Lunora reads only the default export, and codegen reads its settings from this file without loading the modules it imports: move them here as \`export default { … } satisfies LunoraConfig\`.`;const o=n.filter(c=>r.has(c)),a=n.filter(c=>{const d=u(T(t,c));return!r.has(c)&&d!==void 0&&s.isObjectLiteralExpression(d)});let l="`export default { … } satisfies LunoraConfig`";return o.length>0?l=`\`export default { ${o.join(", ")} } satisfies LunoraConfig\``:a.length===1&&(l=`\`export default ${String(a[0])};\` in place of the named export`),`${e} has no default export, so none of its settings are read (it exports ${n.map(c=>`\`${c}\``).join(", ")}). Lunora reads only the default export: ${l}.`},te=e=>{const t=e.getExportAssignments().find(i=>!i.isExportEquals()),r=e.getExportDeclarations().filter(i=>!i.hasModuleSpecifier()&&!i.isTypeOnly()).flatMap(i=>i.getNamedExports()).find(i=>(i.getAliasNode()?.getText()??i.getName())==="default"),n=t===void 0&&r!==void 0?r.getNameNode():u(t?.getExpression());return n!==void 0&&s.isIdentifier(n)?u(T(e,n.getText())):n},Ce=e=>{const t=te(e);return t!==void 0&&s.isObjectLiteralExpression(t)?t:void 0},De=e=>{const t=te(e);if(t!==void 0)return s.isArrayLiteralExpression(t)?"an array":s.isStringLiteral(t)||s.isNoSubstitutionTemplateLiteral(t)||s.isTemplateExpression(t)?"a string":s.isNumericLiteral(t)?"a number":b(t)!==void 0?"a boolean":s.isNullLiteral(t)?"null":void 0},m=(e,t)=>s.isPropertyAssignment(e)?e.getInitializer():T(t,h(e)),x=(e,t,r)=>{const n=u(e);if(n===void 0||!s.isObjectLiteralExpression(n))return{unreadable:!0};const i=n.getProperties(),o=i.filter(c=>s.isPropertyAssignment(c)&&!s.isComputedPropertyName(c.getNameNode())||s.isShorthandPropertyAssignment(c));if(o.length!==i.length)return{unreadable:!0};const a=o.findLast(c=>h(c)===r);if(a===void 0)return{absent:!0};const l=m(a,t);return l===void 0?{unreadable:!0}:{literal:l}},z=["exportName","file","reason","rule"],ze=e=>{const t=u(e);if(t===void 0||!s.isObjectLiteralExpression(t))return;const r={};for(const l of t.getProperties()){if(!s.isPropertyAssignment(l)||s.isComputedPropertyName(l.getNameNode()))return;const c=h(l),d=u(l.getInitializer());if(!z.includes(c)||d===void 0||!s.isStringLiteral(d)&&!s.isNoSubstitutionTemplateLiteral(d))return;r[c]=d.getLiteralValue()}const{exportName:n,file:i,reason:o,rule:a}=r;return n?.trim()&&i?.trim()&&o?.trim()&&a?.trim()?{exportName:n,file:i,reason:o,rule:a}:void 0},we=(e,t)=>{const r=x(e,t,"accept");if("absent"in r)return{};const n="literal"in r?u(r.literal):void 0;if(n===void 0||!s.isArrayLiteralExpression(n))return{acceptUnreadable:!0};const i=[];for(const o of n.getElements()){const a=ze(o);if(a===void 0)return{acceptUnreadable:!0};i.push(a)}return{accept:i}},Me=(e,t)=>{const r=x(e,t,"minSeverity"),n=we(e,t);return"absent"in r?{advisor:n}:"literal"in r&&s.isStringLiteral(r.literal)?{advisor:{...n,minSeverity:r.literal.getLiteralValue()}}:{advisor:{...n,unreadable:!0}}},Re=(e,t)=>{const r=x(e,t,"exclude");if("absent"in r)return{};if(!("literal"in r)||!s.isArrayLiteralExpression(r.literal))return{unreadable:!0};const n=[];for(const i of r.literal.getElements()){if(!s.isStringLiteral(i)&&!s.isNoSubstitutionTemplateLiteral(i)||i.getLiteralValue().startsWith("!"))return{unreadable:!0};n.push(i.getLiteralValue())}return{exclude:n}},Ve=(e,t,r)=>{const n=x(e,t,"lazyFunctions");if("absent"in n)return{};if("unreadable"in n)return e!==void 0&&(s.isIdentifier(e)||e.getText().includes("lazyFunctions")||r&&!s.isObjectLiteralExpression(e))?{lazyFunctionsUnreadable:!0}:{};const i="literal"in n?u(n.literal):void 0,o=i===void 0?void 0:b(i);return o===void 0?{lazyFunctionsUnreadable:!0}:{lazyFunctions:o}},_e=(e,t)=>{const r=u(e),n=r!==void 0&&s.isIdentifier(r),i=r!==void 0&&s.isIdentifier(r)?t.getVariableDeclaration(r.getText()):void 0,o=i?.getVariableStatement()?.getDeclarationKind()===J.Const,a=i?.getNameNode(),c=i!==void 0&&o&&a!==void 0&&s.isIdentifier(a)&&a.findReferencesAsNodes().length===1?u(i.getInitializer())??r:r;return{codegen:{...Re(c,t),...Ve(c,t,n)}}},Ue=(e,t)=>{const r=x(e,t,"merge");if("absent"in r)return{durableObjects:{}};const n="literal"in r?b(r.literal):void 0;return n===void 0?{durableObjects:{unreadable:!0}}:{durableObjects:{merge:n}}},Fe=(e,t)=>{const r=x(e,t,"companion");if("absent"in r)return{studio:{}};const n="literal"in r?b(r.literal):void 0;return n===void 0?{studio:{unreadable:!0}}:{studio:{companion:n}}},Ke=(e,t)=>{const r=x(e,t,"headers");if("absent"in r)return{security:{}};const n="literal"in r?S(r.literal):g;return n===g?{security:{unreadable:!0}}:{security:{headers:n}}},re=(e,t)=>{const r=e.getProperty(t);if(r!==void 0)return(s.isPropertyAssignment(r)?r.getInitializer():void 0)??"unreadable"},U=(e,t)=>{const r=re(e,t);if(r!==void 0)return r!=="unreadable"&&(s.isStringLiteral(r)||s.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():!1},Ye=e=>{const t=re(e,"rpc");if(t!==void 0)return t!=="unreadable"&&b(t)===!1?!1:"unreadable"},He=e=>{const t=u(e);if(t===void 0||!s.isObjectLiteralExpression(t))return{services:{unreadable:!0}};const r={};for(const n of t.getProperties()){if(!s.isPropertyAssignment(n)||s.isComputedPropertyName(n.getNameNode()))return{services:{unreadable:!0}};const i=u(n.getInitializer());if(i===void 0||!s.isObjectLiteralExpression(i)||i.getProperties().some(c=>!s.isPropertyAssignment(c)))return{services:{unreadable:!0}};const o=U(i,"dir"),a=U(i,"entrypoint"),l=Ye(i);if(typeof o!="string"||a===!1||l==="unreadable")return{services:{unreadable:!0}};r[h(n)]={dir:o,...a===void 0?{}:{entrypoint:a},...l===void 0?{}:{rpc:l}}}return{services:{declared:r}}},Ge=(e,t)=>s.isShorthandPropertyAssignment(e)?e.getNameNode():m(e,t),Be=(e,t)=>{const r=m(e,t);return r!==void 0&&s.isStringLiteral(r)?{target:r.getLiteralValue()}:{unreadable:!0}},Je=(e,t)=>{const r=u(m(e,t)),n=r===void 0?void 0:b(r);return n!==void 0?{remote:n}:r!==void 0&&s.isNullLiteral(r)?{}:r!==void 0&&s.isObjectLiteralExpression(r)?{remote:!0}:{unreadable:!0}},A=new Map([["advisor",{read:(e,t)=>Me(m(e,t),t),shape:v({accept:{...D,expected:"an array of objects",items:v(Object.fromEntries(z.map(e=>[e,E])),z)},minSeverity:E}),unreadable:{advisor:{unreadable:!0}}}],["app",{read:()=>({}),shape:xe,unreadable:{}}],["codegen",{read:(e,t)=>_e(Ge(e,t),t),shape:v({exclude:D,lazyFunctions:N}),unreadable:{codegen:{lazyFunctionsUnreadable:!0,unreadable:!0}}}],["durableObjects",{read:(e,t)=>Ue(m(e,t),t),shape:v({merge:N}),unreadable:{durableObjects:{unreadable:!0}}}],["remote",{read:Je,shape:{accepts:["boolean","null","object"],expected:"a boolean"},unreadable:{unreadable:!0}}],["security",{read:(e,t)=>Ke(m(e,t),t),shape:v({headers:Se}),unreadable:{security:{unreadable:!0}}}],["services",{read:(e,t)=>He(m(e,t)),shape:{accepts:["object"],entries:v({dir:E,entrypoint:E,rpc:{accepts:["boolean"],expected:"`false`",hint:"Leave it out for an RPC binding.",literal:!1}},["dir"]),expected:"an object"},unreadable:{services:{unreadable:!0}}}],["studio",{read:(e,t)=>Fe(m(e,t),t),shape:v({companion:N}),unreadable:{studio:{unreadable:!0}}}],["target",{read:Be,shape:E,unreadable:{unreadable:!0}}]]),We=(e,t)=>s.isGetAccessorDeclaration(e)||s.isMethodDeclaration(e)?A.get(h(e))?.unreadable??{}:!s.isPropertyAssignment(e)&&!s.isShorthandPropertyAssignment(e)?{}:A.get(h(e))?.read(e,t)??{},qe=(e,t)=>new oe({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(j(e),t,{overwrite:!0}),Qe=(e,t)=>{if(e.getProperties().some(n=>s.isSpreadAssignment(n))){const n=o=>e.getProperties().some(a=>!s.isSpreadAssignment(a)&&h(a)===o);let i={unreadable:!0};for(const[o,a]of A)n(o)&&(i={...i,...a.unreadable});return i}let r={};for(const n of e.getProperties())r={...r,...We(n,t)};return r},Xe=(e,t)=>{const r=qe(e,t),n=Ce(r);if(n===void 0){const o=De(r),a=o===void 0?Ie(j(e),r,A):`${j(e)} exports ${o} as its default, so none of its settings are read. Lunora reads an object: \`export default { … } satisfies LunoraConfig\`.`;return{literals:{unreadable:!0},...o===void 0?{namedOnly:a}:{notObject:a},problems:a===void 0?[]:[a]}}const i=v(Object.fromEntries([...A].map(([o,a])=>[o,a.shape])));return{literals:Qe(n,r),problems:R(n,i,"",r)}},F=new Map,P=e=>{let t;try{t=se(e,"utf8")}catch{return{literals:{unreadable:!0},problems:[]}}const r=F.get(e);if(r?.source===t)return r.value;const n=Xe(e,t);return F.set(e,{source:t,value:n}),n},K=new Map,at=async e=>{const t=W(e);if(t===void 0)return{};let r;try{const o=B(t);r=`${String(o.mtimeMs)}:${String(o.size)}`}catch{return{}}const n=K.get(t);if(n?.key===r)return n.value;const i=(async()=>{try{const a=(await ie(t,{interopDefault:!1,moduleCache:!1}).import(t))?.default,l=a===void 0?P(t).namedOnly:void 0;return l!==void 0?{error:l}:a!==void 0&&(a===null||typeof a!="object"||Array.isArray(a))?{error:P(t).notObject??`${j(t)}'s default export is not an object, so none of its settings are read. Lunora reads an object: \`export default { … } satisfies LunoraConfig\`.`}:{config:a}}catch(o){return{error:o instanceof Error?o.message:String(o)}}})();return K.set(t,{key:r,value:i}),i},k=e=>P(e).literals,ct=e=>P(e).problems,Ze=e=>{const t=W(e);return t===void 0?{}:k(t)},lt=e=>{const{durableObjects:t}=Ze(e);return t?.unreadable&&console.warn("@lunora/codegen: `durableObjects.merge` in lunora.config is not a boolean literal — the Durable Object classes stay separate."),t?.merge===!0};let Y;const ut=e=>{const t=w(e),{codegen:r}=t===void 0?{}:k(t);if(r?.lazyFunctionsUnreadable){const n=t===void 0?void 0:B(t,{throwIfNoEntry:!1}),i=t===void 0||n===void 0?"":`${t}:${String(n.mtimeMs)}:${String(n.size)}`;i!==Y&&(Y=i,console.warn("@lunora/codegen: `codegen.lazyFunctions` in lunora.config is not a boolean literal, so the config does not turn the function registry lazy."))}return r?.lazyFunctions===!0},H=new Set,dt=e=>{const t=w(e),{studio:r}=t===void 0?{}:k(t);return r?.unreadable&&t!==void 0&&!H.has(t)&&(H.add(t),console.warn("@lunora/codegen: `studio.companion` in lunora.config is not a boolean literal, so the companion Worker is not generated.")),r?.companion===!0},G=new Set,et=(e,t,r)=>{let n;r!==void 0?{problems:n}=r:t.unreadable&&t.security===void 0?n=["is not an object literal codegen can read, so `security.headers` cannot be read either"]:n=["`security.headers` is not built from literals"];const i=`${e??""}:${n.join(";")}`;return G.has(i)||(G.add(i),console.warn(`@lunora/codegen: lunora.config ${n.join("; ")}, so the default security headers apply.`)),!0},ft=e=>{const t=w(e),r=t===void 0?{}:k(t),{security:n}=r,o=n?.unreadable===!0||r.unreadable===!0&&n===void 0?void 0:pe(n?.headers);return o?.ok?o.value:et(t,r,o)};export{g as N,dt as a,at as b,ut as c,ft as d,lt as e,S as l,ct as p,Ze as r};
@@ -0,0 +1 @@
1
+ import{Node as e}from"ts-morph";const i=t=>{if(e.isStringLiteral(t)||e.isNoSubstitutionTemplateLiteral(t)||e.isNumericLiteral(t))return t.getLiteralText();if(e.isComputedPropertyName(t)){const r=t.getExpression();return e.isStringLiteral(r)||e.isNoSubstitutionTemplateLiteral(r)?r.getLiteralText():void 0}return t.getText()},s=t=>i(t)??t.getText(),p=t=>s(t.getNameNode());export{p as a,s as p,i as s};
@@ -0,0 +1 @@
1
+ import{d as E}from"./declared-output-Iaar469J.mjs";import{v as u}from"./shared-Cn7dMQ_u.mjs";const p=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,l=/^(?:\.\.?\/)*_generated\//u,i=/\.[A-Za-z]\w*$/u,R=t=>t.replaceAll(p,(e,r)=>{const o=r.replace(l,"./");return`import("${i.test(o)?o:`${o}.js`}")`}),_=/import\("(?<spec>[^"]+)"\)/gu,a="node_modules/",m=/^@types\//u,A=t=>t.replaceAll(_,(e,r)=>{const o=r.lastIndexOf(a);if(o===-1||o>0&&r[o-1]!=="/")return e;const s=r.slice(o+a.length);return s===""||m.test(s)?e:`import("${s}")`}),I=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,f=/^(?:\.\.?\/)+/u,g=t=>{const e=[];for(const r of t.split("/"))if(!(r===""||r===".")){if(r===".."&&e.length>0&&e.at(-1)!==".."){e.pop();continue}e.push(r)}return e.join("/")},S=(t,e)=>t.replaceAll(I,(r,o)=>{if(l.test(o.replace(f,"")))return r;const s=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",c=`../${g(`${s}/${o}`)}`;return`import("${i.test(c)?c:`${c}.js`}")`}),v=(t,e)=>R(S(A(t),e)),d=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],L=new RegExp(String.raw`import\("@lunora/(?<pkg>${d.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),T={flags:new Set(["/web"]),platform:new Set},M=(t,e)=>e?t.replaceAll(L,(r,o,s)=>{const n=T[o];return s&&n&&!n.has(s)?r:`import("lunorash/${o}${s??""}")`}):t,O=t=>["Doc","Id"].filter(e=>new RegExp(String.raw`(?<![.$\w])${e}<`,"u").test(t)),U=t=>E(t)?u(t.output):t.returnType;export{O as a,M as b,U as c,v as r};
@@ -0,0 +1 @@
1
+ import{join as r}from"node:path";import{readJsonSync as a}from"@visulima/fs";const p=o=>{try{const t=a(r(o,"package.json")),n=new Set;for(const c of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){const e=t[c];if(e!==null&&typeof e=="object")for(const s of Object.keys(e))n.add(s)}return n}catch{return}};export{p as default};
@@ -0,0 +1 @@
1
+ const s=/[\w+/=-]{40,}/u,n=/[a-z]/u,E=/[A-Z]/u,_=/\d/u,c=/\b(?:[\da-f]{32,}|[\dA-F]{32,})\b/u,o=t=>{const e=s.exec(t)?.[0];return e===void 0?!1:n.test(e)&&E.test(e)&&_.test(e)},i=t=>c.test(t),r=/\b(?:sk|rk)_live_[\dA-Za-z]{20,}/u,a=/\bAKIA[\dA-Z]{16}\b/u,R=/\bgh[posru]_[\dA-Za-z]{36,}/u,d=/\bsk-[\dA-Za-z]{32,}/u,A=/\bxox[abprs]-[\dA-Za-z-]{10,}/u,k=/-----BEGIN(?: [A-Z]+)? PRIVATE KEY-----/u,S=[{kind:"stripe_live_key",test:t=>r.test(t)},{kind:"aws_access_key",test:t=>a.test(t)},{kind:"github_token",test:t=>R.test(t)},{kind:"openai_key",test:t=>d.test(t)},{kind:"slack_token",test:t=>A.test(t)},{kind:"private_key",test:t=>k.test(t)},{kind:"high_entropy",test:o},{kind:"hex_secret",test:i}],u=new Set(["hex_secret","high_entropy"]),h=new Set(["auth","bearer","credential","credentials","hmac","key","keys","passphrase","password","private","secret","secrets","signature","signing","token"]),p=/([a-z\d])([A-Z])/gu,T=/[^A-Za-z\d]+/u,I=t=>t.replaceAll(p,"$1 $2").split(T).filter(Boolean).map(e=>e.toLowerCase()),l=t=>t!==void 0&&I(t).some(e=>h.has(e)),K=t=>S.find(e=>e.test(t))?.kind,b=t=>u.has(t),g=t=>`${t.slice(0,4)}…(${String(t.length)} chars)`;export{S as SECRET_RULES,b as isHeuristicSecretKind,l as isSecretishName,g as redact,K as secretKindOf};
@@ -0,0 +1 @@
1
+ const t=new Set(["arguments","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","eval","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),i=/^[$A-Z_a-z][\w$]*$/u,a=e=>i.test(e)&&!t.has(e);export{t as R,a as i};
@@ -0,0 +1 @@
1
+ const o=d=>typeof d.shardMode=="object"&&d.shardMode.kind==="shardBy";export{o as i};
@@ -0,0 +1 @@
1
+ const o=e=>{try{return JSON.parse(e)}catch{const t=e.trim();return t.length>=2&&(t.startsWith("'")||t.startsWith('"'))&&t.at(-1)===t[0]?t.slice(1,-1):t}},n=e=>{const t={};return e.column!==void 0&&(t.column={defaultValue:e.column.hasDefault===!0?null:void 0,notNull:e.column.notNull,unique:e.column.unique}),e.inner!==void 0&&(t.inner=n(e.inner)),e.members!==void 0&&(t.members=e.members.map(a=>n(a))),e.shape!==void 0&&(t.shape=Object.fromEntries(Object.entries(e.shape).map(([a,l])=>[a,n(l)]))),e.tableName!==void 0&&(t.tableName=e.tableName),e.literalValue!==void 0&&(t.value=o(e.literalValue)),e.keyType!==void 0&&(t.keyValidator=n(e.keyType)),e.valueType!==void 0&&(t.valueValidator=n(e.valueType)),{_meta:t,kind:e.kind}},m=e=>({tables:Object.fromEntries(e.tables.map(a=>[a.name,{indexes:a.indexes,shape:Object.fromEntries(Object.entries(a.shape).map(([l,s])=>[l,n(s)]))}]))});export{m as schemaFromIr};
@@ -0,0 +1,377 @@
1
+ import{CAPABILITIES as ze}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{existsSync as W,readdirSync as ue,readlinkSync as pe,lstatSync as Ke,statSync as Ue}from"node:fs";import{join as h,relative as y,dirname as l,sep as me,isAbsolute as Je,resolve as Ye,basename as Xe}from"node:path";import{ts as c,Project as Ze}from"ts-morph";import{G as ye,a as F,u as et,d as tt}from"./shared-Cn7dMQ_u.mjs";import{p as at}from"./platform-8oj7iXQy.mjs";const he=/(?:\.d)?\.([cm]?)tsx?$/u,rt=t=>t.replace(he,".d.$1ts"),fe=(t,o)=>{const a=y(t,o).split(me).join("/").replace(he,".$1js");return a.startsWith(".")?a:`./${a}`},be=t=>t.replaceAll("\\","/"),Z=(t,o,a)=>be(h(t,rt(y(o,a)))),ot=t=>fe(".",h("services",t.name,y(l(t.wranglerPath),t.main))),nt=t=>{const o=[],a=e=>{(c.isImportDeclaration(e)||c.isExportDeclaration(e))&&e.moduleSpecifier!==void 0&&c.isStringLiteral(e.moduleSpecifier)?o.push(e.moduleSpecifier):c.isImportTypeNode(e)&&c.isLiteralTypeNode(e.argument)&&c.isStringLiteral(e.argument.literal)&&o.push(e.argument.literal),c.forEachChild(e,a)};return a(t),o},x=t=>{const{ctimeMs:o,mtimeMs:a,size:e}=Ue(t);return`${String(a)}:${String(o)}:${String(e)}`},st=new Set([".git",".wrangler","dist","node_modules","target"]),ge=t=>ue(t,{withFileTypes:!0}).flatMap(o=>{const a=h(t,o.name);return o.isSymbolicLink()?[`${a}->${pe(a)}`]:o.isDirectory()&&o.name.startsWith("@")?[`${a}:${x(a)}`,...ge(a)]:[]}),xe=t=>[`${t}:${x(t)}`,...ge(t)],Te=t=>{const o=h(t,"node_modules"),a=W(o)?xe(o):[],e=l(t);return e===t?a:[...a,...Te(e)]},it=(t,o)=>{const a=[];try{const e=n=>{for(const s of ue(n,{withFileTypes:!0})){const d=h(n,s.name);if(d!==o)if(s.isSymbolicLink())a.push(`${d}->${pe(d)}`);else if(s.isDirectory()){if(s.name==="node_modules")a.push(...xe(d));else if(!st.has(s.name)){if(!Ke(d).isDirectory())throw new Error(`${d} changed during the scan`);e(d)}}else a.push(`${d}:${x(d)}`)}};e(t),a.push(...Te(t))}catch{return}return[...new Set(a)].toSorted((e,n)=>e.localeCompare(n)).join(`
2
+ `)},dt=t=>Xe(l(t)).startsWith("@")?l(l(t)):l(t),de=(t,o)=>!y(o,t).startsWith("..")&&!t.split(me).includes("node_modules"),le=(t,o)=>{const a=[];let e=t;for(;e!==l(e)&&!W(h(e,"package.json"));)a.push(e),e=l(e);if(W(h(e,"package.json"))){for(const n of[...a,e,h(e,"package.json")])o.add(n);return e}},lt=(t,o,a)=>{let e=t;for(;y(e,o).startsWith("..")&&e!==l(e);)a.add(e),e=l(e);a.add(e)},ct=(t,o)=>{const a=new Set;t.some(e=>de(e,o))&&le(o,a);for(const e of t){if(de(e,o)){for(let s=l(e);s!==o&&s!==l(s);s=l(s))a.add(s);continue}const n=le(l(e),a);n===void 0?lt(l(e),o,a):a.add(dt(n))}return[...a].map(e=>[e,x(e)])},ve=new Map,ce=([t,o])=>{try{return x(t)===o}catch{return!1}},ut=(t,o,a)=>{const e=ve.get(t);return e?.optionsKey===o&&e.stamps.every(s=>ce(s))&&e.directories.every(s=>ce(s))&&a!==void 0&&e.tree===a?e.files:void 0},pt=(t,o,a)=>{const e=[...o.stamps,...o.directories].every(([,n])=>Math.floor(Number.parseFloat(n))<=a);o.tree!==void 0&&e&&ve.set(t,{...o,tree:o.tree})},mt=(t,o)=>({directories:ct(o,t),stamps:o.map(a=>[a,x(a)])}),wt=(t,o)=>{const a=l(t.wranglerPath),e=y(a,t.main);if(e.startsWith("..")||Je(e))throw new Error(`@lunora/codegen: service "${t.name}": its entry module (${t.main}) must be inside ${a} to be typed as RPC`);const n=h(o,"services",t.name),s=c.findConfigFile(a,i=>c.sys.fileExists(i)),d=new Ze({compilerOptions:{composite:!1,declaration:!0,declarationMap:!1,emitDeclarationOnly:!0,incremental:!1,noEmit:!1,noEmitOnError:!1,outDir:n,rootDir:a},skipAddingFilesFromTsConfig:!0,...s===void 0?{}:{tsConfigFilePath:s}}),S=JSON.stringify([t.name,t.main,t.wranglerPath,o]),m=JSON.stringify(d.getCompilerOptions()),T=it(a,Ye(o)),v=ut(S,m,T);if(v!==void 0)return v;const w=Date.now();d.addSourceFileAtPath(t.main),d.resolveSourceFileDependencies();const P=d.getProgram().compilerObject.getSourceFiles().map(i=>i.fileName).filter(i=>W(i)),{directories:$,stamps:j}=mt(a,P),O={...d.getCompilerOptions(),preserveSymlinks:!0},u=new Map(d.getSourceFiles().map(i=>i.getFilePath()).filter(i=>!i.endsWith(".d.ts")&&!y(a,i).startsWith("..")).map(i=>[Z(n,a,i),i])),f={};for(const i of d.emitToMemory({emitOnlyDtsFiles:!0}).getFiles()){const R=u.get(be(i.filePath));if(R===void 0)continue;const B=c.createSourceFile(i.filePath,i.text,c.ScriptTarget.Latest,!1);let{text:b}=i;for(const g of nt(B).toReversed()){const I=c.resolveModuleName(g.text,R,O,c.sys).resolvedModule?.resolvedFileName;if(I===void 0)continue;const k=Z(n,a,I),N=u.has(k)?k:I;b=`${b.slice(0,g.getStart(B))}${JSON.stringify(fe(l(i.filePath),N))}${b.slice(g.getEnd())}`}f[y(o,i.filePath)]=`${ye}${b}`}if(f[y(o,Z(n,a,t.main))]===void 0)throw new Error(`@lunora/codegen: service "${t.name}": TypeScript emitted no declaration for its entry module ${t.main}`);return pt(S,{files:f,optionsKey:m,directories:$,stamps:j,tree:T},w),f},yt=(t,o=[])=>{const a=new Set;for(const e of t.tables)for(const n of Object.values(e.shape)){const s=et(n);s.kind==="storage"&&typeof s.bucket=="string"&&s.bucket!==""&&a.add(s.bucket)}for(const e of o)e!==""&&e!=="default"&&a.add(e);return["default",...[...a].toSorted((e,n)=>e.localeCompare(n))]},$t=({agents:t=[],authClaims:o=[],capabilities:a=new Set,containers:e=[],env:n,hasVectors:s=!0,hasFlags:d=!1,hasNotify:S=!1,identity:m,queues:T=[],schema:v,services:w=[],storageRuleBuckets:P=[],topics:$=[],useUmbrella:j=!1,workflows:O=[]}={})=>{const u=tt(j),f=yt(v??{tables:[]},P).map(r=>JSON.stringify(r)).join(" | "),i=r=>r.sandbox===!0?"SandboxContainerAccessor":"ContainerAccessor",R=[...new Set(e.map(r=>i(r)))].toSorted((r,p)=>r.localeCompare(p)),B=e.length>0?`import type { ${R.join(", ")} } from "@lunora/container";
3
+ `:"",b=e.length>0?`
4
+ readonly containers: {${e.map(r=>`
5
+ readonly ${r.exportName}: ${i(r)};`).join("")}
6
+ };`:"",g=[...a.has("ai")?[" /** Workers AI binding (the conventional `env.AI`), narrowing `ctx.ai`. */\n readonly AI?: unknown;"]:[],...e.map(r=>(F(r.bindingName,`container binding "${r.bindingName}"`),` /** Durable Object namespace for the \`${r.exportName}\` container. */
7
+ readonly ${r.bindingName}?: unknown;`)),...T.map(r=>(F(r.bindingName,`queue binding "${r.bindingName}"`),` /** Queue producer binding for the \`${r.exportName}\` queue. */
8
+ readonly ${r.bindingName}?: unknown;`))].join(`
9
+ `),I=`
10
+
11
+ /**
12
+ * This project's Cloudflare bindings, as far as codegen can discover them from
13
+ * \`lunora/\` source — the container/workflow Durable Object namespaces and the
14
+ * conventional Workers AI binding. Bindings the config layer reconciles from
15
+ * user-named wrangler config (R2/KV/D1/\`services\`/queues/…) aren't statically
16
+ * visible here, so the open index signature keeps them reachable (cast at the
17
+ * use site). Service bindings (\`env.<SERVICE>.fetch(...)\` / RPC stubs) live
18
+ * under this signature too — Lunora can't type a third-party worker's RPC
19
+ * surface, so treat them as \`Fetcher\`/\`Service<unknown>\` and cast.
20
+ */
21
+ export interface CloudflareBindings {
22
+ readonly [binding: string]: unknown;${g?`
23
+ ${g}`:""}
24
+ }
25
+
26
+ /** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
27
+ export type Env = CloudflareBindings;`,k=r=>ze.map(p=>p.tier!==void 0&&r.includes(p.tier)&&a.has(p.key)?p.serverCtxField:"").join(""),N=k(["every"]),we=k(["every","action"]),D=s&&(v?.vectorIndexes.length??0)>0,E=D?' | "vectors"':"",ee=D?`
28
+ readonly vectors: VectorSearch<VectorIndexName>;`:"",$e=D?`
29
+ readonly vectors: VectorSearchReader<VectorIndexName>;`:"",Ie=D?`import type { VectorSearch, VectorSearchReader } from "${u.server}";
30
+ import type { VectorIndexName } from "./dataModel.js";
31
+ `:"",Q=d?`
32
+ /** Feature-flag evaluation (OpenFeature). Reads are memoized per request; evaluations never throw — a provider error resolves to the supplied default. */
33
+ readonly flags: import("${u.flags}").LunoraFlags;`:"",q=S?`
34
+ /** Multi-channel notifications (@lunora/notify): send / chat / inApp / webhook plus the push device sub-facade. Sends are external I/O — confine them to action handlers. */
35
+ readonly notify: import("@lunora/notify").LunoraNotify;
36
+ /** Device push sub-facade — the same object as ctx.notify.push (register / send / broadcast). Sends belong in action handlers. */
37
+ readonly push: import("@lunora/notify").LunoraPush;`:"",M=O.length>0,ke=M?`import type { WorkflowHandle } from "@lunora/workflow";
38
+ import type * as lunoraWorkflowDefinitions from "../workflows.js";
39
+ `:"",Se=M?`
40
+
41
+ /** Params type carried by a \`defineWorkflow\` definition (its phantom \`__params\`). */
42
+ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params }
43
+ ? unknown extends Params
44
+ ? Record<string, unknown>
45
+ : NonNullable<Params>
46
+ : Record<string, unknown>;
47
+
48
+ /** This project's declared workflows, addressable from \`ctx.workflows\` by their \`lunora/workflows.ts\` export name. */
49
+ export interface LunoraWorkflows {
50
+ ${O.map(r=>` get(name: ${JSON.stringify(r.exportName)}): WorkflowHandle<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${r.exportName}>>;`).join(`
51
+ `)}
52
+ }`:"",te=M?' | "workflows"':"",ae=M?`
53
+ readonly workflows: LunoraWorkflows;`:"",L=at(T),_=L.length>0,V=$.length>0,G=[..._?["QueueProducer"]:[],...V?["TopicPublisher"]:[]],re=[...new Set([...L,...$].map(r=>r.filePath))].toSorted((r,p)=>+(p==="queues")-+(r==="queues")||r.localeCompare(p)),H=r=>r==="queues"?"lunoraQueueDefinitions":`lunoraQueueDefinitions${String(re.indexOf(r))}`,Oe=G.length>0?`import type { ${G.join(", ")} } from "@lunora/queue";
54
+ ${re.map(r=>`import type * as ${H(r)} from "../${r}.js";
55
+ `).join("")}`:"",Re=G.length>0?"\n\n/** Message body type carried by a `defineQueue` / `defineTopic` definition (its phantom `__lunoraBody`). */\ntype QueueBodyOf<Definition> = Definition extends { __lunoraBody?: infer Body } ? (unknown extends Body ? unknown : NonNullable<Body>) : unknown;":"",Be=_?`
56
+
57
+ /** This project's declared queues, addressable from \`ctx.queues\` by their \`lunora/queues.ts\` export name. */
58
+ export interface LunoraQueues {
59
+ ${L.map(r=>` readonly ${r.exportName}: QueueProducer<QueueBodyOf<typeof ${H(r.filePath)}.${r.exportName}>>;`).join(`
60
+ `)}
61
+ }`:"",Ne=V?`
62
+
63
+ /** This project's declared topics, addressable from \`ctx.topics\` by their \`lunora/queues.ts\` export name. */
64
+ export interface LunoraTopics {
65
+ ${$.map(r=>` readonly ${r.exportName}: TopicPublisher<QueueBodyOf<typeof ${H(r.filePath)}.${r.exportName}>>;`).join(`
66
+ `)}
67
+ }`:"",De=`${Re}${Be}${Ne}`,oe=_?`
68
+ readonly queues: LunoraQueues;`:"",ne=V?`
69
+ readonly topics: LunoraTopics;`:"",z=w.length>0,se=w.filter(r=>r.rpcEntrypoint!==void 0),Me=se.length>0?"ServiceFetcher, ServiceRpc":"ServiceFetcher",Ce=z?`import type { ${Me} } from "${u.server}";
70
+ ${se.map(r=>`import type * as lunoraService_${r.name} from ${JSON.stringify(ot(r))};
71
+ `).join("")}`:"",Ae=z?`
72
+
73
+ /** This project's service bindings (\`lunora.config\` \`services\`), addressable from \`ctx.services\` in actions. */
74
+ export interface LunoraServices {
75
+ ${w.map(r=>{F(r.name,`service "${r.name}"`);const p=r.rpcEntrypoint===void 0?"ServiceFetcher":`ServiceRpc<typeof lunoraService_${r.name}.${r.rpcEntrypoint}>`;return` readonly ${r.name}: ${p};`}).join(`
76
+ `)}
77
+ }`:"",Fe=z?`
78
+ readonly services: LunoraServices;`:"",K=t.length>0,We=K?`import type { AgentHandle } from "@lunora/agent/core";
79
+ `:"",Pe=K?`
80
+
81
+ /** This project's declared agents, addressable from \`ctx.agents\` by their \`lunora/agents.ts\` export name. */
82
+ export interface LunoraAgents {
83
+ ${t.map(r=>(F(r.exportName,`agent export "${r.exportName}"`),` readonly ${r.exportName}: AgentHandle;`)).join(`
84
+ `)}
85
+ }`:"",ie=K?`
86
+ readonly agents: LunoraAgents;`:"",C=m!==void 0||o.length>0,je=m?`import type { InferIdentity } from "${u.server}";
87
+ import type * as lunoraIdentityContract from "../identity.js";
88
+ `:"",Ee=m===void 0&&o.length>0?`import type { SessionIdentity } from "@lunora/auth";
89
+ `:"",Qe=je+Ee,qe=o.length===0?"":`
90
+
91
+ /** App-declared user columns the session forwards as claims (\`user.additionalFields\` of \`.auth()\`). Optional: a user whose column is unset never carries it. */
92
+ export type AuthClaims = {
93
+ ${o.map(r=>` ${r.name}?: ${r.type};`).join(`
94
+ `)}
95
+ };`;let A;m===void 0?A="export type Identity = SessionIdentity & AuthClaims & Record<string, unknown>;":o.length===0?A=`export type Identity = InferIdentity<typeof lunoraIdentityContract.${m.exportName}>;`:A=`type DeclaredIdentity = InferIdentity<typeof lunoraIdentityContract.${m.exportName}>;
96
+ export type Identity = DeclaredIdentity & Omit<AuthClaims, keyof DeclaredIdentity>;`;const Le=o.length===0?"/** This app's declared identity claim contract (\\`defineIdentity\\` in \\`lunora/identity.ts\\`) — the typed shape of \\`ctx.auth.getIdentity()\\`, the RLS policy \\`ctx.auth.identity\\`, and the \\`authorizeShard\\`/\\`authorizeFanOut\\` identity argument. */":"/** This app's identity: the declared claim contract (\\`defineIdentity\\` in \\`lunora/identity.ts\\`) and the user-column claims, the typed shape of \\`ctx.auth.getIdentity()\\`, the RLS policy \\`ctx.auth.identity\\`, and the \\`authorizeShard\\`/\\`authorizeFanOut\\` identity argument. */",_e=C?`${qe}
97
+
98
+ ${Le}
99
+ ${A}
100
+
101
+ /** \`ctx.auth\` narrowed so \`getIdentity()\` resolves the declared {@link Identity} instead of the untyped claim bag. */
102
+ type NarrowedAuth = Omit<QueryCtxBase["auth"], "getIdentity"> & { getIdentity: () => Promise<Identity | null> };`:"",U=C?' | "auth"':"",J=C?`
103
+ readonly auth: NarrowedAuth;`:"",Ve=C?", Identity":"",Ge=n?`import type * as lunoraEnvContract from "../env.js";
104
+ `:"",He=n?`
105
+
106
+ /** This app's declared env contract (\`defineEnv\` in \`lunora/env.ts\`) — the validated, coercion-aware shape of \`ctx.env\`. */
107
+ export type LunoraEnv = ReturnType<typeof lunoraEnvContract.${n.exportName}>;`:"",Y=n?' | "env"':"",X=n?"\n /** Validated, typed environment declared by `defineEnv` in `lunora/env.ts` — parsed & coercion-aware config values (`ctx.env.STRIPE_KEY`); a missing or invalid value throws at read time. */\n readonly env: LunoraEnv;":"";return`${ye}import { createPolicyDsl, defineMutator as defineMutatorBase, initLunora, v as vBase } from "${u.server}";
108
+ import type {
109
+ ActionBuilder,
110
+ ActionCtx as ActionCtxBase,
111
+ ColumnValidator,
112
+ DatabaseReader,
113
+ DatabaseWriter,
114
+ EmptyArgs,
115
+ InternalActionBuilder,
116
+ InternalMutationBuilder,
117
+ InternalQueryBuilder,
118
+ MutationBuilder,
119
+ MutationCtx as MutationCtxBase,
120
+ MutationStorage,
121
+ MutatorDefinition,
122
+ QueryBuilder,
123
+ QueryCtx as QueryCtxBase,
124
+ ReadOnlyStorage,
125
+ RegisteredMutator,
126
+ Storage as StorageBase,
127
+ TableReader,
128
+ Validator,
129
+ } from "${u.server}";
130
+
131
+ import type {
132
+ DatabaseReaderFacade as DatabaseReaderFacadeOf,
133
+ DatabaseWriterFacade as DatabaseWriterFacadeOf,
134
+ LoadWith as LoadWithOf,
135
+ TableReaderFacade as TableReaderFacadeOf,
136
+ TableWriterFacade as TableWriterFacadeOf,
137
+ WithArg as WithArgOf,
138
+ } from "${u.serverDataModel}";
139
+
140
+ export type {
141
+ AggregateOp,
142
+ GroupByEntry,
143
+ OrderBy,
144
+ QueryArgs,
145
+ QueryPage,
146
+ RankPage,
147
+ RankResult,
148
+ RestrictableQueryOptions,
149
+ RestrictableQueryOptionsOf,
150
+ SearchFilterBuilder,
151
+ SearchReader,
152
+ TableAggregateOptions,
153
+ TableAggregateOptionsOf,
154
+ TableGroupByOptions,
155
+ TableGroupByOptionsOf,
156
+ TableRankOptions,
157
+ TableRankPageOptions,
158
+ Where,
159
+ WhereOf,
160
+ WhereOperators,
161
+ } from "${u.serverDataModel}";
162
+
163
+ import type { DataModel, Doc, GeoIndexNamesByTable, Id as IdOfTable, IndexNamesByTable, Insert, InsertModel, RankIndexNamesByTable, Relations, SearchIndexNamesByTable, TableName } from "./dataModel.js";
164
+ ${Ie}${B}${ke}${Oe}${Ce}${We}${Qe}${Ge}
165
+ export type { AppTableName, DataModel, Doc, Id, TableName } from "./dataModel.js";
166
+
167
+ /**
168
+ * The query-DSL bindings: \`@lunora/server/data-model\`'s generics parameterized
169
+ * over this project's \`DataModel\` / \`InsertModel\` / \`Relations\` / index maps.
170
+ *
171
+ * They live here rather than in \`dataModel.ts\` because they are the half that
172
+ * needs the SERVER package. Keeping \`dataModel.ts\` free of it lets a sibling
173
+ * package — a web app, another Worker — compile \`api.ts\` for its \`Doc\`/\`Id\`
174
+ * types without installing a server dependency to do it.
175
+ */
176
+
177
+ /** The \`with\` argument for table \`T\` — see \`@lunora/server/data-model\`. */
178
+ export type WithArg<T extends keyof DataModel> = WithArgOf<DataModel, Relations, T>;
179
+
180
+ /** \`Doc<T>\` narrowed to exactly the relations requested in the with-arg \`W\`. */
181
+ export type LoadWith<T extends keyof DataModel, W> = LoadWithOf<DataModel, Relations, T, W>;
182
+
183
+ /** Read-only typed table accessor exposed on \`QueryCtx.db.<table>\`. */
184
+ export type TableReaderFacade<T extends keyof DataModel> = TableReaderFacadeOf<DataModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, T, GeoIndexNamesByTable>;
185
+
186
+ /** Read-write typed table accessor exposed on \`MutationCtx.db.<table>\` / \`ActionCtx.db.<table>\`. */
187
+ export type TableWriterFacade<T extends keyof DataModel> = TableWriterFacadeOf<DataModel, InsertModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, T, GeoIndexNamesByTable>;
188
+
189
+ /** Per-table read facade — \`ctx.db.<table>\` on a \`QueryCtx\`. */
190
+ export type DatabaseReaderFacade = DatabaseReaderFacadeOf<DataModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, GeoIndexNamesByTable>;
191
+
192
+ /** Per-table read-write facade — \`ctx.db.<table>\` on a \`MutationCtx\` / \`ActionCtx\`. */
193
+ export type DatabaseWriterFacade = DatabaseWriterFacadeOf<DataModel, InsertModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, GeoIndexNamesByTable>;
194
+
195
+ /** Insert builder returned by \`ctx.orm.insert(table)\`. */
196
+ export interface OrmInsertBuilder<T extends keyof DataModel> {
197
+ values: (values: Insert<T>) => Promise<IdOfTable<T>>;
198
+ }
199
+
200
+ /** Replace builder returned by \`ctx.orm.replace(table, id)\` — swaps the whole document. */
201
+ export interface OrmReplaceBuilder<T extends keyof DataModel> {
202
+ with: (values: Insert<T>) => Promise<void>;
203
+ }
204
+
205
+ /** Update builder returned by \`ctx.orm.update(table, id)\` — patches the named fields. */
206
+ export interface OrmUpdateBuilder<T extends keyof DataModel> {
207
+ set: (values: Partial<Insert<T>>) => Promise<void>;
208
+ }
209
+
210
+ /** Read-only ORM surface — \`ctx.orm\` on a \`QueryCtx\`. Mirrors \`ctx.db\` reads under a kitcn-style \`query\` namespace. */
211
+ export interface OrmReader {
212
+ query: DatabaseReaderFacade;
213
+ }
214
+
215
+ /** Read-write ORM surface — \`ctx.orm\` on a \`MutationCtx\` / \`ActionCtx\`. Writes are addressed by id, like \`ctx.db\`. */
216
+ export interface OrmWriter extends OrmReader {
217
+ delete: <T extends keyof DataModel>(table: T, id: NoInfer<IdOfTable<T>>) => Promise<void>;
218
+ insert: <T extends keyof DataModel>(table: T) => OrmInsertBuilder<T>;
219
+ replace: <T extends keyof DataModel>(table: T, id: NoInfer<IdOfTable<T>>) => OrmReplaceBuilder<T>;
220
+ update: <T extends keyof DataModel>(table: T, id: NoInfer<IdOfTable<T>>) => OrmUpdateBuilder<T>;
221
+ }
222
+
223
+ /** Storage buckets this schema declares (\`v.storage("name")\`), narrowing \`ctx.storage.bucket(name)\`. */
224
+ export type StorageBucketName = ${f};${I}${Se}${De}${Ae}${Pe}${_e}${He}
225
+
226
+ /**
227
+ * Project-typed contexts. The base contexts from \`@lunora/server\` are
228
+ * untyped against the schema; here \`db\` is widened to the generated per-table
229
+ * facade (\`ctx.db.<table>.findMany(...)\`) while keeping the legacy structural
230
+ * \`db.get\`/\`db.query\` surface for back-compat, and \`storage\` is narrowed so
231
+ * \`ctx.storage.bucket(name)\` autocompletes the declared buckets.
232
+ */
233
+ /**
234
+ * The Convex-style fluent reader \`ctx.db.query(table)\`, bound to this schema:
235
+ * a table-name literal narrows the row type, so \`.collect()\` / \`.first()\` /
236
+ * \`.take()\` (and the \`.withIndex()\` / \`.filter()\` / \`.order()\` chain) resolve
237
+ * as \`Doc<table>\` with no \`as unknown as Doc<...>\` casts. The per-table accessor
238
+ * \`ctx.db.<table>\` stays available alongside it via the facade.
239
+ *
240
+ * Intersected with the wide \`(string) => TableReader\` signature so the bound
241
+ * \`ctx.db\` is still structurally assignable to schema-agnostic consumers that
242
+ * call \`db.query(someString)\` (e.g. \`@lunora/ratelimit\`'s \`createDbStore\`).
243
+ *
244
+ * The three index-name unions are what make \`.withIndex("by_TYPO")\` a compile
245
+ * error: each resolves to the table's declared names, or \`never\` when it
246
+ * declares none of that kind. Without them a renamed or dropped index left
247
+ * every call site typechecking, and the query either threw at runtime or
248
+ * degraded silently to a full table scan.
249
+ */
250
+ type TypedTableQuery = (<T extends TableName>(
251
+ table: T,
252
+ ) => TableReader<Doc<T>, IndexNamesByTable[T], SearchIndexNamesByTable[T], GeoIndexNamesByTable[T]>) &
253
+ ((table: string) => TableReader);
254
+
255
+ /**
256
+ * The point read \`ctx.db.get(table, id)\`, bound to this schema: the table literal
257
+ * fixes \`T\`, so the id must be an \`Id<T>\` and the resolved document is typed
258
+ * \`Doc<T>\` (or \`null\` when absent) with no \`as Doc<...>\` cast. Mirrors {@link TypedTableQuery}.
259
+ */
260
+ type TypedTableGet = <T extends TableName>(table: T, id: NoInfer<IdOfTable<T>>) => Promise<Doc<T> | null>;
261
+
262
+ /**
263
+ * Resolves the \`asId\` table argument: a literal in {@link TableName} passes through, a
264
+ * genuinely-wide \`string\` (a computed name) passes through, and any OTHER literal
265
+ * collapses to \`never\` so it fails to typecheck.
266
+ *
267
+ * The \`string extends T\` arm is what distinguishes "the caller passed a computed
268
+ * string" from "the caller passed a misspelled literal" — only the wide \`string\` type
269
+ * is a supertype of \`string\`.
270
+ */
271
+ type AsIdTable<T extends string> = T extends TableName ? T : string extends T ? T : never;
272
+
273
+ /**
274
+ * The id parse boundary \`ctx.db.asId(table, id)\`, bound to this schema: a misspelled
275
+ * table literal is a compile error rather than a call that hands back a confidently-
276
+ * branded id for a table that does not exist. Mirrors {@link TypedTableQuery} /
277
+ * {@link TypedTableGet}.
278
+ *
279
+ * Deliberately NOT an intersection with a wide \`(string, string) => string\` overload:
280
+ * overload resolution would fall through to it for a bad literal, silently restoring
281
+ * the very typo hole this narrowing exists to close. {@link AsIdTable} instead keeps a
282
+ * computed table name working — and keeps \`ctx.db\` structurally assignable to
283
+ * schema-agnostic consumers — without accepting an invalid literal.
284
+ */
285
+ type TypedAsId = <T extends string>(tableName: AsIdTable<T>, id: string) => IdOfTable<T & TableName>;
286
+
287
+ export interface QueryCtx extends Omit<QueryCtxBase, "db" | "storage"${E}${U}${Y}> {
288
+ readonly db: Omit<DatabaseReader, "asId" | "query" | "get"> & DatabaseReaderFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
289
+ readonly orm: OrmReader;
290
+ readonly storage: ReadOnlyStorage<StorageBucketName>;${$e}${N}${Q}${q}${X}${J}
291
+ }
292
+
293
+ export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${E}${te}${U}${Y}> {
294
+ readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
295
+ readonly orm: OrmWriter;
296
+ readonly storage: MutationStorage<StorageBucketName>;${ee}${N}${Q}${q}${X}${ae}${oe}${ne}${ie}${J}
297
+ }
298
+
299
+ export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${E}${te}${U}${Y}> {
300
+ readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
301
+ readonly orm: OrmWriter;
302
+ readonly storage: StorageBase<StorageBucketName>;${ee}${we}${b}${Q}${q}${Fe}${X}${ae}${oe}${ne}${ie}${J}
303
+ }
304
+
305
+ /**
306
+ * Procedure builders bound to this project's typed contexts. Chain
307
+ * \`.input({...})\` to declare args, \`.use(middleware)\` for rate limiting / RLS /
308
+ * masking (each middleware may refine \`ctx\`), then the terminal
309
+ * \`.query()\` / \`.mutation()\` / \`.action()\` with a \`({ ctx, args }) => ...\`
310
+ * handler. \`.output(validator)\` and (queries) \`.stream()\` are also available.
311
+ */
312
+ const lunoraBuilders = initLunora.dataModel<DataModel>().create();
313
+
314
+ /** \`query\` builder bound to this project's typed {@link QueryCtx}. */
315
+ export const query = lunoraBuilders.query as unknown as QueryBuilder<QueryCtx, EmptyArgs>;
316
+
317
+ /** \`mutation\` builder bound to this project's typed {@link MutationCtx}. */
318
+ export const mutation = lunoraBuilders.mutation as unknown as MutationBuilder<MutationCtx, EmptyArgs>;
319
+
320
+ /** \`action\` builder bound to this project's typed {@link ActionCtx}. */
321
+ export const action = lunoraBuilders.action as unknown as ActionBuilder<ActionCtx, EmptyArgs>;
322
+
323
+ /** \`internalQuery\` builder bound to this project's typed {@link QueryCtx} — never exposed on \`api\`. */
324
+ export const internalQuery = lunoraBuilders.internalQuery as unknown as InternalQueryBuilder<QueryCtx, EmptyArgs>;
325
+
326
+ /** \`internalMutation\` builder bound to this project's typed {@link MutationCtx} — never exposed on \`api\`. */
327
+ export const internalMutation = lunoraBuilders.internalMutation as unknown as InternalMutationBuilder<MutationCtx, EmptyArgs>;
328
+
329
+ /** \`internalAction\` builder bound to this project's typed {@link ActionCtx} — never exposed on \`api\`. */
330
+ export const internalAction = lunoraBuilders.internalAction as unknown as InternalActionBuilder<ActionCtx, EmptyArgs>;
331
+
332
+ /**
333
+ * \`defineMutator\` bound to this project's typed {@link MutationCtx} — declare
334
+ * custom mutators (\`lunora/mutators.ts\`) with it instead of importing from
335
+ * \`${u.server}\`, and the authoritative \`server\` impl's \`ctx\` carries the
336
+ * schema-typed \`ctx.db\` (\`ctx.db.query("nodes")\` resolves \`Doc<"nodes">\`,
337
+ * \`ctx.db.patch("nodes", id, …)\` takes an \`Id<"nodes">\`) with no hand-written ctx type and
338
+ * no \`as unknown as\` cast. Runtime-identical to the package export; only the
339
+ * context type narrows, so discovery finds a mutator authored either way.
340
+ * @example
341
+ * export const setText = defineMutator({
342
+ * args: { id: v.id("nodes"), text: v.string() },
343
+ * server: async (ctx, args) => { await ctx.db.patch("nodes", args.id, { text: args.text }); },
344
+ * });
345
+ */
346
+ export const defineMutator = defineMutatorBase as unknown as <Args extends Record<string, Validator> = Record<string, Validator>, ClientTx = unknown, R = unknown>(
347
+ definition: MutatorDefinition<Args, MutationCtx, ClientTx, R>,
348
+ ) => RegisteredMutator<Args, MutationCtx, ClientTx, R>;
349
+
350
+ /**
351
+ * \`definePolicy\` bound to THIS schema's {@link DataModel} + {@link Relations}.
352
+ * Import it from here (\`./_generated/server\`) instead of \`@lunora/server\` to get
353
+ * a relation-aware RLS authoring surface: \`table\` autocompletes to a real table
354
+ * name and the \`when\` predicate type-checks against the table's columns **and**
355
+ * its declared relations — \`{ author: { is: {...} } }\`, \`{ posts: { some: {...} } }\`,
356
+ * etc. (the \`@lunora/do\` pre-resolver resolves relation predicates on reads).
357
+ * Runtime-identical to \`@lunora/server\`'s \`definePolicy\`; only the types narrow,
358
+ * so the \`rls()\` chain discovers a policy authored either way the same.
359
+ */
360
+ export const definePolicy = createPolicyDsl<DataModel, Relations${Ve}>();
361
+
362
+ /**
363
+ * The validator builder \`v\`, with \`v.id(...)\` constrained to THIS schema's
364
+ * table names — so the argument autocompletes and returns a precise
365
+ * \`Id<"table">\`. Identical to \`@lunora/server\`'s \`v\` at runtime; the only
366
+ * difference is the tightened \`id\` type.
367
+ *
368
+ * Import \`v\` from here (\`./_generated/server\`) in your queries/mutations/actions
369
+ * to get table-name autocomplete. \`lunora/schema.ts\` can't use it — it is the
370
+ * file that defines the table names, so they aren't known yet there; pass the
371
+ * names as string literals and the generated \`Id<"table">\` types still catch a
372
+ * typo wherever the id is used.
373
+ */
374
+ export const v = vBase as unknown as Omit<typeof vBase, "id"> & {
375
+ id: <T extends TableName>(table: T) => ColumnValidator<IdOfTable<T>, IdOfTable<T>>;
376
+ };
377
+ `};export{wt as a,$t as e};