@lunora/codegen 1.0.0-alpha.105 → 1.0.0-alpha.107

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/dist/index.d.mts CHANGED
@@ -817,9 +817,10 @@ interface WorkflowCallIR {
817
817
  }
818
818
  /**
819
819
  * A `ctx.db.query("table")…` read discovered in a function body, reduced to what
820
- * the `filter_without_index` advisor lint needs: which table, whether the chain
821
- * narrows with an index, and whether it filters. `table` is `""` when the
822
- * `query(...)` argument is not a string literal (a dynamic table — not lintable).
820
+ * the query advisor lints need: which table, whether the chain narrows with an
821
+ * index, whether it filters, and which terminal materializes the result.
822
+ * `table` is `""` when the `query(...)` argument is not a string literal (a
823
+ * dynamic table — not lintable).
823
824
  */
824
825
  interface QueryReadIR {
825
826
  /** Exported procedure the read sits in, or `""` at module scope. */
@@ -841,6 +842,18 @@ interface QueryReadIR {
841
842
  line: number;
842
843
  /** Queried table name, or `""` when the argument is not a string literal. */
843
844
  table: string;
845
+ /**
846
+ * The materializing call the chain ends in — `"collect"`, `"take"`,
847
+ * `"paginate"`, `"first"`, `"unique"`, … — i.e. how much of the narrowed set
848
+ * the read actually loads.
849
+ *
850
+ * `undefined` when the chain reaches no recognised terminal (a reader passed
851
+ * on, a bare `query(...)`) AND when a feeder predating this field produced
852
+ * the read. The two are deliberately not distinguished: no consumer could act
853
+ * on the difference, so the terminal-shaped lints skip the read either way
854
+ * rather than guessing a terminal.
855
+ */
856
+ terminal?: string;
844
857
  }
845
858
  /**
846
859
  * A `ctx.authApi.<method>(...)` call discovered in a function body, attributed
@@ -2720,10 +2733,13 @@ declare const discoverNotifyConfig: (project: Project, lunoraDirectory: string)
2720
2733
  */
2721
2734
  declare const readPackageDependencies: (projectRoot: string) => Set<string> | undefined;
2722
2735
  /**
2723
- * Discover `ctx.db.query("table")…` reads under the lunora source directory and
2724
- * reduce each to a {@link QueryReadIR}. Only reads that call `.filter()` are
2725
- * returned — an unfiltered read is never a `filter_without_index` candidate, so
2726
- * dropping the rest keeps the lint input small.
2736
+ * Discover every `ctx.db.query("table")…` read under the lunora source directory
2737
+ * and reduce each to a {@link QueryReadIR}.
2738
+ *
2739
+ * Reads without a `.filter()` are kept too. They are never
2740
+ * `filter_without_index` candidates (that lint gates on `hasFilter`), but an
2741
+ * unfiltered, unindexed `.collect()` is the read `unbounded_collect` exists for
2742
+ * — and dropping it here is precisely why nothing could see it.
2727
2743
  */
2728
2744
  declare const discoverQueries: (project: Project, lunoraDirectory: string) => QueryReadIR[];
2729
2745
  /** The only file queues may be declared in — mirrors `lunora/workflows.ts`. */
package/dist/index.d.ts CHANGED
@@ -817,9 +817,10 @@ interface WorkflowCallIR {
817
817
  }
818
818
  /**
819
819
  * A `ctx.db.query("table")…` read discovered in a function body, reduced to what
820
- * the `filter_without_index` advisor lint needs: which table, whether the chain
821
- * narrows with an index, and whether it filters. `table` is `""` when the
822
- * `query(...)` argument is not a string literal (a dynamic table — not lintable).
820
+ * the query advisor lints need: which table, whether the chain narrows with an
821
+ * index, whether it filters, and which terminal materializes the result.
822
+ * `table` is `""` when the `query(...)` argument is not a string literal (a
823
+ * dynamic table — not lintable).
823
824
  */
824
825
  interface QueryReadIR {
825
826
  /** Exported procedure the read sits in, or `""` at module scope. */
@@ -841,6 +842,18 @@ interface QueryReadIR {
841
842
  line: number;
842
843
  /** Queried table name, or `""` when the argument is not a string literal. */
843
844
  table: string;
845
+ /**
846
+ * The materializing call the chain ends in — `"collect"`, `"take"`,
847
+ * `"paginate"`, `"first"`, `"unique"`, … — i.e. how much of the narrowed set
848
+ * the read actually loads.
849
+ *
850
+ * `undefined` when the chain reaches no recognised terminal (a reader passed
851
+ * on, a bare `query(...)`) AND when a feeder predating this field produced
852
+ * the read. The two are deliberately not distinguished: no consumer could act
853
+ * on the difference, so the terminal-shaped lints skip the read either way
854
+ * rather than guessing a terminal.
855
+ */
856
+ terminal?: string;
844
857
  }
845
858
  /**
846
859
  * A `ctx.authApi.<method>(...)` call discovered in a function body, attributed
@@ -2720,10 +2733,13 @@ declare const discoverNotifyConfig: (project: Project, lunoraDirectory: string)
2720
2733
  */
2721
2734
  declare const readPackageDependencies: (projectRoot: string) => Set<string> | undefined;
2722
2735
  /**
2723
- * Discover `ctx.db.query("table")…` reads under the lunora source directory and
2724
- * reduce each to a {@link QueryReadIR}. Only reads that call `.filter()` are
2725
- * returned — an unfiltered read is never a `filter_without_index` candidate, so
2726
- * dropping the rest keeps the lint input small.
2736
+ * Discover every `ctx.db.query("table")…` read under the lunora source directory
2737
+ * and reduce each to a {@link QueryReadIR}.
2738
+ *
2739
+ * Reads without a `.filter()` are kept too. They are never
2740
+ * `filter_without_index` candidates (that lint gates on `hasFilter`), but an
2741
+ * unfiltered, unindexed `.collect()` is the read `unbounded_collect` exists for
2742
+ * — and dropping it here is precisely why nothing could see it.
2727
2743
  */
2728
2744
  declare const discoverQueries: (project: Project, lunoraDirectory: string) => QueryReadIR[];
2729
2745
  /** The only file queues may be declared in — mirrors `lunora/workflows.ts`. */
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as p}from"./packem_shared/formatAdvisories-CQvIhQ04.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as S}from"./packem_shared/describeErrorLevelFindings-IhNx9gPr.mjs";import{CodegenDiagnosticError as E,diagnosticAt as x}from"./packem_shared/CodegenDiagnosticError-DPezpZTz.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-Dk-k250h.mjs";import{default as O}from"./packem_shared/discoverAuthApiCalls-XfNbxqlq.mjs";import{CONTAINERS_FILENAME as g,discoverContainers as C}from"./packem_shared/CONTAINERS_FILENAME-DQpyhY6c.mjs";import{default as h}from"./packem_shared/discoverCrons-RlATa0_t.mjs";import{FLAGS_FILENAME as L,discoverFlags as I}from"./packem_shared/FLAGS_FILENAME-Boqm0YCP.mjs";import{discoverFunctions as F}from"./packem_shared/discoverFunctions-4TNKUv7P.mjs";import{default as P}from"./packem_shared/discoverHttpRoutes-DQivLBqT.mjs";import{default as G}from"./packem_shared/discoverInserts-D6szWzrV.mjs";import{default as y}from"./packem_shared/discoverMaskProcedures-BBPqLXA5.mjs";import{default as k}from"./packem_shared/discoverMigrations-rbjxflR8.mjs";import{MUTATORS_FILENAME as W,discoverMutators as K}from"./packem_shared/MUTATORS_FILENAME-Cp_JxLSz.mjs";import{default as j}from"./packem_shared/discoverNondeterministicCalls-Bxr652Rz.mjs";import{NOTIFY_FILENAME as w,discoverNotifyCalls as B,discoverNotifyConfig as q}from"./packem_shared/NOTIFY_FILENAME-DwyJ5I4Q.mjs";import{default as Y}from"./packem_shared/readPackageDependencies-CogJX1Ia.mjs";import{y as X}from"./packem_shared/discover-queries-i4Vd2si7.mjs";import{QUEUES_FILENAME as ee,discoverQueues as re}from"./packem_shared/QUEUES_FILENAME-QpMZsde0.mjs";import{default as te}from"./packem_shared/discoverR2sqlCalls-DMxG6gHr.mjs";import{discoverRlsMetadata as ae,default as ie}from"./packem_shared/discoverRlsMetadata-B63ARnKG.mjs";import{discoverSandboxUsage as de}from"./packem_shared/discoverSandboxUsage-DBM98vVh.mjs";import{default as fe}from"./packem_shared/discoverSchema-BNr7PVcZ.mjs";import{SHAPES_FILENAME as ne,discoverShapes as Se}from"./packem_shared/SHAPES_FILENAME-WxXOsYfe.mjs";import{default as Ee}from"./packem_shared/discoverStorageRulesMetadata-_40MGqRX.mjs";import{WORKFLOWS_FILENAME as Ae,discoverWorkflows as ue}from"./packem_shared/WORKFLOWS_FILENAME-Dz80zqeT.mjs";import{S as Ne,h as Oe,P as Re,B as ge,p as Ce,L as Me,R as he,C as _e,V as Le,Q as Ie,$ as Te,E as Fe,m as De,F as Pe}from"./packem_shared/emit-B8FxCABN.mjs";import{emitApp as Ge}from"./packem_shared/emitApp-Dg-jOuj6.mjs";import{buildOpenApiDocument as ye,emitOpenApi as be,emitOpenApiModule as ke}from"./packem_shared/buildOpenApiDocument-CDYoRVC6.mjs";import{OPENRPC_VERSION as We,buildOpenRpcDocument as Ke,emitOpenRpc as Qe,emitOpenRpcModule as je}from"./packem_shared/OPENRPC_VERSION-CBWjXJgS.mjs";import{DEFAULT_TARGET as we,platformMatrixIds as Be,readProjectTarget as qe,resolveCodegenTarget as Je}from"./packem_shared/DEFAULT_TARGET-CH5disA3.mjs";import{SCHEMA_SNAPSHOT_FILENAME as $e,createCodegenProject as Xe,refreshCodegenProject as Ze,runCodegen as er}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-BM6kIe4w.mjs";import{SchemaSnapshotParseError as or,buildSchemaSnapshot as tr,evaluateSchemaDrift as sr,parseSchemaSnapshot as ar}from"./packem_shared/SchemaSnapshotParseError-BkgxjBPQ.mjs";import{schemaFromIr as mr}from"./packem_shared/schemaFromIr-R1ZFzVyy.mjs";import{LUNORA_ERROR_CODES as pr,validatorIrToJsonSchema as fr}from"./packem_shared/LUNORA_ERROR_CODES-zfAI2OFs.mjs";import{SDK_LANGUAGES as nr,SDK_TARGETS as Sr,generateSdk as lr}from"./packem_shared/SDK_LANGUAGES-fIqQtE14.mjs";import{redact as xr,secretKindOf as Ar}from"./packem_shared/redact-6jD4lAhq.mjs";import{MESSAGE_SOLUTIONS as vr,findSolutionByMessage as Nr}from"@lunora/errors";import{isTypedSchema as Rr}from"./packem_shared/isTypedSchema-9wiKtXr2.mjs";const e="0.0.0";export{u as AGENTS_FILENAME,g as CONTAINERS_FILENAME,E as CodegenDiagnosticError,we as DEFAULT_TARGET,L as FLAGS_FILENAME,Ne as GENERATED_HEADER,pr as LUNORA_ERROR_CODES,vr as LUNORA_SOLUTION_RULES,W as MUTATORS_FILENAME,w as NOTIFY_FILENAME,We as OPENRPC_VERSION,ee as QUEUES_FILENAME,$e as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,nr as SDK_LANGUAGES,Sr as SDK_TARGETS,ne as SHAPES_FILENAME,or as SchemaSnapshotParseError,e as VERSION,Ae as WORKFLOWS_FILENAME,ye as buildOpenApiDocument,Ke as buildOpenRpcDocument,tr as buildSchemaSnapshot,Xe as createCodegenProject,c as describeErrorLevelFindings,x as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,O as discoverAuthApiCalls,C as discoverContainers,h as discoverCrons,I as discoverFlags,F as discoverFunctions,P as discoverHttpRoutes,G as discoverInserts,y as discoverMaskProcedures,k as discoverMigrations,K as discoverMutators,j as discoverNondeterministicCalls,B as discoverNotifyCalls,q as discoverNotifyConfig,X as discoverQueries,re as discoverQueues,te as discoverR2sqlCalls,ae as discoverRlsMetadata,ie as discoverRlsProcedures,de as discoverSandboxUsage,fe as discoverSchema,Se as discoverShapes,Ee as discoverStorageRulesMetadata,ue as discoverWorkflows,Oe as emitAgents,Re as emitApi,Ge as emitApp,ge as emitCollections,Ce as emitContainers,Me as emitCrons,he as emitDataModel,_e as emitDrizzleSchema,Le as emitFunctions,be as emitOpenApi,ke as emitOpenApiModule,Qe as emitOpenRpc,je as emitOpenRpcModule,Ie as emitServer,Te as emitShard,Fe as emitVectors,De as emitWorkflows,Pe as emitWranglerCronTriggers,n as errorAdvisoryNames,S as errorPlatformDiagnosticNames,sr as evaluateSchemaDrift,Nr as findLunoraSolution,m as formatAdvisories,lr as generateSdk,Rr as isTypedSchema,d as lintSchema,ar as parseSchemaSnapshot,Be as platformMatrixIds,Y as readPackageDependencies,qe as readProjectTarget,xr as redact,Ze as refreshCodegenProject,Je as resolveCodegenTarget,er as runCodegen,mr as schemaFromIr,Ar as secretKindOf,a as serializeSchemaSnapshot,p as toAdvisorContext,fr as validatorIrToJsonSchema};
1
+ import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as p}from"./packem_shared/formatAdvisories-CQvIhQ04.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as S}from"./packem_shared/describeErrorLevelFindings-IhNx9gPr.mjs";import{CodegenDiagnosticError as E,diagnosticAt as x}from"./packem_shared/CodegenDiagnosticError-DPezpZTz.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-Dk-k250h.mjs";import{default as O}from"./packem_shared/discoverAuthApiCalls-XfNbxqlq.mjs";import{CONTAINERS_FILENAME as g,discoverContainers as M}from"./packem_shared/CONTAINERS_FILENAME-DQpyhY6c.mjs";import{default as h}from"./packem_shared/discoverCrons-RlATa0_t.mjs";import{FLAGS_FILENAME as I,discoverFlags as L}from"./packem_shared/FLAGS_FILENAME-Boqm0YCP.mjs";import{discoverFunctions as F}from"./packem_shared/discoverFunctions-4TNKUv7P.mjs";import{default as P}from"./packem_shared/discoverHttpRoutes-DQivLBqT.mjs";import{default as G}from"./packem_shared/discoverInserts-D6szWzrV.mjs";import{default as b}from"./packem_shared/discoverMaskProcedures-BBPqLXA5.mjs";import{default as y}from"./packem_shared/discoverMigrations-rbjxflR8.mjs";import{MUTATORS_FILENAME as W,discoverMutators as K}from"./packem_shared/MUTATORS_FILENAME-Cp_JxLSz.mjs";import{default as j}from"./packem_shared/discoverNondeterministicCalls-Bxr652Rz.mjs";import{NOTIFY_FILENAME as w,discoverNotifyCalls as B,discoverNotifyConfig as q}from"./packem_shared/NOTIFY_FILENAME-DwyJ5I4Q.mjs";import{default as Y}from"./packem_shared/readPackageDependencies-CogJX1Ia.mjs";import{I as X}from"./packem_shared/discover-queries-CU9o_j87.mjs";import{QUEUES_FILENAME as ee,discoverQueues as re}from"./packem_shared/QUEUES_FILENAME-QpMZsde0.mjs";import{default as te}from"./packem_shared/discoverR2sqlCalls-DMxG6gHr.mjs";import{discoverRlsMetadata as ae,default as ie}from"./packem_shared/discoverRlsMetadata-B63ARnKG.mjs";import{discoverSandboxUsage as de}from"./packem_shared/discoverSandboxUsage-DBM98vVh.mjs";import{default as fe}from"./packem_shared/discoverSchema-BNr7PVcZ.mjs";import{SHAPES_FILENAME as ne,discoverShapes as Se}from"./packem_shared/SHAPES_FILENAME-WxXOsYfe.mjs";import{default as Ee}from"./packem_shared/discoverStorageRulesMetadata-_40MGqRX.mjs";import{WORKFLOWS_FILENAME as Ae,discoverWorkflows as ue}from"./packem_shared/WORKFLOWS_FILENAME-Dz80zqeT.mjs";import{S as Ne,h as Oe,M as Re,B as ge,p as Me,L as Ce,R as he,C as _e,V as Ie,Q as Le,$ as Te,E as Fe,m as De,F as Pe}from"./packem_shared/emit-BbLyaTLJ.mjs";import{emitApp as Ge}from"./packem_shared/emitApp-DkO-Qvoo.mjs";import{buildOpenApiDocument as be,emitOpenApi as ke,emitOpenApiModule as ye}from"./packem_shared/buildOpenApiDocument-B8-PH9af.mjs";import{OPENRPC_VERSION as We,buildOpenRpcDocument as Ke,emitOpenRpc as Qe,emitOpenRpcModule as je}from"./packem_shared/OPENRPC_VERSION-Bzh1vxcl.mjs";import{DEFAULT_TARGET as we,platformMatrixIds as Be,readProjectTarget as qe,resolveCodegenTarget as Je}from"./packem_shared/DEFAULT_TARGET-CH5disA3.mjs";import{SCHEMA_SNAPSHOT_FILENAME as $e,createCodegenProject as Xe,refreshCodegenProject as Ze,runCodegen as er}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-DlCvMk66.mjs";import{SchemaSnapshotParseError as or,buildSchemaSnapshot as tr,evaluateSchemaDrift as sr,parseSchemaSnapshot as ar}from"./packem_shared/SchemaSnapshotParseError-BkgxjBPQ.mjs";import{schemaFromIr as mr}from"./packem_shared/schemaFromIr-R1ZFzVyy.mjs";import{LUNORA_ERROR_CODES as pr,validatorIrToJsonSchema as fr}from"./packem_shared/LUNORA_ERROR_CODES-zfAI2OFs.mjs";import{SDK_LANGUAGES as nr,SDK_TARGETS as Sr,generateSdk as lr}from"./packem_shared/SDK_LANGUAGES-fIqQtE14.mjs";import{redact as xr,secretKindOf as Ar}from"./packem_shared/redact-6jD4lAhq.mjs";import{MESSAGE_SOLUTIONS as vr,findSolutionByMessage as Nr}from"@lunora/errors";import{isTypedSchema as Rr}from"./packem_shared/isTypedSchema-9wiKtXr2.mjs";const e="0.0.0";export{u as AGENTS_FILENAME,g as CONTAINERS_FILENAME,E as CodegenDiagnosticError,we as DEFAULT_TARGET,I as FLAGS_FILENAME,Ne as GENERATED_HEADER,pr as LUNORA_ERROR_CODES,vr as LUNORA_SOLUTION_RULES,W as MUTATORS_FILENAME,w as NOTIFY_FILENAME,We as OPENRPC_VERSION,ee as QUEUES_FILENAME,$e as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,nr as SDK_LANGUAGES,Sr as SDK_TARGETS,ne as SHAPES_FILENAME,or as SchemaSnapshotParseError,e as VERSION,Ae as WORKFLOWS_FILENAME,be as buildOpenApiDocument,Ke as buildOpenRpcDocument,tr as buildSchemaSnapshot,Xe as createCodegenProject,c as describeErrorLevelFindings,x as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,O as discoverAuthApiCalls,M as discoverContainers,h as discoverCrons,L as discoverFlags,F as discoverFunctions,P as discoverHttpRoutes,G as discoverInserts,b as discoverMaskProcedures,y as discoverMigrations,K as discoverMutators,j as discoverNondeterministicCalls,B as discoverNotifyCalls,q as discoverNotifyConfig,X as discoverQueries,re as discoverQueues,te as discoverR2sqlCalls,ae as discoverRlsMetadata,ie as discoverRlsProcedures,de as discoverSandboxUsage,fe as discoverSchema,Se as discoverShapes,Ee as discoverStorageRulesMetadata,ue as discoverWorkflows,Oe as emitAgents,Re as emitApi,Ge as emitApp,ge as emitCollections,Me as emitContainers,Ce as emitCrons,he as emitDataModel,_e as emitDrizzleSchema,Ie as emitFunctions,ke as emitOpenApi,ye as emitOpenApiModule,Qe as emitOpenRpc,je as emitOpenRpcModule,Le as emitServer,Te as emitShard,Fe as emitVectors,De as emitWorkflows,Pe as emitWranglerCronTriggers,n as errorAdvisoryNames,S as errorPlatformDiagnosticNames,sr as evaluateSchemaDrift,Nr as findLunoraSolution,m as formatAdvisories,lr as generateSdk,Rr as isTypedSchema,d as lintSchema,ar as parseSchemaSnapshot,Be as platformMatrixIds,Y as readPackageDependencies,qe as readProjectTarget,xr as redact,Ze as refreshCodegenProject,Je as resolveCodegenTarget,er as runCodegen,mr as schemaFromIr,Ar as secretKindOf,a as serializeSchemaSnapshot,p as toAdvisorContext,fr as validatorIrToJsonSchema};
@@ -1 +1 @@
1
- import"@lunora/agent/component";import"@lunora/errors";import"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{S as r,d as o,a as n,h as E,P as l,B as A,p as S,L as p,R as C,C as d,V as g,f as u,M as c,Q as D,$ as R,E as f,m as h,F as B}from"./emit-B8FxCABN.mjs";import"./paths-BmX5O1sG.mjs";export{r as GENERATED_HEADER,o as UMBRELLA_BASE_PACKAGES,n as buildStorageColumns,E as emitAgents,l as emitApi,A as emitCollections,S as emitContainers,p as emitCrons,C as emitDataModel,d as emitDrizzleSchema,g as emitFunctions,u as emitQueues,c as emitSeed,D as emitServer,R as emitShard,f as emitVectors,h as emitWorkflows,B as emitWranglerCronTriggers};
1
+ import"@lunora/agent/component";import"@lunora/errors";import"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{S as r,d as o,a as n,h as E,M as l,B as A,p as S,L as p,R as C,C as d,V as g,f as u,P as c,Q as D,$ as R,E as f,m as h,F as B}from"./emit-BbLyaTLJ.mjs";import"./paths-BmX5O1sG.mjs";export{r as GENERATED_HEADER,o as UMBRELLA_BASE_PACKAGES,n as buildStorageColumns,E as emitAgents,l as emitApi,A as emitCollections,S as emitContainers,p as emitCrons,C as emitDataModel,d as emitDrizzleSchema,g as emitFunctions,u as emitQueues,c as emitSeed,D as emitServer,R as emitShard,f as emitVectors,h as emitWorkflows,B as emitWranglerCronTriggers};
@@ -1,3 +1,3 @@
1
- import{S as a}from"./emit-B8FxCABN.mjs";import{n as i}from"./paths-BmX5O1sG.mjs";import{validatorIrToJsonSchema as s,objectSchema as c,LUNORA_ERROR_CODES as u}from"./LUNORA_ERROR_CODES-zfAI2OFs.mjs";const p="1.3.2",m={description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."},d=e=>{const r=i(e.filePath),t=`${r}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${t}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${t}", "args": { … } }\`).`,errors:u.map((o,n)=>({code:-32e3-n,data:{code:o},message:o})),name:t,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:c(e.args)}],result:{name:"result",schema:e.output?s(e.output):m},summary:`${e.kind}: ${t}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:r}]}},l=e=>{const r=e.version??"0.0.0",t=e.functions.filter(o=>o.visibility!=="internal"&&o.kind!=="stream").map(o=>d(o)).toSorted((o,n)=>o.name.localeCompare(n.name));return{info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora RPC",version:r},methods:t,openrpc:p}},h=e=>`${JSON.stringify(l(e),void 0,2)}
1
+ import{S as a}from"./emit-BbLyaTLJ.mjs";import{n as i}from"./paths-BmX5O1sG.mjs";import{validatorIrToJsonSchema as s,objectSchema as c,LUNORA_ERROR_CODES as u}from"./LUNORA_ERROR_CODES-zfAI2OFs.mjs";const p="1.3.2",m={description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."},d=e=>{const r=i(e.filePath),t=`${r}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${t}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${t}", "args": { … } }\`).`,errors:u.map((o,n)=>({code:-32e3-n,data:{code:o},message:o})),name:t,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:c(e.args)}],result:{name:"result",schema:e.output?s(e.output):m},summary:`${e.kind}: ${t}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:r}]}},l=e=>{const r=e.version??"0.0.0",t=e.functions.filter(o=>o.visibility!=="internal"&&o.kind!=="stream").map(o=>d(o)).toSorted((o,n)=>o.name.localeCompare(n.name));return{info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora RPC",version:r},methods:t,openrpc:p}},h=e=>`${JSON.stringify(l(e),void 0,2)}
2
2
  `,O=e=>`${a}export const openRpcSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
