@lunora/codegen 1.0.0-alpha.118 → 1.0.0-alpha.119

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. package/dist/index.d.mts +15 -22
  2. package/dist/index.d.ts +15 -22
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/{GENERATED_HEADER-BIP8JE2o.mjs → GENERATED_HEADER-Cx5Qh2XJ.mjs} +1 -1
  5. package/dist/packem_shared/{MUTATORS_FILENAME-sGAt-yC1.mjs → MUTATORS_FILENAME-B2-W8Bm3.mjs} +1 -1
  6. package/dist/packem_shared/{NOTIFY_FILENAME-CTZI61e3.mjs → NOTIFY_FILENAME-IJXY4yHt.mjs} +1 -1
  7. package/dist/packem_shared/{OPENRPC_VERSION-CK8lskQm.mjs → OPENRPC_VERSION-14yZ-O3V.mjs} +1 -1
  8. package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-KYdkEFZu.mjs → SCHEMA_SNAPSHOT_FILENAME-CbOqo05-.mjs} +1 -1
  9. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-B0cTpK1D.mjs +2 -0
  10. package/dist/packem_shared/{SchemaSnapshotParseError-Dc1aZAph.mjs → SchemaSnapshotParseError-BoHDfCO3.mjs} +1 -1
  11. package/dist/packem_shared/{buildOpenApiDocument-xvbIL1q6.mjs → buildOpenApiDocument-DI8bgteQ.mjs} +1 -1
  12. package/dist/packem_shared/discoverFunctions-006teuNG.mjs +1 -0
  13. package/dist/packem_shared/{discoverHttpRoutes-DOirwCWw.mjs → discoverHttpRoutes-BxF4FRZL.mjs} +1 -1
  14. package/dist/packem_shared/{discoverMaskProcedures-D-09Qb8S.mjs → discoverMaskProcedures-BCl3fNrQ.mjs} +1 -1
  15. package/dist/packem_shared/{discoverNondeterministicCalls-DhNToI6C.mjs → discoverNondeterministicCalls-BA91Z-vF.mjs} +1 -1
  16. package/dist/packem_shared/{discoverR2sqlCalls-B6e4j4rD.mjs → discoverR2sqlCalls-M2ob41UX.mjs} +1 -1
  17. package/dist/packem_shared/{discoverRlsMetadata-Pw0_c1aS.mjs → discoverRlsMetadata-Dwt2p8IK.mjs} +1 -1
  18. package/dist/packem_shared/{discoverSchema-D_wHstA-.mjs → discoverSchema-gJ93Xjpx.mjs} +1 -1
  19. package/dist/packem_shared/{discoverStorageRulesMetadata-DthHu3mC.mjs → discoverStorageRulesMetadata-69Y8wZb2.mjs} +1 -1
  20. package/dist/packem_shared/{emit-C935cHCe.mjs → emit-C0azW4mT.mjs} +307 -218
  21. package/dist/packem_shared/{emitApp-BpHICt5i.mjs → emitApp-Dyr-onNf.mjs} +1 -1
  22. package/dist/packem_shared/{formatAdvisories-BjTV22uR.mjs → formatAdvisories-CkEu1eye.mjs} +1 -1
  23. package/package.json +6 -6
  24. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-DIqnj_32.mjs +0 -2
  25. package/dist/packem_shared/discoverFunctions-4eSpCR6m.mjs +0 -1
