@lunora/codegen 1.0.0-alpha.42 → 1.0.0-alpha.420
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.
- package/LICENSE.md +201 -104
- package/README.md +4 -4
- package/dist/index.d.mts +4583 -2045
- package/dist/index.d.ts +4583 -2045
- package/dist/index.mjs +1 -35
- package/dist/packem_shared/AGENTS_FILENAME-C4tHmiZZ.mjs +1 -0
- package/dist/packem_shared/ALL_NOTIFY_CHANNELS-BgkkvuUe.mjs +1 -0
- package/dist/packem_shared/CAPABILITY_PROBES-DCzOjTN7.mjs +25 -0
- package/dist/packem_shared/COMPANION_BINDING-Da_v9XpC.mjs +1 -0
- package/dist/packem_shared/CONTAINERS_FILENAME-d3XTFcqV.mjs +1 -0
- package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
- package/dist/packem_shared/DEFAULT_TARGET-CVYzxQ0y.mjs +1 -0
- package/dist/packem_shared/ENV_FILENAME-DJ11PXN5.mjs +1 -0
- package/dist/packem_shared/FLAGS_FILENAME-DeSjFBWq.mjs +1 -0
- package/dist/packem_shared/GENERATED_HEADER-DgrhC3Iv.mjs +1 -0
- package/dist/packem_shared/LUNORA_ERROR_CODES-D7AVT7qF.mjs +1 -0
- package/dist/packem_shared/MUTATORS_FILENAME-C0ZV0hh6.mjs +1 -0
- package/dist/packem_shared/OPENRPC_VERSION-BOBo0zdQ.mjs +3 -0
- package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs +1 -0
- package/dist/packem_shared/QUEUES_FILENAME-DbuJZnrY.mjs +1 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-BljJJD8u.mjs +56 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs +2 -0
- package/dist/packem_shared/SHAPES_FILENAME-C-hrGfJ2.mjs +1 -0
- package/dist/packem_shared/SchemaSnapshotParseError-CV7mmuPi.mjs +17 -0
- package/dist/packem_shared/WORKFLOWS_FILENAME-7FysJsMZ.mjs +1 -0
- package/dist/packem_shared/attribution-Cwt30DDJ.mjs +1 -0
- package/dist/packem_shared/buildOpenApiDocument-DmV_PBFv.mjs +3 -0
- package/dist/packem_shared/capabilitiesUsedBy-BNvoiCu1.mjs +1 -0
- package/dist/packem_shared/classify-procedure-call-BmEirzc_.mjs +1 -0
- package/dist/packem_shared/companionServiceBinding-BZjm486n.mjs +1 -0
- package/dist/packem_shared/context-property-calls-BT1J7BqY.mjs +1 -0
- package/dist/packem_shared/context-root-BpDEhvNE.mjs +1 -0
- package/dist/packem_shared/createCodegenProject-dC6oJh5H.mjs +1 -0
- package/dist/packem_shared/database-calls-d-Sssc-3.mjs +1 -0
- package/dist/packem_shared/declared-output-Iaar469J.mjs +1 -0
- package/dist/packem_shared/describeErrorLevelFindings-DlkgCw8a.mjs +1 -0
- package/dist/packem_shared/discoverAuthApiCalls-CuqaLRa0.mjs +1 -0
- package/dist/packem_shared/discoverCrons-bT8F5GyL.mjs +1 -0
- package/dist/packem_shared/discoverFunctions-C9HUlfiV.mjs +1 -0
- package/dist/packem_shared/discoverHttpRoutes-CesuhqW1.mjs +1 -0
- package/dist/packem_shared/discoverHyperdriveCalls-BmAoOGGq.mjs +1 -0
- package/dist/packem_shared/discoverInserts-DIarYU2P.mjs +1 -0
- package/dist/packem_shared/discoverMaskProcedures-jkRrWS86.mjs +1 -0
- package/dist/packem_shared/discoverMigrations-C9AlZYFi.mjs +1 -0
- package/dist/packem_shared/discoverNondeterministicCalls-ZeZDQJAI.mjs +1 -0
- package/dist/packem_shared/discoverQueries-DLZHcDzB.mjs +1 -0
- package/dist/packem_shared/discoverR2sqlCalls-D_HWbbky.mjs +1 -0
- package/dist/packem_shared/discoverRlsMetadata-C0UkQkWd.mjs +1 -0
- package/dist/packem_shared/discoverRlsProcedures-BbSdCvmA.mjs +1 -0
- package/dist/packem_shared/discoverSandboxUsage-Dgvv6F_7.mjs +1 -0
- package/dist/packem_shared/discoverSchema-BLTROO8Z.mjs +1 -0
- package/dist/packem_shared/discoverStorageRulesMetadata-DeBgC7po.mjs +1 -0
- package/dist/packem_shared/dispatch-namespace-DwTjD7BU.mjs +1 -0
- package/dist/packem_shared/emitAgents-vWoT8-Yb.mjs +1 -0
- package/dist/packem_shared/emitApi-lwadq5G7.mjs +147 -0
- package/dist/packem_shared/emitApp-LFKtDRYu.mjs +1162 -0
- package/dist/packem_shared/emitCrons-CCRKs482.mjs +138 -0
- package/dist/packem_shared/emitDataModel-BvCZS4Yq.mjs +114 -0
- package/dist/packem_shared/emitDrizzleSchema-BzOChEYW.mjs +15 -0
- package/dist/packem_shared/emitFunctions-ppMX7E3X.mjs +528 -0
- package/dist/packem_shared/emitServer-CGRV_uIq.mjs +1 -0
- package/dist/packem_shared/emitShard-CDWgekIG.mjs +1 -0
- package/dist/packem_shared/exported-procedure-chains-CfH5jrzD.mjs +1 -0
- package/dist/packem_shared/fingerprintSchemaSources-TN-rU6Of.mjs +1 -0
- package/dist/packem_shared/formatAdvisories-Bue5tbp6.mjs +2 -0
- package/dist/packem_shared/handler-reference-BkOkxxg8.mjs +1 -0
- package/dist/packem_shared/index-CfSmiylg.mjs +1 -0
- package/dist/packem_shared/index-DtJBMdZ4.mjs +1 -0
- package/dist/packem_shared/ip-reads-D2qhKEb6.mjs +1 -0
- package/dist/packem_shared/isD1GlobalTable-udvHAAzD.mjs +1 -0
- package/dist/packem_shared/isTestPath-Uwb5a6Kq.mjs +1 -0
- package/dist/packem_shared/isTypedSchema-CDv3pJB6.mjs +4 -0
- package/dist/packem_shared/json-data-Chfs2Cz5.mjs +1 -0
- package/dist/packem_shared/loadProjectConfig-BXwH3_gn.mjs +1 -0
- package/dist/packem_shared/module-specifiers-BctA0m_p.mjs +1 -0
- package/dist/packem_shared/modules-DdOd-7Wp.mjs +1 -0
- package/dist/packem_shared/parse-validator-BisfC8bR.mjs +1 -0
- package/dist/packem_shared/platform-8oj7iXQy.mjs +1 -0
- package/dist/packem_shared/policies-Dn_tuTZd.mjs +1 -0
- package/dist/packem_shared/project-config-file-DR7xrrNB.mjs +1 -0
- package/dist/packem_shared/property-name-7cBlgK_O.mjs +1 -0
- package/dist/packem_shared/qualifiers-qqH8fRTo.mjs +1 -0
- package/dist/packem_shared/readPackageDependencies-RHhGiz0k.mjs +1 -0
- package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
- package/dist/packem_shared/reserved-words-CW1QFbTd.mjs +1 -0
- package/dist/packem_shared/schema-BgM8A3XV.mjs +1 -0
- package/dist/packem_shared/schemaFromIr-CByOxuZb.mjs +1 -0
- package/dist/packem_shared/server-Dfxmm5Zw.mjs +377 -0
- package/dist/packem_shared/shard-CWAD5mYy.mjs +1897 -0
- package/dist/packem_shared/shard-runtime-G5mZQjY0.mjs +351 -0
- package/dist/packem_shared/shared-Cn7dMQ_u.mjs +13 -0
- package/dist/packem_shared/unwrap-handler-return-DvbyiLjc.mjs +1 -0
- package/dist/sdk/index.d.mts +288 -0
- package/dist/sdk/index.d.ts +288 -0
- package/dist/sdk/index.mjs +394 -0
- package/package.json +22 -9
- package/dist/packem_shared/CONTAINERS_FILENAME-DjpXMqhp.mjs +0 -224
- package/dist/packem_shared/CodegenDiagnosticError-DyQ5FwkM.mjs +0 -24
- package/dist/packem_shared/FLAGS_FILENAME-fEZtzWXi.mjs +0 -139
- package/dist/packem_shared/GENERATED_HEADER-D6RK1WF1.mjs +0 -3
- package/dist/packem_shared/LUNORA_ERROR_CODES-DvTLozCu.mjs +0 -68
- package/dist/packem_shared/MUTATORS_FILENAME-BZOfUhlY.mjs +0 -81
- package/dist/packem_shared/OPENRPC_VERSION-CzhfvCIQ.mjs +0 -60
- package/dist/packem_shared/QUEUES_FILENAME-Xv6Vy-Ku.mjs +0 -145
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-Cl1EBMdR.mjs +0 -3438
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-D0ARY6rL.mjs +0 -249
- package/dist/packem_shared/SHAPES_FILENAME-DOhPGi-6.mjs +0 -94
- package/dist/packem_shared/WORKFLOWS_FILENAME-B2By8S4s.mjs +0 -152
- package/dist/packem_shared/buildOpenApiDocument-bg-NnLka.mjs +0 -183
- package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
- package/dist/packem_shared/discoverAuthApiCalls-WMx8L2FG.mjs +0 -62
- package/dist/packem_shared/discoverCrons-D-jrpm97.mjs +0 -256
- package/dist/packem_shared/discoverFunctions-CZ91aenA.mjs +0 -518
- package/dist/packem_shared/discoverHttpRoutes-DNZLDCmm.mjs +0 -131
- package/dist/packem_shared/discoverInserts-DFRJhmCv.mjs +0 -61
- package/dist/packem_shared/discoverMaskProcedures-B5iFnZ-X.mjs +0 -273
- package/dist/packem_shared/discoverMigrations-CdKtMlBc.mjs +0 -97
- package/dist/packem_shared/discoverNondeterministicCalls-C_PrQPkA.mjs +0 -122
- package/dist/packem_shared/discoverQueries-B8W9UPrt.mjs +0 -62
- package/dist/packem_shared/discoverR2sqlCalls-Bm7Rfnf4.mjs +0 -80
- package/dist/packem_shared/discoverRlsMetadata-B4GL4ZKm.mjs +0 -280
- package/dist/packem_shared/discoverSchema-DFWVgU5o.mjs +0 -874
- package/dist/packem_shared/discoverStorageRulesMetadata-nosjYcvN.mjs +0 -97
- package/dist/packem_shared/emit-31Yg1Ee5.mjs +0 -3474
- package/dist/packem_shared/emitApp-DCP7Pr6M.mjs +0 -668
- package/dist/packem_shared/formatAdvisories-DRhEiJUz.mjs +0 -114
- package/dist/packem_shared/parse-validator-BSJo1HGP.mjs +0 -144
- package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
- package/dist/packem_shared/redact-oTmsol5A.mjs +0 -33
- package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as b}from"node:fs";import{join as k}from"node:path";import{LunoraError as w}from"@lunora/errors";import y from"@lunora/scheduler/validate";import{workflowDefaultName as E,workflowClassName as v}from"@lunora/workflow";import{Node as n,VariableDeclarationKind as S,SyntaxKind as P}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{unwrapToCallExpression as x,declarationLineOf as L,lunoraRelativePath as N,findObjectProperty as d,stringPropertyFor as $}from"./isTestPath-Uwb5a6Kq.mjs";import{a as A}from"./attribution-Cwt30DDJ.mjs";import{r as O}from"./handler-reference-BkOkxxg8.mjs";const W="workflows.ts",C=new Set(["do","sleep","sleepUntil","waitForEvent"]),F=o=>{const e=o.getSymbol();if(!e)return o.getText()==="defineWorkflow";for(const t of e.getDeclarations())if(n.isImportSpecifier(t))return t.getImportDeclaration().getModuleSpecifierValue()!=="@lunora/workflow"?!1:t.getNameNode().getText()==="defineWorkflow";return!1},m=$("workflow"),I=(o,e,t)=>{if(n.isNumericLiteral(o))return o.getLiteralValue();throw c(o,`workflow "${e}": \`${t}\` must be a static number literal — it is deploy configuration codegen writes into wrangler.jsonc`)},f=(o,e)=>{const t=d(o,e);return t&&n.isPropertyAssignment(t)?t.getInitializerOrThrow():void 0},g=(o,e,t)=>{if(n.isObjectLiteralExpression(o))return o;throw c(o,`workflow "${e}": \`${t}\` must be an inline object literal — it is deploy configuration codegen writes into wrangler.jsonc`)},D=(o,e)=>{if(!n.isArrayLiteralExpression(o)||o.getElements().length===0)throw c(o,`workflow "${e}": \`schedules\` must be a non-empty inline array of cron expression string literals`);return o.getElements().map(t=>{const r=m(t,e,"schedules[]");if(!y(r))throw c(t,`workflow "${e}": schedule "${r}" is not a valid cron expression`);return r})},R=(o,e)=>{const t={},r=f(o,"schedules");r!==void 0&&(t.schedules=D(r,e));const s=f(o,"limits");if(s!==void 0){const i=f(g(s,e,"limits"),"steps");if(i===void 0)t.limits={};else{const l=I(i,e,"limits.steps");if(!Number.isInteger(l)||l<=0)throw c(i,`workflow "${e}": \`limits.steps\` must be a positive integer (got ${String(l)})`);t.limits={steps:l}}}const a=f(o,"defaultRetention");if(a!==void 0){const i=g(a,e,"defaultRetention"),l={};for(const u of["errorRetention","successRetention"]){const p=f(i,u);p!==void 0&&(l[u]=m(p,e,`defaultRetention.${u}`))}t.defaultRetention=l}return t},T=o=>{const e=o.getExpression();if(!n.isPropertyAccessExpression(e)||!C.has(e.getName()))return!1;const t=e.getExpression();return n.isPropertyAccessExpression(t)&&t.getName()==="step"?!0:n.isIdentifier(t)&&t.getText()==="step"},j=o=>{if(!o)return[];const e=[];for(const t of o.getDescendantsOfKind(P.CallExpression)){if(!T(t))continue;const r=t.getArguments()[0];!r||!(n.isStringLiteral(r)||n.isNoSubstitutionTemplateLiteral(r))||e.push({line:t.getStartLineNumber(),method:t.getExpression().getName(),name:r.getLiteralValue()})}return e},h=o=>{let e=o;for(;e&&(n.isAsExpression(e)||n.isSatisfiesExpression(e)||n.isParenthesizedExpression(e));)e=e.getExpression();return e},K=o=>{const e=h(o);if(e&&n.isObjectLiteralExpression(e))return e;if(!(!e||!n.isIdentifier(e)))for(const t of e.getSymbol()?.getDeclarations()??[]){const s=n.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===S.Const?h(t.getInitializer()):void 0;if(s&&n.isObjectLiteralExpression(s))return s}},V=(o,e)=>{const t=d(o,"handler"),r=O(t,e);return r!==void 0?r:{body:t!==void 0&&n.isPropertyAssignment(t)?t.getInitializer():t}},z=(o,e,t)=>{const r=K(o.getArguments()[0]);if(!r)throw c(o,`workflow "${e}": defineWorkflow's argument must be an object literal, or a local \`const\` holding one — codegen reads \`name\` and the \`ctx.step.*\` calls out of it statically. Keep the handler wherever you like and pass it through: \`const config = { handler: myHandler }; export const ${e} = defineWorkflow(config);\`.`);const s=V(r,t),a={className:v(e),exportName:e,file:N(t,o.getSourceFile().getFilePath()),line:L(o),name:E(e),steps:j(s.body),...s.file===void 0?{}:{handlerFile:s.file},...s.site===void 0?{}:{handlerSite:s.site}},i=d(r,"name");return i&&n.isPropertyAssignment(i)&&(a.name=m(i.getInitializerOrThrow(),e,"name")),{...a,...R(r,e)}},M=(o,e)=>{const t=[];for(const r of o.getVariableDeclarations()){const s=x(r.getInitializer());if(!s)continue;const a=s.getExpression();if(!n.isIdentifier(a)||!F(a))continue;const i=r.getNameNode();if(!n.isIdentifier(i)){if(r.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw c(i,"defineWorkflow exports must be plain named exports (no destructuring)")}const l=A(r,"binding");l!==void 0&&t.push(z(s,l,e))}return t},_=o=>{const e=new Map,t=new Map;for(const r of o){const s=e.get(r.name);if(s!==void 0)throw new w("DUPLICATE_WORKFLOW_NAME",`Duplicate workflow name "${r.name}": produced by both "${s}" and "${r.exportName}". Deployed workflow names must be unique across the project.`,{status:500});e.set(r.name,r.exportName);const a=t.get(r.className);if(a!==void 0)throw new w("DUPLICATE_WORKFLOW_CLASS",`Duplicate workflow class "${r.className}": produced by both "${a}" and "${r.exportName}". Workflow export names must yield unique generated class names.`,{status:500});t.set(r.className,r.exportName)}},ee=(o,e)=>{const t=k(e,W);if(!b(t))return[];const r=o.getSourceFile(t)??o.addSourceFileAtPath(t),s=M(r,e);return s.sort((a,i)=>a.exportName.localeCompare(i.exportName)),_(s),s};export{W as WORKFLOWS_FILENAME,ee as discoverWorkflows};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{callSiteCallers as y,byCodepoint as k}from"@lunora/advisor";import{Node as r,SyntaxKind as p,VariableDeclarationKind as F,ts as O}from"ts-morph";import{i as M}from"./reserved-words-CW1QFbTd.mjs";import{isWriteTarget as A,descendantsOfKind as T,unwrapExpression as V}from"./isTestPath-Uwb5a6Kq.mjs";const N=new WeakMap,C=e=>e.getStatements().flatMap(t=>r.isFunctionDeclaration(t)?[t]:r.isVariableStatement(t)?t.getDeclarations().filter(o=>r.isIdentifier(o.getNameNode())):[]),x=e=>r.isStringLiteral(e)?e.getLiteralValue():e.getText(),I=e=>{if(r.isFunctionDeclaration(e)||r.isClassDeclaration(e)){const t=e.getName();return e.hasExportKeyword()?[[t??"default",e.hasDefaultKeyword()?"default":t??"default"]]:[]}return!r.isVariableStatement(e)||!e.hasExportKeyword()?[]:e.getDeclarations().flatMap(t=>{const o=t.getNameNode();return r.isIdentifier(o)?[[o.getText(),o.getText()]]:o.getDescendantsOfKind(p.BindingElement).flatMap(n=>r.isIdentifier(n.getNameNode())?[[n.getName(),n.getName()]]:[])})},P=e=>{if(r.isExportDeclaration(e))return e.hasModuleSpecifier()||e.isTypeOnly()?[]:e.getNamedExports().filter(o=>!o.isTypeOnly()).map(o=>{const n=x(o.getNameNode()),s=o.getAliasNode();return[n,s===void 0?n:x(s)]});const t=r.isExportAssignment(e)&&!e.isExportEquals()?e.getExpression():void 0;return r.isIdentifier(t)?[[t.getText(),"default"]]:I(e)},h=new WeakMap,K=e=>{const t=h.get(e.compilerNode);if(t!==void 0)return t;const o=new Map;for(const[s,c]of e.getStatements().flatMap(i=>P(i)))o.set(s,(o.get(s)??new Set).add(c));const n=new Map([...o].map(([s,c])=>[s,[...c].toSorted(Y)]));return h.set(e.compilerNode,n),n},g=e=>{const t=r.isBindingElement(e)?e.getFirstAncestorByKind(p.VariableStatement):void 0,o=r.isVariableDeclaration(e)?e.getVariableStatement():void 0,n=r.isFunctionDeclaration(e)?e:t??o;if(n===void 0||!r.isSourceFile(n.getParent()))return[];const s=r.isFunctionDeclaration(e)?e.getName()??"default":e.getName();return K(e.getSourceFile()).get(s)??[]},L=e=>new Map(e.flatMap(t=>{const o=g(t);return o.length===0?[]:[[t.compilerNode,o]]})),B=e=>{const t=V(e);return t!==void 0&&(r.isArrowFunction(t)||r.isFunctionExpression(t))},b=(e,t)=>{for(const o of e.getAncestors()){if(r.isExportAssignment(o)&&!o.isExportEquals())return{kind:"export",name:"default"};if((r.isFunctionDeclaration(o)&&r.isSourceFile(o.getParent())||r.isVariableDeclaration(o)&&r.isSourceFile(o.getVariableStatement()?.getParent())&&r.isIdentifier(o.getNameNode()))&&(r.isFunctionDeclaration(o)||r.isVariableDeclaration(o))){const s=t.get(o.compilerNode)?.[0];return s!==void 0?{kind:"export",name:s}:r.isFunctionDeclaration(o)||B(o.getInitializer())?{declaration:o,kind:"helper"}:{kind:"untracked"}}}return{kind:"untracked"}},E=e=>{for(const t of e.getAncestors()){if(r.isExpressionWithTypeArguments(t)){const o=t.getParent();return!(r.isHeritageClause(o)&&o.getToken()===p.ExtendsKeyword&&(r.isClassDeclaration(o.getParent())||r.isClassExpression(o.getParent())))}if(O.isTypeNode(t.compilerNode))return!0}return!1},ee=e=>{const t=e.getParent(),o=r.isPropertyAccessExpression(t)&&t.getNameNode()===e,n=(r.isPropertyAssignment(t)||r.isMethodDeclaration(t))&&t.getNameNode()===e;return!o&&!n&&!E(e)},v=e=>{const t=e.getParent();return r.isShorthandPropertyAssignment(t)&&t.getNameNode()===e?t.getValueSymbol():e.getSymbol()},R=e=>{const t=v(e);return t?.getValueDeclaration()??t?.getDeclarations()[0]},S=new WeakMap,$=/\/typescript\/lib\/lib\.[^/]+\.d\.ts$/u,_=e=>{const t=e.getFilePath();return e.isDeclarationFile()&&($.test(t)||t.includes("/@types/node/"))},te=e=>{const t=e.getNameNode(),o=r.isFunctionDeclaration(e)?void 0:e.getFirstAncestorByKind(p.VariableDeclarationList);if(!r.isIdentifier(t)||o?.getDeclarationKind()===F.Const||_(e.getSourceFile()))return!1;let n=S.get(e.compilerNode);if(n===void 0){const s=r.isFunctionDeclaration(e)?e.getSourceFile():e.getFirstAncestor(i=>r.isFunctionLikeDeclaration(i)||r.isArrowFunction(i))??e.getSourceFile(),c=t.getText();n=s.getDescendantsOfKind(p.Identifier).some(i=>i!==t&&i.getText()===c&&A(i)&&R(i)?.compilerNode===e.compilerNode),S.set(e.compilerNode,n)}return n},W=e=>{const t=new Map,o=new Set,n=new Set;for(const s of e){const c=s.getNameNode(),i=c?.getSymbol()?.compilerSymbol;c!==void 0&&i!==void 0&&(t.set(i,s.compilerNode),o.add(c.compilerNode),n.add(c.getText()))}return{bySymbol:t,nameNodes:o,spellings:n}},z=(e,t,o)=>{const{bySymbol:n,nameNodes:s,spellings:c}=W(t),i=new Map;for(const a of T(e,p.Identifier)){if(!c.has(a.getText())||s.has(a.compilerNode)||E(a))continue;const l=v(a)?.compilerSymbol,d=l===void 0?void 0:n.get(l);d!==void 0&&i.set(d,[...i.get(d)??[],b(a,o)])}return i},H=(e,t)=>{const o=new Map(e.map(a=>[a.compilerNode,new Set])),n=new Set,s=a=>(o.get(a)?.size??0)+(n.has(a)?1:0),c=(a,l)=>{const d=s(a),u=o.get(a),m=l.kind==="helper"?l.declaration.compilerNode:void 0;l.kind==="export"&&u?.add(l.name);for(const w of m===void 0?[]:o.get(m)??[])u?.add(w);return(l.kind==="untracked"||m!==void 0&&n.has(m))&&n.add(a),s(a)!==d};let i=!0;for(;i;){i=!1;for(const[a,l]of t)for(const d of l)i=c(a,d)||i}return new Map([...o].map(([a,l])=>[a,{callers:[...l].toSorted((d,u)=>d.localeCompare(u)),untracked:n.has(a)}]))},q=e=>{const t=N.get(e.compilerNode);if(t!==void 0)return t;const o=C(e),n=L(o),s=o.filter(i=>!n.has(i.compilerNode)),c={exportNames:n,helperReach:s.length===0?new Map:H(s,z(e,s,n))};return N.set(e.compilerNode,c),c},oe=e=>{const t=q(e.getSourceFile()),o=b(e,t.exportNames);switch(o.kind){case"export":return{kind:"export",name:o.name};case"helper":{const n=o.declaration.getName(),s=t.helperReach.get(o.declaration.compilerNode);if(n===void 0||s===void 0)throw new Error(`call-site attribution: helper at ${o.declaration.getSourceFile().getFilePath()} is not indexed`);return{callers:s.callers,kind:"helper",name:n,...s.untracked?{untracked:!0}:{}}}default:return{kind:"module"}}},X=e=>{if(e.kind==="helper"&&e.untracked===!0)return;const t=y(e);return t.length===0?void 0:t},j=(e,t)=>{const o=new Set(y(e).map(n=>t(n)));return o.has("public")?"public":X(e)===void 0||o.has(void 0)?void 0:"internal"},ne=(e,t)=>{const o=new Map(t.map(n=>[`${n.filePath}:${n.exportName}`,n.visibility]));return e.map(n=>{const s=j(n.scope,c=>o.get(`${n.file}:${c}`));return s===void 0?n:{...n,visibility:s}})},f=/^[$A-Z_a-z][\w$]*$/u,D=e=>f.test(e),G=e=>{const t=g(e);return t.length===0?r.isVariableDeclaration(e)&&e.getVariableStatement()?.hasExportKeyword()===!0?e.getName():void 0:t.find(o=>D(o))??e.getName()},re=e=>e.getVariableStatements().flatMap(t=>t.getDeclarations()).filter(t=>G(t)!==void 0),se=(e,t)=>{if(r.isIdentifier(e.getNameNode()))return e.getVariableStatement()?.hasExportKeyword()===!0?e.getName():g(e).find(o=>t==="binding"?M(o):D(o))},Y=(e,t)=>Number(f.test(t))-Number(f.test(e))||k(e,t);export{se as a,te as b,oe as c,R as d,K as e,ee as f,g,G as h,D as i,re as j,E as k,_ as l,X as m,v as r,ne as w};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{m as b}from"./modules-DdOd-7Wp.mjs";import{r as E}from"./json-data-Chfs2Cz5.mjs";import{LUNORA_ERROR_CODES as P,objectSchema as g,validatorIrToJsonSchema as l}from"./LUNORA_ERROR_CODES-D7AVT7qF.mjs";import{G as A}from"./shared-Cn7dMQ_u.mjs";import{s as m}from"./dispatch-namespace-DwTjD7BU.mjs";const T="/_lunora/rest",x=["authorization","cf-access-jwt-assertion","cookie","payment-signature","x-payment"],v=["x-d1-bookmark","x-lunora-shard-key"],j=e=>[...x,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],O=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,$=(...e)=>{const t=[];for(const r of e)for(const n of r?.split(",")??[]){const s=n.trim().toLowerCase();s!==""&&!t.includes(s)&&t.push(s)}return t.length===0?void 0:t.join(", ")},k=(e,t)=>{const r=[t,`max-age=${String(O(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(O(e.staleWhileRevalidate))}`),r.join(", ")},N=e=>e.scope==="public"?$(e.vary,...j(e),...v):$(e.vary,...v),q=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},_=e=>{const t=q(e);if(t!==void 0)return`${T}/${t.namespace}/${t.name}`},C=e=>e==="query"?"GET":"POST",y="#/components/responses/LunoraError",R=/:([A-Za-z_$][\w$]*)/gu,w=e=>[...e.matchAll(R)].map(t=>t[1]),D=e=>e.replaceAll(R,"{$1}"),f=e=>e.kind==="optional"?e.inner??e:e,I=e=>{const t=new Set(w(e.path)),r=[];for(const[n,s]of Object.entries(e.searchParams)){const c=f(s);r.push({description:`Query parameter \`${n}\``,in:"query",name:n,required:s.kind!=="optional",schema:l(c)})}for(const[n,s]of Object.entries(e.params)){const c=f(s);r.push({description:`Path parameter \`${n}\``,in:t.has(n)?"path":"query",name:n,required:t.has(n)?!0:s.kind!=="optional",schema:l(c)})}return r},S=e=>e?{content:{"application/json":{schema:l(e)}},description:"Successful response."}:{content:{"application/json":{schema:{description:"Return shape is TS-inferred (no `.output()` declared); best-effort — any JSON."}}},description:"Successful response. The return shape is TypeScript-inferred and not declared via `.output()`, so it is documented best-effort."},L=(e,t)=>{const r=I(e),n={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${m(e.path)}`,responses:{200:S(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:y}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(n.parameters=r),Object.keys(e.body).length>0&&(n.requestBody={content:{"application/json":{schema:g(e.body)}},required:!0}),e.stream&&(n["x-lunora-stream"]="text/event-stream"),n},F=(e,t)=>{const r=`${m(e.filePath)}:${e.exportName}`,n={additionalProperties:!1,properties:{args:g(e.args),functionPath:{const:r,type:"string"},shardKey:{description:"Optional shard key; omitted routes to the default shard.",type:"string"}},required:["functionPath"],type:"object"};return{operation:{description:`Invoke the \`${e.kind}\` \`${r}\` over the Lunora RPC envelope (POST /_lunora/rpc).`,operationId:r,requestBody:{content:{"application/json":{schema:n}},required:!0},responses:{200:S(e.output),default:{$ref:y}},summary:`${e.kind}: ${r}`,tags:[t],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${r}`}},H=(e,t)=>{if(e===void 0||t!=="get"||e.scope===void 0||e.maxAge===void 0)return{};const r={maxAge:e.maxAge,scope:e.scope,...e.staleWhileRevalidate===void 0?{}:{staleWhileRevalidate:e.staleWhileRevalidate},...e.tag===void 0?{}:{tag:e.tag},...e.vary===void 0?{}:{vary:e.vary}},n={"Cache-Control":{description:r.scope==="public"?"Caching policy. `public` applies only to an uncredentialed request — a request carrying `Authorization` or `Cookie` is always answered `private`.":"Caching policy. Restricted to the caller's own cache; never stored by a shared/edge cache.",schema:{example:k(r,r.scope),type:"string"}}};r.tag!==void 0&&(n["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const s=N(r);return s!==void 0&&(n.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:s,type:"string"}}),{headers:n}},M=(e,t)=>{const r=`${m(e.filePath)}:${e.exportName}`,n=_(r);if(n===void 0)return;const s=C(e.kind),c=s==="GET",i={description:`Public REST endpoint for the \`${e.kind}\` \`${r}\` (opt-in via \`.expose({ rest: true })\`). Routed through the procedure, so auth / RLS / validators are enforced.`,operationId:`rest_${m(n)}`,responses:{200:{content:{"application/json":{schema:{description:"Procedure result. The shape is TS-inferred from the return type; best-effort — any JSON."}}},description:"Successful result (TypeScript-inferred return shape, documented best-effort).",...H(e.expose?.cache,c?"get":"post")},default:{$ref:y}},summary:`${s} ${n}`,tags:[t],"x-lunora-function-kind":e.kind};if(c){const d=Object.entries(e.args).map(([u,h])=>{const o=f(h);return{description:`Argument \`${u}\` (JSON-encoded for non-string values).`,in:"query",name:u,required:h.kind!=="optional",schema:l(o)}});return d.length>0&&(i.parameters=d),{method:"get",operation:i,path:n}}return i.requestBody={content:{"application/json":{schema:g(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:i,path:n}},J=e=>{const t=e.version??"0.0.0",r=Object.create(null),n=o=>r[o]??Object.create(null),s=new Set,c=e.modules??[],i=o=>b(c,o);for(const o of e.httpRoutes){const a=D(o.path),p=n(a);p[o.method.toLowerCase()]=L(o,i(o.filePath)),r[a]=p,s.add(i(o.filePath))}const d=e.functions.filter(o=>o.visibility!=="internal"&&o.kind!=="stream");for(const o of d){const{operation:a,pathKey:p}=F(o,i(o.filePath));r[p]={post:a},s.add(i(o.filePath))}for(const o of d){if(o.expose?.rest!==!0)continue;const a=M(o,i(o.filePath));if(a===void 0)continue;const p=n(a.path);p[a.method]=a.operation,r[a.path]=p}const u=[...s].toSorted((o,a)=>o.localeCompare(a)).map(o=>({description:c.find(p=>p.name===o)?.description??`Operations declared in \`lunora/${o}\`.`,name:o}));return{components:{responses:{LunoraError:{content:{"application/json":{schema:{additionalProperties:!1,description:"Standard Lunora error envelope.",properties:{error:{additionalProperties:!1,properties:{code:{description:"Machine-readable error code. Clients switch on this value.",enum:P,type:"string"},message:{description:"Human-readable error message (never echoes internal details).",type:"string"}},required:["code","message"],type:"object"}},required:["error"],type:"object"}}},description:"A Lunora error response. The HTTP status reflects the error code (e.g. BAD_REQUEST→400, UNAUTHORIZED→401, FORBIDDEN→403, NOT_FOUND→404)."}}},info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora API",version:t},openapi:"3.1.0",paths:Object.fromEntries(Object.entries(r).map(([o,a])=>[o,{...a}])),tags:u}},z=e=>`${JSON.stringify(J(e),void 0,2)}
|
|
2
|
+
`,K=e=>`${A}export const openApiSpec = ${E(e,"Record<string, unknown>")};
|
|
3
|
+
`;export{J as buildOpenApiDocument,z as emitOpenApi,K as emitOpenApiModule};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{SyntaxKind as g,Node as m,ts as D,Project as M}from"ts-morph";import{CAPABILITIES as u}from"./CAPABILITY_PROBES-DCzOjTN7.mjs";import{descendantsOfKind as l,bindingKeyName as v,listLunoraSourceFiles as P}from"./isTestPath-Uwb5a6Kq.mjs";import{scanImportDeclaration as A,noSandboxUsage as I}from"./discoverSandboxUsage-Dgvv6F_7.mjs";const f="ctx",L=(e,t,s)=>{for(const o of l(e,g.ElementAccessExpression)){const r=o.getArgumentExpression();t(o.getExpression())&&r!==void 0&&(m.isStringLiteral(r)||m.isNoSubstitutionTemplateLiteral(r))&&s.add(r.getLiteralValue())}},C=e=>{const t=new Set,s=new Set,o=new Set(l(e,g.Parameter).map(n=>n.getName())),r=l(e,g.VariableDeclaration).some(n=>{const c=n.getInitializer();return n.getName()===f&&m.isIdentifier(c)&&o.has(c.getText())});(o.has(f)||r)&&s.add(f);const i=n=>{if(m.isObjectBindingPattern(n))for(const c of n.getElements()){const d=v(c);d&&t.add(d)}};for(const n of l(e,g.BindingElement)){if(v(n)!==f)continue;const c=n.getNameNode();m.isIdentifier(c)?s.add(c.getText()):i(c)}const a=n=>m.isIdentifier(n)&&s.has(n.getText());for(const n of l(e,g.PropertyAccessExpression))a(n.getExpression())&&t.add(n.getName());L(e,a,t);for(const n of l(e,g.VariableDeclaration)){const c=n.getInitializer();c!==void 0&&a(c)&&i(n.getNameNode())}return t},V=e=>{if(e.isTypeOnly())return!0;if(m.isExportDeclaration(e)){const s=e.getNamedExports();return!e.isNamespaceExport()&&s.length>0&&s.every(o=>o.isTypeOnly())}const t=e.getNamedImports();return e.getDefaultImport()===void 0&&e.getNamespaceImport()===void 0&&t.length>0&&t.every(s=>s.isTypeOnly())},z=new Map(u.flatMap(({bindingFreeExports:e,moduleSpecifier:t})=>e===void 0?[]:[[t,new Set(e)]])),F=(e,t)=>{const s=z.get(t);if(s===void 0||m.isImportDeclaration(e)&&(e.getDefaultImport()!==void 0||e.getNamespaceImport()!==void 0))return!1;const o=m.isExportDeclaration(e)?e.getNamedExports():e.getNamedImports();return o.length>0&&o.every(r=>r.isTypeOnly()||s.has(r.getName()))},_=e=>{const t=new Set;for(const s of l(e,g.CallExpression)){const[o]=s.getArguments();s.getExpression().getKind()===g.ImportKeyword&&(m.isStringLiteral(o)||m.isNoSubstitutionTemplateLiteral(o))&&t.add(o.getLiteralValue())}return t},T="@lunora/agent",E="requestSecretTool",b=e=>e.startsWith("./")||e.startsWith("../"),S=e=>e.getAliasNode()?.getText()??e.getNameNode().getText(),h=(e,t)=>{const s=e!==void 0&&m.isCallExpression(e)?e.getExpression():e;return s!==void 0&&m.isIdentifier(s)&&t.has(s.getText())},k=e=>{const t=new Set;for(const s of e.getImportDeclarations())if(!(s.getModuleSpecifierValue()!==T||s.isTypeOnly()))for(const o of s.getNamedImports())!o.isTypeOnly()&&o.getNameNode().getText()===E&&t.add(S(o));for(const s of e.getVariableStatements())for(const o of s.getDeclarations())h(o.getInitializer(),t)&&t.add(o.getName());return t},p=e=>({names:new Set(e),namespaces:new Map}),x=new WeakMap,y=()=>{const e=Object.freeze({});return x.set(e,{projects:new Map,origins:new Map}),e},B=(e,t)=>{const s=x.get(e);if(s.origins.has(t))return t;let o=s.projects.get(t);return o===void 0&&(o=new M({compilerOptions:{...t.getCompilerOptions(),allowJs:!0},fileSystem:t.getFileSystem(),skipAddingFilesFromTsConfig:!0,skipFileDependencyResolution:!0,skipLoadingLibFiles:!0}),s.projects.set(t,o),s.origins.set(o,t)),o},O=(e,t,s)=>{const o=t.getSourceFile(),r=o.getProject(),i=x.get(e)?.origins.get(r)??r,{resolvedModule:a}=D.resolveModuleName(s,o.getFilePath(),i.getCompilerOptions(),i.getModuleResolutionHost()),n=a?.resolvedFileName;if(n===void 0)return;const c=i.getSourceFile(n)??r.getSourceFile(n);if(c!==void 0)return c;const d=B(e,r);return d.getSourceFile(n)??d.addSourceFileAtPath(n)},K=(e,t,s)=>{const o=e.getNamespaceExport();if(o!==void 0){const r=new Set(t.names);t.namespaces.forEach((i,a)=>{i.forEach(n=>{r.add(`${a}.${n}`)})}),r.size>0&&s.namespaces.set(o.getName(),r);return}if(!e.hasNamedExports()){t.names.forEach(r=>s.names.add(r)),t.namespaces.forEach((r,i)=>s.namespaces.set(i,r));return}for(const r of e.getNamedExports()){if(r.isTypeOnly())continue;const i=r.getNameNode().getText(),a=S(r);t.names.has(i)&&s.names.add(a);const n=t.namespaces.get(i);n!==void 0&&s.namespaces.set(a,n)}},W=(e,t,s,o)=>{const r=t.getModuleSpecifierValue();if(r===void 0)return p(s);if(r===T)return p([E]);const i=b(r)?O(e,t,r):void 0;return i===void 0?p([]):o(i)},w=(e,t,s)=>{const o=p([]),r=e.getFilePath();if(t.has(r))return o;t.add(r);const i=k(e);for(const a of e.getExportDeclarations())a.isTypeOnly()||K(a,W(s,a,i,n=>w(n,t,s)),o);for(const a of e.getVariableStatements())if(a.hasExportKeyword())for(const n of a.getDeclarations())h(n.getInitializer(),i)&&o.names.add(n.getName());return t.delete(r),o},j=(e,t,s)=>{const o=e.getModuleSpecifierValue();if(o===T)return p([E]);const r=b(o)?O(s,e,o):void 0;return r===void 0?p([]):w(r,new Set([t.getFilePath()]),s)},$=e=>{const t=e.getPropertyNameNode();return t===void 0?e.getName():m.isStringLiteral(t)?t.getLiteralValue():t.getText()},N=(e,t,s)=>{const o=(n,c)=>n===t?s.has(c):n.startsWith(`${t}.`)&&s.has(`${n.slice(t.length+1)}.${c}`),r=e.getDescendantsOfKind(g.PropertyAccessExpression).some(n=>o(n.getExpression().getText(),n.getName())),i=l(e,g.ElementAccessExpression).some(n=>{const c=n.getArgumentExpression();return m.isStringLiteral(c)&&o(n.getExpression().getText(),c.getLiteralValue())}),a=l(e,g.VariableDeclaration).some(n=>{const c=n.getInitializer(),d=n.getNameNode();return c!==void 0&&m.isObjectBindingPattern(d)&&d.getElements().some(R=>o(c.getText(),$(R)))});return r||i||a},q=(e,t,s)=>{if(s.names.has(t.getNameNode().getText()))return!0;const o=s.namespaces.get(t.getNameNode().getText());return o!==void 0&&N(e,S(t),o)},U=(e,t=y())=>e.getImportDeclarations().some(s=>{if(s.isTypeOnly())return!1;const o=j(s,e,t);if(o.names.size===0&&o.namespaces.size===0)return!1;const r=s.getDefaultImport(),i=s.getNamespaceImport();return r!==void 0&&(o.names.has("default")||N(e,r.getText(),o.namespaces.get("default")??new Set))||s.getNamedImports().some(n=>!n.isTypeOnly()&&q(e,n,o))||i!==void 0&&N(e,i.getText(),o.names)}),X=(e,t=y())=>{const s=e.getImportDeclarations(),o=I();for(const r of s){const i=A(r);for(const a of Object.keys(o))o[a]||=i[a]}return{contextReads:C(e),dynamicImports:_(e),requestSecretTool:U(e,t),sandboxTools:o,valueImports:new Set([...s,...e.getExportDeclarations()].flatMap(r=>{const i=r.getModuleSpecifierValue();return i===void 0||V(r)||F(r,i)?[]:[i]}))}},G=e=>{const t=new Set,s=new Set,o=I(),r=new Set;let i=!1;for(const a of e){i||=a.requestSecretTool;for(const n of a.contextReads)t.add(n);for(const n of a.dynamicImports)s.add(n);for(const n of a.valueImports)r.add(n);for(const n of Object.keys(o))o[n]||=a.sandboxTools[n]}return{contextReads:t,dynamicImports:s,requestSecretTool:i,sandboxTools:o,valueImports:r}},H=e=>new Set(u.filter(({contextProperty:t,moduleSpecifier:s})=>e.valueImports.has(s)||t!==void 0&&e.contextReads.has(t)).map(({key:t})=>t)),J=new RegExp(String.raw`\b${f}\b`,"u"),Q=new RegExp(String.raw`\b(?:${u.flatMap(({contextProperty:e})=>e===void 0?[]:[e]).join("|")})\b`,"u"),se=e=>J.test(e)&&Q.test(e),oe=(e,t)=>{const s=y(),o=G(P(t).map(i=>X(e.getSourceFile(i)??e.addSourceFileAtPath(i),s))),r=H(o);return Object.fromEntries(u.map(({key:i})=>[i,r.has(i)]))};export{H as capabilitiesUsedBy,C as contextPropertiesRead,y as createTargetScope,oe as discoverFeatureUsage,U as fileWiresRequestSecretTool,G as foldCapabilitySignals,se as mayReadCapabilityContext,X as sourceCapabilitySignals};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as o,VariableDeclarationKind as b,SyntaxKind as h}from"ts-morph";import{a as y,b as l}from"./module-specifiers-BctA0m_p.mjs";import{unwrapExpression as c,symbolConstInitializer as F,isConstDeclaration as z}from"./isTestPath-Uwb5a6Kq.mjs";const ee=e=>o.isIdentifier(e)?e.getText():o.isPropertyAccessExpression(e)?e.getName():void 0,N=(e,t,r=l)=>{const i=new Set;for(const n of e.getImportDeclarations())if(r(n.getModuleSpecifierValue()))for(const s of n.getNamedImports())s.getNameNode().getText()===t&&i.add(s.getAliasNode()?.getText()??s.getName());return i},K=(e,t)=>{if(o.isPropertyAccessExpression(e))return e.getName()===t;if(!o.isIdentifier(e))return!1;const r=e.getText();return r===t||N(e.getSourceFile(),t).has(r)},x=e=>{for(const t of e.getSymbol()?.getDeclarations()??[])if(o.isImportSpecifier(t)&&l(t.getImportDeclaration().getModuleSpecifierValue()))return t.getNameNode().getText()},C=e=>e.getSymbol()?x(e):e.getText(),R=(e,t)=>o.isIdentifier(e)&&x(e)===t,te=(e,t)=>{const r=e.getExpression(),i=e.getSourceFile();if(o.isIdentifier(r))return N(i,t,y).has(r.getText());if(!o.isPropertyAccessExpression(r)||r.getName()!==t)return!1;const n=r.getExpression().getText();return i.getImportDeclarations().some(s=>s.getNamespaceImport()?.getText()===n&&y(s.getModuleSpecifierValue()))},_=3,B=e=>{if(!e||!o.isIdentifier(e))return;const t=e.getSymbol()?.getValueDeclaration();if(!z(t))return;const r=c(t.getInitializer());return r&&o.isCallExpression(r)?r:void 0},d=e=>{const t=[];let r=c(e),i=0;for(;;){for(;r&&o.isCallExpression(r);){const s=c(r.getExpression());if(!s||!o.isPropertyAccessExpression(s))return{root:void 0,steps:t};t.push({call:r,name:s.getName()}),r=c(s.getExpression())}const n=i<_?B(r):void 0;if(!n)return{root:r,steps:t};i+=1,r=n}},E=e=>d(e).steps,L=e=>{if(o.isCallExpression(e))return e;if(!o.isIdentifier(e))return;const t=c(F(e.getSymbol()));return t&&o.isCallExpression(t)?t:void 0},D=(e,t,r)=>E(e).filter(i=>i.name===t).map(i=>i.call.getArguments()[0]).map(i=>i===void 0?void 0:L(i)).filter(i=>i!==void 0&&r(i.getExpression())),j=(e,t,r)=>D(e,t,i=>K(i,r)),ie=(e,t)=>E(e).some(r=>r.name===t),re=(e,t,r)=>j(e,t,r).length>0,A=new Set(["action","internalAction","internalMutation","internalQuery","mutation","query","stream"]),T=e=>{if(o.isIdentifier(e)){for(const t of e.getSymbol()?.getDeclarations()??[])if(o.isImportSpecifier(t)&&l(t.getImportDeclaration().getModuleSpecifierValue()))return t.getName()}if(o.isPropertyAccessExpression(e)){const t=e.getExpression();if(o.isIdentifier(t))return t.getSymbol()?.getDeclarations().some(i=>o.isNamespaceImport(i)&&l(i.getFirstAncestorByKindOrThrow(h.ImportDeclaration).getModuleSpecifierValue()))?e.getName():void 0}},W=e=>{const t=e.getParent(),r=t.getParent(),i=e.getPropertyNameNode()??e.getNameNode();if(!o.isObjectBindingPattern(t)||!o.isVariableDeclaration(r)||r.getVariableStatement()?.getDeclarationKind()!==b.Const||e.getDotDotDotToken()||e.getInitializer()||!o.isIdentifier(i)||!A.has(i.getText())||i.getText()==="stream")return;const n=r.getInitializer();if(!n)return;const{root:s,steps:a}=d(n);return s&&T(s)==="initLunora"&&a.length===2&&a[0]?.name==="create"&&a[1]?.name==="dataModel"?i.getText():void 0},U=e=>{const t=T(e);if(t)return A.has(t)?{factory:t}:{};if(!o.isIdentifier(e))return{};const r=e.getSymbol(),i=(r?.isAlias()?r.getAliasedSymbol():r)?.getValueDeclaration();return i&&o.isBindingElement(i)?{factory:W(i)}:i&&o.isVariableDeclaration(i)&&i.getVariableStatement()?.getDeclarationKind()===b.Const?{initializer:i.getInitializer()}:{}},q=e=>{const t=[],r=new Set;let i=e;for(;i!==void 0&&!r.has(i);){r.add(i);const n=d(i);if(t.push(...n.steps),!n.root)break;const{factory:s,initializer:a}=U(n.root);if(s)return{factory:s,steps:t};i=a}return{steps:t}},g=new Set(["action","mutation","query","stream"]),w={internalAction:"action",internalMutation:"mutation",internalQuery:"query"},f={onConnect:"connect",onDisconnect:"disconnect",onQueryChange:"reactor",onShardInit:"init",onWhisper:"whisper",defineWebSocket:"socket"},p={defineRoom:"room"},H=e=>e==="whisper"?"query":"mutation",O=e=>{const{root:t}=d(e);return t&&o.isIdentifier(t)?t:void 0},k=(e,t=!1)=>{const r=O(e);if(!r)return;const i=C(r);if(i===void 0){if(t)return;const n=r.getSymbol()?.getValueDeclaration();if(n&&o.isVariableDeclaration(n)){const s=n.getInitializer();return s?k(s,!0):void 0}return}return g.has(i)?"public":w[i]?"internal":void 0},V=(e,t=!1)=>{if(D(e,"use",s=>R(s,"platformAdmin")).length>0)return!0;if(t)return!1;const r=O(e)?.getSymbol(),i=(r?.isAlias()?r.getAliasedSymbol():r)?.getValueDeclaration(),n=i&&o.isVariableDeclaration(i)?i.getInitializer():void 0;return n!==void 0&&V(n,!0)},v=e=>V(e)?{adminOnly:!0}:{},Q=(e,t)=>{const r=e.getName();if(!g.has(r))return;const i=e.getExpression(),n=c(i)??i,s=i===n?[n]:[i,n];if(s.some(u=>u.getType().getProperty("__lunoraProcedure"))){const u=s.some(M=>M.getType().getProperty("__lunoraVisibility"));return{kind:r,receiver:n,visibility:u?"internal":"public",...v(n)}}const a=t?q(n).factory:void 0,P=a?.startsWith("internal")?"internal":"public",m=a?P:k(n);if(m)return{kind:r,receiver:n,visibility:m,...v(n)}},X=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>o.isNamespaceImport(t)&&l(t.getFirstAncestorByKind(h.ImportDeclaration)?.getModuleSpecifierValue()??"")),Y=e=>Object.hasOwn(p,e)||Object.hasOwn(f,e),I=e=>{if(Object.hasOwn(p,e))return{channel:p[e],kind:"mutation",visibility:"internal"};const t=Object.hasOwn(f,e)?f[e]:void 0;return t?{kind:H(t),lifecycle:t,visibility:"internal"}:void 0},G=(e,t)=>{const r=e.getExpression();if(o.isPropertyAccessExpression(r)){const s=r.getExpression(),a=r.getName();return Y(a)&&o.isIdentifier(s)&&X(s)?I(a):Q(r,t)}if(!o.isIdentifier(r))return;const i=C(r);if(!i)return;if(g.has(i))return{kind:i,visibility:"public"};const n=w[i];return n?{kind:n,visibility:"internal"}:I(i)},S=new WeakMap,ne=(e,t=!1)=>{const r=e.getProject().getTypeChecker().compilerObject;let i=S.get(r);i===void 0&&(i=new WeakMap,S.set(r,i));let n=i.get(e.compilerNode);return n===void 0&&(n=new Map,i.set(e.compilerNode,n)),n.has(t)||n.set(t,G(e,t)),n.get(t)};export{ee as a,E as b,ne as c,te as d,re as e,R as f,L as g,ie as h,N as i,K as r,q as s,j as w};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as u,readFileSync as w}from"node:fs";import{join as d,isAbsolute as h,resolve as g}from"node:path";import{ts as E}from"ts-morph";import{companionDirectory as b,COMPANION_SERVICE_NAME as $,COMPANION_BINDING as p,companionName as S}from"./COMPANION_BINDING-Da_v9XpC.mjs";import{a as y,r as C}from"./project-config-file-DR7xrrNB.mjs";const v=/^[A-Za-z_$][\w$]*$/u,N=["wrangler.jsonc","wrangler.json"],I=i=>`SERVICE_${i.replaceAll(/(?<=[a-z0-9])(?=[A-Z])/gu,"_").toUpperCase()}`,_=(i,e)=>{const r=N.map(n=>d(e,n)).find(n=>u(n));if(r===void 0){const n=u(d(e,"wrangler.toml"))?" (its wrangler.toml is not read — Lunora reads a service's config as JSON(C) only)":"";throw new Error(`@lunora/codegen: service "${i}" points at ${e}, which has no wrangler.jsonc / wrangler.json${n}`)}const o=E.parseConfigFileTextToJson(r,w(r,"utf8"));if(o.error!==void 0||typeof o.config!="object"||o.config===null)throw new Error(`@lunora/codegen: service "${i}": ${r} is not valid JSON(C)`);return{config:o.config,path:r}},f=(i,e)=>{const r=i.route??e.route,o=i.routes??e.routes;return!(r!==void 0||Array.isArray(o)&&o.length>0)&&(i.workers_dev??e.workers_dev)!==!1},O=(i,e,r)=>{if(!v.test(e))throw new Error(`@lunora/codegen: service key "${e}" must be an identifier — it becomes ctx.services.${e}`);if(r.entrypoint!==void 0&&!v.test(r.entrypoint))throw new Error(`@lunora/codegen: service "${e}": entrypoint "${r.entrypoint}" must name an exported WorkerEntrypoint class`);const o=h(r.dir)?r.dir:g(i,r.dir),{config:n,path:t}=_(e,o),{main:s,name:m}=n;if(typeof m!="string"||m==="")throw new Error(`@lunora/codegen: service "${e}": ${t} declares no Worker "name"`);if(typeof s!="string"||s==="")throw new Error(`@lunora/codegen: service "${e}": ${t} declares no "main" entry module`);const l=Object.entries(n.env??{}).map(([c,a])=>[c,a??{}]);return{binding:I(e),...r.entrypoint===void 0?{}:{entrypoint:r.entrypoint},envWorkers:Object.fromEntries(l.flatMap(([c,a])=>typeof a.name=="string"&&a.name!==""?[[c,a.name]]:[])),main:g(o,s),name:e,publicScopes:[...f(n,n)?[""]:[],...l.filter(([,c])=>f(c,n)).map(([c])=>c)],...r.entrypoint===void 0||r.rpc===!1?{}:{rpcEntrypoint:r.entrypoint},worker:m,wranglerPath:t}},j=i=>{const{services:e}=C(i);if(e?.unreadable===!0)throw new Error('@lunora/codegen: lunora.config `services` must be an inline object of { dir: "…", entrypoint?: "…", rpc?: false } literals — codegen reads it without running the file');const r=Object.entries(e?.declared??{}).map(([o,n])=>O(i,o,n)).toSorted((o,n)=>o.name.localeCompare(n.name));for(const[o,n]of r.entries()){const t=r.slice(o+1).find(s=>s.binding===n.binding);if(t!==void 0)throw new Error(`@lunora/codegen: services "${n.name}" and "${t.name}" both map to the binding ${n.binding} — rename one`)}return r},A=i=>{try{return{services:j(i)}}catch(e){return{error:e instanceof Error?e.message:String(e),services:[]}}},B=(i,e="lunora")=>{if(!y(d(i,e)))return;const r=b(i,e);return{binding:p,envWorkers:{},main:d(r,"src","worker.ts"),name:$,publicScopes:[],worker:S(i),wranglerPath:d(r,"wrangler.jsonc")}},P=(i,e="lunora")=>{const{error:r,services:o}=A(i);try{const n=B(i,e);if(n===void 0)return{...r===void 0?{}:{error:r},services:o};const t=o.find(s=>s.worker===n.worker);return t!==void 0?{error:`lunora.config services.${t.name} deploys as "${t.worker}", the name the studio.companion Worker is given; rename that Worker or turn studio.companion off`,services:o}:{...r===void 0?{}:{error:r},services:[...o,n]}}catch(n){return{error:r??(n instanceof Error?n.message:String(n)),services:o}}},D=(i,e="lunora")=>{const r=P(i,e);return{...r,services:r.services.filter(o=>o.binding!==p||u(o.wranglerPath))}};export{B as companionServiceBinding,P as readBoundServiceBindings,D as readDevServiceBindings,A as readServiceBindings,j as resolveServiceBindings};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as i}from"ts-morph";import{listLunoraSourceFiles as a,lunoraRelativePath as c,handlerOf as l}from"./isTestPath-Uwb5a6Kq.mjs";import{j as d,h as f}from"./attribution-Cwt30DDJ.mjs";import{b as u}from"./context-root-BpDEhvNE.mjs";import{c as m}from"./classify-procedure-call-BmEirzc_.mjs";const p=t=>{const r=t.getInitializer();if(!r||!i.isCallExpression(r))return;const e=m(r);if(!e||e.kind!=="query"&&e.kind!=="mutation")return;const o=l(r,e.receiver);return o?{exportName:f(t)??t.getName(),handler:o,kind:e.kind}:void 0},x=(t,r)=>{const e=t.getParent();return e&&i.isPropertyAccessExpression(e)&&e.getExpression()===t?`ctx.${r}.${e.getName()}`:`ctx.${r}`},h=(t,r,e)=>{const o=[];for(const n of u(t.handler,e))o.push({callee:x(n,e),exportName:t.exportName,file:r,kind:t.kind,line:n.getStartLineNumber()});return o},N=(t,r,e)=>{const o=[];for(const n of d(t)){const s=p(n);s&&o.push(...h(s,r,e))}return o},F=(t,r,e)=>{const o=[];for(const n of a(r)){const s=t.getSourceFile(n)??t.addSourceFileAtPath(n);o.push(...N(s,c(r,n),e))}return o};export{F as d};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as s,SyntaxKind as d}from"ts-morph";import{unwrapExpression as l,memberAccessOf as C,descendantsOfKind as p,bindingKeyName as I,isConstDeclaration as D,findObjectProperty as h,walkChain as M}from"./isTestPath-Uwb5a6Kq.mjs";import{d as v,b as O,f as F}from"./attribution-Cwt30DDJ.mjs";import{c as b}from"./classify-procedure-call-BmEirzc_.mjs";import{isDefineMutatorCallee as w}from"./MUTATORS_FILENAME-C0ZV0hh6.mjs";const x=8,E=t=>{if(s.isMethodDeclaration(t))return t;const e=s.isPropertyAssignment(t)?l(t.getInitializer()):void 0,o=s.isShorthandPropertyAssignment(t)?t.getNameNode():e;if(s.isArrowFunction(o)||s.isFunctionExpression(o))return o;const i=s.isIdentifier(o)?v(o):void 0;if(s.isFunctionDeclaration(i))return i;const n=D(i)?l(i.getInitializer()):void 0;return s.isArrowFunction(n)||s.isFunctionExpression(n)?n:void 0},T=t=>{const e=l(t.getArguments()[0]),o=s.isObjectLiteralExpression(e)?e:void 0,i=h(o,"server"),n=h(o,"handler"),r=i!==void 0&&w(t.getExpression()),a=n===void 0?void 0:b(t),u=a!==void 0&&a.receiver===void 0;return[r?E(i):void 0,u?E(n):void 0].filter(f=>f!==void 0)},P=new WeakMap,S=t=>{const e=t.getSourceFile(),o=P.get(e.compilerNode);if(o!==void 0)return o;const i=new Set(e.getDescendantsOfKind(d.CallExpression).flatMap(n=>T(n)).map(n=>n.compilerNode));return P.set(e.compilerNode,i),i},A=t=>{const e=t.getParent();return(s.isArrowFunction(e)||s.isFunctionExpression(e)||s.isFunctionDeclaration(e)||s.isMethodDeclaration(e))&&e.getParameters()[0]===t&&S(t).has(e.compilerNode)},Q=t=>{const e=t.getParent();return(s.isArrowFunction(e)||s.isFunctionExpression(e)||s.isFunctionDeclaration(e)||s.isMethodDeclaration(e))&&e.getParameters()[1]===t&&S(t).has(e.compilerNode)},B=t=>t.getNameNode().getDescendantsOfKind(d.BindingElement).some(e=>e.getParent().getParent()===t&&["args","ctx"].includes(I(e))),g=(t,e,o)=>{const i=t.getParent().getParent(),n=I(t);if(t.getDotDotDotToken()!==void 0||e==="trust"&&O(t))return;let r;if(s.isParameterDeclaration(i)){if(!A(i)||B(i))return n==="ctx"?[]:void 0;r=[]}else s.isBindingElement(i)?r=g(i,e,o):s.isVariableDeclaration(i)&&o>0&&(r=c(i.getInitializer(),e,o-1));return r===void 0?void 0:[...r,n]},c=(t,e="discover",o=x)=>{const i=l(t),n=C(i);if(n!==void 0){const r=c(n.object,e,o);return r===void 0?void 0:[...r,n.member]}return s.isIdentifier(i)?H(i,e,o):void 0},H=(t,e,o)=>{const i=t.getText()==="ctx",n=e==="trust"||!i?v(t):void 0;return i&&!s.isVariableDeclaration(n)?s.isBindingElement(n)?g(n,e,o):[]:s.isParameterDeclaration(n)?s.isIdentifier(n.getNameNode())&&A(n)?[]:void 0:s.isBindingElement(n)?g(n,e,o):!(s.isVariableDeclaration(n)&&s.isIdentifier(n.getNameNode())&&o>0)||e==="trust"&&O(n)?void 0:c(n.getInitializer(),e,o-1)},q=t=>c(t,"discover"),J=t=>c(t,"trust"),K=t=>{const e=c(t);return e===void 0?void 0:["ctx",...e].join(".")},Y=(t,e)=>{if(e(t.getText()))return!0;const o=K(t);return o!==void 0&&e(o)},Z=(t,e)=>{const o=l(t),i=C(o);if(i!==void 0&&i.member!==e.at(-1))return!1;const n=o===void 0?void 0:c(o);return n?.length===e.length&&n.every((r,a)=>r===e[a])},$=(t,e)=>y(t).get(e)??[],U=t=>{const e=new Map;for(const i of p(t,d.BindingElement)){const n=s.isIdentifier(i.getNameNode())?g(i,"discover",x):void 0;n?.length===1&&n[0]!==void 0&&e.set(i.compilerNode,n[0])}const o=new Set([...e.keys()].map(i=>i.name.getText()));return p(t,d.Identifier).flatMap(i=>{const r=o.has(i.getText())&&!s.isBindingElement(i.getParent())?v(i):void 0,a=r===void 0?void 0:e.get(r.compilerNode);return a===void 0?[]:[[a,i]]})},N=new WeakMap,y=t=>{const e=N.get(t.compilerNode);if(e!==void 0)return e;const o=new Map;for(const[n,r]of[...z(t),...U(t)])o.set(n,[...o.get(n)??[],r]);const i=new Map([...o].map(([n,r])=>[n,r.toSorted((a,u)=>a.getPos()-u.getPos())]));return N.set(t.compilerNode,i),i},z=t=>t.getDescendantsOfKind(d.PropertyAccessExpression).flatMap(e=>_(e.getExpression())?[[e.getName(),e]]:[]),_=t=>s.isIdentifier(t)&&c(t)?.length===0,ee=t=>{const e=c(t);return e?.length===1&&e[0]==="db"},R=new Set(["asId","createMultipartUpload","fetch","generateUploadUrl","getPresignedUrl","getSignedUrl","getUrl","normalizeId","resumeMultipartUpload","runAction","runMutation","runQuery","store","upload"]),k=new Set(["catch","flatMap","map","reduce","reduceRight","then"]),L=(t,e=x)=>{const o=M(t,u=>{const f=l(u.getExpression()),m=s.isPropertyAccessExpression(f)?f.getName():void 0;return m!==void 0&&(R.has(m)||k.has(m))?!1:void 0}),i=o.root;if(o.verdict!==void 0||!s.isIdentifier(i))return o.verdict??!1;if(c(i,"trust")!==void 0)return!0;const n=v(i),r=s.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n,a=D(r)&&e>0?r.getInitializer():void 0;return a!==void 0&&L(a,e-1)},te=t=>(s.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(o=>F(o)&&c(o,"trust")!==void 0);export{k as C,R as E,_ as a,$ as b,J as c,ee as d,Z as e,K as f,q as g,L as h,Q as i,E as j,Y as m,te as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHash as R}from"node:crypto";import{readFileSync as F,existsSync as d,readdirSync as A,statSync as L}from"node:fs";import{dirname as h,join as g}from"node:path";import{Project as x,ts as i}from"ts-morph";import{listSecurityScanFiles as T,listLunoraSourceFiles as K}from"./isTestPath-Uwb5a6Kq.mjs";import{projectConfigCandidatePaths as O}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";const m=e=>e.replaceAll("\\","/"),_=e=>{const t=K(e),s=g(e,"schema.ts");return d(s)&&t.push(s),t},$=e=>{const t=g(e,"_generated");return d(t)?A(t,{encoding:"utf8",recursive:!0}).filter(s=>s.endsWith(".ts")).map(s=>g(t,s)).filter(s=>L(s).isFile()):[]},D=/\.d\.(?:ts|mts|cts)$/,W=/\.[cm]?jsx?$/,G=/\bdeclare\b|\/\/\//,J=e=>{const t=i.createScanner(i.ScriptTarget.Latest,!0,i.LanguageVariant.Standard,e),s=t.scan();if(s===i.SyntaxKind.ExportKeyword)return!0;if(s!==i.SyntaxKind.ImportKeyword)return!1;const n=t.scan();return n===i.SyntaxKind.OpenBraceToken||n===i.SyntaxKind.AsteriskToken||n===i.SyntaxKind.StringLiteral},U=e=>i.isCallExpression(e)?i.isIdentifier(e.expression)&&e.expression.text==="require":i.isPropertyAccessExpression(e)&&i.isIdentifier(e.expression)?e.expression.text==="exports"||e.expression.text==="module"&&e.name.text==="exports":!1,P=e=>U(e)||i.forEachChild(e,P)===!0,V=e=>i.isModuleDeclaration(e)&&i.isIdentifier(e.name)&&e.name.text==="global",C=new Map,q=(e,t,s)=>{if(!G.test(t)&&(s||J(t)))return{augments:[],hasGlobal:!1,isModule:!0};const n=i.createSourceFile(e,t,i.ScriptTarget.Latest,!1),r=n.referencedFiles.length>0||n.typeReferenceDirectives.length>0||n.libReferenceDirectives.length>0;return{augments:n.statements.flatMap(o=>i.isModuleDeclaration(o)&&i.isStringLiteral(o.name)?[o.name.text]:[]),hasGlobal:r||n.statements.some(o=>V(o)),isModule:s||i.isExternalModule(n)||W.test(e)&&P(n)}},z=(e,t,s)=>{const n=`${s?"force":"auto"}:${R("sha256").update(t).digest("hex")}`,r=C.get(e);if(r?.key===n)return r.analysis;const o=q(e,t,s);return C.set(e,{analysis:o,key:n}),o},w=e=>{const t={...i.sys,onUnRecoverableConfigFileDiagnostic:()=>{}},s=i.getParsedCommandLineOfConfigFile(e,void 0,t);return{fileNames:s?.fileNames??[],forceModules:s?.options.moduleDetection===i.ModuleDetectionKind.Force}},N=new WeakMap,E=(e,t)=>{const{fileNames:s=[],forceModules:n=!1}=t??{},r=`${m(e)}/`,o=[],l=[],f=[];for(const c of s){if(!d(c))continue;if(D.test(c)){o.push(c);continue}if(m(c).startsWith(r))continue;const a=z(c,F(c,"utf8"),n);!a.isModule||a.hasGlobal?l.push(c):a.augments.length>0&&f.push({augments:a.augments,path:c})}return{augmentations:f,files:[...new Set([..._(e),...T(e).map(({filePath:c})=>c),...$(e),...o,...l,...O(e).filter(c=>d(c))])]}},b=(e,t,s)=>i.resolveModuleName(e,t,s,i.sys).resolvedModule?.resolvedFileName??e,B=(e,t)=>{const s=e.getCompilerOptions(),n=new Set;for(const r of t){const o=e.getSourceFile(r);if(o!==void 0)for(const{fileName:l}of i.preProcessFile(o.getFullText(),!0,!1).importedFiles)n.add(b(l,o.getFilePath(),s))}return n},M=new WeakMap,H=(e,t)=>{const s=e.getCompilerOptions(),n=new Map,r=new Set,o=[...t],l=f=>{const c=f.fileName,a=h(c);let u=M.get(f);u===void 0&&(u=i.preProcessFile(f.text,!0,!0),M.set(f,u));const y=u.referencedFiles.map(({fileName:p})=>g(a,p));for(const{fileName:p}of u.importedFiles){const S=`${a}\0${p}`;n.has(S)||n.set(S,i.resolveModuleName(p,c,s,i.sys).resolvedModule?.resolvedFileName);const v=n.get(S);v!==void 0&&y.push(v)}return y};for(;o.length>0;){const f=o.pop();if(f===void 0||m(f).includes("/node_modules/")||r.has(m(f)))continue;r.add(m(f));const c=e.getSourceFile(f);c!==void 0&&o.push(...l(c.compilerNode))}return r},k=(e,t,s)=>{const n=e.getCompilerOptions(),r=[];let o;for(;;){e.resolveSourceFileDependencies(),o=H(e,[...t,...r]);const l=s.filter(a=>!r.includes(a.path));if(l.length===0)break;const f=B(e,o),c=l.filter(a=>a.augments.some(u=>f.has(b(u,a.path,n))));if(c.length===0)break;for(const a of c)e.getSourceFile(a.path)===void 0&&e.createSourceFile(a.path,F(a.path,"utf8"),{overwrite:!0});r.push(...c.map(a=>a.path))}for(const l of e.getSourceFiles())!l.isInNodeModules()&&!o.has(l.getFilePath())&&e.removeSourceFile(l)},I=e=>{let t=d(e)?e:h(e);for(;t&&t!==h(t);){const s=g(t,"tsconfig.json");if(d(s))return s;t=h(t)}},se=e=>{const t={...i.sys,onUnRecoverableConfigFileDiagnostic:()=>{}},s=i.getParsedCommandLineOfConfigFile(e,{},t);return s===void 0?"":JSON.stringify({fileNames:s.fileNames,options:s.options})},te=e=>{const t=I(e);if(t===void 0)return new x({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1});const s=new x({skipAddingFilesFromTsConfig:!0,tsConfigFilePath:t,useInMemoryFileSystem:!1}),n=w(t);N.set(s,n);const r=E(e,n);for(const o of r.files)s.createSourceFile(o,F(o,"utf8"),{overwrite:!0});return k(s,r.files,r.augmentations),s},oe=(e,t)=>{const s=I(t),n=E(t,N.get(e)??(s===void 0?void 0:w(s)));for(const o of n.files){const l=e.getSourceFile(o);l===void 0?e.createSourceFile(o,F(o,"utf8"),{overwrite:!0}):l.refreshFromFileSystemSync()}const r=new Set(n.files);for(const o of e.getSourceFiles())if(!(r.has(o.getFilePath())||o.isInNodeModules()))try{o.refreshFromFileSystemSync()}catch{e.removeSourceFile(o)}k(e,n.files,n.augmentations)};export{te as createCodegenProject,I as findTsconfig,oe as refreshCodegenProject,se as tsconfigFingerprint};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{SyntaxKind as g,Node as n}from"ts-morph";import{descendantsOfKind as p}from"./isTestPath-Uwb5a6Kq.mjs";import{d as l}from"./context-root-BpDEhvNE.mjs";const c=e=>n.isPropertyAccessExpression(e)&&e.getName()==="db"||n.isIdentifier(e)&&e.getText()==="db"||l(e),b=new Set(["findFirst","findFirstOrThrow","findMany","findUnique"]),E=e=>{const t=e.getExpression();if(!n.isPropertyAccessExpression(t)||!b.has(t.getName()))return;const s=t.getExpression();if(c(s))return{options:e.getArguments()[1],table:d(e)};if(n.isPropertyAccessExpression(s)){const o=s.getExpression();if(c(o))return{options:e.getArguments()[0],table:s.getName()}}},f=(e,t)=>{const s=e.getExpression();return!n.isPropertyAccessExpression(s)||!t.has(s.getName())?!1:c(s.getExpression())},d=e=>{const t=e.getArguments()[0];return t&&n.isStringLiteral(t)?t.getLiteralText():""},A=(e,t,s)=>{const o=new Set,i=new Set;for(const a of p(e,g.CallExpression))if(f(a,t)){const r=d(a);r!==""&&o.add(r)}else if(f(a,s)){const r=d(a);r!==""&&i.add(r)}return{tablesRead:[...o],tablesWritten:[...i]}};export{c as i,E as r,A as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const u=t=>t.output!==void 0&&t.output.kind!=="any"&&t.kind!=="stream";export{u as d};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o=r=>[...new Set(r)].toSorted((e,s)=>e.localeCompare(s)),a=r=>o(r.filter(e=>e.level==="ERROR"&&e.suppressed===void 0).map(e=>e.name)),t=r=>o(r.filter(e=>e.level==="error").map(e=>e.name)),i=r=>({advisoryNames:a(r.advisories),platformDiagnosticNames:t(r.platformDiagnostics)});export{i as describeErrorLevelFindings,a as errorAdvisoryNames,t as errorPlatformDiagnosticNames,o as sortedUniqueNames};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as t}from"ts-morph";import{collectCallRows as n}from"./isTestPath-Uwb5a6Kq.mjs";import{c as p}from"./attribution-Cwt30DDJ.mjs";import{a}from"./property-name-7cBlgK_O.mjs";const c=s=>{const r=s.getExpression();if(!t.isPropertyAccessExpression(r))return!1;const e=r.getExpression();return t.isPropertyAccessExpression(e)?e.getName()==="authApi":t.isIdentifier(e)&&e.getText()==="authApi"},u=s=>{const r=s.getArguments()[0];if(r===void 0)return!1;if(!t.isObjectLiteralExpression(r))return!0;for(const e of r.getProperties())if((t.isPropertyAssignment(e)||t.isShorthandPropertyAssignment(e))&&a(e)==="headers"||t.isSpreadAssignment(e))return!0;return!1},d=(s,r)=>n(s,r,(e,o)=>{if(!c(e))return;const i=e.getExpression();return{file:o,hasHeaders:u(e),line:e.getStartLineNumber(),method:t.isPropertyAccessExpression(i)?i.getName():"",scope:p(e)}});export{d as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as x}from"@lunora/errors";import{CRON_SCHEDULE_KINDS as A,warnIfSecondsLeading as O,compileCronSchedule as S}from"@lunora/scheduler";import I from"@lunora/scheduler/validate";import{SyntaxKind as p,Node as i}from"ts-morph";import{diagnosticAt as f,CodegenDiagnosticError as R}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{i as b}from"./module-specifiers-BctA0m_p.mjs";import{listLunoraSourceFiles as y,declarationLineOf as $,lunoraRelativePath as P,functionKeyOf as v}from"./isTestPath-Uwb5a6Kq.mjs";import{a as D}from"./property-name-7cBlgK_O.mjs";const F=new Set([...A,"cron"]),V=e=>{const t=e.getSymbol();if(!t)return e.getText()==="cronJobs";for(const r of t.getDeclarations())if(i.isImportSpecifier(r))return b(r.getImportDeclaration().getModuleSpecifierValue())?r.getNameNode().getText()==="cronJobs":!1;return!1},k=e=>{const t=new Set;for(const r of e.getVariableDeclarations()){const n=r.getInitializer();if(n?.getKind()!==p.CallExpression)continue;const s=n.getExpression();i.isIdentifier(s)&&V(s)&&t.add(r.getName())}return t},j=e=>{let t=e;for(;i.isCallExpression(t)||i.isPropertyAccessExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t.getText():void 0},L=(e,t)=>{const r=e.getArguments()[t];return r&&(i.isStringLiteral(r)||i.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},_=(e,t)=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e)||i.isNumericLiteral(e))return e.getLiteralValue();if(i.isTrueLiteral(e))return!0;if(i.isFalseLiteral(e))return!1;if(i.isPrefixUnaryExpression(e)&&e.getOperatorToken()===p.MinusToken){const r=e.getOperand();if(i.isNumericLiteral(r))return-r.getLiteralValue()}if(i.isObjectLiteralExpression(e))return d(e,t);if(i.isArrayLiteralExpression(e))return e.getElements().map(r=>_(r,t));throw f(e,`Cron job "${t}" passes a non-static value where a literal is required; codegen can only read literals.`,{code:"CRON_NON_STATIC_VALUE",name:"LunoraError",status:500})},d=(e,t)=>{const r={};for(const n of e.getProperties()){if(!i.isPropertyAssignment(n))throw f(n,`Cron job "${t}" uses an unsupported object property (shorthand/spread/method) where a static literal is required.`,{code:"CRON_NON_STATIC_VALUE",name:"LunoraError",status:500});const s=n.getInitializer();s&&(r[D(n)]=_(s,t))}return r},C=(e,t,r)=>{const n=e.getArguments()[t];if(!n||!i.isPropertyAccessExpression(n))throw f(e,`Cron job "${r}" must reference a function statically (e.g. internal.email.digest); codegen cannot resolve a dynamic reference.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500});const s=v(n);if(s===void 0)throw f(n,`Cron job "${r}" function reference must be of the form internal.<…path>.fn (or api.<…path>.fn).`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500});return s},h=e=>({workflow:{className:e.className,exportName:e.exportName}}),w=e=>({workflow:{className:e.className,exportName:e.exportName}}),T=(e,t,r,n,s,o)=>{const a=e.getExpression();if(!i.isIdentifier(a)||a.getText()!==t)return;const c=r.get(e.getName());if(c)return o(c);throw f(e,`Cron job "${n}" targets ${t}.${e.getName()}, but no such ${s} is declared in lunora/${s}s.ts.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500})},U=(e,t,r,n,s)=>{const o=e.getArguments()[t];if(o&&i.isPropertyAccessExpression(o)){const a=T(o,"workflows",n,r,"workflow",h);if(a)return a;const c=T(o,"agents",s,r,"agent",w);return c||{functionPath:C(e,t,r)}}if(o&&i.isIdentifier(o)){const a=n.get(o.getText()),c=s.get(o.getText());if(a&&c)throw f(o,`Cron job "${r}" references "${o.getText()}", which is ambiguous: a workflow and an agent are both declared under that name.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500});if(a)return h(a);if(c)return w(c);throw f(o,`Cron job "${r}" references "${o.getText()}", which is neither a function (internal.file.fn / api.file.fn) nor a declared workflow in lunora/workflows.ts nor a declared agent in lunora/agents.ts.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500})}return{functionPath:C(e,t,r)}},M=/^@lunora\/scheduler:\s*/u,K=(e,t)=>{const r=L(e,1);if(r===void 0)throw f(e,`Cron job "${t}" must pass a string-literal cron expression to ".cron(...)".`,{code:"CRON_EXPR_NOT_STATIC",name:"LunoraError",status:500});if(!I(r))throw f(e,`Cron job "${t}" has an invalid cron expression "${r}" — expected 5 or 6 space-separated fields.`,{code:"CRON_EXPR_INVALID",name:"LunoraError",status:500});return O(r,`cron expression for job "${t}"`),r},z=(e,t,r)=>{const n=e.getArguments()[1];if(!n||!i.isObjectLiteralExpression(n))throw f(e,`Cron job "${r}" must pass an object-literal schedule to ".${t}(...)".`,{code:"CRON_SCHEDULE_NOT_STATIC",name:"LunoraError",status:500});try{return S(t,d(n,r),r)}catch(s){if(s instanceof R)throw s;const o=s instanceof Error?s.message.replace(M,""):String(s);throw f(e,o,{code:"CRON_SCHEDULE_INVALID",name:"LunoraError",status:500})}},H=(e,t,r,n,s)=>{const o=t.getName();if(!F.has(o)||!r.has(j(t.getExpression())??""))return;const a=L(e,0);if(a===void 0||a.trim()==="")throw f(e,`A cron ".${o}(...)" registration must pass a non-empty string-literal name as its first argument.`,{code:"CRON_NAME_NOT_STATIC",name:"LunoraError",status:500});const c=o==="cron"?K(e,a):z(e,o,a),u=U(e,2,a,n,s),l=e.getArguments()[3];return{args:l&&i.isObjectLiteralExpression(l)?d(l,a):{},cron:c,name:a,...u}},q=e=>{const t=new Set;for(const r of e){if(t.has(r.name))throw new x("DUPLICATE_CRON_NAME",`Duplicate cron job name "${r.name}": cron names must be unique across the project.`,{status:500});t.add(r.name)}},ee=(e,t,r=[],n=[])=>{const s=y(t),o=[],a=new Map(r.map(u=>[u.exportName,u])),c=new Map(n.map(u=>[u.exportName,u]));for(const u of s){const l=e.getSourceFile(u)??e.addSourceFileAtPath(u),g=k(l);if(g.size!==0)for(const m of l.getDescendantsOfKind(p.CallExpression)){const N=m.getExpression();if(!i.isPropertyAccessExpression(N))continue;const E=H(m,N,g,a,c);E&&o.push({...E,file:P(t,u),line:$(m)})}}return o.sort((u,l)=>u.name.localeCompare(l.name)),q(o),o};export{ee as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./declared-output-Iaar469J.mjs";import"./isTestPath-Uwb5a6Kq.mjs";import"./attribution-Cwt30DDJ.mjs";import"./unwrap-handler-return-DvbyiLjc.mjs";import"./ip-reads-D2qhKEb6.mjs";import"./classify-procedure-call-BmEirzc_.mjs";import{d as f}from"./index-DtJBMdZ4.mjs";import"./dispatch-namespace-DwTjD7BU.mjs";export{f as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as n}from"ts-morph";import{a as m,p as l}from"./parse-validator-BisfC8bR.mjs";import{listLunoraSourceFiles as d,lunoraRelativePath as h}from"./isTestPath-Uwb5a6Kq.mjs";import{j as f,h as g}from"./attribution-Cwt30DDJ.mjs";import{u as x}from"./unwrap-handler-return-DvbyiLjc.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}},T=(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},b=s=>{const e=s.getArguments()[0];return!e||!(n.isArrowFunction(e)||n.isFunctionExpression(e))?"unknown":x(e,!0)},y=(s,e,o,a)=>{const t=e.getName();if(!v.has(t))return;const r=T(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:b(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-BT1J7BqY.mjs";const t=(r,e)=>o(r,e,"sql");export{t as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as i}from"ts-morph";import{collectCallRows as n}from"./isTestPath-Uwb5a6Kq.mjs";import{c as a}from"./attribution-Cwt30DDJ.mjs";import{i as c}from"./database-calls-d-Sssc-3.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-Uwb5a6Kq.mjs";import"./attribution-Cwt30DDJ.mjs";import"./database-calls-d-Sssc-3.mjs";import"./classify-procedure-call-BmEirzc_.mjs";import{d as a}from"./index-CfSmiylg.mjs";export{a as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{SyntaxKind as p,Node as n}from"ts-morph";import{diagnosticAt as h}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{a as I}from"./module-specifiers-BctA0m_p.mjs";import{listLunoraSourceFiles as P,lunoraRelativePath as b,findObjectProperty as d}from"./isTestPath-Uwb5a6Kq.mjs";import{j as x,a as A}from"./attribution-Cwt30DDJ.mjs";const S=i=>{const r=i.getSymbol();if(!r)return i.getText()==="defineMigration";for(const t of r.getDeclarations())if(n.isImportSpecifier(t))return I(t.getImportDeclaration().getModuleSpecifierValue())?t.getNameNode().getText()==="defineMigration":!1;return!1},u=(i,r)=>{const t=d(i,r);if(!t||!n.isPropertyAssignment(t))return;const e=t.getInitializer();return e&&n.isStringLiteral(e)?e.getLiteralValue():void 0},z=i=>{const r=n.isPropertyAssignment(i)?i.getInitializer():void 0;if(r===void 0||!n.isObjectLiteralExpression(r))return;const t=u(r,"field"),e=d(r,"after"),o=n.isPropertyAssignment(e)?e.getInitializer():void 0;if(!(t===void 0||e!==void 0&&!(o!==void 0&&n.isNumericLiteral(o))))return{...o!==void 0&&n.isNumericLiteral(o)?{after:o.getLiteralValue()}:{},field:t}},E=i=>{const r=d(i,"covers"),t=n.isPropertyAssignment(r)?r.getInitializer():void 0;if(t===void 0||!n.isObjectLiteralExpression(t))return;const e={};for(const s of["jurisdiction","shardMode","table"]){const c=u(t,s);c!==void 0&&(e[s]=c)}const o=z(d(t,"ttl"));o!==void 0&&(e.ttl=o);const a=d(t,"memory");return n.isPropertyAssignment(a)&&a.getInitializer()?.getKind()===p.TrueKeyword&&(e.memory=!0),Object.keys(e).length===0?void 0:e},g=i=>n.isParenthesizedExpression(i)?g(i.getExpression()):i,v=i=>n.isArrowFunction(i)||n.isFunctionExpression(i)||n.isMethodDeclaration(i)||n.isFunctionDeclaration(i),y=(i,r=4)=>{const t=g(i);if(v(t))return t;if(r===0||!n.isIdentifier(t))return;const e=t.getParent(),o=n.isShorthandPropertyAssignment(e)?e.getValueSymbol():t.getSymbol(),a=o?.getAliasedSymbol()??o,s=a?.getValueDeclaration()??a?.getDeclarations()[0];if(s!==void 0){if(n.isVariableDeclaration(s)){const c=s.getInitializer();return c===void 0?void 0:y(c,r-1)}return v(s)?s:void 0}},N=i=>{const r=d(i,"up");let t=r;n.isPropertyAssignment(r)?t=r.getInitializer():n.isShorthandPropertyAssignment(r)&&(t=r.getNameNode());const e=t===void 0?void 0:y(t);if(e===void 0)return!1;const o=e.getParameters()[0]?.getNameNode();if(o===void 0||!n.isIdentifier(o))return!1;const a=m=>{const f=m===void 0?void 0:g(m);return f!==void 0&&n.isIdentifier(f)&&f.getText()===o.getText()},s=e.getBody();if(s===void 0)return!1;if(!n.isBlock(s))return a(s);const[c,...l]=s.getStatements();return l.length===0&&c!==void 0&&n.isReturnStatement(c)&&a(c.getExpression())},D=(i,r)=>{const t=i.getInitializer();if(t?.getKind()!==p.CallExpression)return;const e=t.getExpression();if(!n.isIdentifier(e)||!S(e))return;const o=t.getArguments()[0];if(!o||!n.isObjectLiteralExpression(o))return;const a=u(o,"id"),s=A(i,"member");if(s===void 0)return;if(a===void 0||a.trim()==="")throw h(o,`Migration "${s}" in "${r}" must declare \`id\` as a non-empty string literal so codegen can key the registry.`,{code:"MIGRATION_ID_NOT_STATIC",name:"LunoraError",status:500});const c=E(o);return{...c===void 0?{}:{covers:c},exportName:s,filePath:r,id:a,...N(o)?{identity:!0}:{},table:u(o,"table")??""}},M=i=>{const r=new Map;for(const t of i){const e=r.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});r.set(t.id,t.filePath)}},V=(i,r)=>{const t=P(r),e=[];for(const o of t){const a=i.getSourceFile(o)??i.addSourceFileAtPath(o),s=b(r,o);for(const c of x(a)){const l=D(c,s);l&&e.push(l)}}return e.sort((o,a)=>o.id.localeCompare(a.id)),M(e),e};export{V as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as s,SyntaxKind as d}from"ts-morph";import{listLunoraSourceFiles as m,lunoraRelativePath as g,handlerOf as u,descendantsOfKind as l}from"./isTestPath-Uwb5a6Kq.mjs";import{j as N,h as x}from"./attribution-Cwt30DDJ.mjs";import{c as p}from"./classify-procedure-call-BmEirzc_.mjs";const h={"crypto.getRandomValues":"crypto.getRandomValues","crypto.randomUUID":"crypto.randomUUID","Date.now":"Date.now","Math.random":"Math.random"},E=new Set(["globalThis","self"]),v=new Set(["globalThis","self","window"]),I=e=>{if(s.isIdentifier(e))return e.getText();if(s.isPropertyAccessExpression(e)){const t=e.getExpression();if(s.isIdentifier(t)&&v.has(t.getText()))return e.getName()}},S=e=>{const t=e.getExpression();if(s.isIdentifier(t)){const o=t.getText();return o==="fetch"||o==="Date"?o:void 0}if(!s.isPropertyAccessExpression(t))return;const n=t.getName(),i=I(t.getExpression());if(i!==void 0)return n==="fetch"&&E.has(i)?"fetch":h[`${i}.${n}`]},T=e=>{const t=e.getExpression();if(!s.isIdentifier(t)||t.getText()!=="Date")return;const n=e.getArguments(),i=n.every(o=>s.isNumericLiteral(o)||s.isStringLiteral(o)||s.isNoSubstitutionTemplateLiteral(o));return n.length>0&&i?void 0:"new Date"},y=e=>{const t=e.getInitializer();if(!t||!s.isCallExpression(t))return;const n=p(t);if(!n||n.kind!=="query"&&n.kind!=="mutation")return;const i=u(t,n.receiver);return i?{exportName:x(e)??e.getName(),handler:i,kind:n.kind}:void 0},L=e=>{const t=new Set(["ctx"]),n=r=>{if(s.isObjectBindingPattern(r))for(const a of r.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getNameNode().getText(),f=a.getNameNode();c==="ctx"&&s.isIdentifier(f)&&t.add(f.getText())}},[i]=s.isParametered(e)?e.getParameters():[],o=i!==void 0&&s.isIdentifier(i.getNameNode())?i.getNameNode().getText():void 0;if(i!==void 0){const r=i.getNameNode();s.isIdentifier(r)?t.add(r.getText()):n(r)}for(const r of l(e,d.VariableDeclaration)){const a=r.getInitializer();o!==void 0&&a!==void 0&&s.isIdentifier(a)&&a.getText()===o&&n(r.getNameNode())}return t},P=(e,t,n)=>{const i=e.getExpression();if(!s.isPropertyAccessExpression(i)||i.getName()!=="random")return!1;const o=i.getExpression();return!s.isIdentifier(o)||!t.has(o.getText())?!1:o.getSymbol()?.getDeclarations()[0]?.getFirstAncestor(c=>s.isFunctionLikeDeclaration(c))===n},w=(e,t)=>{const n=[],i=L(e.handler);for(const o of l(e.handler,d.CallExpression)){const r=e.kind==="query"&&P(o,i,e.handler)?"ctx.random":S(o);r!==void 0&&n.push({callee:r,exportName:e.exportName,file:t,kind:e.kind,line:o.getStartLineNumber()})}for(const o of l(e.handler,d.NewExpression)){const r=T(o);r!==void 0&&n.push({callee:r,exportName:e.exportName,file:t,kind:e.kind,line:o.getStartLineNumber()})}return n},O=(e,t)=>{const n=[];for(const i of N(e)){const o=y(i);o&&n.push(...w(o,t))}return n},A=(e,t)=>{const n=[];for(const i of m(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...O(o,g(t,i)))}return n};export{A as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as i,SyntaxKind as u}from"ts-morph";import{collectCallRows as x}from"./isTestPath-Uwb5a6Kq.mjs";import{w as E,c as h}from"./attribution-Cwt30DDJ.mjs";import{i as v}from"./database-calls-d-Sssc-3.mjs";const A=new Set(["withGeoIndex","withIndex","withSearchIndex"]),S=new Set(["collect","collectWithScores","first","paginate","take","unique"]),w=t=>{const e=t.getExpression();if(!i.isPropertyAccessExpression(e)||e.getName()!=="query")return!1;const n=e.getExpression();return v(n)},y=t=>{const e=[];let n=t;for(;;){const s=n.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;e.push(r),n=r}return e},l=t=>{const e=t.getExpression();return i.isPropertyAccessExpression(e)?e.getName():""},m=t=>{if(t===void 0||!(i.isArrowFunction(t)||i.isFunctionExpression(t)))return;const e=t.getParameters()[0]?.getNameNode();return e!==void 0&&i.isIdentifier(e)?e.getText():void 0},O=t=>{let e=t;for(;i.isCallExpression(e)||i.isPropertyAccessExpression(e);)e=e.getExpression();return e},P=(t,e)=>{const n=new Set,s=[t,...t.getDescendantsOfKind(u.CallExpression)].filter(r=>i.isCallExpression(r));for(const r of s){const c=r.getExpression();if(i.isPropertyAccessExpression(c)){const o=O(c);i.isIdentifier(o)&&o.getText()===e&&n.add(c.getName())}}return n},f=(t,e)=>{if(i.isParenthesizedExpression(t))return f(t.getExpression(),e);if(i.isConditionalExpression(t)){const n=f(t.getWhenFalse(),e);return new Set([...f(t.getWhenTrue(),e)].filter(s=>n.has(s)))}return P(t,e)},C=t=>{if(!(i.isArrowFunction(t)||i.isFunctionExpression(t)))return;const e=t.getBody();if(!i.isBlock(e))return i.isExpression(e)?[e]:void 0;const n=e.getDescendantsOfKind(u.ReturnStatement).filter(s=>s.getFirstAncestor(r=>i.isArrowFunction(r)||i.isFunctionExpression(r))?.compilerNode===t.compilerNode).map(s=>s.getExpression()).filter(s=>s!==void 0);return n.length===0?void 0:n},F=(t,e)=>{const n=C(t);if(n===void 0)return;const[s,...r]=n.map(o=>f(o,e));return[...s??new Set].filter(o=>r.every(d=>d.has(o))).toSorted((o,d)=>o.localeCompare(d))},I=(t,e)=>{const n=new Set;for(const s of t.getDescendantsOfKind(u.PropertyAccessExpression)){const r=s.getExpression();i.isIdentifier(r)&&r.getText()===e&&n.add(s.getName())}for(const s of t.getDescendantsOfKind(u.ElementAccessExpression)){const r=s.getExpression(),c=s.getArgumentExpression();i.isIdentifier(r)&&r.getText()===e&&c!==void 0&&i.isStringLiteral(c)&&n.add(c.getLiteralText())}return[...n]},N=t=>{if(t===void 0)return;const[e,n]=t.getArguments(),s=m(n),r=e!==void 0&&i.isStringLiteral(e)?e.getLiteralText():void 0;return n===void 0?{bounds:[],name:r}:{bounds:s===void 0?void 0:F(n,s),name:r}},T=t=>{const e=t.flatMap(n=>{const s=n.getArguments()[0],r=m(s);return s===void 0||r===void 0?[]:I(s,r)});if(e.length!==0)return[...new Set(e)].toSorted((n,s)=>n.localeCompare(s))},b=/\b[A-Za-z_$][\w$]*\._id\s*===?[^=]/u,D=t=>t.some(e=>l(e)==="filter"&&b.test(e.getArguments()[0]?.getText()??"")),L=t=>{const e=t.getArguments()[0];return e&&i.isStringLiteral(e)?e.getLiteralText():""},k=(t,e,n=[])=>{const s=x(t,e,(r,c)=>{if(!w(r))return;const o=y(r),d=o.map(a=>l(a)),p=o.filter(a=>l(a)==="filter"),g=p.length>0;return{file:c,filterFields:g?T(p):void 0,filtersPrimaryKey:g&&D(o),hasFilter:g,hasIndex:d.some(a=>A.has(a)),index:N(o.find(a=>l(a)==="withIndex")),line:r.getStartLineNumber(),scope:h(r),table:L(r),terminal:d.findLast(a=>S.has(a))}});return E(s,n)};export{k as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as r}from"./context-property-calls-BT1J7BqY.mjs";const t=(s,o)=>r(s,o,"r2sql");export{t as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as o}from"ts-morph";import{listLunoraSourceFiles as h,lunoraRelativePath as x,findObjectProperty as m,stringPropertyOf as a}from"./isTestPath-Uwb5a6Kq.mjs";import{e as L}from"./exported-procedure-chains-CfH5jrzD.mjs";import{r as P,p as A}from"./policies-Dn_tuTZd.mjs";const v=new Set(["delete","insert","read","update"]),E=(e,t,s)=>{const i=[];for(const r of A(e)){const n=a(r,"on");n===void 0||!v.has(n)||i.push({file:t,on:n,procedure:s,table:a(r,"table")??""})}return i},f=e=>{if(!o.isObjectLiteralExpression(e))return[];const t=m(e,"permissions");if(!t||!o.isPropertyAssignment(t))return[];const s=t.getInitializer();if(!s||!o.isArrayLiteralExpression(s))return[];const i=[];for(const r of s.getElements()){if(o.isStringLiteral(r)){i.push(r.getLiteralText());continue}if(o.isCallExpression(r)){const n=r.getArguments()[0];n&&o.isStringLiteral(n)&&i.push(n.getLiteralText())}}return i},u=(e,t)=>t===void 0?e:{...e,description:t},y=e=>{if(o.isCallExpression(e)){const t=e.getArguments()[0];if(!t||!o.isStringLiteral(t))return;const s=e.getArguments()[1],i=s?a(s,"description"):void 0,r=s?f(s):[];return u({name:t.getLiteralText(),permissions:r},i)}if(o.isObjectLiteralExpression(e)){const t=a(e,"name");return t===void 0?void 0:u({name:t,permissions:f(e)},a(e,"description"))}},O=e=>{const t=e.getArguments()[1];if(!t||!o.isObjectLiteralExpression(t))return[];const s=m(t,"roles");if(!s||!o.isPropertyAssignment(s))return[];const i=s.getInitializer();if(!i||!o.isArrayLiteralExpression(i))return[];const r=[];for(const n of i.getElements()){const c=y(n);c&&r.push(c)}return r},S=(e,t,s)=>{const i=P(e);return{policies:i.flatMap(r=>E(r,t,s)),roles:i.flatMap(r=>O(r))}},M=(e,t)=>{const s=[],i=new Map;for(const r of h(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),c=x(t,r);for(const{name:g,receiver:d}of L(n)){const p=S(d,c,g);s.push(...p.policies);for(const l of p.roles)i.has(l.name)||i.set(l.name,l)}}return{policies:s,roles:[...i.values()]}};export{M as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as l}from"ts-morph";import{listLunoraSourceFiles as c,lunoraRelativePath as f,declarationLineOf as u,findObjectProperty as p}from"./isTestPath-Uwb5a6Kq.mjs";import{j as d,h as m}from"./attribution-Cwt30DDJ.mjs";import{t as b}from"./database-calls-d-Sssc-3.mjs";import{c as h}from"./classify-procedure-call-BmEirzc_.mjs";import{r as y,p as v}from"./policies-Dn_tuTZd.mjs";const P=e=>{const s=[];for(const r of v(e)){const t=p(r,"table");if(!t||!l.isPropertyAssignment(t))continue;const i=t.getInitializer();i&&l.isStringLiteral(i)&&s.push(i.getLiteralText())}return s},T=e=>{const s=y(e);return{rlsTables:s.flatMap(r=>P(r)),usesRls:s.length>0}},g=new Set(["explain","findFirst","findFirstOrThrow","findMany","get","query"]),R=new Set(["delete","deleteMany","insert","insertMany","patch","patchIf","patchMany","replace"]),x=(e,s)=>{if(!l.isVariableDeclaration(e))return;const r=e.getInitializer();if(!r||!l.isCallExpression(r))return;const t=h(r);if(!t)return;const i=t.receiver?T(t.receiver):{rlsTables:[],usesRls:!1},{tablesRead:o,tablesWritten:a}=b(e,g,R);return{exportName:m(e)??e.getName(),file:s,line:u(e),rlsTables:i.rlsTables,tablesRead:o,tablesWritten:a,usesRls:i.usesRls,visibility:t.visibility}},D=(e,s)=>{const r=[];for(const t of c(s)){const i=e.getSourceFile(t)??e.addSourceFileAtPath(t),o=f(s,t);for(const a of d(i)){const n=x(a,o);n&&r.push(n)}}return r};export{D as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{listLunoraSourceFiles as d}from"./isTestPath-Uwb5a6Kq.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{join as j,relative as Q,isAbsolute as Y,sep as $,dirname as ee}from"node:path";import{LunoraError as te}from"@lunora/errors";import{Node as a,SyntaxKind as N}from"ts-morph";import{diagnosticAt as d}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{findObjectProperty as m,lunoraRelativePath as ne,unwrapExpression as D,symbolConstInitializer as re,descendantsOfKind as se}from"./isTestPath-Uwb5a6Kq.mjs";import{createRequire as ie}from"node:module";import{fileURLToPath as oe}from"node:url";import{createJiti as ae}from"jiti";import{l as le,N as ce}from"./project-config-file-DR7xrrNB.mjs";import{r as de,p as fe}from"./parse-validator-BisfC8bR.mjs";import{R as ue}from"./reserved-words-CW1QFbTd.mjs";import{a as P}from"./property-name-7cBlgK_O.mjs";const ge=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,me=e=>{switch(typeof e){case"bigint":return e.toString();case"boolean":case"number":return String(e);case"string":return JSON.stringify(e);default:return e===null?"null":void 0}},pe=e=>({...e?.defaultValue!==void 0||e?.defaultFn!==void 0||e?.serverDefault!==void 0?{hasDefault:!0}:{},...e?.onUpdateFn===void 0?{}:{hasOnUpdate:!0},notNull:e?.notNull??!0,...e?.unique===!0?{unique:!0}:{}}),b=e=>{const t=e?._meta??{},n=e?.kind??"unknown",r={column:pe(t.column),kind:n,...t.sensitive===!0?{sensitive:!0}:{}};switch(n){case"array":case"optional":{r.inner=b(t.inner);break}case"from":break;case"id":{r.tableName=t.tableName;break}case"literal":{r.literalValue=me(t.value);break}case"object":{const i=t.shape??{};r.shape=Object.fromEntries(Object.entries(i).map(([o,l])=>[o,b(l)]));break}case"record":{r.valueType=b(t.valueValidator),t.keyValidator!==void 0&&(r.keyType=b(t.keyValidator));break}case"storage":{typeof t.bucket=="string"&&(r.bucket=t.bucket);break}case"union":{const i=t.members??[];r.members=i.map(o=>b(o));break}}const s=t.constraints;return s!==void 0&&Object.keys(s).length>0&&(r.hasRefinement=!0,n==="string"&&typeof s.maxLength=="number"&&(r.stringMaxLength=s.maxLength)),r},he=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",be=e=>{const t=r=>typeof e[r]=="string"?e[r]:void 0,n=Array.isArray(e.columns)?e.columns.filter(r=>typeof r=="string"):void 0;return{binding:t("binding")??"",...n===void 0?{}:{columns:n},hasReconcile:e.reconcileEveryMs!==void 0,hasSoftDelete:e.softDeleteColumn!==void 0,hasTenantBy:e.tenantBy!==void 0,...t("idColumn")===void 0?{}:{idColumn:t("idColumn")},...t("mode")===void 0?{}:{mode:t("mode")},...t("query")===void 0?{}:{query:t("query")}}},xe=(e,t)=>{const n=e.shape??{},r=(e.indexes??[]).map(i=>({fields:i.fields,name:i.name,...i.unique?{unique:!0}:{}})),s=he(e.shardMode);return{...e.aggregateIndexes&&e.aggregateIndexes.length>0?{aggregateIndexed:!0}:{},...e.commitOrderedMode===!0?{commitOrdered:!0}:{},...e.isExternallyManaged?{externallyManaged:!0}:{},...e.externalSource?{externalSource:be(e.externalSource)}:{},...e.isPublic===!0?{isPublic:!0}:{},geoIndexes:(e.geoIndexes??[]).map(({field:i,name:o,precision:l})=>({field:i,name:o,...l===void 0?{}:{precision:l}})),...s==="global"?{globalBackend:e.shardMode?.backend==="hyperdrive"?"hyperdrive":"d1"}:{},indexes:r,...e.memoryMode===!0?{memory:!0}:{},name:t,rankIndexes:(e.rankIndexes??[]).map(({name:i,partitionBy:o,sortBy:l})=>({name:i,...o===void 0?{}:{partitionBy:o},sortBy:l.map(({direction:c,field:u})=>({direction:c,field:u}))})),relations:Object.entries(e.relationMap??{}).map(([i,o])=>o.through!==void 0?{kind:"many",name:i,table:o.table,through:{...o.through}}:{field:o.field,kind:o.kind,name:i,...o.onDelete===void 0?{}:{onDelete:o.onDelete},references:o.references,table:o.table}),searchIndexes:(e.searchIndexes??[]).map(i=>({field:i.field,...i.filterFields?{filterFields:i.filterFields}:{},...i.language===void 0?{}:{language:i.language},...i.staged===void 0?{}:{staged:i.staged},...i.strategy===void 0?{}:{strategy:i.strategy},name:i.name})),shape:Object.fromEntries(Object.entries(n).map(([i,o])=>[i,b(o)])),shardMode:s,...e.softDeleteMode?{softDelete:{field:e.softDeleteMode.field}}:{},...e.ttlPolicy?{ttl:{field:e.ttlPolicy.field,...e.ttlPolicy.after===void 0?{}:{after:e.ttlPolicy.after}}}:{},vectorIndexes:(e.vectorIndexes??[]).map(i=>({...i.dimensions===void 0?{}:{dimensions:i.dimensions},field:i.field,...i.metadata===void 0?{}:{metadata:i.metadata},...i.metric===void 0?{}:{metric:i.metric},name:i.name,table:t}))}},ye=e=>{const{key:t,tables:n}=e;if(typeof t!="string"||typeof n!="object"||n===null)return;const r=Object.entries(n).map(([o,l])=>xe(l,o)),s=e.vectorIndexes??{},i=Object.entries(s??{}).map(([o,l])=>({...l.dimensions===void 0?{}:{dimensions:l.dimensions},...l.field===void 0?{}:{field:l.field},...l.metadata===void 0?{}:{metadata:l.metadata},...l.metric===void 0?{}:{metric:l.metric},name:o,table:l.table??""}));return{bareTables:r,bareVectorIndexes:i,key:t}},ve=e=>{if(a.isIdentifier(e))return e.getText();if(a.isPropertyAccessExpression(e)){const t=e.getExpression();return a.isIdentifier(t)?t.getText():void 0}},Ee=e=>{const t=ve(e);if(t===void 0)return;const n=a.isPropertyAccessExpression(e)?e.getName():void 0,r=n===void 0?[]:[n];for(const s of e.getSourceFile().getImportDeclarations()){const i=s.getModuleSpecifierValue();for(const o of s.getNamedImports())if((o.getAliasNode()?.getText()??o.getName())===t)return{importedName:o.getName(),moduleSpecifier:i,propertyPath:r};if(s.getDefaultImport()?.getText()===t)return{importedName:"default",moduleSpecifier:i,propertyPath:r};if(s.getNamespaceImport()?.getText()===t&&n!==void 0)return{importedName:n,moduleSpecifier:i,propertyPath:[]}}},R=e=>a.isCallExpression(e)?e:a.isParenthesizedExpression(e)||a.isAsExpression(e)||a.isSatisfiesExpression(e)?R(e.getExpression()):void 0,Ie=(e,t,n)=>{const r=n.getSymbol()?.compilerSymbol,s=i=>r!==void 0&&i?.getSymbol()?.compilerSymbol===r;return a.isPropertyAccessExpression(t)?s(e.getNamespaceImport())?t.getName():void 0:s(e.getDefaultImport())?"default":e.getNamedImports().find(i=>s(i.getAliasNode()??i.getNameNode()))?.getName()},Se=e=>{if(!a.isPropertyAccessExpression(e)||!a.isIdentifier(e.getExpression()))return;const t=e.getExpression().getSymbol(),n=(t?.getAliasedSymbol()??t)?.getValueDeclaration(),r=a.isVariableDeclaration(n)?n.getInitializer():void 0,s=r===void 0?void 0:R(r),i=s?.getExpression(),o=i!==void 0&&a.isPropertyAccessExpression(i)?i.getExpression():i;if(s===void 0||i===void 0||o===void 0||!a.isIdentifier(o))return;const l=s.getArguments().map(u=>le(u)),c=s.getReturnType().getProperty(e.getName())?.getTypeAtLocation(s).getNonNullableType();if(!(l.includes(ce)||c?.getProperty("tables")===void 0))for(const u of s.getSourceFile().getImportDeclarations()){const g=u.getModuleSpecifierValue();if(g.startsWith("."))continue;const h=Ie(u,i,o);if(h!==void 0)return{args:l,importedName:h,moduleSpecifier:g,propertyPath:[e.getName()]}}},F=(e,t)=>{let n=e;for(const r of t){if(typeof n!="object"||n===null)return;n=n[r]}return n},we=(e,t)=>F(e[t.importedName],t.propertyPath),C=(e,t)=>{const n=ae(j(t,"noop.js")).esmResolve(e);return ie(j(t,"noop.cjs"))(n.startsWith("file:")?oe(n):n)},Te=(e,t)=>{const n=Ee(e);if(n&&!n.moduleSpecifier.startsWith("."))return we(C(n.moduleSpecifier,t),n);const r=Se(e);if(!r)return;const s=C(r.moduleSpecifier,t)[r.importedName];return typeof s=="function"?F(s(...r.args),r.propertyPath):void 0},ke=(e,t)=>{try{const n=Te(e,t);return typeof n!="object"||n===null?void 0:ye(n)}catch{return}},Ne=new Set(["cosine","dot-product","euclidean"]),v=(e,t)=>{const n=m(e,t);if(n&&a.isPropertyAssignment(n))return n.getInitializer()},f=(e,t)=>{const n=v(e,t);if(n&&a.isStringLiteral(n))return n.getLiteralText()},I=(e,t)=>{const n=v(e,t);if(n&&a.isNumericLiteral(n))return Number(n.getLiteralText())},B=(e,t)=>{const n=v(e,t);if(n&&(a.isTrueLiteral(n)||a.isFalseLiteral(n)))return n.getLiteralValue()},S=(e,t)=>{const n=v(e,t);if(n&&a.isArrayLiteralExpression(n))return n.getElements().filter(r=>a.isStringLiteral(r)).map(r=>r.getLiteralText())},V=e=>e&&Ne.has(e)?e:void 0,w=e=>e&&a.isStringLiteral(e)?e.getLiteralText():"_unnamed_",Ae=(e,t)=>{const n=S(e,t);return n!==void 0&&n.length>0?n:void 0},q=(e,t,n,r,s)=>{let i=e;for(;;){const o=i.getParent();if(!o||!a.isPropertyAccessExpression(o))break;const l=o.getParent();if(!l||!a.isCallExpression(l))break;if(o.getName()===t){const c=l.getArguments()[0];if(!c||!a.isStringLiteral(c))throw d(l,`\`.${t}(...)\` expects a string literal (${s})`);const u=c.getLiteralText();if(!r.has(u))throw d(c,`unknown ${n} ${JSON.stringify(u)} — expected ${s}`);return u}i=l}},Pe=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,Oe=/^(?:sqlite_|_cf_|__)/u,Le=/__(?:agg|rank|geo|fts)_/u,_e=e=>Oe.test(e)||Le.test(e),J=()=>{},je=e=>t=>{const n=t.getSourceFile().getFilePath(),r=Q(e,n);if(!(r===""||Y(r)||r.split($)[0]===".."||r.split($).includes("node_modules")))return{file:ne(e,n),line:t.getStartLineNumber()}},$e=new Set(["cascade","restrict","set null"]),De=new Set(["aggregate","asId","assertPatchAllowed","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteRereadTables","deleteWhere","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","inTransaction","lookupById","normalizeId","patch","patchIf","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","relationWrites","replace","restore","softDeleteFields","system","wipeShard"]),U=/^[A-Za-z_$][\w$]*$/u,O=(e,t)=>{if(De.has(e))throw d(t,`table name "${e}" is reserved — the generated shard binds each table's facade onto the same object that carries \`ctx.db\`'s own members, so this table would overwrite \`ctx.db.${e}\` and every use of it would break. Rename the table.`);if(ue.has(e))throw d(t,`table name "${e}" is a reserved JavaScript word — codegen interpolates table names into a bare \`const ${e} = sqliteTable(...)\` binding in the generated Drizzle module, which is a syntax error for a keyword. Rename the table.`);if(!U.test(e))throw d(t,`table name ${JSON.stringify(e)} is not a valid JS identifier — table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the table.`);if(_e(e))throw d(t,`table name ${JSON.stringify(e)} is reserved for framework tables — a leading \`__\` and the \`__agg_\`/\`__rank_\`/\`__geo_\`/\`__fts_\` infixes name Lunora's own bookkeeping and index companions, so the Studio and the admin API hide and refuse such a table. Rename the table.`)},Ce=e=>e&&$e.has(e)?e:void 0,ze=e=>{if(!a.isArrowFunction(e))return;let t=e.getBody();if(a.isParenthesizedExpression(t))t=t.getExpression();else if(a.isBlock(t)){const n=t.getStatements().find(r=>a.isReturnStatement(r));t=n&&a.isReturnStatement(n)?n.getExpression()??t:t}return a.isObjectLiteralExpression(t)?t:void 0},Me=(e,t,n)=>{const r=a.isPropertyAssignment(e)?e.getInitializer():void 0;if(!r||!a.isObjectLiteralExpression(r))throw d(e,"relation `through` must be an object literal `{ table, from, to }` — codegen resolves it statically.");const[s,i,o]=["table","from","to"].map(l=>f(r,l));if(s===void 0||i===void 0||o===void 0)throw d(r,"relation `through` needs string-literal `table`, `from` and `to` — codegen resolves them statically.");if(i===o)throw d(r,`relation \`through\` has \`from\` and \`to\` both set to "${i}"; a link needs two different columns.`);return{kind:"many",name:t,table:n,through:{from:i,table:s,to:o}}},Re=(e,t,n,r)=>{const s=r&&a.isObjectLiteralExpression(r)?r:void 0,i=e==="many"?s?.getProperty("through"):void 0;return i?Me(i,t,n):{field:(s&&f(s,"field"))??"_unknown_",kind:e,name:t,onDelete:e==="one"&&s?Ce(f(s,"onDelete")):void 0,references:(s&&f(s,"references"))??"_id",table:n}},Fe=e=>{if(!a.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!a.isCallExpression(t))return;const n=t.getExpression();if(!a.isPropertyAccessExpression(n))return;const r=n.getName();if(r!=="one"&&r!=="many")return;const[s,i]=t.getArguments();if(!s||!a.isStringLiteral(s))throw d(s??t,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${s?s.getText():"no argument"}.`);const o=s.getLiteralText();return Re(r,P(e),o,i)},Be=(e,t)=>{const n=ze(e);if(!n)return[];const r=[];for(const s of n.getProperties()){const i=Fe(s);if(i){const o=t(s);r.push(o===void 0?i:{...i,site:o})}}return r},Ve=(e,t,n)=>{if(!t.includes("."))return;const[r="",...s]=t.split("."),i=`${r}${s.map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join("")}`;throw d(e,`index "${n}" indexes the nested path ${JSON.stringify(t)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${i}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`,{code:"INDEX_FIELD_NESTED_PATH",name:"LunoraError",status:500})},qe=e=>{if(!e||!a.isObjectLiteralExpression(e))return!1;const t=m(e,"unique");if(!t||!a.isPropertyAssignment(t))return!1;const n=t.getInitializer();if(n===void 0)return!1;if(!a.isTrueLiteral(n)&&!a.isFalseLiteral(n))throw d(n,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(n.getText())}`);return a.isTrueLiteral(n)},Je=e=>{const[t,n,r]=e,s=qe(r),i=w(t),o=n&&a.isArrayLiteralExpression(n)?n.getElements():[];for(const c of o)if(!a.isStringLiteral(c))throw d(c,`index "${i}" lists a non-literal field (${JSON.stringify(c.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=o.filter(c=>a.isStringLiteral(c));for(const c of l)Ve(c,c.getLiteralText(),i);return{fields:l.map(c=>c.getLiteralText()),name:i,unique:s}},Ue=e=>{const[t,n]=e;let r="_unknown_",s,i,o,l;return n&&a.isObjectLiteralExpression(n)&&(r=f(n,"field")??r,s=S(n,"filterFields"),i=f(n,"language"),o=B(n,"staged"),l=f(n,"strategy")),{field:r,filterFields:s,language:i,name:w(t),staged:o,strategy:l}},Ke=e=>{const[t,n]=e;let r="_unknown_",s;return n&&a.isObjectLiteralExpression(n)&&(r=f(n,"field")??r,s=I(n,"precision")),{field:r,name:w(t),precision:s}},We=e=>{const[t,n]=e,r=t&&a.isStringLiteral(t)?t.getLiteralText():"_unknown_";let s;return n&&a.isObjectLiteralExpression(n)&&(s=I(n,"after")),{after:s,field:r}},He=e=>{if(!a.isObjectLiteralExpression(e))return;const t=f(e,"field");return t===void 0?void 0:{direction:f(e,"direction")==="desc"?"desc":"asc",field:t}},Xe=e=>{const[t,n]=e;let r=[],s;if(n&&a.isObjectLiteralExpression(n)){const i=m(n,"sortBy");if(i&&a.isPropertyAssignment(i)){const o=i.getInitializer();o&&a.isArrayLiteralExpression(o)&&(r=o.getElements().map(l=>He(l)).filter(l=>l!==void 0))}s=S(n,"partitionBy")}return{name:w(t),partitionBy:s,sortBy:r}},Ze=(e,t)=>{const[n,r]=e,s=n&&a.isStringLiteral(n)?n.getLiteralText():"_unknown_";if(!(!r||!a.isObjectLiteralExpression(r)))return{dimensions:I(r,"dimensions"),field:s,metadata:S(r,"metadata"),metric:V(f(r,"metric")),name:f(r,"index")??"_unnamed_",table:t}},Ge=e=>{const t=e[0];return t&&a.isObjectLiteralExpression(t)&&f(t,"backend")==="hyperdrive"?"hyperdrive":"d1"},z=(e,t)=>{if(e===void 0)return t;if(!a.isObjectLiteralExpression(e))throw d(e,"the options must be an object literal — codegen reads the column name from the source and cannot evaluate a variable or an expression here.");const n=m(e,"field");if(n===void 0)return t;const r=a.isPropertyAssignment(n)?n.getInitializer():void 0;if(r&&a.isStringLiteral(r))return r.getLiteralText();throw d(n,"`field` must be a string literal — codegen reads the column name from the source and cannot evaluate a constant or an expression here.")},Qe=e=>{const t=e[0];return!t||!a.isObjectLiteralExpression(t)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(t,"binding")??"",columns:Ae(t,"columns"),hasReconcile:m(t,"reconcileEveryMs")!==void 0,hasSoftDelete:m(t,"softDeleteColumn")!==void 0,hasTenantBy:m(t,"tenantBy")!==void 0,idColumn:f(t,"idColumn"),mode:f(t,"mode"),query:f(t,"query")}},x=(e,t)=>t===void 0?e:{...e,site:t},Ye=(e,t,n,r,s)=>{const i=e.locate(s);switch(t){case"aggregateIndex":{e.aggregateIndexed=!0;break}case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(x(Ke(n),i));break}case"global":{e.shardMode="global",e.globalBackend=Ge(n);break}case"index":{e.indexes.unshift(x(Je(n),i));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(x(Xe(n),i));break}case"relations":{const o=n[0];o&&e.relations.push(...Be(o,e.locate));break}case"searchIndex":{e.searchIndexes.push(x(Ue(n),i));break}case"shardBy":{const o=n[0];e.shardMode={field:o&&a.isStringLiteral(o)?o.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:z(n[0],"deletedAt")};break}case"source":{e.externalSource=Qe(n),e.externallyManaged=!0;break}case"timestamps":{e.timestampsFields.push(z(n[0],"updatedAt"));break}case"ttl":{e.ttl=We(n);break}case"vectorize":{const o=Ze(n,r);o&&e.vectorIndexes.push(x(o,i));break}}},M=["__vocab","_config","_content","_data","_docsize","_idx"],et=(e,t,n)=>{const r=new Set(n.map(s=>s.name));for(const s of n)for(const i of M){const o=`${s.name}${i}`;if(!r.has(o))continue;const l=i==="__vocab"?`the \`fts5vocab\` companion for "${o}" is created \`IF NOT EXISTS\`, so it silently resolves to "${s.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${o}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw d(e,`table "${t}" declares search indexes "${s.name}" and "${o}", whose generated FTS5 tables collide: "${s.name}" already owns "${t}__fts_${o}" as its "${i}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${M.join(", ")}.`)}},tt=(e,t,n)=>{if(n.ttl!==void 0&&n.shardMode==="global")throw d(e,Pe(t))},nt=(e,t,n)=>{const{softDelete:r,timestampsFields:s}=n,i={};r&&!(r.field in t)&&(i[r.field]={inner:{column:{notNull:!1},kind:"number"},kind:"optional"});const[o]=s;if(o===void 0)return{...t,...i};if(s.length>1)throw d(e,"`.timestamps()` was called more than once; one table tracks one last-change column.");if(o===r?.field)throw d(e,`\`.softDelete()\` and \`.timestamps()\` both use "${o}"; give one of them another field.`);const l=t[o];if(l===void 0)i[o]={column:{hasDefault:!0,hasOnUpdate:!0,notNull:!0},kind:"timestamp"};else if(l.kind!=="timestamp"||l.column?.hasOnUpdate!==!0||l.column.hasDefault!==!0)throw d(e,`\`.timestamps()\` would add "${o}", but the table already declares it as something other than \`v.timestamp().defaultNow().$onUpdateFn(() => Date.now())\`; remove the column or declare it that way.`);return{...t,...i}},k=4,rt=e=>{const t=e.getParent(),n=a.isShorthandPropertyAssignment(t)&&t.getNameNode()===e?t.getValueSymbol():e.getSymbol();return re(n?.isAlias()===!0?n.getAliasedSymbol():n)},A=(e,t)=>d(e,`table "${t}" is defined as ${JSON.stringify(e.getText())}, but codegen reads a table only from an inline defineTable(...) chain or one bound to a module-scope const. Inline the defineTable(...) call, or bind it to a const.`),st=(e,t,n)=>{const s=t.getParentIfKind(N.VariableDeclaration)?.getNameNode();if(!(s===void 0||!a.isIdentifier(s)))for(const i of s.findReferencesAsNodes()){const o=i.getParent();if(i!==e&&a.isPropertyAccessExpression(o)&&o.getExpression()===i&&a.isCallExpression(o.getParent())&&o.getParentIfKindOrThrow(N.CallExpression).getExpression()===o)throw d(i,`table "${n}" is built from "${s.getText()}", which also has .${o.getName()}(...) called on it outside the chain the schema uses. Table builder methods change the shared builder, so codegen cannot see that call. Chain every method in one expression.`)}},it=e=>{let t=0;return n=>{let r=D(n)??n;for(;a.isIdentifier(r);){if(t+=1,t>k)throw d(r,`table "${e}" is reached through more than ${String(k)} const bindings, and codegen follows at most ${String(k)}. Inline the defineTable(...) call.`);const s=rt(r);if(s===void 0)throw A(r,e);st(r,s,e),r=D(s)??s}return r}},ot=e=>e.getText()==="defineTable"?!0:e.getSymbol()?.getDeclarations().some(t=>a.isImportSpecifier(t)&&t.getName()==="defineTable")===!0,at=(e,t)=>{if(e===void 0)return{};if(a.isObjectLiteralExpression(e))return fe(e);throw d(e,`table "${t}" calls defineTable(${JSON.stringify(e.getText())}), but codegen reads the field map syntactically and can only read an object literal. Inline the fields into the defineTable(...) call. To reuse them in an \`.input()\`, derive from the generated \`Doc_${t}\` / \`Insert_${t}\` type instead of sharing the runtime value.`)},K=(e,t,n=J)=>{const r={aggregateIndexed:!1,commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,locate:n,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",timestampsFields:[],vectorIndexes:[]};let s={};const i=it(t);let o=i(e),l=!1,c;for(;a.isCallExpression(o);){const g=o.getExpression(),h=o.getArguments();if(a.isPropertyAccessExpression(g))Ye(r,g.getName(),h,t,g.getNameNode()),o=i(g.getExpression());else if(a.isIdentifier(g)&&ot(g)){c=o,s=at(h[0],t),l=!0;break}else throw A(o,t)}if(!l)throw A(o,t);s=nt(e,s,r),et(e,t,r.searchIndexes),tt(e,t,r);const u=c===void 0?void 0:n(c);return{...r.aggregateIndexed?{aggregateIndexed:!0}:{},commitOrdered:r.commitOrdered,externallyManaged:r.externallyManaged,externalSource:r.externalSource,geoIndexes:r.geoIndexes,...u===void 0?{}:{site:u},globalBackend:r.shardMode==="global"?r.globalBackend??"d1":void 0,indexes:r.indexes,isPublic:r.isPublic,memory:r.memory,name:t,rankIndexes:r.rankIndexes,relations:r.relations,searchIndexes:r.searchIndexes,shape:s,shardMode:r.shardMode,softDelete:r.softDelete,ttl:r.ttl,vectorIndexes:r.vectorIndexes}},W=e=>a.isPropertyAssignment(e)?e.getInitializer():e.getNameNode(),H=(e,t=J,n=[],r=new Set,s=new Set)=>{s.add(e);for(const i of e.getProperties()){if(a.isSpreadAssignment(i)){const l=de(i.getExpression());l!==void 0&&!s.has(l)&&H(l,t,n,r,s);continue}if(!a.isPropertyAssignment(i)&&!a.isShorthandPropertyAssignment(i))continue;const o=W(i);if(o){const l=P(i);if(O(l,i.getNameNode()),r.has(l))throw d(i.getNameNode(),`defineSchema({...}): table "${l}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);r.add(l),n.push(K(o,l,t))}}return n},lt=e=>{const t=m(e,"source");if(t&&a.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&a.isObjectLiteralExpression(n))return f(n,"table")??"_unknown_"}return"_unknown_"},ct=(e,t)=>{if(!a.isPropertyAssignment(e))return;const n=e.getInitializer();if(!n||!a.isCallExpression(n))return;const r=n.getExpression();if(!a.isIdentifier(r)||r.getText()!=="defineVectorIndex")return;const s=n.getArguments()[0];if(!s||!a.isObjectLiteralExpression(s))return;const i=e.getNameNode(),o=a.isStringLiteral(i)?i.getLiteralText():i.getText(),l=t(n);return{dimensions:I(s,"dimensions"),metric:V(f(s,"metric")),name:o,...l===void 0?{}:{site:l},table:lt(s)}},X=(e,t)=>{const n=[];for(const r of e.getProperties()){const s=ct(r,t);s&&n.push(s)}return n},L=(e,t)=>`${e}_${t}`,dt=(e,t)=>{if(!U.test(e))throw d(t,`defineSchemaExtension key ${JSON.stringify(e)} is not a valid JS identifier — it is prefixed onto every table the extension contributes (\`${e}_<table>\`), and table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the extension key.`)},y=(e,t,n)=>n.has(e)?L(t,e):e,E=(e,t)=>{const n=r=>r===void 0?void 0:E(r,t);return{...e,...e.tableName===void 0?{}:{tableName:t(e.tableName)},...e.inner===void 0?{}:{inner:n(e.inner)},...e.keyType===void 0?{}:{keyType:n(e.keyType)},...e.valueType===void 0?{}:{valueType:n(e.valueType)},...e.members===void 0?{}:{members:e.members.map(r=>E(r,t))},...e.shape===void 0?{}:{shape:Object.fromEntries(Object.entries(e.shape).map(([r,s])=>[r,E(s,t)]))}}},ft=(e,t,n,r)=>{const s=L(t,e.name);return{...e,extensionKey:t,...r?{extensionFromPackage:!0}:{},name:s,shape:Object.fromEntries(Object.entries(e.shape).map(([i,o])=>[i,E(o,l=>y(l,t,n))])),relations:e.relations.map(i=>{const o=y(i.table,t,n);return i.through===void 0?{...i,table:o}:{...i,table:o,through:{...i.through,table:y(i.through.table,t,n)}}}),vectorIndexes:e.vectorIndexes.map(i=>({...i,table:y(i.table,t,n)}))}},ut=e=>{if(a.isVariableDeclaration(e)||a.isPropertyAssignment(e))return e.getInitializer();if(a.isShorthandPropertyAssignment(e))return e.getNameNode()},gt=e=>{if(!a.isCallExpression(e))return!1;const t=e.getExpression();return a.isIdentifier(t)&&t.getText()==="defineSchemaExtension"},mt=e=>{if(a.isIdentifier(e))return e;if(a.isPropertyAccessExpression(e)){const t=e.getExpression();return a.isIdentifier(t)?t:void 0}},pt=e=>{if(a.isObjectLiteralExpression(e))return e;if(a.isCallExpression(e)){const t=e.getExpression();let n;if(a.isIdentifier(t)?n=t.getText():a.isPropertyAccessExpression(t)&&(n=t.getName()),n==="definePlugin"){const r=e.getArguments()[1];return r&&a.isObjectLiteralExpression(r)?r:void 0}}},ht=(e,t)=>{const n=ut(e);if(n){if(a.isPropertyAccessExpression(t)){const r=pt(n);return r?v(r,t.getName()):void 0}return n}},bt=e=>{let t=e,n=0;for(;t&&n<32;){if(n+=1,gt(t))return t;const r=mt(t),s=r&&a.isIdentifier(r)?r.getSymbol():void 0,o=(s?.getAliasedSymbol()?.getDeclarations()??s?.getDeclarations()??[])[0];if(!o)return;const l=o.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;t=ht(o,t)}},xt=e=>{const[t,n]=e.getArguments();if(!(!t||!a.isStringLiteral(t))&&!(!n||!a.isObjectLiteralExpression(n)))return{key:t.getLiteralText(),keyNode:t,options:n}},yt=(e,t)=>{const n=m(e,"tables");if(!n||!a.isPropertyAssignment(n))return[];const r=n.getInitializer();if(!r||!a.isObjectLiteralExpression(r))return[];const s=[];for(const i of r.getProperties()){if(!a.isPropertyAssignment(i)&&!a.isShorthandPropertyAssignment(i))continue;const o=W(i);if(!o)continue;const l=P(i);O(l,i.getNameNode()),s.push(K(o,l,t))}return s},vt=(e,t)=>{const n=m(e,"vectorIndexes");if(!n||!a.isPropertyAssignment(n))return[];const r=n.getInitializer();return!r||!a.isObjectLiteralExpression(r)?[]:X(r,t)},Z=(e,t,n,r,s)=>{dt(e,r);const i=new Set(t.map(c=>c.name)),o=t.map(c=>ft(c,e,i,s)),l=n.map(c=>({...c,name:L(e,c.name),table:y(c.table,e,i)}));return{tables:o,vectorIndexes:l}},Et=(e,t,n,r)=>Z(e,yt(n,r),vt(n,r),t,t.getSourceFile().getFilePath().includes("/node_modules/")),It=(e,t,n)=>{const r=e.getArguments()[0];if(!r)return;let s=r;for(;a.isParenthesizedExpression(s)||a.isAsExpression(s)||a.isSatisfiesExpression(s);)s=s.getExpression();const i=bt(s);if(!i){if(t!==void 0){const l=ke(s,t);if(l){for(const c of l.bareTables)O(c.name,s);return Z(l.key,l.bareTables,l.bareVectorIndexes,s,!0)}}console.warn(`@lunora/codegen: skipping \`.extend(${s.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${t===void 0?"no project root was available to resolve the package":"the package could not be imported/introspected"}. Extension tables will be absent from the generated types. If the receiver is a component built with options codegen cannot evaluate (a function, a variable), extend with the standalone extension the package exports instead (e.g. \`presenceExtension\`, \`actionCacheExtension\` or \`documentHistoryExtension\` from \`@lunora/server\`).`);return}const o=xt(i);if(!o){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return Et(o.key,o.keyNode,o.options,n)},St=e=>{const t=[];let n=e;for(;;){const r=n.getParent();if(!r||!a.isPropertyAccessExpression(r))break;const s=r.getParent();if(!s||!a.isCallExpression(s))break;r.getName()==="extend"&&t.push(s),n=s}return t},wt=(e,t,n,r)=>{const s=new Set(t.map(o=>o.name)),i=[];for(const o of St(e)){const l=It(o,n,r);if(l){for(const c of l.tables){if(s.has(c.name))throw d(o,`defineSchema(...).extend(...): table "${c.name}" already exists — another extension with the same key already contributed it.`);s.add(c.name),t.push(c)}i.push(...l.vectorIndexes)}}return i},Tt=new Set(["eu","fedramp","us"]),kt=e=>q(e,"jurisdiction","jurisdiction",Tt,'"eu", "us", or "fedramp"'),Nt=e=>{let t=e;for(;;){const n=t.getParent(),r=n?.getParent();if(!n||!a.isPropertyAccessExpression(n)||!r||!a.isCallExpression(r))return!1;if(n.getName()==="jurisdiction"){const s=r.getArguments()[1];return s!==void 0&&a.isObjectLiteralExpression(s)&&B(s,"pinAuth")===!0}t=r}},At=new Set(["required"]),Pt=e=>q(e,"rls","rls mode",At,'"required"'),Ot=e=>{if(!a.isObjectLiteralExpression(e))return;const t=new Set;for(const n of e.getProperties()){const r=a.isPropertyAssignment(n)?n.getInitializer():void 0;if(!r||!a.isCallExpression(r))return;const s=r.getExpression(),i=r.getArguments()[1],o=i&&a.isObjectLiteralExpression(i)?f(i,"on"):void 0;if(!a.isIdentifier(s)||s.getText()!=="defineAggregateIndex"||o===void 0)return;t.add(o)}return t},Lt=(e,t)=>{if(t===void 0)return;const n=Ot(t);for(const r of e)(n===void 0||n.has(r.name))&&(r.aggregateIndexed=!0)},Jt=(e,t,n)=>{const r=e.addSourceFileAtPath(t),s=se(r,N.CallExpression).find(p=>{const _=p.getExpression();return a.isIdentifier(_)&&_.getText()==="defineSchema"});if(!s)throw new te("INTERNAL",`defineSchema() not found in ${t}`);const i=s.getArguments()[0];if(!i||!a.isObjectLiteralExpression(i))throw d(s,"defineSchema() expects an object literal");const o=je(ee(t)),l=H(i,o),c=s.getArguments()[1],u=c&&a.isObjectLiteralExpression(c)?X(c,o):[],g=wt(s,l,n,o);Lt(l,s.getArguments()[2]);const h=[...l.flatMap(p=>p.vectorIndexes),...u,...g],G=new Set(l.filter(p=>p.shardMode==="global").map(p=>p.name)),T=h.find(p=>G.has(p.table));if(T)throw d(s,ge(T.table,T.name));return{jurisdiction:kt(s),...Nt(s)?{jurisdictionPinsAuth:!0}:{},rlsMode:Pt(s),tables:l,vectorIndexes:h}};export{Jt as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as u}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as p,stringPropertyOf as l}from"./isTestPath-Uwb5a6Kq.mjs";import{w as d}from"./classify-procedure-call-BmEirzc_.mjs";import{e as m}from"./exported-procedure-chains-CfH5jrzD.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const a=/\/index$/u,n=/[^\dA-Za-z]/gu,c=e=>e.replace(a,"").split("/").map(s=>s.replaceAll(n,"_")),t=e=>c(e).join("_");export{c as n,t as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./json-data-Chfs2Cz5.mjs";import{p as i,j as r,t as n,h as o,u as g,k as F,d as u,x as p,n as l,g as f,f as d,m as k,i as w,v as W,l as v,w as A}from"./shard-runtime-G5mZQjY0.mjs";import"./shared-Cn7dMQ_u.mjs";import"./platform-8oj7iXQy.mjs";export{i as buildDoTypeImports,r as emitAgentFragments,n as emitAgents,o as emitContainerFragments,g as emitContainers,F as emitPaymentFragments,u as emitQueueFragments,p as emitQueues,l as emitQueuesMetadataFragments,f as emitServiceFragments,d as emitTopicFragments,k as emitWorkflowEventFragments,w as emitWorkflowFragments,W as emitWorkflows,v as emitWorkflowsMetadataFragments,A as queueAliasFindings};
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import{AGENT_RUNTIME_FUNCTIONS as N}from"@lunora/agent/naming";import{LunoraError as R}from"@lunora/errors";import{r as d,a as w,b as P,c as L}from"./qualifiers-qqH8fRTo.mjs";import{a as A,r as y,p as $,G as x,b as k,c as m,d as S,e as O,i as T}from"./shared-Cn7dMQ_u.mjs";import{s as g}from"./dispatch-namespace-DwTjD7BU.mjs";const j=t=>k(t,e=>{const s=d(y(e.args),e.filePath),n=d(L(e),e.filePath),o=`FunctionReference<"${e.kind}", ${s}, ${n}>`;return`${e.exportName}: ${T(e)?`${o} & { readonly sensitive: true }`:o};`},"type"),I=(t,e)=>{if(t.length===0&&e.length===0)return{block:"",importLine:""};const s=[];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+=`
|
|
2
|
+
/** A typed reference to a durable workflow, addressable for \`cronJobs()\` targets. Mirrors \`@lunora/scheduler\`'s \`WorkflowReference\` structurally. */
|
|
3
|
+
export interface WorkflowReference<Params = Record<string, unknown>> {
|
|
4
|
+
readonly isLunoraWorkflow: true;
|
|
5
|
+
readonly __params?: Params;
|
|
6
|
+
readonly className: string;
|
|
7
|
+
readonly name: string;
|
|
8
|
+
}
|
|
9
|
+
`,t.length>0){const o=[...t].toSorted((r,i)=>r.exportName.localeCompare(i.exportName)),a=o.map(r=>` ${r.exportName}: WorkflowReference<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${r.exportName}>>;`).join(`
|
|
10
|
+
`),l=o.map(r=>` ${m(r.exportName)}: { isLunoraWorkflow: true, className: ${JSON.stringify(r.className)}, name: ${JSON.stringify(r.exportName)} },`).join(`
|
|
11
|
+
`);n+=`
|
|
12
|
+
/** This project's durable workflows, addressable as typed references (e.g. \`crons.daily("digest", …, workflows.digestPipeline, params)\`). */
|
|
13
|
+
export interface WorkflowsRef {
|
|
14
|
+
${a}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export const workflows: WorkflowsRef = {
|
|
18
|
+
${l}
|
|
19
|
+
};
|
|
20
|
+
`,s.push(`import type * as lunoraWorkflowDefinitions from "../workflows.js";
|
|
21
|
+
`)}if(e.length>0){const o=[...e].toSorted((r,i)=>r.exportName.localeCompare(i.exportName)),a=o.map(r=>` ${r.exportName}: WorkflowReference<AgentRunInput>;`).join(`
|
|
22
|
+
`),l=o.map(r=>` ${m(r.exportName)}: { isLunoraWorkflow: true, className: ${JSON.stringify(r.className)}, name: ${JSON.stringify(r.name)} },`).join(`
|
|
23
|
+
`);n+=`
|
|
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 })\`). */
|
|
25
|
+
export interface AgentsRef {
|
|
26
|
+
${a}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const agents: AgentsRef = {
|
|
30
|
+
${l}
|
|
31
|
+
};
|
|
32
|
+
`,s.push(`import type { AgentRunInput } from "@lunora/agent/core";
|
|
33
|
+
`)}return{block:n,importLine:s.join("")}},M=()=>Object.keys(N).toSorted((t,e)=>t.localeCompare(e)),v=t=>new Set(t.filter(e=>g(e.filePath)==="agents").map(e=>e.exportName)),K=()=>new Set(Object.entries(N).filter(([,t])=>t==="internal").map(([t])=>t)),G=(t,e)=>{const s={importLine:"",lines:"",prelude:""};if(t.length===0)return s;const n=v(e),o=K(),a=e.find(r=>g(r.filePath)==="agents"&&o.has(r.exportName));if(a)throw new R("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 l=M().filter(r=>!n.has(r));return l.length===0?s:{importLine:`import { agentComponent } from "@lunora/agent/component";
|
|
34
|
+
`,lines:l.map(r=>` "agents:${r}": lunoraAgentRuntimeFunctions.${r} as unknown as RegisteredLunoraFunction,`).join(`
|
|
35
|
+
`),prelude:`
|
|
36
|
+
/**
|
|
37
|
+
* The \`@lunora/agent\` runtime component — auto-registered because \`lunora/agents.ts\`
|
|
38
|
+
* declares agents. The durable loop dispatches the internal mutations; clients
|
|
39
|
+
* subscribe to the public queries (\`agents:agentMessages\` is the live thread view).
|
|
40
|
+
*/
|
|
41
|
+
const lunoraAgentRuntimeFunctions = agentComponent().functions;
|
|
42
|
+
`}},V=(t,e)=>{if(!t)return{importLine:"",lines:"",prelude:""};const s=e.find(n=>g(n.filePath)==="sandbox"&&n.exportName==="invoke");if(s)throw new R("INTERNAL",`@lunora/codegen: "sandbox:invoke" is reserved for the batteries-included sandbox tool dispatcher (browserTool/containerTool) — rename the "invoke" export in ${s.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"}},E=(t,e)=>{if(t.length===0)return[];const s=v(e),n=[{args:{key:{kind:"string"},limit:{inner:{kind:"number"},kind:"optional"}},exportName:"agentMessages",filePath:"agents",kind:"query",returnType:"Record<string, unknown>[]"},{args:{limit:{inner:{kind:"number"},kind:"optional"}},exportName:"agentPendingApprovals",filePath:"agents",kind:"query",returnType:"Record<string, unknown>[]"},{args:{decision:{kind:"union",members:[{kind:"literal",literalValue:'"approve"'},{kind:"literal",literalValue:'"approve_for_thread"'},{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:{secret:{kind:"string",sensitive:!0},threadKey:{kind:"string"},toolCallId:{kind:"string"}},exportName:"agentSupplySecret",filePath:"agents",kind:"mutation",returnType:"{ resolved: boolean }"},{args:{threadKey:{kind:"string"},toolCallId:{kind:"string"}},exportName:"agentDeclineSecret",filePath:"agents",kind:"mutation",returnType:"{ resolved: boolean }"},{args:{threadKey:{kind:"string"}},exportName:"agentSecretRequests",filePath:"agents",kind:"query",returnType:'{ createdAt: number; expiresAt: number; label?: string; status: "consumed" | "declined" | "expired" | "pending" | "supplied"; toolCallId: string; toolName: string }[]'},{args:{key:{kind:"string"}},exportName:"agentApprovalGrants",filePath:"agents",kind:"query",returnType:"{ createdAt: number; toolName: string }[]"},{args:{threadKey:{kind:"string"},toolName:{kind:"string"}},exportName:"agentRevokeApprovalGrant",filePath:"agents",kind:"mutation",returnType:"{ revoked: 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 o of t)o.voice&&n.push({args:{threadKey:{kind:"string"}},exportName:`${o.exportName}Voice`,filePath:"agents",kind:"stream",returnType:"Record<string, unknown>"});return n.filter(o=>!s.has(o.exportName))},F=(t,e)=>{if(t.length===0)return[];const s=new Set(e.filter(n=>g(n.filePath)==="mutators").map(n=>n.exportName));return t.filter(n=>!s.has(n.exportName)).map(n=>({args:n.args,exportName:n.exportName,filePath:n.filePath,kind:"mutation",returnType:n.returnType}))},W=t=>{const e=t.flatMap(o=>o.channel?.kind==="room"?[o.channel.name]:[]);if(e.length===0)return{block:"",importLine:""};const s=e.map(o=>` ${m(o)}: RoomRef<LunoraRoomMessages[${JSON.stringify(o)}]>;`).join(`
|
|
44
|
+
`),n=e.map(o=>` ${m(o)}: { name: ${JSON.stringify(o)} },`).join(`
|
|
45
|
+
`);return{block:`
|
|
46
|
+
/** This project's \`defineRoom\` rooms, addressable as typed references for \`client.connectRoom\`. */
|
|
47
|
+
export interface RoomsRef {
|
|
48
|
+
${s}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export const rooms: RoomsRef = {
|
|
52
|
+
${n}
|
|
53
|
+
};
|
|
54
|
+
`,importLine:`import type { LunoraRoomMessages } from "./functions.js";
|
|
55
|
+
`}},_=t=>{const e=t.filter(a=>a.stream);if(e.length===0)return{block:"",body:""};const s=k(e,a=>{const l=d(a.chunkType??"unknown",a.filePath),r=d(y(a.searchParams),a.filePath),i=d(y(a.params),a.filePath);return`${O(a.exportName)}: HttpStreamRef<${l}, ${r}, ${i}>;`},"type"),n=k(e,a=>`${m(a.exportName)}: { method: ${JSON.stringify(a.method)}, path: ${JSON.stringify(a.path)} },`,"value");return{block:`
|
|
56
|
+
/** This project's HTTP-SSE stream routes (\`httpRoute.<verb>(path).stream()\`), addressable as typed references for \`client.httpStream\` / \`useHttpStream\`. */
|
|
57
|
+
export interface HttpStreamsRef {
|
|
58
|
+
${s}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export const httpStreams: HttpStreamsRef = {
|
|
62
|
+
${n}
|
|
63
|
+
};
|
|
64
|
+
`,body:s}},J=t=>k(t,e=>`${m(e.exportName)}: { __lunoraRef: ${JSON.stringify(`${g(e.filePath)}:${e.exportName}`)}${T(e)?", sensitive: true":""} },`,"value"),C=t=>{const{block:e="",constName:s,docComment:n="",functions:o,importLine:a="",typeName:l,typesBody:r="",useUmbrella:i}=t,c=j(o),p=J(o),u=w(`${c}
|
|
65
|
+
${r}`),b=u.length>0?`
|
|
66
|
+
import type { ${u.join(", ")} } from "./dataModel.js";
|
|
67
|
+
`:"",h=[...c===""?[]:["FunctionReference"],...t.clientImports??[]],f=h.length>0?`import type { ${h.join(", ")} } from "${S(i).client}";
|
|
68
|
+
`:"";return P(`${x}${f}${a}${b}
|
|
69
|
+
${n}export interface ${l} {${c?`
|
|
70
|
+
${c}
|
|
71
|
+
`:""}}
|
|
72
|
+
|
|
73
|
+
export const ${s}: ${l} = {${p?`
|
|
74
|
+
${p}
|
|
75
|
+
`:""}};
|
|
76
|
+
${e}`,i)},z=t=>{const{agents:e=[],functions:s,httpRoutes:n=[],mutators:o=[],useUmbrella:a=!1,workflows:l=[]}=t,r=_(n),i=W(s),c=I(l,e);return C({block:`${c.block}${r.block}${i.block}`,clientImports:[...r.block===""?[]:["HttpStreamRef"],...i.block===""?[]:["RoomRef"]],constName:"api",functions:[...s.filter(p=>p.visibility!=="internal"),...E(e,s),...F(o,s)],importLine:`${c.importLine}${i.importLine}`,typeName:"ApiTypes",typesBody:r.body,useUmbrella:a})},Q=t=>C({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}),X=t=>t?`${x}import { createSeedClient as createSeedClientBase } from "@lunora/seed";
|
|
77
|
+
import type { SeedClient, SeedClientOptions } from "@lunora/seed";
|
|
78
|
+
|
|
79
|
+
import schema from "../schema.js";
|
|
80
|
+
import type { InsertModel } from "./dataModel.js";
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Schema-aware seed client with this project's \`InsertModel\` and runtime schema
|
|
84
|
+
* pre-bound. Each table is a method; call it with a count, a range, explicit
|
|
85
|
+
* partial rows, or per-field overrides. Foreign keys connect to rows seeded
|
|
86
|
+
* earlier in the run, and FK-parent tables are seeded automatically.
|
|
87
|
+
* @example
|
|
88
|
+
* const seed = createSeedClient({ seed: 1 });
|
|
89
|
+
* const { users } = await seed.users(5);
|
|
90
|
+
* const { posts } = await seed.posts((x) => x([10, 20]));
|
|
91
|
+
*/
|
|
92
|
+
export const createSeedClient = (options?: SeedClientOptions): SeedClient<InsertModel> => createSeedClientBase<InsertModel>(schema, options);
|
|
93
|
+
`:"",Y=(t,e,s=!1)=>{if(t.length===0||!e)return"";const n=S(s),o=i=>i.table===void 0?"Row":`Doc<${JSON.stringify(i.table)}> & Row`,a=t.map(i=>{A(i.exportName,"shape export name");const c=o(i),p=d(y(i.args),i.filePath),u=Object.keys(i.args).length>0,b=u?` args: ${p};`:` args?: ${p};`,h=u?`(args: ${p}) => void`:`(args?: ${p}) => void`,f=`${i.exportName}CollectionOptions`;return`/** Options for the \`${i.exportName}\` shape binding. */
|
|
94
|
+
export interface ${$(f)} {
|
|
95
|
+
${b}
|
|
96
|
+
/**
|
|
97
|
+
* Share the optimistic-overlay gate with other collections + mutators on this
|
|
98
|
+
* shard. Defaults to the shared per-shard registry, which is almost always what
|
|
99
|
+
* you want — pass one only to isolate this collection's gate.
|
|
100
|
+
*/
|
|
101
|
+
checkpoints?: CheckpointRegistry;
|
|
102
|
+
/** The Lunora client to subscribe through. */
|
|
103
|
+
client: LunoraClient;
|
|
104
|
+
/** Row key extractor — defaults to \`row._id\`. Override when the app keys rows by a natural column. */
|
|
105
|
+
getKey?: (row: ${c}) => string;
|
|
106
|
+
/** \`"eager"\` starts syncing at creation; \`"lazy"\` (default) on the first subscriber. */
|
|
107
|
+
load?: "eager" | "lazy";
|
|
108
|
+
/** Notified when the underlying subscription errors; the collection always leaves \`loading\`. */
|
|
109
|
+
onError?: (error: SubscriptionError) => void;
|
|
110
|
+
/** Routes the subscription to a shard's DO. **Required for a \`.shardBy()\` table** — without it the watermark lands in the default bucket. */
|
|
111
|
+
shardKey?: string;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Collection options for the \`${i.exportName}\` replication shape: \`config\` for
|
|
116
|
+
* \`createCollection\`, plus the \`checkpoints\` registry to hand \`bindMutators\` and
|
|
117
|
+
* \`scope\` to re-point the subscription.
|
|
118
|
+
*/
|
|
119
|
+
export const ${i.exportName}CollectionOptions = (options: ${$(f)}): LunoraCollectionOptions<${c}> =>
|
|
120
|
+
lunoraCollectionOptions<${c}>({
|
|
121
|
+
client: options.client,
|
|
122
|
+
...(options.checkpoints === undefined ? {} : { checkpoints: options.checkpoints }),
|
|
123
|
+
...(options.getKey === undefined ? {} : { getKey: options.getKey }),
|
|
124
|
+
...(options.load === undefined ? {} : { load: options.load }),
|
|
125
|
+
...(options.onError === undefined ? {} : { onError: options.onError }),
|
|
126
|
+
...(options.shardKey === undefined ? {} : { shardKey: options.shardKey }),
|
|
127
|
+
shape: { args: options.args, name: ${JSON.stringify(i.exportName)}, ...(options.shardKey === undefined ? {} : { shardKey: options.shardKey }) },
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
/** Live collection for the \`${i.exportName}\` shape, with its sync controls. */
|
|
131
|
+
export const ${i.exportName}Collection = (
|
|
132
|
+
options: ${$(f)},
|
|
133
|
+
): { checkpoints: CheckpointRegistry; collection: Collection<${c}, string>; scope: ${h} } => {
|
|
134
|
+
const { checkpoints, config, scope } = ${i.exportName}CollectionOptions(options);
|
|
135
|
+
|
|
136
|
+
return { checkpoints, collection: createCollection(config), scope };
|
|
137
|
+
};`}).join(`
|
|
138
|
+
|
|
139
|
+
`),l=w(a),r=l.length>0?`import type { ${l.join(", ")} } from "./dataModel.js";
|
|
140
|
+
`:"";return`${x}import type { LunoraClient, SubscriptionError } from "${n.client}";
|
|
141
|
+
import { lunoraCollectionOptions } from "@lunora/db/collections";
|
|
142
|
+
import type { CheckpointRegistry, LunoraCollectionOptions, Row } from "@lunora/db";
|
|
143
|
+
import type { Collection } from "@tanstack/db";
|
|
144
|
+
import { createCollection } from "@tanstack/db";
|
|
145
|
+
${r}
|
|
146
|
+
${a}
|
|
147
|
+
`};export{z as emitApi,Y as emitCollections,Q as emitInternalApi,X as emitSeed,G as renderAgentFunctionRegistry,V as renderSandboxFunctionRegistry};
|