3
3
  `;export{p as OPENRPC_VERSION,l as buildOpenRpcDocument,h as emitOpenRpc,O as emitOpenRpcModule};
@@ -1,4 +1,4 @@
1
- import{existsSync as b,mkdirSync as qt,readFileSync as dt,writeFileSync as Bt,rmSync as Ut}from"node:fs";import{join as g,dirname as le}from"node:path";import{performance as ue}from"node:perf_hooks";import{runAdvisor as Vt}from"@lunora/advisor";import{LunoraError as k}from"@lunora/errors";import{SyntaxKind as l,Node as o,Project as Ge}from"ts-morph";import{serializeSchemaSnapshot as Wt}from"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{toAdvisorContext as _t}from"./formatAdvisories-CQvIhQ04.mjs";import{discoverAgents as Gt}from"./AGENTS_FILENAME-Dk-k250h.mjs";import{discoverContainers as Ht}from"./CONTAINERS_FILENAME-DQpyhY6c.mjs";import{diagnosticAt as Z}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{o as Y}from"./module-specifiers-8FEEiUcv.mjs";import{r as de,Q as Qt,R as Jt,a as Xt,P as Zt,V as Yt,$ as es,B as ts,p as ss,m as rs,h as ns,f as is,L as os,E as as,C as cs,M as ls,F as us}from"./emit-B8FxCABN.mjs";import{g as h,p as E,P as N,C as $,O as gt,z as ds,R as pt,h as gs}from"./discover-ast-7ABwvTVn.mjs";import ps from"./readPackageDependencies-CogJX1Ia.mjs";import{discoverQueues as fs}from"./QUEUES_FILENAME-QpMZsde0.mjs";import{discoverSandboxUsage as ms}from"./discoverSandboxUsage-DBM98vVh.mjs";import hs from"./discoverStorageRulesMetadata-_40MGqRX.mjs";import{discoverWorkflows as xs}from"./WORKFLOWS_FILENAME-Dz80zqeT.mjs";import{gatePlatformFeatures as Es,resolveCodegenTarget as ys}from"./DEFAULT_TARGET-CH5disA3.mjs";import{i as I,a as D,e as x,c as A,r as $s,b as vs,s as ee,d as bs,f as Ns,y as Ss}from"./discover-queries-i4Vd2si7.mjs";import{classifyProcedureCall as M,inlineHandler as As,procedureHandler as ft,chainUsesWrappedCall as mt,isDatabaseAccessor as R,chainHasStep as ws,discoverFunctions as Ps,resolveStandardSchemaType as Is}from"./discoverFunctions-4TNKUv7P.mjs";import Ts from"./discoverAuthApiCalls-XfNbxqlq.mjs";import Ls from"./discoverCrons-RlATa0_t.mjs";import{discoverFlagKeys as ks}from"./FLAGS_FILENAME-Boqm0YCP.mjs";import Ds from"./discoverHttpRoutes-DQivLBqT.mjs";import Os from"./discoverInserts-D6szWzrV.mjs";import Cs,{discoverMaskStrategies as Fs,discoverMaskMetadata as Ks,discoverMaskHasNonLiteralPolicy as Rs}from"./discoverMaskProcedures-BBPqLXA5.mjs";import Ms from"./discoverMigrations-rbjxflR8.mjs";import{MUTATORS_FILENAME as js,isDefineMutatorCallee as zs,discoverMutators as qs}from"./MUTATORS_FILENAME-Cp_JxLSz.mjs";import Bs from"./discoverNondeterministicCalls-Bxr652Rz.mjs";import{discoverNotifyConfig as Us,discoverNotifyCalls as Vs}from"./NOTIFY_FILENAME-DwyJ5I4Q.mjs";import Ws from"./discoverR2sqlCalls-DMxG6gHr.mjs";import _s,{discoverRlsMetadata as Gs}from"./discoverRlsMetadata-B63ARnKG.mjs";import Hs from"./discoverSchema-BNr7PVcZ.mjs";import{secretKindOf as Qs,redact as Js,isHeuristicSecretKind as Xs,isSecretishName as Zs}from"./redact-6jD4lAhq.mjs";import{discoverShapes as Ys}from"./SHAPES_FILENAME-WxXOsYfe.mjs";import{emitApp as er}from"./emitApp-Dg-jOuj6.mjs";import{buildOpenApiDocument as tr,emitOpenApiModule as sr}from"./buildOpenApiDocument-CDYoRVC6.mjs";import{buildOpenRpcDocument as rr,emitOpenRpcModule as nr}from"./OPENRPC_VERSION-CBWjXJgS.mjs";import{y as ir}from"./parse-validator-CusS8QwU.mjs";import{buildSchemaSnapshot as or}from"./SchemaSnapshotParseError-BkgxjBPQ.mjs";const ar=e=>{const t=[],s=e.tables.filter(r=>r.shardMode==="global");return s.some(r=>r.globalBackend!=="hyperdrive")&&t.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),s.some(r=>r.globalBackend==="hyperdrive")&&t.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'}),e.vectorIndexes.length>0&&t.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/vectors.ts` import `@lunora/bindings/vectors`"}),t},cr=(e,t)=>{if(t===void 0)return;const s=ar(e).filter(i=>!t.has(i.name));if(s.length===0)return;const r=s.map(i=>` - ${i.name} — ${i.reason}`).join(`
1
+ import{existsSync as b,mkdirSync as qt,readFileSync as dt,writeFileSync as Bt,rmSync as Ut}from"node:fs";import{join as g,dirname as le}from"node:path";import{performance as ue}from"node:perf_hooks";import{runAdvisor as Vt}from"@lunora/advisor";import{LunoraError as k}from"@lunora/errors";import{SyntaxKind as l,Node as o,Project as Ge}from"ts-morph";import{serializeSchemaSnapshot as Wt}from"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{toAdvisorContext as _t}from"./formatAdvisories-CQvIhQ04.mjs";import{discoverAgents as Gt}from"./AGENTS_FILENAME-Dk-k250h.mjs";import{discoverContainers as Ht}from"./CONTAINERS_FILENAME-DQpyhY6c.mjs";import{diagnosticAt as Z}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{o as Y}from"./module-specifiers-8FEEiUcv.mjs";import{r as de,Q as Qt,R as Jt,a as Xt,M as Zt,V as Yt,$ as es,B as ts,p as ss,m as rs,h as ns,f as is,L as os,E as as,C as cs,P as ls,F as us}from"./emit-BbLyaTLJ.mjs";import{g as h,p as E,P as N,C as $,O as gt,z as ds,R as pt,h as gs}from"./discover-ast-7ABwvTVn.mjs";import ps from"./readPackageDependencies-CogJX1Ia.mjs";import{discoverQueues as fs}from"./QUEUES_FILENAME-QpMZsde0.mjs";import{discoverSandboxUsage as ms}from"./discoverSandboxUsage-DBM98vVh.mjs";import hs from"./discoverStorageRulesMetadata-_40MGqRX.mjs";import{discoverWorkflows as xs}from"./WORKFLOWS_FILENAME-Dz80zqeT.mjs";import{gatePlatformFeatures as Es,resolveCodegenTarget as ys}from"./DEFAULT_TARGET-CH5disA3.mjs";import{i as I,a as D,e as x,c as A,r as $s,b as vs,s as ee,d as bs,f as Ns,I as Ss}from"./discover-queries-CU9o_j87.mjs";import{classifyProcedureCall as M,inlineHandler as As,procedureHandler as ft,chainUsesWrappedCall as mt,isDatabaseAccessor as R,chainHasStep as ws,discoverFunctions as Ps,resolveStandardSchemaType as Is}from"./discoverFunctions-4TNKUv7P.mjs";import Ts from"./discoverAuthApiCalls-XfNbxqlq.mjs";import Ls from"./discoverCrons-RlATa0_t.mjs";import{discoverFlagKeys as ks}from"./FLAGS_FILENAME-Boqm0YCP.mjs";import Ds from"./discoverHttpRoutes-DQivLBqT.mjs";import Os from"./discoverInserts-D6szWzrV.mjs";import Cs,{discoverMaskStrategies as Fs,discoverMaskMetadata as Ks,discoverMaskHasNonLiteralPolicy as Rs}from"./discoverMaskProcedures-BBPqLXA5.mjs";import Ms from"./discoverMigrations-rbjxflR8.mjs";import{MUTATORS_FILENAME as js,isDefineMutatorCallee as zs,discoverMutators as qs}from"./MUTATORS_FILENAME-Cp_JxLSz.mjs";import Bs from"./discoverNondeterministicCalls-Bxr652Rz.mjs";import{discoverNotifyConfig as Us,discoverNotifyCalls as Vs}from"./NOTIFY_FILENAME-DwyJ5I4Q.mjs";import Ws from"./discoverR2sqlCalls-DMxG6gHr.mjs";import _s,{discoverRlsMetadata as Gs}from"./discoverRlsMetadata-B63ARnKG.mjs";import Hs from"./discoverSchema-BNr7PVcZ.mjs";import{secretKindOf as Qs,redact as Js,isHeuristicSecretKind as Xs,isSecretishName as Zs}from"./redact-6jD4lAhq.mjs";import{discoverShapes as Ys}from"./SHAPES_FILENAME-WxXOsYfe.mjs";import{emitApp as er}from"./emitApp-DkO-Qvoo.mjs";import{buildOpenApiDocument as tr,emitOpenApiModule as sr}from"./buildOpenApiDocument-B8-PH9af.mjs";import{buildOpenRpcDocument as rr,emitOpenRpcModule as nr}from"./OPENRPC_VERSION-Bzh1vxcl.mjs";import{y as ir}from"./parse-validator-CusS8QwU.mjs";import{buildSchemaSnapshot as or}from"./SchemaSnapshotParseError-BkgxjBPQ.mjs";const ar=e=>{const t=[],s=e.tables.filter(r=>r.shardMode==="global");return s.some(r=>r.globalBackend!=="hyperdrive")&&t.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),s.some(r=>r.globalBackend==="hyperdrive")&&t.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'}),e.vectorIndexes.length>0&&t.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/vectors.ts` import `@lunora/bindings/vectors`"}),t},cr=(e,t)=>{if(t===void 0)return;const s=ar(e).filter(i=>!t.has(i.name));if(s.length===0)return;const r=s.map(i=>` - ${i.name} — ${i.reason}`).join(`
2
2
  `);throw new k("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
3
3
  ${r}
4
4
 
@@ -1,3 +1,3 @@
1
- import{S as b}from"./emit-B8FxCABN.mjs";import{n as p}from"./paths-BmX5O1sG.mjs";import{LUNORA_ERROR_CODES as x,objectSchema as l,validatorIrToJsonSchema as d}from"./LUNORA_ERROR_CODES-zfAI2OFs.mjs";const O="/_lunora/rest",k=["authorization","cf-access-jwt-assertion","cookie"],f=["x-d1-bookmark","x-lunora-shard-key"],T=e=>[...k,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],g=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,y=(...e)=>{const t=[];for(const r of e)for(const o of r?.split(",")??[]){const a=o.trim().toLowerCase();a!==""&&!t.includes(a)&&t.push(a)}return t.length===0?void 0:t.join(", ")},R=(e,t)=>{const r=[t,`max-age=${String(g(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(g(e.staleWhileRevalidate))}`),r.join(", ")},P=e=>e.scope==="public"?y(e.vary,...T(e),...f):y(e.vary,...f),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)}},j=e=>{const t=q(e);if(t!==void 0)return`${O}/${t.namespace}/${t.name}`},A=e=>e==="query"?"GET":"POST",h="#/components/responses/LunoraError",$=/:([A-Za-z_$][\w$]*)/gu,N=e=>[...e.matchAll($)].map(t=>t[1]),w=e=>e.replaceAll($,"{$1}"),u=e=>e.kind==="optional"?e.inner??e:e,C=e=>{const t=new Set(N(e.path)),r=[];for(const[o,a]of Object.entries(e.searchParams)){const c=u(a);r.push({description:`Query parameter \`${o}\``,in:"query",name:o,required:a.kind!=="optional",schema:d(c)})}for(const[o,a]of Object.entries(e.params)){const c=u(a);r.push({description:`Path parameter \`${o}\``,in:t.has(o)?"path":"query",name:o,required:t.has(o)?!0:a.kind!=="optional",schema:d(c)})}return r},v=e=>e?{content:{"application/json":{schema:d(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."},E=e=>{const t=p(e.filePath),r=C(e),o={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${p(e.path)}`,responses:{200:v(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:h}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(o.parameters=r),Object.keys(e.body).length>0&&(o.requestBody={content:{"application/json":{schema:l(e.body)}},required:!0}),e.stream&&(o["x-lunora-stream"]="text/event-stream"),o},L=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o={additionalProperties:!1,properties:{args:l(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:o}},required:!0},responses:{200:v(e.output),default:{$ref:h}},summary:`${e.kind}: ${r}`,tags:[t],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${r}`}},_=(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}},o={"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:R(r,r.scope),type:"string"}}};r.tag!==void 0&&(o["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const a=P(r);return a!==void 0&&(o.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:a,type:"string"}}),{headers:o}},I=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o=j(r);if(o===void 0)return;const a=A(e.kind),c=a==="GET",n={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_${p(o)}`,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).",..._(e.expose?.cache,c?"get":"post")},default:{$ref:h}},summary:`${a} ${o}`,tags:[t],"x-lunora-function-kind":e.kind};if(c){const s=Object.entries(e.args).map(([i,m])=>{const S=u(m);return{description:`Argument \`${i}\` (JSON-encoded for non-string values).`,in:"query",name:i,required:m.kind!=="optional",schema:d(S)}});return s.length>0&&(n.parameters=s),{method:"get",operation:n,path:o}}return n.requestBody={content:{"application/json":{schema:l(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:n,path:o}},D=e=>{const t=e.version??"0.0.0",r={},o=new Set;for(const n of e.httpRoutes){const s=w(n.path),i=r[s]??{};i[n.method.toLowerCase()]=E(n),r[s]=i,o.add(p(n.filePath))}const a=e.functions.filter(n=>n.visibility!=="internal"&&n.kind!=="stream");for(const n of a){const{operation:s,pathKey:i}=L(n);r[i]={post:s},o.add(p(n.filePath))}for(const n of a){if(n.expose?.rest!==!0)continue;const s=I(n);if(s===void 0)continue;const i=r[s.path]??{};i[s.method]=s.operation,r[s.path]=i}const c=[...o].toSorted((n,s)=>n.localeCompare(s)).map(n=>({description:`Operations declared in \`lunora/${n}\`.`,name:n}));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:x,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:r,tags:c}},U=e=>`${JSON.stringify(D(e),void 0,2)}
1
+ import{S as b}from"./emit-BbLyaTLJ.mjs";import{n as p}from"./paths-BmX5O1sG.mjs";import{LUNORA_ERROR_CODES as x,objectSchema as l,validatorIrToJsonSchema as d}from"./LUNORA_ERROR_CODES-zfAI2OFs.mjs";const O="/_lunora/rest",k=["authorization","cf-access-jwt-assertion","cookie"],f=["x-d1-bookmark","x-lunora-shard-key"],T=e=>[...k,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],g=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,y=(...e)=>{const t=[];for(const r of e)for(const o of r?.split(",")??[]){const a=o.trim().toLowerCase();a!==""&&!t.includes(a)&&t.push(a)}return t.length===0?void 0:t.join(", ")},R=(e,t)=>{const r=[t,`max-age=${String(g(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(g(e.staleWhileRevalidate))}`),r.join(", ")},P=e=>e.scope==="public"?y(e.vary,...T(e),...f):y(e.vary,...f),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)}},j=e=>{const t=q(e);if(t!==void 0)return`${O}/${t.namespace}/${t.name}`},A=e=>e==="query"?"GET":"POST",h="#/components/responses/LunoraError",$=/:([A-Za-z_$][\w$]*)/gu,N=e=>[...e.matchAll($)].map(t=>t[1]),w=e=>e.replaceAll($,"{$1}"),u=e=>e.kind==="optional"?e.inner??e:e,C=e=>{const t=new Set(N(e.path)),r=[];for(const[o,a]of Object.entries(e.searchParams)){const c=u(a);r.push({description:`Query parameter \`${o}\``,in:"query",name:o,required:a.kind!=="optional",schema:d(c)})}for(const[o,a]of Object.entries(e.params)){const c=u(a);r.push({description:`Path parameter \`${o}\``,in:t.has(o)?"path":"query",name:o,required:t.has(o)?!0:a.kind!=="optional",schema:d(c)})}return r},v=e=>e?{content:{"application/json":{schema:d(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."},E=e=>{const t=p(e.filePath),r=C(e),o={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${p(e.path)}`,responses:{200:v(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:h}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(o.parameters=r),Object.keys(e.body).length>0&&(o.requestBody={content:{"application/json":{schema:l(e.body)}},required:!0}),e.stream&&(o["x-lunora-stream"]="text/event-stream"),o},L=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o={additionalProperties:!1,properties:{args:l(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:o}},required:!0},responses:{200:v(e.output),default:{$ref:h}},summary:`${e.kind}: ${r}`,tags:[t],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${r}`}},_=(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}},o={"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:R(r,r.scope),type:"string"}}};r.tag!==void 0&&(o["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const a=P(r);return a!==void 0&&(o.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:a,type:"string"}}),{headers:o}},I=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o=j(r);if(o===void 0)return;const a=A(e.kind),c=a==="GET",n={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_${p(o)}`,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).",..._(e.expose?.cache,c?"get":"post")},default:{$ref:h}},summary:`${a} ${o}`,tags:[t],"x-lunora-function-kind":e.kind};if(c){const s=Object.entries(e.args).map(([i,m])=>{const S=u(m);return{description:`Argument \`${i}\` (JSON-encoded for non-string values).`,in:"query",name:i,required:m.kind!=="optional",schema:d(S)}});return s.length>0&&(n.parameters=s),{method:"get",operation:n,path:o}}return n.requestBody={content:{"application/json":{schema:l(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:n,path:o}},D=e=>{const t=e.version??"0.0.0",r={},o=new Set;for(const n of e.httpRoutes){const s=w(n.path),i=r[s]??{};i[n.method.toLowerCase()]=E(n),r[s]=i,o.add(p(n.filePath))}const a=e.functions.filter(n=>n.visibility!=="internal"&&n.kind!=="stream");for(const n of a){const{operation:s,pathKey:i}=L(n);r[i]={post:s},o.add(p(n.filePath))}for(const n of a){if(n.expose?.rest!==!0)continue;const s=I(n);if(s===void 0)continue;const i=r[s.path]??{};i[s.method]=s.operation,r[s.path]=i}const c=[...o].toSorted((n,s)=>n.localeCompare(s)).map(n=>({description:`Operations declared in \`lunora/${n}\`.`,name:n}));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:x,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:r,tags:c}},U=e=>`${JSON.stringify(D(e),void 0,2)}
2
2
  `,W=e=>`${b}export const openApiSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
3
3
  `;export{D as buildOpenApiDocument,U as emitOpenApi,W as emitOpenApiModule};
@@ -0,0 +1 @@
1
+ import{Node as s,SyntaxKind as l}from"ts-morph";import{g as N,p as A}from"./discover-ast-7ABwvTVn.mjs";const m=(e,t)=>{if(e.getText()!==t)return!1;const r=e.getParent();return s.isPropertyAccessExpression(r)&&r.getNameNode()===e?!1:!(s.isPropertyAssignment(r)&&r.getNameNode()===e)},x=(e,t)=>s.isIdentifier(e)?m(e,t):e.getDescendantsOfKind(l.Identifier).some(r=>m(r,t)),d=e=>x(e,"ctx"),I=e=>{let t=e;for(;s.isPropertyAccessExpression(t)||s.isElementAccessExpression(t)||s.isNonNullExpression(t);)t=t.getExpression();return s.isIdentifier(t)?t:void 0},C=e=>{if(s.isIdentifier(e))return e.getText();if(s.isPropertyAccessExpression(e))return e.getName()},E=e=>x(e,"args"),f=e=>{if(!s.isIdentifier(e))return;const t=e.getText(),r=e.getFirstAncestor(o=>s.isArrowFunction(o)||s.isFunctionExpression(o)||s.isFunctionDeclaration(o));if(r===void 0)return;const n=e.getStart();let i,u=-1;for(const o of r.getDescendantsOfKind(l.VariableDeclaration)){if(o.getName()!==t)continue;const a=o.getInitializer(),c=o.getStart();a!==void 0&&c<n&&c>u&&(i=a,u=c)}return i},T=e=>{if(E(e))return!0;const t=f(e);return t!==void 0&&E(t)},q=e=>{if(s.isCallExpression(e)||s.isNewExpression(e))return!1;const t=f(e);return t===void 0||!(s.isCallExpression(t)||s.isNewExpression(t))},L=e=>{if(d(e))return!0;const t=f(e);if(t!==void 0&&d(t))return!0;const r=t??e;return(s.isIdentifier(r)?[r]:r.getDescendantsOfKind(l.Identifier)).some(n=>{const i=f(n);return i!==void 0&&d(i)})},p=(e,t)=>x(e,t),O=(e,t)=>{if(p(e,t))return!0;const r=f(e);if(r!==void 0&&p(r,t))return!0;const n=I(e);if(n!==void 0){const i=f(n);return i!==void 0&&p(i,t)}return!1},P=e=>{for(const t of e.getAncestors())if(s.isVariableDeclaration(t)&&t.getVariableStatement()?.hasExportKeyword()===!0)return t.getName();return"<module>"},h=new Set(["withGeoIndex","withIndex","withSearchIndex"]),y=new Set(["collect","collectWithScores","first","paginate","take","unique"]),S=e=>{const t=e.getExpression();if(!s.isPropertyAccessExpression(t)||t.getName()!=="query")return!1;const r=t.getExpression();return s.isPropertyAccessExpression(r)?r.getName()==="db":s.isIdentifier(r)&&r.getText()==="db"},v=e=>{const t=[];let r=e;for(;;){const n=r.getParent();if(!n||!s.isPropertyAccessExpression(n))break;const i=n.getParent();if(!i||!s.isCallExpression(i))break;t.push(n.getName()),r=i}return t},b=/\b[A-Za-z_$][\w$]*\._id\s*===?[^=]/u,w=e=>{let t=e;for(;;){const r=t.getParent();if(!r||!s.isPropertyAccessExpression(r))return!1;const n=r.getParent();if(!n||!s.isCallExpression(n))return!1;if(r.getName()==="filter"){const i=n.getArguments()[0];if(i&&b.test(i.getText()))return!0}t=n}},D=e=>{const t=e.getArguments()[0];return t&&s.isStringLiteral(t)?t.getLiteralText():""},$=(e,t)=>{const r=[];for(const n of N(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),u=A(t,n);for(const o of i.getDescendantsOfKind(l.CallExpression)){if(!S(o))continue;const a=v(o),c=a.includes("filter");r.push({exportName:P(o),file:u,filtersPrimaryKey:c&&w(o),hasFilter:c,hasIndex:a.some(g=>h.has(g)),line:o.getStartLineNumber(),table:D(o),terminal:a.findLast(g=>y.has(g))})}}return r};export{$ as I,L as a,q as b,C as c,O as d,P as e,p as f,T as i,E as r,f as s};
@@ -0,0 +1 @@
1
+ import"ts-morph";import{I as p}from"./discover-queries-CU9o_j87.mjs";import"./discover-ast-7ABwvTVn.mjs";export{p as default};
@@ -15,13 +15,13 @@ import{agentComponent as rt}from"@lunora/agent/component";import{LunoraError as
15
15
  /**
16
16
  * R2 SQL over Apache Iceberg tables (window functions, DISTINCT, set operations). Non-deterministic — available only in actions. Reads here are NOT tracked by Lunora live queries.
17
17
  */
18
- readonly r2sql: import("@lunora/bindings/r2sql").R2SqlClient;`,tier:"action"}},{contextProperty:"scheduler",key:"scheduler",moduleSpecifier:"@lunora/scheduler"},{contextProperty:"storage",key:"storage",moduleSpecifier:"@lunora/storage"},{appMethod:{configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},contextProperty:"vectors",key:"vectors",moduleSpecifier:"@lunora/bindings/vectors"},{contextProperty:"workflows",key:"workflows",moduleSpecifier:"@lunora/workflow"}],gn=at,fn=new Map(gn.flatMap(e=>e.serverCtxField?[[e.key,e.serverCtxField]]:[])),Pr=at.flatMap(e=>"appMethod"in e?[{appMethod:e.appMethod,key:e.key}]:[]),ot=/^(?:"(?:[^"\\]|\\(?:["\\/bfnrt]|u[0-9A-Fa-f]{4}))*"|'[^'\\]*'|-?\d+(?:\.\d+)?|true|false|null)$/u,yn=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),it=e=>e.column!==void 0,bn=(e,n)=>{switch(e){case"bigint":return`if (typeof ${n} !== "bigint") return DEFER;
18
+ readonly r2sql: import("@lunora/bindings/r2sql").R2SqlClient;`,tier:"action"}},{contextProperty:"scheduler",key:"scheduler",moduleSpecifier:"@lunora/scheduler"},{contextProperty:"storage",key:"storage",moduleSpecifier:"@lunora/storage"},{appMethod:{configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},contextProperty:"vectors",key:"vectors",moduleSpecifier:"@lunora/bindings/vectors"},{contextProperty:"workflows",key:"workflows",moduleSpecifier:"@lunora/workflow"}],gn=at,fn=new Map(gn.flatMap(e=>e.serverCtxField?[[e.key,e.serverCtxField]]:[])),Er=at.flatMap(e=>"appMethod"in e?[{appMethod:e.appMethod,key:e.key}]:[]),ot=/^(?:"(?:[^"\\]|\\(?:["\\/bfnrt]|u[0-9A-Fa-f]{4}))*"|'[^'\\]*'|-?\d+(?:\.\d+)?|true|false|null)$/u,bn=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),it=e=>e.column!==void 0,yn=(e,n)=>{switch(e){case"bigint":return`if (typeof ${n} !== "bigint") return DEFER;
19
19
  `;case"boolean":return`if (typeof ${n} !== "boolean") return DEFER;
20
20
  `;case"date":case"number":case"timestamp":return`if (typeof ${n} !== "number" || !Number.isFinite(${n})) return DEFER;
21
21
  `;case"null":return`if (${n} !== null) return DEFER;
22
22
  `;default:return`if (typeof ${n} !== "string") return DEFER;
23
23
  `}},wn=(e,n)=>{const t=e.literalValue?.trim();if(!(t===void 0||!ot.test(t)))return{out:n,pre:`if (${n} !== ${t}) return DEFER;
24
- `}},We=(e,n,t)=>{if(!it(e)&&!(e.hasRefinement||e.sourceText!==void 0)){if(yn.has(e.kind))return e.kind==="any"?{out:n,pre:""}:{out:n,pre:bn(e.kind,n)};switch(e.kind){case"array":return xn(e,n,t);case"literal":return wn(e,n);case"object":return vn(e,n,t);default:return}}},xn=(e,n,t)=>{const{inner:r}=e;if(!r)return;const a=t.next(),o=`__arr${String(a)}`,i=`__i${String(a)}`,s=`__e${String(a)}`,d=We(r,s,t);if(!d)return;const u=`if (!Array.isArray(${n})) return DEFER;
24
+ `}},We=(e,n,t)=>{if(!it(e)&&!(e.hasRefinement||e.sourceText!==void 0)){if(bn.has(e.kind))return e.kind==="any"?{out:n,pre:""}:{out:n,pre:yn(e.kind,n)};switch(e.kind){case"array":return xn(e,n,t);case"literal":return wn(e,n);case"object":return vn(e,n,t);default:return}}},xn=(e,n,t)=>{const{inner:r}=e;if(!r)return;const a=t.next(),o=`__arr${String(a)}`,i=`__i${String(a)}`,s=`__e${String(a)}`,d=We(r,s,t);if(!d)return;const u=`if (!Array.isArray(${n})) return DEFER;
25
25
  const ${o} = new Array(${n}.length);
26
26
  for (let ${i} = 0; ${i} < ${n}.length; ${i}++) {
27
27
  const ${s} = ${n}[${i}];
@@ -46,7 +46,7 @@ ${t.pre}return { ${t.entries} };
46
46
  ${n}
47
47
  `:"";return`export interface Insert_${e.name} {
48
48
  _id?: Id<"${e.name}">;
49
- _creationTime?: number;${t}}`},Ue="schema",Er=e=>{for(const c of e.tables)m(c.name,"table name");const n=e.tables.map(c=>`"${c.name}"`).join(" | ")||"never",t=e.tables.filter(c=>c.extensionKey===void 0).map(c=>`"${c.name}"`).join(" | ")||"never",r=e.tables.map(c=>{const l=Object.entries(c.shape).map(([x,k])=>{const v=_(x);if(k.kind==="optional"){const L=k.inner?N(k.inner):"unknown";return` ${v}?: ${L};`}return` ${v}: ${N(k)};`}).join(`
49
+ _creationTime?: number;${t}}`},Ue="schema",Pr=e=>{for(const c of e.tables)m(c.name,"table name");const n=e.tables.map(c=>`"${c.name}"`).join(" | ")||"never",t=e.tables.filter(c=>c.extensionKey===void 0).map(c=>`"${c.name}"`).join(" | ")||"never",r=e.tables.map(c=>{const l=Object.entries(c.shape).map(([x,k])=>{const v=_(x);if(k.kind==="optional"){const L=k.inner?N(k.inner):"unknown";return` ${v}?: ${L};`}return` ${v}: ${N(k)};`}).join(`
50
50
  `),f=l?`
51
51
  ${l}
52
52
  `:"";return`export interface Doc_${c.name} {
@@ -61,7 +61,7 @@ ${l}
61
61
  `),u=e.vectorIndexes.map(c=>JSON.stringify(c.name)).join(" | ")||"never",h=e.tables.map(c=>An(c)).join(`
62
62
 
63
63
  `),g=e.tables.map(c=>` ${c.name}: Insert_${c.name};`).join(`
64
- `),y=e.tables.map(c=>{const l=c.relations.map(f=>(m(f.table,"relation target table"),` ${_(f.name)}: ${f.kind==="one"?"OneRelation":"ManyRelation"}<"${f.table}">;`)).join(`
64
+ `),b=e.tables.map(c=>{const l=c.relations.map(f=>(m(f.table,"relation target table"),` ${_(f.name)}: ${f.kind==="one"?"OneRelation":"ManyRelation"}<"${f.table}">;`)).join(`
65
65
  `);return l?` ${c.name}: {
66
66
  ${l}
67
67
  };`:` ${c.name}: {};`}).join(`
@@ -154,10 +154,10 @@ export interface ManyRelation<Target extends keyof DataModel> {
154
154
 
155
155
  /** Per-table relation map keyed by accessor name. \`{}\` for tables with none. */
156
156
  export interface Relations {
157
- ${y}
157
+ ${b}
158
158
  }
159
159
 
160
- `,Ue)},Tn=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,ut=/^(?:\.\.?\/)*_generated\//u,pt=/\.[A-Za-z]\w*$/u,On=e=>e.replaceAll(Tn,(n,t)=>{const r=t.replace(ut,"./");return`import("${pt.test(r)?r:`${r}.js`}")`}),Ln=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,Cn=/^(?:\.\.?\/)+/u,In=e=>{const n=[];for(const t of e.split("/"))if(!(t===""||t===".")){if(t===".."&&n.length>0&&n.at(-1)!==".."){n.pop();continue}n.push(t)}return n.join("/")},_n=(e,n)=>e.replaceAll(Ln,(t,r)=>{if(ut.test(r.replace(Cn,"")))return t;const a=n.includes("/")?n.slice(0,n.lastIndexOf("/")):"",o=`../${In(`${a}/${r}`)}`;return`import("${pt.test(o)?o:`${o}.js`}")`}),D=(e,n)=>On(_n(e,n)),Dn=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],Pn=new RegExp(String.raw`import\("@lunora/(?<pkg>${Dn.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),En={flags:new Set(["/web"]),platform:new Set},ht=(e,n)=>n?e.replaceAll(Pn,(t,r,a)=>{const o=En[r];return a&&o&&!o.has(a)?t:`import("lunorash/${r}${a??""}")`}):e,Ke=e=>["Doc","Id"].filter(n=>new RegExp(String.raw`\b${n}<`,"u").test(e)),Mn=e=>e.output===void 0||e.output.kind==="any"?e.returnType:N(e.output),Qe=e=>{const n=new Map;for(const t of e){const r=n.get(t.filePath)??[];r.push(t),n.set(t.filePath,r)}return[...n.entries()].toSorted(([t],[r])=>t.localeCompare(r))},tt=e=>{const n=([t,r])=>{const a=r.toSorted((o,i)=>o.exportName.localeCompare(i.exportName)).map(o=>{const i=D(we(o.args),o.filePath),s=D(Mn(o),o.filePath);return` ${o.exportName}: FunctionReference<"${o.kind}", ${i}, ${s}>;`}).join(`
160
+ `,Ue)},Tn=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,ut=/^(?:\.\.?\/)*_generated\//u,pt=/\.[A-Za-z]\w*$/u,On=e=>e.replaceAll(Tn,(n,t)=>{const r=t.replace(ut,"./");return`import("${pt.test(r)?r:`${r}.js`}")`}),Ln=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,Cn=/^(?:\.\.?\/)+/u,In=e=>{const n=[];for(const t of e.split("/"))if(!(t===""||t===".")){if(t===".."&&n.length>0&&n.at(-1)!==".."){n.pop();continue}n.push(t)}return n.join("/")},_n=(e,n)=>e.replaceAll(Ln,(t,r)=>{if(ut.test(r.replace(Cn,"")))return t;const a=n.includes("/")?n.slice(0,n.lastIndexOf("/")):"",o=`../${In(`${a}/${r}`)}`;return`import("${pt.test(o)?o:`${o}.js`}")`}),D=(e,n)=>On(_n(e,n)),Dn=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],En=new RegExp(String.raw`import\("@lunora/(?<pkg>${Dn.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),Pn={flags:new Set(["/web"]),platform:new Set},ht=(e,n)=>n?e.replaceAll(En,(t,r,a)=>{const o=Pn[r];return a&&o&&!o.has(a)?t:`import("lunorash/${r}${a??""}")`}):e,Ke=e=>["Doc","Id"].filter(n=>new RegExp(String.raw`\b${n}<`,"u").test(e)),Mn=e=>e.output===void 0||e.output.kind==="any"?e.returnType:N(e.output),Qe=e=>{const n=new Map;for(const t of e){const r=n.get(t.filePath)??[];r.push(t),n.set(t.filePath,r)}return[...n.entries()].toSorted(([t],[r])=>t.localeCompare(r))},tt=e=>{const n=([t,r])=>{const a=r.toSorted((o,i)=>o.exportName.localeCompare(i.exportName)).map(o=>{const i=D(we(o.args),o.filePath),s=D(Mn(o),o.filePath);return` ${o.exportName}: FunctionReference<"${o.kind}", ${i}, ${s}>;`}).join(`
161
161
  `);return` ${_(R(t))}: {
162
162
  ${a}
163
163
  };`};return Qe(e).map(t=>n(t)).join(`
@@ -220,9 +220,9 @@ ${r}
220
220
  export const httpStreams: HttpStreamsRef = {
221
221
  ${a}
222
222
  };
223
- `,body:r}},Mr=e=>{const{agents:n=[],functions:t,httpRoutes:r=[],mutators:a=[],useUmbrella:o=!1,workflows:i=[]}=e,s=ne(o),d=[...t.filter($=>$.visibility!=="internal"),...Un(n,t),...Kn(a,t)],u=t.filter($=>$.visibility==="internal"),h=tt(d),g=tt(u),y=Qn(r),c=`${h}
223
+ `,body:r}},Mr=e=>{const{agents:n=[],functions:t,httpRoutes:r=[],mutators:a=[],useUmbrella:o=!1,workflows:i=[]}=e,s=ne(o),d=[...t.filter($=>$.visibility!=="internal"),...Un(n,t),...Kn(a,t)],u=t.filter($=>$.visibility==="internal"),h=tt(d),g=tt(u),b=Qn(r),c=`${h}
224
224
  ${g}
225
- ${y.body}`,l=Ke(c),f=l.length>0?`
225
+ ${b.body}`,l=Ke(c),f=l.length>0?`
226
226
  import type { ${l.join(", ")} } from "./dataModel.js";
227
227
  `:"",x=h?`
228
228
  ${h}
@@ -236,7 +236,7 @@ export const api = anyApi as unknown as ApiTypes;
236
236
  export interface InternalApiTypes {${k}}
237
237
 
238
238
  export const internal = anyApi as unknown as InternalApiTypes;
239
- ${v.block}${y.block}`,M=[...L.includes("FunctionReference<")?["FunctionReference"]:[],...y.block===""?[]:["HttpStreamRef"]],C=M.length>0?`import type { ${M.join(", ")} } from "${s.client}";
239
+ ${v.block}${b.block}`,M=[...L.includes("FunctionReference<")?["FunctionReference"]:[],...b.block===""?[]:["HttpStreamRef"]],C=M.length>0?`import type { ${M.join(", ")} } from "${s.client}";
240
240
  `:"";return ht(`${S}import { anyApi } from "${s.client}";
241
241
  ${C}${v.importLine}${f}
242
242
  ${L}`,o)},Fr=e=>e?`${S}import { createSeedClient as createSeedClientBase } from "@lunora/seed";
@@ -256,9 +256,9 @@ import type { InsertModel } from "./dataModel.js";
256
256
  * const { posts } = await seed.posts((x) => x([10, 20]));
257
257
  */
258
258
  export const createSeedClient = (options?: SeedClientOptions): SeedClient<InsertModel> => createSeedClientBase<InsertModel>(schema, options);
259
- `:"",Br=(e,n,t=!1)=>{if(e.length===0||!n)return"";const r=ne(t),a=d=>d.table===void 0?"Row":`Doc<${JSON.stringify(d.table)}> & Row`,o=e.map(d=>{m(d.exportName,"shape export name");const u=a(d),h=D(we(d.args),d.filePath),g=Object.keys(d.args).length>0,y=g?` args: ${h};`:` args?: ${h};`,c=g?`(args: ${h}) => void`:`(args?: ${h}) => void`,l=`${d.exportName}CollectionOptions`;return`/** Options for the \`${d.exportName}\` shape binding. */
259
+ `:"",Br=(e,n,t=!1)=>{if(e.length===0||!n)return"";const r=ne(t),a=d=>d.table===void 0?"Row":`Doc<${JSON.stringify(d.table)}> & Row`,o=e.map(d=>{m(d.exportName,"shape export name");const u=a(d),h=D(we(d.args),d.filePath),g=Object.keys(d.args).length>0,b=g?` args: ${h};`:` args?: ${h};`,c=g?`(args: ${h}) => void`:`(args?: ${h}) => void`,l=`${d.exportName}CollectionOptions`;return`/** Options for the \`${d.exportName}\` shape binding. */
260
260
  export interface ${qe(l)} {
261
- ${y}
261
+ ${b}
262
262
  /**
263
263
  * Share the optimistic-overlay gate with other collections + mutators on this
264
264
  * shard. Defaults to the shared per-shard registry, which is almost always what
@@ -323,10 +323,10 @@ ${o}
323
323
  `),d=n.map(l=>` ${JSON.stringify(l.id)}: ${a.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredDataMigration,`).join(`
324
324
  `),u=t.map(l=>` "${R(l.filePath)}:${l.exportName}": ${a.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredLunoraFunction,`).join(`
325
325
  `),h=r.map(l=>` "${l.exportName}": ${a.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredShape,`).join(`
326
- `),g=t.map(l=>`${R(l.filePath)}:${l.exportName}`),y=[s,u].filter(l=>l.length>0).join(`
326
+ `),g=t.map(l=>`${R(l.filePath)}:${l.exportName}`),b=[s,u].filter(l=>l.length>0).join(`
327
327
  `),c=e.map(l=>{if(l.lifecycle||Object.keys(l.args).length===0)return;const f=$n(l.args);return f===void 0?void 0:`installCompiledValidatorMap(${a.get(l.filePath)??""}.${l.exportName}.args, ${f});`}).filter(l=>l!==void 0).join(`
328
- `);return{dispatchBody:y.length>0?`
329
- ${y}
328
+ `);return{dispatchBody:b.length>0?`
329
+ ${b}
330
330
  `:"",importBlock:i.length>0?`${i}
331
331
 
332
332
  `:"",installBlock:c,migrationBody:d.length>0?`
@@ -341,10 +341,10 @@ ${o}
341
341
  `);return` ${_(o)}: {
342
342
  ${i}
343
343
  },`}).join(`
344
- `),types:t}},Gn=(e,n=[])=>{const t=new Set;for(const r of e.tables)for(const a of Object.values(r.shape)){const o=re(a);o.kind==="storage"&&typeof o.bucket=="string"&&o.bucket!==""&&t.add(o.bucket)}for(const r of n)r!==""&&r!=="default"&&t.add(r);return["default",...[...t].toSorted((r,a)=>r.localeCompare(a))]},jr=({agents:e=[],containers:n=[],env:t,hasAccessFacade:r=!1,hasAi:a=!1,hasAnalytics:o=!1,hasBrowser:i=!1,hasFlags:s=!1,hasHyperdrive:d=!1,hasImages:u=!1,hasKv:h=!1,hasNotify:g=!1,hasPayments:y=!1,hasPipelines:c=!1,hasR2sql:l=!1,hasX402:f=!1,identity:x,queues:k=[],schema:v,storageRuleBuckets:L=[],useUmbrella:M=!1,workflows:C=[]}={})=>{const $=ne(M),w=Gn(v??{tables:[]},L).map(p=>JSON.stringify(p)).join(" | "),F=a?`import type { LunoraAi } from "@lunora/ai";
344
+ `),types:t}},Gn=(e,n=[])=>{const t=new Set;for(const r of e.tables)for(const a of Object.values(r.shape)){const o=re(a);o.kind==="storage"&&typeof o.bucket=="string"&&o.bucket!==""&&t.add(o.bucket)}for(const r of n)r!==""&&r!=="default"&&t.add(r);return["default",...[...t].toSorted((r,a)=>r.localeCompare(a))]},jr=({agents:e=[],containers:n=[],env:t,hasAccessFacade:r=!1,hasAi:a=!1,hasAnalytics:o=!1,hasBrowser:i=!1,hasFlags:s=!1,hasHyperdrive:d=!1,hasImages:u=!1,hasKv:h=!1,hasNotify:g=!1,hasPayments:b=!1,hasPipelines:c=!1,hasR2sql:l=!1,hasX402:f=!1,identity:x,queues:k=[],schema:v,storageRuleBuckets:L=[],useUmbrella:M=!1,workflows:C=[]}={})=>{const $=ne(M),w=Gn(v??{tables:[]},L).map(p=>JSON.stringify(p)).join(" | "),F=a?`import type { LunoraAi } from "@lunora/ai";
345
345
  `:"",ae=a?`
346
- readonly ai: LunoraAi;`:"",B=y?`import type { LunoraPayment } from "@lunora/payment";
347
- `:"",oe=y?`
346
+ readonly ai: LunoraAi;`:"",B=b?`import type { LunoraPayment } from "@lunora/payment";
347
+ `:"",oe=b?`
348
348
  readonly payments: LunoraPayment;`:"",ie=f?`import type { X402Pay } from "@lunora/x402/pay";
349
349
  `:"",W=f?`
350
350
  readonly x402: X402Pay;`:"",T=n.length>0?`import type { ContainerAccessor } from "@lunora/container";
@@ -374,9 +374,9 @@ ${O}`:""}
374
374
  }
375
375
 
376
376
  /** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
377
- export type Env = CloudflareBindings;`,j=(p,Fe)=>Fe?fn.get(p)?.field??"":"",se=j("kv",h),le=j("analytics",o),Re=j("hyperdrive",d),Ne=j("browser",i),Ae=j("images",u),de=j("pipelines",c),V=j("r2sql",l),E=(v?.vectorIndexes.length??0)>0,H=E?' | "vectors"':"",Z=E?`
378
- readonly vectors: VectorSearch<VectorIndexName>;`:"",ce=E?`
379
- readonly vectors: VectorSearchReader<VectorIndexName>;`:"",J=E?`import type { VectorSearch, VectorSearchReader } from "${$.server}";
377
+ export type Env = CloudflareBindings;`,j=(p,Fe)=>Fe?fn.get(p)?.field??"":"",se=j("kv",h),le=j("analytics",o),Re=j("hyperdrive",d),Ne=j("browser",i),Ae=j("images",u),de=j("pipelines",c),V=j("r2sql",l),P=(v?.vectorIndexes.length??0)>0,H=P?' | "vectors"':"",Z=P?`
378
+ readonly vectors: VectorSearch<VectorIndexName>;`:"",ce=P?`
379
+ readonly vectors: VectorSearchReader<VectorIndexName>;`:"",J=P?`import type { VectorSearch, VectorSearchReader } from "${$.server}";
380
380
  import type { VectorIndexName } from "./dataModel.js";
381
381
  `:"",U=r?`
382
382
  /** Verified Cloudflare Access identity — a synchronous facade over the resolved claims (email / groups / hasGroup / claims). Anonymous when no Access token is present. */
@@ -431,7 +431,7 @@ export type Identity = InferIdentity<typeof lunoraIdentityContract.${x.exportNam
431
431
 
432
432
  /** \`ctx.auth\` narrowed so \`getIdentity()\` resolves the declared {@link Identity} contract instead of the untyped claim bag. */
433
433
  type NarrowedAuth = Omit<QueryCtxBase["auth"], "getIdentity"> & { getIdentity: () => Promise<Identity | null> };`:"",he=x?' | "auth"':"",me=x?`
434
- readonly auth: NarrowedAuth;`:"",Pe=x?", Identity":"",Ee=t?`import type * as lunoraEnvContract from "../env.js";
434
+ readonly auth: NarrowedAuth;`:"",Ee=x?", Identity":"",Pe=t?`import type * as lunoraEnvContract from "../env.js";
435
435
  `:"",Me=t?`
436
436
 
437
437
  /** This app's declared env contract (\`defineEnv\` in \`lunora/env.ts\`) — the validated, coercion-aware shape of \`ctx.env\`. */
@@ -491,7 +491,7 @@ export type {
491
491
  } from "${$.serverDataModel}";
492
492
 
493
493
  import type { DataModel, Doc, GeoIndexNamesByTable, Id as IdOfTable, IndexNamesByTable, Insert, InsertModel, RankIndexNamesByTable, Relations, SearchIndexNamesByTable, TableName } from "./dataModel.js";
494
- ${J}${F}${B}${ie}${T}${ee}${Oe}${Ce}${_e}${Ee}
494
+ ${J}${F}${B}${ie}${T}${ee}${Oe}${Ce}${_e}${Pe}
495
495
  export type { AppTableName, DataModel, Doc, Id, TableName } from "./dataModel.js";
496
496
 
497
497
  /**
@@ -687,7 +687,7 @@ export const defineMutator = defineMutatorBase as unknown as <Args extends Recor
687
687
  * Runtime-identical to \`@lunora/server\`'s \`definePolicy\`; only the types narrow,
688
688
  * so the \`rls()\` chain discovers a policy authored either way the same.
689
689
  */
690
- export const definePolicy = createPolicyDsl<DataModel, Relations${Pe}>();
690
+ export const definePolicy = createPolicyDsl<DataModel, Relations${Ee}>();
691
691
 
692
692
  /**
693
693
  * The validator builder \`v\`, with \`v.id(...)\` constrained to THIS schema's
@@ -704,7 +704,7 @@ export const definePolicy = createPolicyDsl<DataModel, Relations${Pe}>();
704
704
  export const v = vBase as unknown as Omit<typeof vBase, "id"> & {
705
705
  id: <T extends TableName>(table: T) => ColumnValidator<IdOfTable<T>, IdOfTable<T>>;
706
706
  };
707
- `},Xn=e=>{const n={connect:[],disconnect:[]};for(const t of e)t.lifecycle&&n[t.lifecycle].push(`${R(t.filePath)}:${t.exportName}`);return n},qr=e=>{const{agents:n=[],functions:t,migrations:r=[],mutators:a=[],shapes:o=[],useUmbrella:i=!1,usesSandbox:s=!1}=e,d=t.length>0,u=ne(i),{dispatchBody:h,importBlock:g,installBlock:y,migrationBody:c,mutatorPaths:l,shapeBody:f}=Jn(t,r,a,o),x=qn(n,t),k=Wn(s,t),v=[x.lines,k.lines].filter(I=>I.length>0).join(`
707
+ `},Xn=e=>{const n={connect:[],disconnect:[]};for(const t of e)t.lifecycle&&n[t.lifecycle].push(`${R(t.filePath)}:${t.exportName}`);return n},qr=e=>{const{agents:n=[],functions:t,migrations:r=[],mutators:a=[],shapes:o=[],useUmbrella:i=!1,usesSandbox:s=!1}=e,d=t.length>0,u=ne(i),{dispatchBody:h,importBlock:g,installBlock:b,migrationBody:c,mutatorPaths:l,shapeBody:f}=Jn(t,r,a,o),x=qn(n,t),k=Wn(s,t),v=[x.lines,k.lines].filter(I=>I.length>0).join(`
708
708
  `);let L=h;v.length>0&&(L=h.length>0?`${h.trimEnd()}
709
709
  ${v}
710
710
  `:`
@@ -725,14 +725,14 @@ export const LUNORA_SHAPES: Record<string, RegisteredShape> = {${f}};
725
725
  * protocol (\`x-lunora-client-id\`/\`x-lunora-client-seq\` ordering).
726
726
  */
727
727
  export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${l.map(I=>JSON.stringify(I)).join(", ")}]);
728
- `:"",F=y.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${u.values}";
729
- `:"",ae=y.length>0?`
728
+ `:"",F=b.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${u.values}";
729
+ `:"",ae=b.length>0?`
730
730
  /**
731
731
  * AOT-compiled argument validators (Worker-safe, no \`eval\`). Each is installed
732
732
  * onto its function's live \`.args\` object and consulted by the interpreted
733
733
  * parser as a zero-allocation fast path; anything it can't model is deferred.
734
734
  */
735
- ${y}
735
+ ${b}
736
736
  `:"",B=zn(t),oe=B.types?`
737
737
  ${B.types}
738
738
  `:"",ie=B.implementation?`
@@ -752,6 +752,12 @@ ${T}
752
752
  export interface RegisteredLunoraFunction {
753
753
  kind: "action" | "mutation" | "query" | "stream";
754
754
  args: Record<string, unknown>;
755
+ /**
756
+ * Present on a \`"stream"\` declared \`durable\`: its run is persisted and
757
+ * survives the socket that opened it. Absent on every other kind, and on an
758
+ * ephemeral stream.
759
+ */
760
+ durable?: { ttlMs?: number };
755
761
  /**
756
762
  * For \`"action" | "mutation" | "query"\` the handler is awaited and its result returned.
757
763
  * For \`"stream"\` the handler returns an \`AsyncIterable\` synchronously and takes an
@@ -876,12 +882,12 @@ const aiStub: LunoraAi = {
876
882
  const ${e} = {
877
883
  ${o}
878
884
  }${r};
879
- `},P={build:"",configField:"",contextField:"",importLines:[],stub:""},or=e=>e?{build:`
885
+ `},E={build:"",configField:"",contextField:"",importLines:[],stub:""},or=e=>e?{build:`
880
886
  const kvBinding = config.kv?.(env) ?? (env as Record<string, unknown>).KV;
881
887
  const kv: Kv = kvBinding ? createKv({ namespace: kvBinding as KVNamespaceLike }) : kvStub;
882
888
  `,configField:`
883
889
  kv?: (env: Record<string, unknown>) => KVNamespaceLike;`,contextField:`
884
- kv,`,importLines:['import type { Kv, KVNamespaceLike } from "@lunora/bindings/kv";','import { createKv } from "@lunora/bindings/kv";'],stub:A("kvStub: Kv",'throw new Error("ctx.kv: no KV binding found. Add a \\`kv_namespaces\\` binding (env.KV) to wrangler.jsonc, or pass \\`kv\\` to createShardDO().");',["delete","get","getRaw","getWithMetadata","list","put"])}:P,ir=(e,n)=>e?{build:`
890
+ kv,`,importLines:['import type { Kv, KVNamespaceLike } from "@lunora/bindings/kv";','import { createKv } from "@lunora/bindings/kv";'],stub:A("kvStub: Kv",'throw new Error("ctx.kv: no KV binding found. Add a \\`kv_namespaces\\` binding (env.KV) to wrangler.jsonc, or pass \\`kv\\` to createShardDO().");',["delete","get","getRaw","getWithMetadata","list","put"])}:E,ir=(e,n)=>e?{build:`
885
891
  const flags: import("${n}").LunoraFlags = createFlags({
886
892
  hooks: flagsConfig.hooks,
887
893
  logger: flagsConfig.logger,
@@ -890,17 +896,17 @@ ${o}
890
896
  });
891
897
  `,configField:`
892
898
  flags?: (env: Record<string, unknown>) => import("${n}").Provider;`,contextField:`
893
- flags,`,importLines:[`import { createFlags } from "${n}";`,'import flagsConfig from "../flags.js";'],stub:""}:P,sr=e=>e?{build:`
899
+ flags,`,importLines:[`import { createFlags } from "${n}";`,'import flagsConfig from "../flags.js";'],stub:""}:E,sr=e=>e?{build:`
894
900
  const { notify, push } = createNotify(notifyConfig, env, { log, metrics });
895
901
  `,configField:"",contextField:`
896
902
  notify,
897
- push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:P,lr=e=>e?{build:`
903
+ push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:E,lr=e=>e?{build:`
898
904
  const envConfig = lunoraEnvContract.${e.exportName}(env);
899
905
  `,configField:"",contextField:`
900
- env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:P,dr=e=>e?{build:`
906
+ env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:E,dr=e=>e?{build:`
901
907
  const access = accessFacade(identity, userId);
902
908
  `,configField:"",contextField:`
903
- access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:P,cr=(e,n,t)=>{if(!n)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const r=s=>`
909
+ access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:E,cr=(e,n,t)=>{if(!n)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const r=s=>`
904
910
  const env = (this.env ?? {}) as Record<string, unknown>;
905
911
  const flags: import("${t}").LunoraFlags = createFlags({
906
912
  hooks: flagsConfig.hooks,
@@ -969,20 +975,20 @@ const LUNORA_FLAG_KEYS: ReadonlyArray<{ key: string; type: "boolean" | "number"
969
975
  const analytics: AnalyticsClient = analyticsBinding ? createAnalytics(analyticsBinding as AnalyticsEngineDatasetLike) : analyticsStub;
970
976
  `,configField:`
971
977
  analytics?: (env: Record<string, unknown>) => AnalyticsEngineDatasetLike;`,contextField:`
972
- analytics,`,importLines:['import type { AnalyticsClient, AnalyticsEngineDatasetLike } from "@lunora/bindings/analytics";','import { createAnalytics } from "@lunora/bindings/analytics";'],stub:A("analyticsStub: AnalyticsClient",'throw new Error("ctx.analytics: no Analytics Engine binding found. Add an \\`analytics_engine_datasets\\` binding (env.ANALYTICS) to wrangler.jsonc, or pass \\`analytics\\` to createShardDO().");',["track","writeDataPoint"],{sync:["track","writeDataPoint"]})}:P,pr=e=>e?{build:`
978
+ analytics,`,importLines:['import type { AnalyticsClient, AnalyticsEngineDatasetLike } from "@lunora/bindings/analytics";','import { createAnalytics } from "@lunora/bindings/analytics";'],stub:A("analyticsStub: AnalyticsClient",'throw new Error("ctx.analytics: no Analytics Engine binding found. Add an \\`analytics_engine_datasets\\` binding (env.ANALYTICS) to wrangler.jsonc, or pass \\`analytics\\` to createShardDO().");',["track","writeDataPoint"],{sync:["track","writeDataPoint"]})}:E,pr=e=>e?{build:`
973
979
  const imagesBinding = config.images?.(env) ?? (env as Record<string, unknown>).IMAGES;
974
980
  const images: Images = imagesBinding ? createImages({ binding: imagesBinding as ImagesBindingLike }) : imagesStub;
975
981
  `,configField:`
976
982
  images?: (env: Record<string, unknown>) => ImagesBindingLike;`,contextField:`
977
- images,`,importLines:['import type { Images, ImagesBindingLike } from "@lunora/bindings/images";','import { createImages } from "@lunora/bindings/images";'],stub:A("imagesStub: Images",'throw new Error("ctx.images: no Images binding found. Add an \\`images\\` binding (env.IMAGES) to wrangler.jsonc, or pass \\`images\\` to createShardDO().");',["info","transform"])}:P,hr=e=>e?{build:`
983
+ images,`,importLines:['import type { Images, ImagesBindingLike } from "@lunora/bindings/images";','import { createImages } from "@lunora/bindings/images";'],stub:A("imagesStub: Images",'throw new Error("ctx.images: no Images binding found. Add an \\`images\\` binding (env.IMAGES) to wrangler.jsonc, or pass \\`images\\` to createShardDO().");',["info","transform"])}:E,hr=e=>e?{build:`
978
984
  const sql: SqlClient = config.sql ? config.sql(env) : sqlStub;
979
985
  `,configField:`
980
986
  sql?: (env: Record<string, unknown>) => SqlClient;`,contextField:`
981
- sql,`,importLines:['import type { SqlClient } from "@lunora/hyperdrive";'],stub:A("sqlStub: SqlClient",'throw new Error("ctx.sql: provide a \\`sql\\` config thunk that builds a SqlClient from your driver, e.g. \\`sql: (env) => fromPostgresJs(postgres(env.HYPERDRIVE.connectionString))\\`.");',["query"])}:P,mr=e=>e?{build:`
987
+ sql,`,importLines:['import type { SqlClient } from "@lunora/hyperdrive";'],stub:A("sqlStub: SqlClient",'throw new Error("ctx.sql: provide a \\`sql\\` config thunk that builds a SqlClient from your driver, e.g. \\`sql: (env) => fromPostgresJs(postgres(env.HYPERDRIVE.connectionString))\\`.");',["query"])}:E,mr=e=>e?{build:`
982
988
  const browser: Browser = config.browser ? config.browser(env) : browserStub;
983
989
  `,configField:`
984
990
  browser?: (env: Record<string, unknown>) => Browser;`,contextField:`
985
- browser,`,importLines:['import type { Browser } from "@lunora/browser";'],stub:A("browserStub: Browser","throw new Error(\"ctx.browser: provide a \\`browser\\` config thunk, e.g. \\`browser: (env) => createBrowser({ binding: env.BROWSER, launch })\\` with \\`import { launch } from '@cloudflare/playwright'\\`. Session reuse (connect/sessions) additionally needs those two exports passed the same way.\");",["connect","content","launch","pdf","scrape","screenshot","sessions"])}:P,gr=e=>e?{build:`
991
+ browser,`,importLines:['import type { Browser } from "@lunora/browser";'],stub:A("browserStub: Browser","throw new Error(\"ctx.browser: provide a \\`browser\\` config thunk, e.g. \\`browser: (env) => createBrowser({ binding: env.BROWSER, launch })\\` with \\`import { launch } from '@cloudflare/playwright'\\`. Session reuse (connect/sessions) additionally needs those two exports passed the same way.\");",["connect","content","launch","pdf","scrape","screenshot","sessions"])}:E,gr=e=>e?{build:`
986
992
  const r2sqlEnv = env as Record<string, unknown>;
987
993
  const r2sqlAccountId = (r2sqlEnv.R2_SQL_ACCOUNT_ID ?? r2sqlEnv.CLOUDFLARE_ACCOUNT_ID) as string | undefined;
988
994
  const r2sqlToken = r2sqlEnv.R2_SQL_TOKEN as string | undefined;
@@ -993,11 +999,11 @@ const LUNORA_FLAG_KEYS: ReadonlyArray<{ key: string; type: "boolean" | "number"
993
999
  ? createR2Sql({ accountId: r2sqlAccountId, apiToken: r2sqlToken, bucket: r2sqlBucket })
994
1000
  : r2sqlStub;
995
1001
  `,configField:`
996
- r2sql?: (env: Record<string, unknown>) => R2SqlClient;`,contextField:"",importLines:['import type { R2SqlClient } from "@lunora/bindings/r2sql";','import { createR2Sql } from "@lunora/bindings/r2sql";'],stub:A("r2sqlStub: R2SqlClient",'throw new Error("ctx.r2sql: no R2 SQL credentials found. Set \\`R2_SQL_TOKEN\\`, \\`R2_SQL_ACCOUNT_ID\\` (or \\`CLOUDFLARE_ACCOUNT_ID\\`), and \\`R2_SQL_BUCKET\\` in your env/.dev.vars, or pass an \\`r2sql\\` config thunk to createShardDO().");',["describe","explain","from","query","showDatabases","showTables"],{sync:["from"]})}:P,fr=e=>e?{build:`
1002
+ r2sql?: (env: Record<string, unknown>) => R2SqlClient;`,contextField:"",importLines:['import type { R2SqlClient } from "@lunora/bindings/r2sql";','import { createR2Sql } from "@lunora/bindings/r2sql";'],stub:A("r2sqlStub: R2SqlClient",'throw new Error("ctx.r2sql: no R2 SQL credentials found. Set \\`R2_SQL_TOKEN\\`, \\`R2_SQL_ACCOUNT_ID\\` (or \\`CLOUDFLARE_ACCOUNT_ID\\`), and \\`R2_SQL_BUCKET\\` in your env/.dev.vars, or pass an \\`r2sql\\` config thunk to createShardDO().");',["describe","explain","from","query","showDatabases","showTables"],{sync:["from"]})}:E,fr=e=>e?{build:`
997
1003
  const pipelinesBinding = config.pipelines?.(env) ?? (env as Record<string, unknown>).PIPELINES;
998
1004
  const pipelines: PipelineClient = pipelinesBinding ? createPipelines({ binding: pipelinesBinding as PipelineBindingLike }) : pipelinesStub;
999
1005
  `,configField:`
1000
- pipelines?: (env: Record<string, unknown>) => PipelineBindingLike;`,contextField:"",importLines:['import type { PipelineBindingLike, PipelineClient } from "@lunora/bindings/pipelines";','import { createPipelines } from "@lunora/bindings/pipelines";'],stub:A("pipelinesStub: PipelineClient",'throw new Error("ctx.pipelines: no Pipelines binding found. Add a \\`pipelines\\` binding (env.PIPELINES) to wrangler.jsonc, or pass \\`pipelines\\` to createShardDO().");',["send"])}:P,Wr=(e,n)=>{if(e.length===0)return"";const t=n?`, ${JSON.stringify(n)}`:"",r=e.map(o=>(m(o.exportName,`container export "${o.exportName}"`),m(o.className,`container class "${o.className}"`),`/** Container DO for the \`${o.exportName}\` definition (binding \`${o.bindingName}\`). */
1006
+ pipelines?: (env: Record<string, unknown>) => PipelineBindingLike;`,contextField:"",importLines:['import type { PipelineBindingLike, PipelineClient } from "@lunora/bindings/pipelines";','import { createPipelines } from "@lunora/bindings/pipelines";'],stub:A("pipelinesStub: PipelineClient",'throw new Error("ctx.pipelines: no Pipelines binding found. Add a \\`pipelines\\` binding (env.PIPELINES) to wrangler.jsonc, or pass \\`pipelines\\` to createShardDO().");',["send"])}:E,Wr=(e,n)=>{if(e.length===0)return"";const t=n?`, ${JSON.stringify(n)}`:"",r=e.map(o=>(m(o.exportName,`container export "${o.exportName}"`),m(o.className,`container class "${o.className}"`),`/** Container DO for the \`${o.exportName}\` definition (binding \`${o.bindingName}\`). */
1001
1007
  export class ${o.className} extends LunoraContainer {
1002
1008
  public constructor(ctx: ConstructorParameters<typeof LunoraContainer>[0], env: Record<string, unknown>) {
1003
1009
  super(ctx, env, ${o.exportName}, "${o.exportName}"${t});
@@ -1022,7 +1028,7 @@ import { ${a} } from "../containers.js";
1022
1028
 
1023
1029
  export { ContainerProxy } from "@lunora/container/do";
1024
1030
 
1025
- ${r}`},yr=(e,n)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const r of e)m(r.exportName,`container export "${r.exportName}"`),m(r.bindingName,`container binding "${r.bindingName}"`);const t=e.map(r=>{const a=r.maxInstances===void 0?"":`, maxInstances: ${String(r.maxInstances)}`;return` { binding: "${r.bindingName}", exportName: "${r.exportName}"${a} },`}).join(`
1031
+ ${r}`},br=(e,n)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const r of e)m(r.exportName,`container export "${r.exportName}"`),m(r.bindingName,`container binding "${r.bindingName}"`);const t=e.map(r=>{const a=r.maxInstances===void 0?"":`, maxInstances: ${String(r.maxInstances)}`;return` { binding: "${r.bindingName}", exportName: "${r.exportName}"${a} },`}).join(`
1026
1032
  `);return{build:`
1027
1033
  const containers = createContainerContext(env, LUNORA_CONTAINERS, ${n?JSON.stringify(n):"undefined"}, this.getCurrentTraceparent());
1028
1034
  `,contextField:`
@@ -1102,7 +1108,7 @@ import { ${t} } from "../queues.js";
1102
1108
  export const LUNORA_QUEUE_REGISTRY: QueueRegistry = {
1103
1109
  ${r}
1104
1110
  };
1105
- `},br=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const t of e)m(t.exportName,`workflow export "${t.exportName}"`),m(t.bindingName,`workflow binding "${t.bindingName}"`);const n=e.map(t=>` { binding: "${t.bindingName}", exportName: "${t.exportName}" },`).join(`
1111
+ `},yr=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const t of e)m(t.exportName,`workflow export "${t.exportName}"`),m(t.bindingName,`workflow binding "${t.bindingName}"`);const n=e.map(t=>` { binding: "${t.bindingName}", exportName: "${t.exportName}" },`).join(`
1106
1112
  `);return{build:`
1107
1113
  const workflows = createWorkflowContext(env, LUNORA_WORKFLOWS);
1108
1114
  `,contextField:`
@@ -1147,10 +1153,10 @@ const ${e}: ${n} = ${JSON.stringify(r,void 0,4)};
1147
1153
  ? lazyX402Pay(config.x402(env), { getSecret: (name: string) => secrets.get(name) })
1148
1154
  : x402Stub;
1149
1155
  `,configField:`
1150
- x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:A("x402Stub: X402Pay",'throw new Error("ctx.x402: no pay rail configured. Pass \\`x402\\` to createShardDO().");',["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}:{build:"",configField:"",imports:[],stub:""},Rr=(e,n,t,r)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult",...t?["QueuesResult"]:[],"RunShardApplyCdcArgs","RunShardExportArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike","TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SystemReaderStorageLike","TelemetrySink",...n?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],Vr=({advisories:e=[],advisorProcedures:n=[],agents:t=[],containers:r=[],env:a,flagKeys:o=[],hasAccessFacade:i=!1,hasAi:s=!1,hasAnalytics:d=!1,hasBrowser:u=!1,hasFlags:h=!1,hasHyperdrive:g=!1,hasImages:y=!1,hasKv:c=!1,hasNotify:l=!1,hasPayments:f=!1,hasPipelines:x=!1,hasR2sql:k=!1,hasX402:v=!1,maskMetadata:L,mutators:M=[],queues:C=[],rlsMetadata:$,schema:w,schemaSnapshot:F,shapes:ae=[],storageRules:B,studioFeatures:oe,useUmbrella:ie=!1,workflows:W=[]})=>{const T=ne(ie),Y=M.length>0,O=ae.length>0,I=F===void 0?"":hn(F),j=F===void 0?"":`
1156
+ x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:A("x402Stub: X402Pay",'throw new Error("ctx.x402: no pay rail configured. Pass \\`x402\\` to createShardDO().");',["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}:{build:"",configField:"",imports:[],stub:""},Rr=(e,n,t,r)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult",...t?["QueuesResult"]:[],"RunShardApplyCdcArgs","RunShardExportArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike","TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SystemReaderStorageLike","TelemetrySink",...n?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],Vr=({advisories:e=[],advisorProcedures:n=[],agents:t=[],containers:r=[],env:a,flagKeys:o=[],hasAccessFacade:i=!1,hasAi:s=!1,hasAnalytics:d=!1,hasBrowser:u=!1,hasFlags:h=!1,hasHyperdrive:g=!1,hasImages:b=!1,hasKv:c=!1,hasNotify:l=!1,hasPayments:f=!1,hasPipelines:x=!1,hasR2sql:k=!1,hasX402:v=!1,maskMetadata:L,mutators:M=[],queues:C=[],rlsMetadata:$,schema:w,schemaSnapshot:F,shapes:ae=[],storageRules:B,studioFeatures:oe,useUmbrella:ie=!1,workflows:W=[]})=>{const T=ne(ie),Y=M.length>0,O=ae.length>0,I=F===void 0?"":hn(F),j=F===void 0?"":`
1151
1157
  /** Structural schema snapshot + its content hash, recorded in the shard's \`__lunora_schema_history\` ledger on cold start so the studio can show a schema-version timeline and diff any two versions. */
1152
1158
  const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(mn(F))}, json: ${JSON.stringify(I)} };
1153
- `,se=F===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:le,configField:Re,contextField:Ne,stub:Ae}=ar(s),de=dr(i),V=or(c),E=ir(h,T.flags),H=cr(o,h,T.flags),Z=sr(l),ce=lr(a),J=ur(d),U=pr(y),K=hr(g),Q=mr(u),q=gr(k),ee=fr(x),{build:Te,contextField:xe,importLines:ke,specs:ue}=wr(C),{build:Oe,contextField:Le,importLines:ve,specs:pe}=yr(r,w.jurisdiction),{build:Ce,contextField:Ie,importLines:$e,specs:_e}=br(W),{build:De,contextField:he,importLines:me,specs:Pe}=xr(t),{build:Ee,configField:Me,contextField:ge,imports:fe,stub:p}=$r(f),{build:Fe,configField:yt,imports:bt,stub:wt}=Sr(v),xt=e,kt=n,vt=$??{policies:[],roles:[]},$t=L??{columns:[]},St=B??{rules:[]},Rt=oe??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:Nt,override:At}=kr(W),{constant:Tt,override:Ot}=vr(C),z=w.vectorIndexes.length>0,He=new Set(w.tables.filter(b=>typeof b.shardMode=="object"&&b.shardMode.kind==="shardBy").map(b=>b.name)),Se=w.vectorIndexes.some(b=>He.has(b.table)),ye=w.tables.some(b=>b.shardMode==="global"),Be=w.tables.some(b=>b.shardMode==="global"&&b.globalBackend==="hyperdrive"),Je=w.tables.some(b=>b.shardMode==="global"&&b.globalBackend!=="hyperdrive"),G=w.tables.some(b=>b.externalSource!==void 0);if(Je&&Be)throw new te("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const je=w.tables.length>0,Lt=Yn(w),Ct=er(w),It=nr(w),_t=Zn(w),ze=tr(w),Ge=Rr(z,W.length>0,C.length>0,h);O&&Ge.push("WhereInput");const Xe=rr(ye),Dt=O?`
1159
+ `,se=F===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:le,configField:Re,contextField:Ne,stub:Ae}=ar(s),de=dr(i),V=or(c),P=ir(h,T.flags),H=cr(o,h,T.flags),Z=sr(l),ce=lr(a),J=ur(d),U=pr(b),K=hr(g),Q=mr(u),q=gr(k),ee=fr(x),{build:Te,contextField:xe,importLines:ke,specs:ue}=wr(C),{build:Oe,contextField:Le,importLines:ve,specs:pe}=br(r,w.jurisdiction),{build:Ce,contextField:Ie,importLines:$e,specs:_e}=yr(W),{build:De,contextField:he,importLines:me,specs:Ee}=xr(t),{build:Pe,configField:Me,contextField:ge,imports:fe,stub:p}=$r(f),{build:Fe,configField:bt,imports:yt,stub:wt}=Sr(v),xt=e,kt=n,vt=$??{policies:[],roles:[]},$t=L??{columns:[]},St=B??{rules:[]},Rt=oe??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:Nt,override:At}=kr(W),{constant:Tt,override:Ot}=vr(C),z=w.vectorIndexes.length>0,He=new Set(w.tables.filter(y=>typeof y.shardMode=="object"&&y.shardMode.kind==="shardBy").map(y=>y.name)),Se=w.vectorIndexes.some(y=>He.has(y.table)),be=w.tables.some(y=>y.shardMode==="global"),Be=w.tables.some(y=>y.shardMode==="global"&&y.globalBackend==="hyperdrive"),Je=w.tables.some(y=>y.shardMode==="global"&&y.globalBackend!=="hyperdrive"),G=w.tables.some(y=>y.externalSource!==void 0);if(Je&&Be)throw new te("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const je=w.tables.length>0,Lt=Yn(w),Ct=er(w),It=nr(w),_t=Zn(w),ze=tr(w),Ge=Rr(z,W.length>0,C.length>0,h);O&&Ge.push("WhereInput");const Xe=rr(be),Dt=O?`
1154
1160
  protected override resolveShape(name: string, args: Record<string, unknown>, identity?: { identity?: Record<string, unknown>; userId?: string }): { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined {
1155
1161
  const shape = LUNORA_SHAPES[name];
1156
1162
 
@@ -1203,17 +1209,17 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
1203
1209
 
1204
1210
  return { columns: shape.columns, effectiveWhere, global: isGlobal, table: shape.table };
1205
1211
  }
1206
- `:"",Pt=Y?`
1212
+ `:"",Et=Y?`
1207
1213
  protected override isCustomMutator(functionPath: string): boolean {
1208
1214
  return LUNORA_MUTATOR_PATHS.has(functionPath);
1209
1215
  }
1210
- `:"",Et=O?"\n/** Per-table RLS read policies (hoisted from `.use(rls(...))` chains) the shape resolver AND-merges into each `defineShape` predicate so partial replication honours read policies. */\nconst LUNORA_RLS_READ_REGISTRY = buildRlsReadRegistry(Object.values(LUNORA_FUNCTIONS));\n":"",Mt=O?"assertShapeShardable, ":"",be=[`import type { ${Ge.join(", ")} } from "${T.do}";`,`import { applyCdcChanges, buildReprojectionMigration, ${Mt}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${G?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}${Se?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${Xe.importFragment}ShardDO as ShardDOBase } from "${T.do}";`,...G?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${T.do}";`]:[],O?`import { asBucketStorage, buildRlsReadRegistry, composeShapeReadWhere, createSecrets, LunoraError } from "${T.server}";`:`import { asBucketStorage, createSecrets, LunoraError } from "${T.server}";`];je&&be.push(`import { bindOrm, bindTableFacade } from "${T.server}";`),z&&be.push('import type { SchemaLike as VectorSchemaLike, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectors, createVectorSyncHook } from "@lunora/bindings/vectors";'),s&&be.push('import type { AiBindingLike, LunoraAi } from "@lunora/ai";','import { createAi } from "@lunora/ai";'),be.push(...de.importLines,...V.importLines,...E.importLines,...Z.importLines,...ce.importLines,...J.importLines,...U.importLines,...K.importLines,...Q.importLines,...q.importLines,...ee.importLines,...ve,...$e,...ke,...me,...fe,...bt,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...Y?["LUNORA_MUTATOR_PATHS"]:[],...O?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const Ft=z?`
1216
+ `:"",Pt=O?"\n/** Per-table RLS read policies (hoisted from `.use(rls(...))` chains) the shape resolver AND-merges into each `defineShape` predicate so partial replication honours read policies. */\nconst LUNORA_RLS_READ_REGISTRY = buildRlsReadRegistry(Object.values(LUNORA_FUNCTIONS));\n":"",Mt=O?"assertShapeShardable, ":"",ye=[`import type { ${Ge.join(", ")} } from "${T.do}";`,`import { applyCdcChanges, buildReprojectionMigration, ${Mt}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${G?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}${Se?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${Xe.importFragment}ShardDO as ShardDOBase } from "${T.do}";`,...G?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${T.do}";`]:[],O?`import { asBucketStorage, buildRlsReadRegistry, composeShapeReadWhere, createSecrets, LunoraError } from "${T.server}";`:`import { asBucketStorage, createSecrets, LunoraError } from "${T.server}";`];je&&ye.push(`import { bindOrm, bindTableFacade } from "${T.server}";`),z&&ye.push('import type { SchemaLike as VectorSchemaLike, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectors, createVectorSyncHook } from "@lunora/bindings/vectors";'),s&&ye.push('import type { AiBindingLike, LunoraAi } from "@lunora/ai";','import { createAi } from "@lunora/ai";'),ye.push(...de.importLines,...V.importLines,...P.importLines,...Z.importLines,...ce.importLines,...J.importLines,...U.importLines,...K.importLines,...Q.importLines,...q.importLines,...ee.importLines,...ve,...$e,...ke,...me,...fe,...yt,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...Y?["LUNORA_MUTATOR_PATHS"]:[],...O?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const Ft=z?`
1211
1217
  vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",Bt=Je?`
1212
1218
  d1?: (env: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",jt=Be?`
1213
1219
  hyperdriveGlobal?: (env: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",qt=G?`
1214
- sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",Wt='throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");',Ut='throw new Error("ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().");',Kt='throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().");',Qt='throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO().");',Vt=ye?A("globalDbStub: DatabaseWriterLike",Wt,["aggregate","count","delete","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",Ht=z?A("vectorsStub: VectorSearchLike",Ut,["deleteByIds","getByIds","query","upsert","upsertNow"]):"",Jt=Se?`
1220
+ sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",Wt='throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");',Ut='throw new Error("ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().");',Kt='throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().");',Qt='throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO().");',Vt=be?A("globalDbStub: DatabaseWriterLike",Wt,["aggregate","count","delete","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",Ht=z?A("vectorsStub: VectorSearchLike",Ut,["deleteByIds","getByIds","query","upsert","upsertNow"]):"",Jt=Se?`
1215
1221
  const vectorShardKey = this.currentShardKey();
1216
- `:"",zt=Se?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",Gt=Se?`, { namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, shardedIndexNames: [${w.vectorIndexes.filter(b=>He.has(b.table)).map(b=>JSON.stringify(b.name)).join(", ")}] }`:"",Xt=z?`
1222
+ `:"",zt=Se?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",Gt=Se?`, { namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, shardedIndexNames: [${w.vectorIndexes.filter(y=>He.has(y.table)).map(y=>JSON.stringify(y.name)).join(", ")}] }`:"",Xt=z?`
1217
1223
  let vectors: VectorSearchLike;
1218
1224
  let onWrite: WriteHook | undefined;
1219
1225
 
@@ -1241,7 +1247,7 @@ ${Jt}
1241
1247
  scheduler,
1242
1248
  schema: schema as unknown as SchemaLike,
1243
1249
  sql: this.sql as SqlExec,
1244
- storage,${ye?`
1250
+ storage,${be?`
1245
1251
  globalDb,`:""}
1246
1252
  }`,X=` const env = (this.env ?? {}) as Record<string, unknown>;
1247
1253
  const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
@@ -1255,8 +1261,8 @@ ${Jt}
1255
1261
  sql: this.sql as SqlExec,
1256
1262
  });`,Zt=z?`
1257
1263
  vectors,`:"",en=je?`
1258
- orm: bindOrm(facade),`:"",Ye=Be?"config.hyperdriveGlobal":"config.d1",tn=ye?` const globalDb: DatabaseWriterLike = ${Ye}?.(env, { identity, userId }) ?? globalDbStub;
1259
- `:"",nn=O&&ye?`
1264
+ orm: bindOrm(facade),`:"",Ye=Be?"config.hyperdriveGlobal":"config.d1",tn=be?` const globalDb: DatabaseWriterLike = ${Ye}?.(env, { identity, userId }) ?? globalDbStub;
1265
+ `:"",nn=O&&be?`
1260
1266
  protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: { identity?: Record<string, unknown>; userId?: string }): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
1261
1267
  const env = this.env as Record<string, unknown>;
1262
1268
  const globalDb: DatabaseWriterLike = ${Ye}?.(env, identity) ?? globalDbStub;
@@ -1444,20 +1450,20 @@ ${G?`
1444
1450
  `:""} }
1445
1451
  `:"",sn=je?`
1446
1452
  const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
1447
- ${w.tables.map(b=>` facade[${JSON.stringify(b.name)}] = bindTableFacade(db, ${JSON.stringify(b.name)});`).join(`
1453
+ ${w.tables.map(y=>` facade[${JSON.stringify(y.name)}] = bindTableFacade(db, ${JSON.stringify(y.name)});`).join(`
1448
1454
  `)}
1449
- `:"",ln=`${de.build}${V.build}${E.build}${J.build}${ce.build}
1455
+ `:"",ln=`${de.build}${V.build}${P.build}${J.build}${ce.build}
1450
1456
  const secrets = createSecrets(env);
1451
- `,dn=`${de.contextField}${V.contextField}${E.contextField}${Z.contextField}${J.contextField}${ce.contextField}
1452
- secrets,`,cn=Z.build,et=y||g||u||k||x||v,un=et?`
1457
+ `,dn=`${de.contextField}${V.contextField}${P.contextField}${Z.contextField}${J.contextField}${ce.contextField}
1458
+ secrets,`,cn=Z.build,et=b||g||u||k||x||v,un=et?`
1453
1459
  // ActionCtx-only helpers (external, non-deterministic I/O): constructed
1454
1460
  // and attached only for an \`action\` so query/mutation ctx never carry them.
1455
1461
  if (isAction) {
1456
- ${U.build}${K.build}${Q.build}${q.build}${ee.build}${Fe}${[...y?[" ctx.images = images;"]:[],...g?[" ctx.sql = sql;"]:[],...u?[" ctx.browser = browser;"]:[],...k?[" ctx.r2sql = r2sql;"]:[],...x?[" ctx.pipelines = pipelines;"]:[],...v?[" ctx.x402 = x402;"]:[]].join(`
1462
+ ${U.build}${K.build}${Q.build}${q.build}${ee.build}${Fe}${[...b?[" ctx.images = images;"]:[],...g?[" ctx.sql = sql;"]:[],...u?[" ctx.browser = browser;"]:[],...k?[" ctx.r2sql = r2sql;"]:[],...x?[" ctx.pipelines = pipelines;"]:[],...v?[" ctx.x402 = x402;"]:[]].join(`
1457
1463
  `)}
1458
1464
  }
1459
1465
  `:"",pn=et?` const isAction = LUNORA_FUNCTIONS[options.functionPath ?? ""]?.kind === "action";
1460
- `:"";return`${S}${be.join(`
1466
+ `:"";return`${S}${ye.join(`
1461
1467
  `)}
1462
1468
 
1463
1469
  type FunctionKind = "action" | "mutation" | "query";
@@ -1498,16 +1504,16 @@ const LUNORA_STORAGE_RULES: StorageRulesResult = ${JSON.stringify(St,void 0,4)};
1498
1504
 
1499
1505
  /** Which optional package-backed features this app wires up (discovered from imports / \`ctx.*\` reads / schema signals) served via \`__lunora_admin__:studioFeatures\` so the studio hides nav pages whose package isn't enabled. */
1500
1506
  const LUNORA_STUDIO_FEATURES: StudioFeaturesResult = ${JSON.stringify(Rt,void 0,4)};
1501
- ${j}${H.constant}${Et}${Nt}${Tt}${pe}${_e}${ue}${Pe}
1507
+ ${j}${H.constant}${Pt}${Nt}${Tt}${pe}${_e}${ue}${Ee}
1502
1508
  export interface ShardDOConfig {
1503
1509
  /** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
1504
1510
  cdc?: boolean;
1505
1511
  /** Optional telemetry sink. When supplied, each \`ctx.log.*\` call is forwarded to \`sink.onLog\`. Pass the SAME sink you give \`createWorker({ observability })\` (which drives \`onRpc\`) to route both RPC and log events. */
1506
1512
  observability?: (env: Record<string, unknown>) => TelemetrySink | undefined;
1507
1513
  scheduler?: (env: Record<string, unknown>) => unknown;
1508
- storage?: (env: Record<string, unknown>) => unknown;${Ft}${Re}${V.configField}${E.configField}${J.configField}${U.configField}${K.configField}${Q.configField}${q.configField}${ee.configField}${Me}${yt}${Bt}${jt}${qt}
1514
+ storage?: (env: Record<string, unknown>) => unknown;${Ft}${Re}${V.configField}${P.configField}${J.configField}${U.configField}${K.configField}${Q.configField}${q.configField}${ee.configField}${Me}${bt}${Bt}${jt}${qt}
1509
1515
  }
1510
- ${A("schedulerStub",Kt,["cancel","runAfter","runAt"])}${A("storageStub",Qt,["delete","download","getMetadata","getSignedUrl","getUrl","list","upload"],{sync:["getUrl"]})}${Vt}${rn}${Ht}${Ae}${V.stub}${E.stub}${J.stub}${U.stub}${K.stub}${Q.stub}${q.stub}${ee.stub}${p}${wt}
1516
+ ${A("schedulerStub",Kt,["cancel","runAfter","runAt"])}${A("storageStub",Qt,["delete","download","getMetadata","getSignedUrl","getUrl","list","upload"],{sync:["getUrl"]})}${Vt}${rn}${Ht}${Ae}${V.stub}${P.stub}${J.stub}${U.stub}${K.stub}${Q.stub}${q.stub}${ee.stub}${p}${wt}
1511
1517
  // Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
1512
1518
  // referencing call fails loudly with a clear error instead of overflowing the
1513
1519
  // stack. Tracked across the awaited handler chain (one DO invocation is
@@ -1615,7 +1621,7 @@ ${Xe.override}
1615
1621
  return { ranges: footprint.ranges(), result, tables: footprint.tables };
1616
1622
  }
1617
1623
 
1618
- protected override executeStream(functionPath: string, args: Record<string, unknown>): null | { iterator: (signal: AbortSignal) => AsyncIterable<unknown> } {
1624
+ protected override executeStream(functionPath: string, args: Record<string, unknown>): null | { durable?: { ttlMs?: number }; iterator: (signal: AbortSignal) => AsyncIterable<unknown> } {
1619
1625
  const registered = LUNORA_FUNCTIONS[functionPath];
1620
1626
 
1621
1627
  if (!registered || registered.kind !== "stream" || registered.visibility === "internal") {
@@ -1625,10 +1631,11 @@ ${Xe.override}
1625
1631
  this.ensureMigrated();
1626
1632
 
1627
1633
  return {
1634
+ ...(registered.durable ? { durable: registered.durable as { ttlMs?: number } } : {}),
1628
1635
  iterator: (signal) => (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath }), args, signal),
1629
1636
  };
1630
1637
  }
1631
- ${Pt}${Dt}${nn}${an}
1638
+ ${Et}${Dt}${nn}${an}
1632
1639
  protected override lifecycleHookPaths(event: "connect" | "disconnect"): readonly string[] {
1633
1640
  return LUNORA_LIFECYCLE_HOOKS[event];
1634
1641
  }
@@ -1934,7 +1941,7 @@ ${tn} // \`ctx.db\`, wrapped in automatic instrumentation: by default
1934
1941
  // handler making hundreds of queries stays readable. See
1935
1942
  // \`instrumentDatabase\` for the \`"spans"\` / \`"off"\` levels.
1936
1943
  const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${Yt}), logFunctionPath, traceAnchor, observability);
1937
- ${sn}${Ee}
1944
+ ${sn}${Pe}
1938
1945
 
1939
1946
  // \`ctx.trace\` / \`ctx.metrics\`: spans and measurements to the same sink.
1940
1947
  // The trace anchor is threaded explicitly for the same reason \`identity\`
@@ -1986,7 +1993,7 @@ ${e.indexes.map(a=>Ar(a)).join(`
1986
1993
  })`:"";return`export const ${e.name} = sqliteTable("${e.name}", {
1987
1994
  ${t}
1988
1995
  }${r});`},Or=e=>e.typeAnnotation?.includes('Id<"')??!1,Lr=(e,n)=>{const t=new Set(["integer","sqliteTable","text"]),r=new Set;let a=!1,o=!1;for(const i of e){for(const s of Object.values(i.shape)){const d=Ve(s);t.add(d.builder),o=o||Or(d),a=a||ft(s,n)!==void 0}for(const s of i.indexes)r.add(s.unique?"uniqueIndex":"index")}return{columns:[...t].toSorted((i,s)=>i.localeCompare(s)),indexes:[...r].toSorted((i,s)=>i.localeCompare(s)),needsAnyColumn:a,needsId:o}},nt=(e,n=!1)=>{if(e.length===0)return`${S}export {};
1989
- `;const t=ne(n),r=new Set(e.map(g=>g.name)),{columns:a,indexes:o,needsAnyColumn:i,needsId:s}=Lr(e,r),d=[...o,...a].toSorted((g,y)=>g.localeCompare(y)),u=e.map(g=>Tr(g,r)).join(`
1996
+ `;const t=ne(n),r=new Set(e.map(g=>g.name)),{columns:a,indexes:o,needsAnyColumn:i,needsId:s}=Lr(e,r),d=[...o,...a].toSorted((g,b)=>g.localeCompare(b)),u=e.map(g=>Tr(g,r)).join(`
1990
1997
 
1991
1998
  `),h=[i?`import type { AnySQLiteColumn } from "${t.serverDrizzle}";
1992
1999
  `:"",s?`import type { Id } from "./dataModel.js";
@@ -2051,4 +2058,4 @@ export interface LunoraVectorIndex {
2051
2058
  * \`createWorker({ vectorIntrospector })\` to back the studio's vector browser.
2052
2059
  */
2053
2060
  export const LUNORA_VECTOR_INDEXES: ReadonlyArray<LunoraVectorIndex> = [${t}];
2054
- `},Gr=e=>[...new Set(e.map(n=>n.cron))];export{Vr as $,Br as B,Hr as C,zr as E,Gr as F,Jr as L,Fr as M,Mr as P,jr as Q,Er as R,S,qr as V,Zn as a,Dn as d,Qr as f,Kr as h,Ur as m,Pr as n,Wr as p,gn as r};
2061
+ `},Gr=e=>[...new Set(e.map(n=>n.cron))];export{Vr as $,Br as B,Hr as C,zr as E,Gr as F,Jr as L,Mr as M,Fr as P,jr as Q,Pr as R,S,qr as V,Zn as a,Dn as d,Qr as f,Kr as h,Ur as m,Er as n,Wr as p,gn as r};
@@ -1,4 +1,4 @@
1
- import{n as S,S as D}from"./emit-B8FxCABN.mjs";const E=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,v=S.map(({appMethod:e,key:t})=>[E(t),e.method,e.configKey,e.doc]),m=e=>v.some(([t])=>e[t]),A=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],R=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],x=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],O=e=>e?['import notifyConfig from "../notify.js";']:[],k=e=>(e.emailAgents?.length??0)>0,C=e=>k(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],L=e=>k(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],T=e=>{const{hasAccess:t,hasAuth:a,hasFramework:r,hasGlobal:n,hasHyperdriveGlobal:o,hasKv:c,hasQueue:s,hasScheduler:d,hasStorage:u,hasWorkflow:h,useUmbrella:l,wantsOpenApi:p,wantsOpenRpc:b}=e,i=l?"lunorash/runtime":"@lunora/runtime",g=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions"];n&&g.push("GlobalIntrospector","AdminTableResolver"),r&&g.push("FrameworkHostHandler");const f=[...n||o?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...r?["withFrameworkWorker"]:[]].join(", ");return[...a?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...R(t,a),...n?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { createD1CtxDb, facetGlobalColumn, importGlobalRows, listGlobalTables, readGlobalTablePage } from "@lunora/d1";']:[],...o?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...x(c),...d?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...u?['import type { R2BucketLike, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...h?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...C(e),`import type { ${[...g].toSorted((w,y)=>w.localeCompare(y)).join(", ")} } from "${i}";`,`import { ${f} } from "${i}";`,"",...A(e.identity),...L(e),...n||o?['import schema from "../schema.js";']:[],...O(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...s?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...p?['import { openApiSpec } from "./openapi.js";']:[],...b?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";']},j=e=>[...e.hasStorage?[`/** \`.storage(...)\` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs \`ctx.storage\` AND the studio file browser. */
1
+ import{n as S,S as D}from"./emit-BbLyaTLJ.mjs";const E=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,v=S.map(({appMethod:e,key:t})=>[E(t),e.method,e.configKey,e.doc]),m=e=>v.some(([t])=>e[t]),A=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],R=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],x=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],O=e=>e?['import notifyConfig from "../notify.js";']:[],k=e=>(e.emailAgents?.length??0)>0,C=e=>k(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],L=e=>k(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],T=e=>{const{hasAccess:t,hasAuth:a,hasFramework:r,hasGlobal:n,hasHyperdriveGlobal:o,hasKv:c,hasQueue:s,hasScheduler:d,hasStorage:u,hasWorkflow:h,useUmbrella:l,wantsOpenApi:p,wantsOpenRpc:b}=e,i=l?"lunorash/runtime":"@lunora/runtime",g=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions"];n&&g.push("GlobalIntrospector","AdminTableResolver"),r&&g.push("FrameworkHostHandler");const f=[...n||o?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...r?["withFrameworkWorker"]:[]].join(", ");return[...a?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...R(t,a),...n?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { createD1CtxDb, facetGlobalColumn, importGlobalRows, listGlobalTables, readGlobalTablePage } from "@lunora/d1";']:[],...o?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...x(c),...d?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...u?['import type { R2BucketLike, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...h?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...C(e),`import type { ${[...g].toSorted((w,y)=>w.localeCompare(y)).join(", ")} } from "${i}";`,`import { ${f} } from "${i}";`,"",...A(e.identity),...L(e),...n||o?['import schema from "../schema.js";']:[],...O(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...s?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...p?['import { openApiSpec } from "./openapi.js";']:[],...b?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";']},j=e=>[...e.hasStorage?[`/** \`.storage(...)\` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs \`ctx.storage\` AND the studio file browser. */
2
2
  interface StorageDeclaration<Env> {
3
3
  /** The default R2 bucket binding (the bare \`ctx.storage\`). */
4
4
  bucket: Selector<Env, R2BucketLike>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.105",
3
+ "version": "1.0.0-alpha.107",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,15 +46,15 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/advisor": "1.0.0-alpha.75",
50
- "@lunora/agent": "1.0.0-alpha.51",
51
- "@lunora/container": "1.0.0-alpha.29",
52
- "@lunora/errors": "1.0.0-alpha.20",
53
- "@lunora/platform": "1.0.0-alpha.9",
54
- "@lunora/queue": "1.0.0-alpha.25",
55
- "@lunora/scheduler": "1.0.0-alpha.28",
56
- "@lunora/values": "1.0.0-alpha.25",
57
- "@lunora/workflow": "1.0.0-alpha.26",
49
+ "@lunora/advisor": "1.0.0-alpha.77",
50
+ "@lunora/agent": "1.0.0-alpha.52",
51
+ "@lunora/container": "1.0.0-alpha.30",
52
+ "@lunora/errors": "1.0.0-alpha.21",
53
+ "@lunora/platform": "1.0.0-alpha.10",
54
+ "@lunora/queue": "1.0.0-alpha.26",
55
+ "@lunora/scheduler": "1.0.0-alpha.29",
56
+ "@lunora/values": "1.0.0-alpha.26",
57
+ "@lunora/workflow": "1.0.0-alpha.27",
58
58
  "jsonc-parser": "^3.3.1",
59
59
  "quicktype-core": "^26.0.0",
60
60
  "ts-morph": "^28.0.0"
@@ -1 +0,0 @@
1
- import{Node as s,SyntaxKind as g}from"ts-morph";import{g as E,p as N}from"./discover-ast-7ABwvTVn.mjs";const x=(e,t)=>{if(e.getText()!==t)return!1;const r=e.getParent();return s.isPropertyAccessExpression(r)&&r.getNameNode()===e?!1:!(s.isPropertyAssignment(r)&&r.getNameNode()===e)},p=(e,t)=>s.isIdentifier(e)?x(e,t):e.getDescendantsOfKind(g.Identifier).some(r=>x(r,t)),l=e=>p(e,"ctx"),A=e=>{let t=e;for(;s.isPropertyAccessExpression(t)||s.isElementAccessExpression(t)||s.isNonNullExpression(t);)t=t.getExpression();return s.isIdentifier(t)?t:void 0},F=e=>{if(s.isIdentifier(e))return e.getText();if(s.isPropertyAccessExpression(e))return e.getName()},m=e=>p(e,"args"),a=e=>{if(!s.isIdentifier(e))return;const t=e.getText(),r=e.getFirstAncestor(o=>s.isArrowFunction(o)||s.isFunctionExpression(o)||s.isFunctionDeclaration(o));if(r===void 0)return;const n=e.getStart();let i,f=-1;for(const o of r.getDescendantsOfKind(g.VariableDeclaration)){if(o.getName()!==t)continue;const c=o.getInitializer(),u=o.getStart();c!==void 0&&u<n&&u>f&&(i=c,f=u)}return i},K=e=>{if(m(e))return!0;const t=a(e);return t!==void 0&&m(t)},C=e=>{if(s.isCallExpression(e)||s.isNewExpression(e))return!1;const t=a(e);return t===void 0||!(s.isCallExpression(t)||s.isNewExpression(t))},T=e=>{if(l(e))return!0;const t=a(e);if(t!==void 0&&l(t))return!0;const r=t??e;return(s.isIdentifier(r)?[r]:r.getDescendantsOfKind(g.Identifier)).some(n=>{const i=a(n);return i!==void 0&&l(i)})},d=(e,t)=>p(e,t),$=(e,t)=>{if(d(e,t))return!0;const r=a(e);if(r!==void 0&&d(r,t))return!0;const n=A(e);if(n!==void 0){const i=a(n);return i!==void 0&&d(i,t)}return!1},P=e=>{for(const t of e.getAncestors())if(s.isVariableDeclaration(t)&&t.getVariableStatement()?.hasExportKeyword()===!0)return t.getName();return"<module>"},y=new Set(["withIndex","withSearchIndex"]),I=e=>{const t=e.getExpression();if(!s.isPropertyAccessExpression(t)||t.getName()!=="query")return!1;const r=t.getExpression();return s.isPropertyAccessExpression(r)?r.getName()==="db":s.isIdentifier(r)&&r.getText()==="db"},h=e=>{const t=[];let r=e;for(;;){const n=r.getParent();if(!n||!s.isPropertyAccessExpression(n))break;const i=n.getParent();if(!i||!s.isCallExpression(i))break;t.push(n.getName()),r=i}return t},v=/\b[A-Za-z_$][\w$]*\._id\s*===?[^=]/u,b=e=>{let t=e;for(;;){const r=t.getParent();if(!r||!s.isPropertyAccessExpression(r))return!1;const n=r.getParent();if(!n||!s.isCallExpression(n))return!1;if(r.getName()==="filter"){const i=n.getArguments()[0];if(i&&v.test(i.getText()))return!0}t=n}},S=e=>{const t=e.getArguments()[0];return t&&s.isStringLiteral(t)?t.getLiteralText():""},O=(e,t)=>{const r=[];for(const n of E(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),f=N(t,n);for(const o of i.getDescendantsOfKind(g.CallExpression)){if(!I(o))continue;const c=h(o);c.includes("filter")&&r.push({exportName:P(o),file:f,filtersPrimaryKey:b(o),hasFilter:!0,hasIndex:c.some(u=>y.has(u)),line:o.getStartLineNumber(),table:S(o)})}}return r};export{T as a,C as b,F as c,$ as d,P as e,d as f,K as i,m as r,a as s,O as y};
@@ -1 +0,0 @@
1
- import"ts-morph";import{y as p}from"./discover-queries-i4Vd2si7.mjs";import"./discover-ast-7ABwvTVn.mjs";export{p as default};