@@ -1,4 +1,4 @@
1
- import{A as S,G as D}from"./emit-C935cHCe.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]),g=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:r,hasFramework:a,hasGlobal:n,hasHyperdriveGlobal:o,hasKv:l,hasQueue:s,hasScheduler:d,hasStorage:u,hasWorkflow:h,useUmbrella:c,wantsOpenApi:p,wantsOpenRpc:b}=e,i=c?"lunorash/runtime":"@lunora/runtime",m=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions"];n&&m.push("GlobalIntrospector","AdminTableResolver"),a&&m.push("FrameworkHostHandler");const f=[...n||o?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...a?["withFrameworkWorker"]:[]].join(", ");return[...r?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...R(t,r),...n?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { createD1CtxDb, facetGlobalColumn, importGlobalRows, listGlobalTables, readGlobalTablePage, retryingExec } 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(l),...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 { ${[...m].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";']},I=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{A as S,G as D}from"./emit-C0azW4mT.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]),g=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:r,hasFramework:a,hasGlobal:n,hasHyperdriveGlobal:o,hasKv:l,hasQueue:s,hasScheduler:d,hasStorage:u,hasWorkflow:h,useUmbrella:c,wantsOpenApi:p,wantsOpenRpc:b}=e,i=c?"lunorash/runtime":"@lunora/runtime",m=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions"];n&&m.push("GlobalIntrospector","AdminTableResolver"),a&&m.push("FrameworkHostHandler");const f=[...n||o?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...a?["withFrameworkWorker"]:[]].join(", ");return[...r?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...R(t,r),...n?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { createD1CtxDb, facetGlobalColumn, importGlobalRows, listGlobalTables, readGlobalTablePage, retryingExec } 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(l),...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 { ${[...m].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";']},I=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>;
@@ -1,2 +1,2 @@
1
- import{runAdvisor as o}from"@lunora/advisor";const i=n=>[...n.indexes.map(e=>({fields:e.fields,kind:"index",name:e.name,unique:e.unique})),...n.searchIndexes.map(e=>({fields:[e.field,...e.filterFields??[]],kind:"search",name:e.name})),...n.rankIndexes.map(e=>({fields:[...e.sortBy.map(r=>r.field),...e.partitionBy??[]],kind:"rank",name:e.name})),...n.vectorIndexes.filter(e=>e.field!==void 0).map(e=>({fields:[e.field],kind:"vector",name:e.name})),...(n.geoIndexes??[]).map(e=>({fields:[e.field],kind:"geo",name:e.name}))],d=n=>{const e={};for(const[r,s]of Object.entries(n.shape))e[r]=s.kind==="optional"?s.inner?.kind??"optional":s.kind;return e},l=n=>({rlsMode:n.rlsMode,tables:n.tables.map(e=>({externallyManaged:e.externallyManaged??!1,externalSource:e.externalSource?{hasReconcile:e.externalSource.hasReconcile??!1,hasSoftDelete:e.externalSource.hasSoftDelete??!1,hasTenantBy:e.externalSource.hasTenantBy,mode:e.externalSource.mode,unanalyzable:e.externalSource.unanalyzable}:void 0,columnKinds:d(e),fields:Object.keys(e.shape),indexes:i(e),isPublic:e.isPublic??!1,name:e.name,relations:e.relations.map(r=>({field:r.field,kind:r.kind,name:r.name,onDelete:r.onDelete,references:r.references,table:r.table})),shardKind:typeof e.shardMode=="string"?e.shardMode:"shardBy",softDelete:e.softDelete,ttl:e.ttl}))}),c=n=>n.map(e=>({exportName:e.exportName,file:`lunora/${e.filePath}.ts`,table:e.table})),m=n=>{const{argumentValidators:e,queries:r,schema:s,shapes:a,...t}=n;return{...t,argValidators:e,queries:r??[],schema:l(s),shapes:a===void 0?void 0:c(a)}},f=n=>o(m(n),{source:"static"}),h=n=>{if(n.length===0)return"";const e=`@lunora/codegen: ${String(n.length)} schema advisor finding${n.length===1?"":"s"}`,r=n.map(s=>` [${s.level}] ${s.name}: ${s.detail}`);return[e,...r].join(`
1
+ import{runAdvisor as t}from"@lunora/advisor";const i=n=>[...n.indexes.map(e=>({fields:e.fields,kind:"index",name:e.name,unique:e.unique})),...n.searchIndexes.map(e=>({fields:[e.field,...e.filterFields??[]],kind:"search",name:e.name})),...n.rankIndexes.map(e=>({fields:[...e.sortBy.map(r=>r.field),...e.partitionBy??[]],kind:"rank",name:e.name})),...n.vectorIndexes.filter(e=>e.field!==void 0).map(e=>({fields:[e.field],kind:"vector",name:e.name})),...(n.geoIndexes??[]).map(e=>({fields:[e.field],kind:"geo",name:e.name}))],d=n=>{const e={};for(const[r,s]of Object.entries(n.shape))e[r]=s.kind==="optional"?s.inner?.kind??"optional":s.kind;return e},l=n=>({rlsMode:n.rlsMode,tables:n.tables.map(e=>({externallyManaged:e.externallyManaged??!1,externalSource:e.externalSource?{hasReconcile:e.externalSource.hasReconcile??!1,hasSoftDelete:e.externalSource.hasSoftDelete??!1,hasTenantBy:e.externalSource.hasTenantBy,mode:e.externalSource.mode,unanalyzable:e.externalSource.unanalyzable}:void 0,columnKinds:d(e),fields:Object.keys(e.shape),indexes:i(e),isPublic:e.isPublic??!1,name:e.name,relations:e.relations.map(r=>({field:r.field,kind:r.kind,name:r.name,onDelete:r.onDelete,references:r.references,table:r.table})),commitOrdered:e.commitOrdered,shardKind:typeof e.shardMode=="string"?e.shardMode:"shardBy",softDelete:e.softDelete,ttl:e.ttl}))}),c=n=>n.map(e=>({exportName:e.exportName,file:`lunora/${e.filePath}.ts`,table:e.table})),m=n=>{const{argumentValidators:e,queries:r,schema:s,shapes:a,...o}=n;return{...o,argValidators:e,queries:r??[],schema:l(s),shapes:a===void 0?void 0:c(a)}},f=n=>t(m(n),{source:"static"}),h=n=>{if(n.length===0)return"";const e=`@lunora/codegen: ${String(n.length)} schema advisor finding${n.length===1?"":"s"}`,r=n.map(s=>` [${s.level}] ${s.name}: ${s.detail}`);return[e,...r].join(`
2
2
  `)};export{h as formatAdvisories,f as lintSchema,m as toAdvisorContext};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.118",
3
+ "version": "1.0.0-alpha.119",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,13 +46,13 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/advisor": "1.0.0-alpha.84",
50
- "@lunora/agent": "1.0.0-alpha.59",
49
+ "@lunora/advisor": "1.0.0-alpha.85",
50
+ "@lunora/agent": "1.0.0-alpha.60",
51
51
  "@lunora/container": "1.0.0-alpha.32",
52
52
  "@lunora/errors": "1.0.0-alpha.22",
53
- "@lunora/platform": "1.0.0-alpha.14",
54
- "@lunora/queue": "1.0.0-alpha.30",
55
- "@lunora/scheduler": "1.0.0-alpha.34",
53
+ "@lunora/platform": "1.0.0-alpha.15",
54
+ "@lunora/queue": "1.0.0-alpha.31",
55
+ "@lunora/scheduler": "1.0.0-alpha.35",
56
56
  "@lunora/values": "1.0.0-alpha.27",
57
57
  "@lunora/workflow": "1.0.0-alpha.30",
58
58
  "jsonc-parser": "^3.3.1",
@@ -1,2 +0,0 @@
1
- const v=1;function b(e){const i={},s=Object.keys(e);s.sort();for(const o of s)i[o]=e[o];return i}const r=e=>`${JSON.stringify(e,void 0,2)}
2
- `,g=e=>{const i=r(e),s=o=>{let t=o;for(let d=0;d<i.length;d+=1)t^=i.codePointAt(d)??0,t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")};return`${s(2166136261)}${s(16777619)}`},a=e=>typeof e=="object"&&e!==null,l=e=>a(e)&&a(e.fields)&&a(e.indexes)&&a(e.relations)&&typeof e.shardMode=="string",$=e=>{if(e===void 0||e.trim()==="")return{status:"absent"};let i;try{i=JSON.parse(e)}catch(o){return{error:`baseline is not valid JSON: ${o instanceof Error?o.message:String(o)}`,status:"invalid"}}if(!a(i)||i.version!==1||!a(i.tables))return{error:`baseline is malformed or written by an incompatible version (expected version ${String(1)})`,status:"invalid"};for(const[o,t]of Object.entries(i.tables))if(!l(t))return{error:`baseline table "${o}" has an invalid structure`,status:"invalid"};return{snapshot:{jurisdiction:typeof i.jurisdiction=="string"?i.jurisdiction:void 0,migrationIds:Array.isArray(i.migrationIds)?i.migrationIds:[],tables:i.tables,version:1},status:"ok"}},c=(e,i)=>e.unique===i.unique&&e.fields.length===i.fields.length&&e.fields.every((s,o)=>s===i.fields[o]),f=(e,i,s,o)=>{const t=[];return s.kind!==o.kind&&t.push({severity:"breaking",summary:`field ${e}.${i} changed type: ${s.kind} → ${o.kind} — add a data migration to convert existing values`,table:e,scope:"table",type:"changedFieldKind"}),s.optional&&!o.optional?t.push({severity:"breaking",summary:`field ${e}.${i} became required — rows missing it would be invalid; add a data migration to backfill it`,table:e,scope:"table",type:"fieldOptionalToRequired"}):!s.optional&&o.optional&&t.push({scope:"table",severity:"safe",summary:`field ${e}.${i} became optional`,table:e,type:"fieldRequiredToOptional"}),t},p=(e,i,s)=>s.optional?{scope:"table",severity:"safe",summary:`added optional field ${e}.${i}`,table:e,type:"addedOptionalField"}:{severity:"breaking",summary:`added required field ${e}.${i} — existing rows have no value; add a data migration to backfill it`,table:e,scope:"table",type:"addedRequiredField"},u=(e,i,s,o)=>{for(const[t,d]of Object.entries(s.fields)){const n=i.fields[t];n===void 0?o.push(p(e,t,d)):o.push(...f(e,t,n,d))}for(const t of Object.keys(i.fields))s.fields[t]===void 0&&o.push({severity:"breaking",summary:`removed field ${e}.${t} — add a data migration if stored data must be cleaned up`,table:e,scope:"table",type:"removedField"})},y=(e,i,s,o)=>{for(const[t,d]of Object.entries(s.indexes)){const n=i.indexes[t];if(n===void 0){o.push({scope:"table",severity:"safe",summary:`added index ${t} on ${e}`,table:e,type:"addedIndex"});continue}c(n,d)||o.push({severity:"breaking",summary:`index ${t} on ${e} changed shape — a query may have relied on the old index`,table:e,scope:"table",type:"changedIndex"})}for(const t of Object.keys(i.indexes))s.indexes[t]===void 0&&o.push({severity:"breaking",summary:`removed index ${t} on ${e} — a query that used \`.withIndex("${t}")\` would break`,table:e,scope:"table",type:"removedIndex"})},h=(e,i,s,o)=>{for(const t of Object.keys(s.relations))i.relations[t]===void 0&&o.push({scope:"schema",severity:"safe",summary:`added relation ${e}.${t}`,table:e,type:"addedRelation"});for(const t of Object.keys(i.relations))s.relations[t]===void 0&&o.push({scope:"schema",severity:"breaking",summary:`removed relation ${e}.${t}`,table:e,type:"removedRelation"})},m=(e,i,s,o)=>{i.shardMode!==s.shardMode&&o.push({severity:"breaking",summary:`table ${e} changed shard mode: ${i.shardMode} → ${s.shardMode} — its physical storage moves; add a data migration / re-shard plan`,table:e,scope:"table",type:"changedShardMode"}),u(e,i,s,o),y(e,i,s,o),h(e,i,s,o)},S=(e,i)=>{const s=[],o=e?.tables??{};for(const[t,d]of Object.entries(i.tables)){const n=o[t];if(n===void 0){s.push({scope:"table",severity:"safe",summary:`added table ${t}`,table:t,type:"addedTable"});continue}m(t,n,d,s)}for(const t of Object.keys(o))i.tables[t]===void 0&&s.push({scope:"table",severity:"breaking",summary:`removed table ${t} — add a data migration if its data must be archived/cleaned up`,table:t,type:"removedTable"});if(e!==void 0&&e.jurisdiction!==i.jurisdiction){const t=e.jurisdiction??"(none)",d=i.jurisdiction??"(none)";s.push({scope:"schema",severity:"breaking",summary:`Durable Object jurisdiction changed from ${t} to ${d} — this re-homes every DO and strands all existing shard, scheduler, and session-DO data in the old region (no in-place migration; export then import to move it). Revert the change, or override the gate to proceed intentionally.`,type:"changedJurisdiction"})}return{changes:s}};export{v as SCHEMA_SNAPSHOT_VERSION,S as diffSchemaSnapshots,g as hashSchemaSnapshot,l as isValidTableSnapshot,$ as parseSnapshotJson,r as serializeSchemaSnapshot,b as sortKeys};
@@ -1 +0,0 @@
1
- import{Node as s,SyntaxKind as O}from"ts-morph";import{l as w,a as k}from"./discover-ast-D33zP-NZ.mjs";import{a as z}from"./module-specifiers-WF8iAydP.mjs";import{p as _,a as b}from"./parse-validator-C5ycrhR3.mjs";import{s as R}from"./paths-C-9fwEgQ.mjs";const y=new Set(["action","mutation","query","stream"]),P=/\bany\b(?!\s*(?:\?\s*)?:)/u,T=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,U=/^[A-Za-z_$][\w$]*$/u,j=e=>U.test(e)?e:JSON.stringify(e),N={internalAction:"action",internalMutation:"mutation",internalQuery:"query"},$={onConnect:"connect",onDisconnect:"disconnect"},V=z,h=e=>{const t=e.getSymbol();if(!t)return e.getText();const r=t.getDeclarations();for(const i of r){if(!s.isImportSpecifier(i))continue;const o=i.getImportDeclaration().getModuleSpecifierValue();return V(o)?i.getNameNode().getText():void 0}},S=(e,t=!1)=>{let r=e;for(;s.isCallExpression(r);){const n=r.getExpression();if(!s.isPropertyAccessExpression(n))return;r=n.getExpression()}if(!s.isIdentifier(r))return;const i=h(r);if(i===void 0){if(t)return;const n=r.getSymbol()?.getValueDeclaration();if(n&&s.isVariableDeclaration(n)){const o=n.getInitializer();return o?S(o,!0):void 0}return}return y.has(i)?"public":N[i]?"internal":void 0},m=(e,t)=>{const r=e.getProperty(t);if(r===void 0||!s.isPropertyAssignment(r))return;const i=r.getInitializer();return i!==void 0&&s.isStringLiteral(i)?i.getLiteralValue():void 0},E=(e,t)=>{const r=e.getProperty(t);if(r===void 0||!s.isPropertyAssignment(r))return;const i=r.getInitializer();return i!==void 0&&s.isNumericLiteral(i)?i.getLiteralValue():void 0},M=e=>{const t=e.getProperty("cache");if(t===void 0||!s.isPropertyAssignment(t))return;const r=t.getInitializer();if(r===void 0||!s.isObjectLiteralExpression(r))return;const i=m(r,"scope"),n=E(r,"maxAge"),o=E(r,"staleWhileRevalidate"),a=m(r,"tag"),c=m(r,"vary"),l={...n===void 0?{}:{maxAge:n},...i==="private"||i==="public"?{scope:i}:{},...o===void 0?{}:{staleWhileRevalidate:o},...a===void 0?{}:{tag:a},...c===void 0?{}:{vary:c}};return Object.keys(l).length===0?void 0:l},B=e=>{if(e===void 0||!s.isObjectLiteralExpression(e))return{};const t=M(e),r=e.getProperty("rest");return r!==void 0&&s.isPropertyAssignment(r)?{...t===void 0?{}:{cache:t},rest:r.getInitializer()?.getText()==="true"}:t===void 0?{}:{cache:t}},K=e=>{let t=e;for(;s.isCallExpression(t);){const r=t.getExpression();if(!s.isPropertyAccessExpression(r))return;if(r.getName()==="expose")return B(t.getArguments()[0]);t=r.getExpression()}},H=e=>{const t=e.getArguments()[0];if(!t||!s.isObjectLiteralExpression(t))return{};const r=t.getProperty("args");if(!r||!s.isPropertyAssignment(r))return{};const i=r.getInitializer();return!i||!s.isObjectLiteralExpression(i)?{}:b(i)},G="/_generated/",q=(e,t,r)=>{const i=t.getSourceFile(),n=(a,c)=>i.getImportDeclarations().some(l=>l.getModuleSpecifierSourceFile()!==a?!1:l.getNamespaceImport()!==void 0||l.getNamedImports().some(f=>f.getName()===c)),o=a=>{const c=a.getSourceFile();if(c.isInNodeModules()||c.isDeclarationFile()||!s.isInterfaceDeclaration(a)&&!s.isTypeAliasDeclaration(a))return!1;const l=c.getFilePath();return l.includes(G)?!1:l===r||n(c,a.getName())};return[e.getSymbol(),e.getAliasSymbol()].flatMap(a=>a?.getDeclarations()??[]).some(a=>o(a))},W=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},I=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0,g=(e,t,r,i=new Set)=>i.has(e)?!1:(i.add(e),q(e,t,r)||W(e).some(n=>g(n,t,r,i))?!0:I(e)?e.getProperties().some(n=>g(n.getTypeAtLocation(t),t,r,i)):!1),X=(e,t)=>{const r=e.getValueDeclaration()??e.getDeclarations()[0];return r&&(s.isPropertySignature(r)||s.isPropertyDeclaration(r))&&r.hasQuestionToken()?!0:t.isUnion()&&t.getUnionTypes().some(i=>i.isUndefined())},Y=8,J=(e,t,r,i,n,o)=>{const a=e.getArrayElementType(),c=a?o(a,t,r,i,n):void 0;if(c!==void 0)return a?.isUnion()?`(${c})[]`:`${c}[]`},Q=(e,t,r,i,n,o)=>{const a=[];for(const c of e.getUnionTypes()){const l=o(c,t,r,i,n);if(l===void 0)return;a.push(l)}return a.join(" | ")},Z=(e,t,r,i,n,o)=>{if(!I(e))return;const a=[];for(const c of e.getProperties()){const l=c.getTypeAtLocation(t),f=X(c,l),L=f&&l.isUnion()?l.getUnionTypes().filter(d=>!d.isUndefined()):[l],v=[];for(const d of L){const x=o(d,t,r,i+1,n);if(x===void 0)return;v.push(x)}a.push(`${j(c.getName())}${f?"?":""}: ${v.join(" | ")}`)}return a.length>0?`{ ${a.join("; ")} }`:"{}"},p=(e,t,r,i,n)=>{if(i>Y||n.has(e))return;if(!g(e,t,r))return e.getText(t);const o=new Set(n).add(e);return e.isArray()?J(e,t,r,i,o,p):e.isUnion()?Q(e,t,r,i,o,p):Z(e,t,r,i,o,p)},C=e=>{const t=e.getType().getCallSignatures()[0];if(!t)return"unknown";let r=t.getReturnType();const n=(r.getSymbol()??r.getAliasSymbol())?.getName();if(n==="Promise"||n==="AsyncIterable"||n==="AsyncIterableIterator"||n==="AsyncGenerator"){const c=r.getTypeArguments()[0];c&&(r=c)}const o=r.getText(e);if(!o||o==="any"||o==="never"||P.test(o.replaceAll(T,"")))return"unknown";const a=e.getSourceFile().getFilePath();return g(r,e,a)?p(r,e,a,0,new Set)??"unknown":o},ve=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const r=t.getTypeAtLocation(e).getProperty("types");if(!r)return;const i=r.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!i)return;const n=i.getTypeAtLocation(e),o=n.getText(e);if(!o||o==="any"||o==="never"||P.test(o.replaceAll(T,"")))return;const a=e.getSourceFile().getFilePath();return g(n,e,a)?p(n,e,a,0,new Set):o},ee=e=>{const t=e.getArguments()[0];if(!t||!s.isObjectLiteralExpression(t))return"unknown";const r=t.getProperty("handler");if(!r||!s.isPropertyAssignment(r))return"unknown";const i=r.getInitializer();return!i||!(s.isArrowFunction(i)||s.isFunctionExpression(i))?"unknown":C(i)},te=e=>{const t=e.getArguments()[0];return!t||!(s.isArrowFunction(t)||s.isFunctionExpression(t))?"unknown":C(t)},re=e=>{let t={},r=e;for(;s.isCallExpression(r);){const i=r.getExpression();if(!s.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const n=r.getArguments()[0];n&&s.isObjectLiteralExpression(n)&&(t={...b(n),...t})}r=i.getExpression()}return t},ie=e=>{let t=e;for(;s.isCallExpression(t);){const r=t.getExpression();if(!s.isPropertyAccessExpression(r))return;if(r.getName()==="output"){const i=t.getArguments()[0];return i&&s.isExpression(i)?_(i):void 0}t=r.getExpression()}},ne=e=>{const t=e.getExpression();if(s.isPropertyAccessExpression(t)){const o=t.getName();if(!y.has(o))return;const a=t.getExpression();if(a.getType().getProperty("__lunoraProcedure"))return{kind:o,receiver:a,visibility:a.getType().getProperty("__lunoraVisibility")?"internal":"public"};const c=S(a);return c?{kind:o,receiver:a,visibility:c}:void 0}if(!s.isIdentifier(t))return;const r=h(t);if(!r)return;if(y.has(r))return{kind:r,visibility:"public"};const i=N[r];if(i)return{kind:i,visibility:"internal"};const n=$[r];if(n)return{kind:"mutation",lifecycle:n,visibility:"internal"}},A=e=>e!==void 0&&(s.isArrowFunction(e)||s.isFunctionExpression(e))?e:void 0,xe=e=>s.isPropertyAccessExpression(e)&&e.getName()==="db"||s.isIdentifier(e)&&e.getText()==="db",Ee=e=>{const t=e.getArguments()[0],r=A(t);if(r!==void 0)return r;if(t===void 0||!s.isObjectLiteralExpression(t))return;const i=t.getProperty("handler");return i!==void 0&&s.isPropertyAssignment(i)?A(i.getInitializer()):void 0},se=e=>s.isIdentifier(e)?e.getText():s.isPropertyAccessExpression(e)?e.getName():"",Ae=(e,t)=>{let r=e;for(;s.isCallExpression(r);){const i=r.getExpression();if(!s.isPropertyAccessExpression(i))break;if(i.getName()===t)return!0;r=i.getExpression()}return!1},be=(e,t,r)=>{let i=e;for(;s.isCallExpression(i);){const n=i.getExpression();if(!s.isPropertyAccessExpression(n))break;const o=i.getArguments()[0];if(n.getName()===t&&o!==void 0&&s.isCallExpression(o)&&se(o.getExpression())===r)return!0;i=n.getExpression()}return!1},oe=e=>{const t=ne(e);if(t){if(t.receiver){const r=K(t.receiver),i=ie(t.receiver);return{args:re(t.receiver),...r?{expose:r}:{},kind:t.kind,...i?{output:i}:{},returnType:te(e),visibility:t.visibility}}return t.lifecycle?{args:{},kind:t.kind,lifecycle:t.lifecycle,returnType:"void",visibility:t.visibility}:{args:H(e),kind:t.kind,returnType:ee(e),visibility:t.visibility}}},ae=8,u=(e,t=0)=>{if(t>ae)return;if(s.isCallExpression(e))return e;if(s.isParenthesizedExpression(e)||s.isAsExpression(e)||s.isSatisfiesExpression(e)||s.isNonNullExpression(e))return u(e.getExpression(),t+1);if(!s.isIdentifier(e)&&!s.isPropertyAccessExpression(e))return;const r=e.getSymbol()?.getValueDeclaration();return r?F(r,t+1):void 0},F=(e,t)=>{if(s.isVariableDeclaration(e)||s.isPropertyAssignment(e)){const r=e.getInitializer();return r?u(r,t):void 0}if(s.isShorthandPropertyAssignment(e))return u(e.getNameNode(),t);if(s.isBindingElement(e)){const r=e.getPropertyNameNode()?.getText()??e.getName(),o=e.getFirstAncestorByKind(O.VariableDeclaration)?.getInitializer()?.getType().getProperty(r)?.getValueDeclaration();return o?F(o,t+1):void 0}},ce=e=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t)){const n=[];for(const o of t.getElements()){const a=u(o.getNameNode());a&&n.push([o.getName(),a])}return n}const r=e.getInitializer(),i=r&&(s.isCallExpression(r)?r:u(r));return i?[[e.getName(),i]]:[]},D=(e,t,r)=>{const i=oe(e);if(i)return{args:i.args,exportName:t,filePath:r,kind:i.kind,returnType:i.returnType,...i.output?{output:i.output}:{},visibility:i.visibility,...i.expose?{expose:i.expose}:{},...i.lifecycle?{lifecycle:i.lifecycle}:{}}},le=(e,t)=>{const r=[];for(const i of e.getExportAssignments()){if(i.isExportEquals())continue;const n=u(i.getExpression()),o=n?D(n,"default",t):void 0;o&&r.push(o)}return r},ue=(e,t)=>{const r=[];for(const i of e.getVariableStatements())if(i.isExported())for(const n of i.getDeclarations())for(const[o,a]of ce(n)){const c=D(a,o,t);c&&r.push(c)}return r.push(...le(e,t)),r},pe=e=>{const t=new Map;for(const r of e){const i=R(r.filePath),n=t.get(i);if(n&&n!==r.filePath)throw Object.assign(new Error(`Namespace collision: "${n}" and "${r.filePath}" both resolve to "${i}". Rename one of the files so the JS-identifier-sanitized names differ. (note: case-insensitive filesystems may also cause this — \`foo\` and \`FOO\` map to the same identifier)`),{code:"NAMESPACE_COLLISION",name:"LunoraError",paths:[n,r.filePath],status:500});t.set(i,r.filePath)}},Pe=(e,t)=>{const r=w(t),i=[];for(const n of r){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),a=k(t,n);i.push(...ue(o,a))}return i.sort((n,o)=>`${n.filePath}:${n.exportName}`.localeCompare(`${o.filePath}:${o.exportName}`)),pe(i),i};export{Ae as chainHasStep,be as chainUsesWrappedCall,ne as classifyProcedureCall,Pe as discoverFunctions,A as inlineHandler,xe as isDatabaseAccessor,w as listLunoraSourceFiles,k as lunoraRelativePath,Ee as procedureHandler,ve as resolveStandardSchemaType,C as unwrapHandlerReturn};