@lunora/codegen 1.0.0-alpha.315 → 1.0.0-alpha.317

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 (39) hide show
  1. package/dist/index.d.mts +15 -6
  2. package/dist/index.d.ts +15 -6
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/DEFAULT_TARGET-B0FkdiZq.mjs +1 -0
  5. package/dist/packem_shared/{MUTATORS_FILENAME--5kUJd5I.mjs → MUTATORS_FILENAME-Jkk8Zgkb.mjs} +1 -1
  6. package/dist/packem_shared/{NOTIFY_FILENAME-BOZ8G8zT.mjs → NOTIFY_FILENAME-CjbDYC2a.mjs} +1 -1
  7. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-By-jJ8_K.mjs +11 -0
  8. package/dist/packem_shared/chain-CubC5VoS.mjs +1 -0
  9. package/dist/packem_shared/classify-procedure-call-CcgP-9I0.mjs +1 -0
  10. package/dist/packem_shared/{context-property-calls-DdoCuhv4.mjs → context-property-calls-Bw8u2Pz4.mjs} +1 -1
  11. package/dist/packem_shared/{context-root-lGZCyHyj.mjs → context-root-YkWLB6M2.mjs} +1 -1
  12. package/dist/packem_shared/{database-calls-CVsXSVhv.mjs → database-calls-BnVUlTx_.mjs} +1 -1
  13. package/dist/packem_shared/discoverFunctions-5Zy6K4uA.mjs +1 -0
  14. package/dist/packem_shared/{discoverHttpRoutes-BccLtGKg.mjs → discoverHttpRoutes-WBAqBcfK.mjs} +1 -1
  15. package/dist/packem_shared/discoverHyperdriveCalls-DFbp-ILH.mjs +1 -0
  16. package/dist/packem_shared/{discoverInserts-rFszl3Al.mjs → discoverInserts-DUbjhNzk.mjs} +1 -1
  17. package/dist/packem_shared/discoverMaskProcedures-BfVFPpAJ.mjs +1 -0
  18. package/dist/packem_shared/{discoverNondeterministicCalls-9ZDpRptb.mjs → discoverNondeterministicCalls-D7Ovq8ae.mjs} +1 -1
  19. package/dist/packem_shared/{discoverQueries-DDds61UD.mjs → discoverQueries-BNqjOBY_.mjs} +1 -1
  20. package/dist/packem_shared/discoverR2sqlCalls-TNwsmYje.mjs +1 -0
  21. package/dist/packem_shared/{discoverRlsMetadata-Cb8JR1b4.mjs → discoverRlsMetadata-CbdfaVep.mjs} +1 -1
  22. package/dist/packem_shared/{discoverRlsProcedures-BfEFJmU5.mjs → discoverRlsProcedures-BeLdV5RT.mjs} +1 -1
  23. package/dist/packem_shared/{discoverStorageRulesMetadata-BPJplDfz.mjs → discoverStorageRulesMetadata-BBMy9JVZ.mjs} +1 -1
  24. package/dist/packem_shared/{emitApi-Zx6VPN-7.mjs → emitApi-CDgIPAG2.mjs} +45 -33
  25. package/dist/packem_shared/{emitFunctions-BeKgL3dl.mjs → emitFunctions-amc10WSc.mjs} +112 -62
  26. package/dist/packem_shared/{emitShard-D_dkDtuY.mjs → emitShard-o8m4pR4Z.mjs} +1 -1
  27. package/dist/packem_shared/{exported-procedure-chains-DKK5HoK3.mjs → exported-procedure-chains-DAl7xBBx.mjs} +1 -1
  28. package/dist/packem_shared/{index-Bxn8ZjS0.mjs → index-DvmKcoFV.mjs} +1 -1
  29. package/dist/packem_shared/{shard-Av4rUyYS.mjs → shard-26v1MJxM.mjs} +90 -78
  30. package/dist/packem_shared/{unwrap-handler-return-BwclbliB.mjs → unwrap-handler-return-CeaOifqX.mjs} +1 -1
  31. package/package.json +9 -9
  32. package/dist/packem_shared/DEFAULT_TARGET-BnQiNNKu.mjs +0 -1
  33. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DM4csP6n.mjs +0 -11
  34. package/dist/packem_shared/chain-CRDaTj2c.mjs +0 -1
  35. package/dist/packem_shared/classify-procedure-call-BAj0D1u2.mjs +0 -1
  36. package/dist/packem_shared/discoverFunctions-BiA7jv30.mjs +0 -1
  37. package/dist/packem_shared/discoverHyperdriveCalls-DxYmsE3Y.mjs +0 -1
  38. package/dist/packem_shared/discoverMaskProcedures-BZlL43UV.mjs +0 -1
  39. package/dist/packem_shared/discoverR2sqlCalls-CEbVN9V1.mjs +0 -1
@@ -1,4 +1,4 @@
1
- import{LunoraError as Rt}from"@lunora/errors";import{serializeSchemaSnapshot as xt,hashSchemaSnapshot as At}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as Ot,isD1GlobalTable as Dt}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as Tt}from"./json-data-Chfs2Cz5.mjs";import{r as L,e as Et,a as Lt,b as Ct,c as It,d as _t,f as Mt,g as Pt,h as Nt,i as $t,j as qt,k as Ft,l as Ut,m as Bt,n as Wt,o as jt,p as Ht,q as Vt}from"./shard-runtime-CkTgY8tL.mjs";import{u as K,i as Kt,G as Gt,d as Qt}from"./shared-DnCokNcE.mjs";import{p as zt}from"./platform-8oj7iXQy.mjs";import{i as Jt}from"./schema-BgM8A3XV.mjs";const h=(n,e)=>`((): (() => ${e}) => { let cached: ${e} | undefined; return () => (cached ??= JSON.parse(${JSON.stringify(JSON.stringify(n))}) as ${e}); })()`,te=["categories","description","facing","level","remediation","title"],Yt=n=>{const e={};return{advisoryRows:n.map(a=>{let r=e[a.name];return r||(r=Object.fromEntries(te.filter(s=>s in a).map(s=>[s,a[s]])),e[a.name]=r),Object.fromEntries(Object.entries(a).filter(([s,d])=>!te.includes(s)||JSON.stringify(d)!==JSON.stringify(r[s])))}),advisoryRules:e}},Xt=` /**
1
+ import{LunoraError as At}from"@lunora/errors";import{serializeSchemaSnapshot as Ot,hashSchemaSnapshot as Dt}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as Tt,isD1GlobalTable as Et}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as Ct}from"./json-data-Chfs2Cz5.mjs";import{r as T,e as Lt,a as _t,b as It,c as Mt,d as Pt,f as Nt,g as $t,h as qt,i as Ft,j as Ut,k as Bt,l as Wt,m as jt,n as Ht,o as Vt,p as Kt,q as Gt}from"./shard-runtime-CkTgY8tL.mjs";import{u as K,i as Qt,G as zt,d as Jt}from"./shared-DnCokNcE.mjs";import{p as Yt}from"./platform-8oj7iXQy.mjs";import{i as Xt}from"./schema-BgM8A3XV.mjs";const h=(a,e)=>`((): (() => ${e}) => { let cached: ${e} | undefined; return () => (cached ??= JSON.parse(${JSON.stringify(JSON.stringify(a))}) as ${e}); })()`,te=["categories","description","facing","level","remediation","title"],Zt=a=>{const e={};return{advisoryRows:a.map(n=>{let r=e[n.name];return r||(r=Object.fromEntries(te.filter(s=>s in n).map(s=>[s,n[s]])),e[n.name]=r),Object.fromEntries(Object.entries(n).filter(([s,d])=>!te.includes(s)||JSON.stringify(d)!==JSON.stringify(r[s])))}),advisoryRules:e}},er=` /**
2
2
  * The bare writer every admin/maintenance entry point writes through.
3
3
  *
4
4
  * Admin and maintenance writes go through the SAME reactive-cache hooks as a
@@ -30,7 +30,7 @@ import{LunoraError as Rt}from"@lunora/errors";import{serializeSchemaSnapshot as
30
30
  schema: schema as unknown as SchemaLike,
31
31
  sql: this.sql as SqlExec,
32
32
  });
33
- }`,p=(n="")=>` const writer = this.adminWriter(${n});`,Zt=`${Xt}
33
+ }`,m=(a="")=>` const writer = this.adminWriter(${a});`,tr=`${er}
34
34
 
35
35
  protected override async runShardDataMigration(args: RunShardMigrationArgs): Promise<MigrationRunResult> {
36
36
  this.ensureMigrated();
@@ -47,7 +47,7 @@ import{LunoraError as Rt}from"@lunora/errors";import{serializeSchemaSnapshot as
47
47
  throw new LunoraError("MIGRATION_NOT_FOUND", \`data migration "\${args.id}" is not registered\`, { status: 404 });
48
48
  }
49
49
 
50
- ${p()}
50
+ ${m()}
51
51
 
52
52
  return runDataMigration({
53
53
  batchSize: args.batchSize,
@@ -80,7 +80,7 @@ ${p()}
80
80
 
81
81
  this.ensureMigrated();
82
82
 
83
- ${p("headroom ?? this.transactionHeadroom()")}
83
+ ${m("headroom ?? this.transactionHeadroom()")}
84
84
 
85
85
  if (args.op === "insert") {
86
86
  const id = await writer.insert(args.table, args.doc ?? {});
@@ -135,7 +135,7 @@ ${p("headroom ?? this.transactionHeadroom()")}
135
135
  protected override async runShardExport(args: RunShardExportArgs): Promise<ExportRow[]> {
136
136
  this.ensureMigrated();
137
137
 
138
- ${p()}
138
+ ${m()}
139
139
 
140
140
  const rows: ExportRow[] = [];
141
141
 
@@ -152,7 +152,7 @@ ${p()}
152
152
  protected override async runShardImport(args: RunShardImportArgs): Promise<ImportShardResult> {
153
153
  this.ensureMigrated();
154
154
 
155
- ${p()}
155
+ ${m()}
156
156
 
157
157
  // \`importShardRows\` inserts with \`allowExplicitId\`, so a source
158
158
  // database's \`_id\`s carry across verbatim and every foreign key
@@ -163,7 +163,7 @@ ${p()}
163
163
  protected override async runShardRankBefore(args: RunShardRankBeforeArgs): Promise<{ before: number; total: number }> {
164
164
  this.ensureMigrated();
165
165
 
166
- ${p()}
166
+ ${m()}
167
167
 
168
168
  // \`rankBefore\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
169
169
  // but the shard writer from \`createShardCtxDb\` always defines it.
@@ -181,7 +181,7 @@ ${p()}
181
181
  protected override async runShardFindRelated(args: RunShardFindRelatedArgs): Promise<RelatedPage> {
182
182
  this.ensureMigrated();
183
183
 
184
- ${p()}
184
+ ${m()}
185
185
 
186
186
  // \`related\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
187
187
  // but the shard writer from \`createShardCtxDb\` always defines it — it
@@ -199,7 +199,7 @@ ${p()}
199
199
  protected override async runShardRankPage(args: RunShardRankPageArgs): Promise<ShardRankPageResult> {
200
200
  this.ensureMigrated();
201
201
 
202
- ${p()}
202
+ ${m()}
203
203
 
204
204
  // \`rankPageRows\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
205
205
  // but the shard writer from \`createShardCtxDb\` always defines it. The sort
@@ -220,16 +220,16 @@ ${p()}
220
220
  protected override async runShardApplyCdc(args: RunShardApplyCdcArgs): Promise<{ applied: number }> {
221
221
  this.ensureMigrated();
222
222
 
223
- ${p()}
223
+ ${m()}
224
224
 
225
225
  await applyCdcChanges(writer, args.changes);
226
226
 
227
227
  return { applied: args.changes.length };
228
- }`,er=({actionOnlyBuild:n,actionOnlyFields:e,agentsBuild:t,agentsContextField:a,containersBuild:r,containersContextField:s,databaseOptions:d,everyContextBuild:m,everyContextField:f,facadeBlock:c,globalDatabaseLine:y,notifyBuild:S,ormContextField:w,paymentsBuild:C,paymentsContextField:i,queuesBuild:g,queuesContextField:I,topicsBuild:_,topicsContextField:M,vectorsBuild:A,vectorsContextField:P,workflowsBuild:N,workflowsContextField:R})=>{const l=e.length>0,O=l?`
228
+ }`,rr=({actionOnlyBuild:a,actionOnlyFields:e,agentsBuild:t,agentsContextField:n,containersBuild:r,containersContextField:s,databaseOptions:d,everyContextBuild:g,everyContextField:w,facadeBlock:c,globalDatabaseLine:y,notifyBuild:S,ormContextField:E,paymentsBuild:v,paymentsContextField:C,queuesBuild:i,queuesContextField:f,topicsBuild:L,topicsContextField:_,vectorsBuild:I,vectorsContextField:x,workflowsBuild:M,workflowsContextField:P})=>{const k=e.length>0,l=k?`
229
229
  // ActionCtx-only helpers (external, non-deterministic I/O): constructed
230
230
  // and attached only for an \`action\` so query/mutation ctx never carry them.
231
231
  if (isAction) {
232
- ${n.replaceAll(/^(?=.)/gmu," ")}${e.map(k=>` ctx.${k} = ${k};`).join(`
232
+ ${a.replaceAll(/^(?=.)/gmu," ")}${e.map(u=>` ctx.${u} = ${u};`).join(`
233
233
  `)}
234
234
  }
235
235
  `:"";return` private buildCtx(options: { bookmarks?: DispatchBookmark; functionPath?: string; headroom?: TransactionHeadroomTracker; identity?: SubscriptionIdentity; kind?: "query"; onRead?: (table: string, idOrScan?: string) => void; onReadRange?: (range: KeyRange) => void; scope?: QueryReadScope; trusted?: boolean } = {}): unknown {
@@ -253,7 +253,7 @@ ${n.replaceAll(/^(?=.)/gmu," ")}${e.map(k=>` ctx.${k} = ${k};`
253
253
  userId: this.getCurrentUserId(),
254
254
  };
255
255
  const { identity, ip, userId } = caller;
256
- ${A}${m}${r}${N}${g}${_}${t}
256
+ ${I}${g}${r}${M}${i}${L}${t}
257
257
  // Which dispatch this ctx belongs to. Drives the two deferral facades
258
258
  // below and the \`ctx.run*\` caller guard; a ctx built for an
259
259
  // admin/lifecycle path has no registered function, and so no kind. An
@@ -368,7 +368,7 @@ ${y} // \`ctx.db\`, wrapped in automatic instrumentation: by default
368
368
  // handler making hundreds of queries stays readable. See
369
369
  // \`instrumentDatabase\` for the \`"spans"\` / \`"off"\` levels.
370
370
  const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${d}), logFunctionPath, traceAnchor, observability);
371
- ${c}${C}
371
+ ${c}${v}
372
372
 
373
373
  // \`ctx.trace\` / \`ctx.metrics\`: spans and measurements to the same sink.
374
374
  // The trace anchor is threaded explicitly for the same reason \`identity\`
@@ -427,14 +427,14 @@ ${S}
427
427
  // to the handler so code that signs its own URLs (a copy-in
428
428
  // \`createStorage\`) can fall back to it too. \`undefined\` for a
429
429
  // query and for a deferred dispatch, for the reasons given there.
430
- origin: requestOrigin,${w}
430
+ origin: requestOrigin,${E}
431
431
  scheduler,
432
432
  span,
433
433
  storage: contextStorage,
434
- trace,${P}${f}${i}${s}${R}${I}${M}${a}
434
+ trace,${x}${w}${C}${s}${P}${f}${_}${n}
435
435
  };
436
- ${l?` const isAction = contextKind === "action";
437
- `:""}${O}
436
+ ${k?` const isAction = contextKind === "action";
437
+ `:""}${l}
438
438
  const installRun = (target: Record<string, unknown>, kind: typeof contextKind): void => {
439
439
  target.runAction = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("action", reference.__lunoraRef, fnArgs, target, kind);
440
440
  // The composed mutation runs under the SAME wrapper the top-level RPC
@@ -485,7 +485,7 @@ ${l?` const isAction = contextKind === "action";
485
485
 
486
486
  if (queryView === undefined) {
487
487
  const descriptors: PropertyDescriptorMap = Object.getOwnPropertyDescriptors(ctx);
488
- ${e.map(k=>` delete descriptors.${k};
488
+ ${e.map(u=>` delete descriptors.${u};
489
489
  `).join("")} // Writable and configurable, like the plain fields they replace.
490
490
  const field = (value: unknown): PropertyDescriptor => ({ configurable: true, enumerable: true, value, writable: true });
491
491
 
@@ -504,7 +504,7 @@ ${e.map(k=>` delete descriptors.${k};
504
504
  installRun(ctx, contextKind);
505
505
 
506
506
  return ctx;
507
- }`},tr=`// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
507
+ }`},ar=`// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
508
508
  // referencing call fails loudly with a clear error instead of overflowing the
509
509
  // stack. Tracked across the awaited handler chain (one DO invocation is
510
510
  // single-threaded), so the counter reflects true nesting depth.
@@ -570,7 +570,7 @@ const dispatchRun = async (
570
570
  } finally {
571
571
  runDepth -= 1;
572
572
  }
573
- };`,rr=` public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark): Promise<unknown> {
573
+ };`,nr=` public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark): Promise<unknown> {
574
574
  const registered = LUNORA_FUNCTIONS[functionPath];
575
575
 
576
576
  // Internal functions are reachable server-side only: via \`ctx.run*\`
@@ -716,7 +716,7 @@ const dispatchRun = async (
716
716
  // rows were durably gone and their objects leaked with nothing logged.
717
717
  try {
718
718
  await settleSchedules(true);
719
- } finally {
719
+ __COMMITTED_CATCH__ } finally {
720
720
  // Then the objects whose rows are now durably gone. Deliberately AFTER
721
721
  // the span, never inside it: an R2 delete cannot roll back, so a delete
722
722
  // issued from within a transaction that later aborts destroys data the
@@ -747,7 +747,7 @@ const dispatchRun = async (
747
747
  // \`ctx.scheduler\` call that reached the buffer in the first place.
748
748
  protected override scheduleOutboxScheduler(): SchedulerLike | undefined {
749
749
  return config.scheduler?.((this.env ?? {}) as Record<string, unknown>) as SchedulerLike | undefined;
750
- }`,ar=` protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
750
+ }`,sr=` protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
751
751
  const registered = LUNORA_FUNCTIONS[functionPath];
752
752
 
753
753
  if (!registered || registered.kind !== "query" || registered.visibility === "internal") {
@@ -786,7 +786,15 @@ const dispatchRun = async (
786
786
  // \`ctx.auth\` stream as nobody — or as a concurrent RPC's caller.
787
787
  iterator: (signal) => (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath, identity }), args, signal),
788
788
  };
789
- }`,nr=n=>{const e={};for(const t of n.tables){const a={};for(const[r,s]of Object.entries(t.shape)){const d=K(s);d.kind==="id"&&d.tableName!==void 0&&(a[r]=d.tableName)}Object.keys(a).length>0&&(e[t.name]=a)}return e},sr=n=>{const e={};for(const t of n.tables){const a=[];for(const[r,s]of Object.entries(t.shape))K(s).kind==="storage"&&a.push(r);a.length>0&&(e[t.name]=a)}return e},or=n=>{const e={};for(const t of n.tables){const a=[...t.indexes.map(r=>({fields:[...r.fields],name:r.name,type:"index",...r.unique===!0?{unique:!0}:{}})),...t.searchIndexes.map(r=>({fields:[r.field,...r.filterFields??[]],name:r.name,type:"search"})),...(t.geoIndexes??[]).map(r=>({fields:[r.field],name:r.name,type:"geo"})),...t.rankIndexes.map(r=>({fields:r.sortBy.map(s=>s.field),name:r.name,type:"rank"})),...t.vectorIndexes.map(r=>({fields:r.field===void 0?[]:[r.field],name:r.name,type:"vector"}))];a.length>0&&(e[t.name]=a)}return e},ir=n=>{const e=[];for(const t of n.tables)!t.ttl||t.shardMode==="global"||e.push({...t.ttl.after===void 0?{}:{after:t.ttl.after},field:t.ttl.field,...t.softDelete?{softDeleteField:t.softDelete.field}:{},table:t.name});return e},dr=n=>{if(n.kind!=="union"||n.members===void 0||n.members.length===0)return;const e=[];for(const t of n.members){if(t.kind!=="literal"||t.literalValue===void 0)return;try{const a=JSON.parse(t.literalValue);if(typeof a!="string")return;e.push(a)}catch{return}}return e},cr=(n,e,t)=>{const a=K(e),r={name:n,optional:Kt(e),type:a.kind};if(a.kind==="id"&&a.tableName!==void 0){r.ref=a.tableName;const d=t.get(n);d!==void 0&&(r.onDelete=d)}a.kind==="storage"&&(r.isStorage=!0,a.bucket!==void 0&&(r.bucket=a.bucket));const s=dr(a);return s!==void 0&&(r.enumValues=s),a.column?.notNull===!1&&(r.nullable=!0),r},lr=n=>{const e={};for(const t of n.tables){const a=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...t.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]],r=new Map(t.relations.flatMap(s=>s.kind==="one"?[[s.field,s.onDelete]]:[]));for(const[s,d]of Object.entries(t.shape))a.push(cr(s,d,r));e[t.name]=a}return e},hr=({hasMutators:n,hasShapes:e,rlsData:t})=>{const a=e?`
789
+ }`,or=` } catch (error) {
790
+ // The write committed before this failed. Mark the error so the caller can tell
791
+ // a durable write from a rollback: the rethrow still reaches the caller unchanged.
792
+ if (typeof error === "object" && error !== null) {
793
+ Object.assign(error, { committed: true });
794
+ }
795
+
796
+ throw error;
797
+ `,ir=a=>nr.replace("__COMMITTED_CATCH__",a?or:""),dr=a=>{const e={};for(const t of a.tables){const n={};for(const[r,s]of Object.entries(t.shape)){const d=K(s);d.kind==="id"&&d.tableName!==void 0&&(n[r]=d.tableName)}Object.keys(n).length>0&&(e[t.name]=n)}return e},cr=a=>{const e={};for(const t of a.tables){const n=[];for(const[r,s]of Object.entries(t.shape))K(s).kind==="storage"&&n.push(r);n.length>0&&(e[t.name]=n)}return e},lr=a=>{const e={};for(const t of a.tables){const n=[...t.indexes.map(r=>({fields:[...r.fields],name:r.name,type:"index",...r.unique===!0?{unique:!0}:{}})),...t.searchIndexes.map(r=>({fields:[r.field,...r.filterFields??[]],name:r.name,type:"search"})),...(t.geoIndexes??[]).map(r=>({fields:[r.field],name:r.name,type:"geo"})),...t.rankIndexes.map(r=>({fields:r.sortBy.map(s=>s.field),name:r.name,type:"rank"})),...t.vectorIndexes.map(r=>({fields:r.field===void 0?[]:[r.field],name:r.name,type:"vector"}))];n.length>0&&(e[t.name]=n)}return e},hr=a=>{const e=[];for(const t of a.tables)!t.ttl||t.shardMode==="global"||e.push({...t.ttl.after===void 0?{}:{after:t.ttl.after},field:t.ttl.field,...t.softDelete?{softDeleteField:t.softDelete.field}:{},table:t.name});return e},ur=a=>{if(a.kind!=="union"||a.members===void 0||a.members.length===0)return;const e=[];for(const t of a.members){if(t.kind!=="literal"||t.literalValue===void 0)return;try{const n=JSON.parse(t.literalValue);if(typeof n!="string")return;e.push(n)}catch{return}}return e},pr=(a,e,t)=>{const n=K(e),r={name:a,optional:Qt(e),type:n.kind};if(n.kind==="id"&&n.tableName!==void 0){r.ref=n.tableName;const d=t.get(a);d!==void 0&&(r.onDelete=d)}n.kind==="storage"&&(r.isStorage=!0,n.bucket!==void 0&&(r.bucket=n.bucket));const s=ur(n);return s!==void 0&&(r.enumValues=s),n.column?.notNull===!1&&(r.nullable=!0),r},mr=a=>{const e={};for(const t of a.tables){const n=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...t.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]],r=new Map(t.relations.flatMap(s=>s.kind==="one"?[[s.field,s.onDelete]]:[]));for(const[s,d]of Object.entries(t.shape))n.push(pr(s,d,r));e[t.name]=n}return e},gr=({hasMutators:a,hasShapes:e,rlsData:t})=>{const n=e?`
790
798
  protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined {
791
799
  const shape = LUNORA_SHAPES[name];
792
800
 
@@ -853,11 +861,11 @@ const dispatchRun = async (
853
861
  `:"",r=e?[...new Set(t.policies.filter(c=>c.on==="read"&&c.table!=="").map(c=>c.table))].toSorted((c,y)=>c.localeCompare(y)):[],s=r.length>0?`
854
862
  /** Refuses to boot a shape that would replicate around the read policies its table is governed by (\`defineShape({ use })\` is how a shape opts in; \`use: []\` acknowledges an ungoverned one). */
855
863
  assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(r)}, (schema as unknown as { rlsMode?: string }).rlsMode === "required");
856
- `:"";return{customMutatorOverride:n?`
864
+ `:"";return{customMutatorOverride:a?`
857
865
  protected override isCustomMutator(functionPath: string): boolean {
858
866
  return LUNORA_MUTATOR_PATHS.has(functionPath);
859
867
  }
860
- `:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:s,shapeReadPolicyImport:s===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:a}},ur=(n,e)=>n?`
868
+ `:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:s,shapeReadPolicyImport:s===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:n}},fr=(a,e)=>a?`
861
869
  protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: SubscriptionIdentity): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
862
870
  const env = this.env as Record<string, unknown>;
863
871
  // A shape read performs no writes, so the widened request only needs
@@ -916,7 +924,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(r)}, (schema as
916
924
 
917
925
  return globalDb.cdcChangedTables?.(sinceSeq, { cursorOnly });
918
926
  }
919
- `:"",pr=n=>({externalSourceOverride:n?`
927
+ `:"",br=a=>({externalSourceOverride:a?`
920
928
  protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
921
929
  const env = (this.env ?? {}) as Record<string, unknown>;
922
930
  const sourced = Object.entries((schema as unknown as SchemaLike).tables)
@@ -1056,7 +1064,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(r)}, (schema as
1056
1064
 
1057
1065
  return nextDueAt;
1058
1066
  }
1059
- `:"",sourceBootstrap:n?`
1067
+ `:"",sourceBootstrap:a?`
1060
1068
  const autoSourced = Object.values((schema as unknown as SchemaLike).tables).some((definition) => {
1061
1069
  const source = (definition as { externalSource?: ExternalSourceLike }).externalSource;
1062
1070
 
@@ -1066,11 +1074,11 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(r)}, (schema as
1066
1074
  if (autoSourced) {
1067
1075
  void this.scheduleSourcePoll();
1068
1076
  }
1069
- `:"",sourceClientCacheConst:n?`
1077
+ `:"",sourceClientCacheConst:a?`
1070
1078
  const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
1071
1079
  const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1072
- `:""}),mr=(n,e)=>{const t=e.length>0,r=n?L("vectorsStub: VectorSearchLike","ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().",["deleteByIds","getByIds","query","upsert","upsertMany","upsertNow"]):"",s=t?` const vectorShardKey = this.currentShardKey();
1073
- `:"",d=t?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",f=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...t?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${e.map(S=>JSON.stringify(S)).join(", ")}]`]:[]].join(", ")} }`,c=n?`
1080
+ `:""}),wr=(a,e)=>{const t=e.length>0,r=a?T("vectorsStub: VectorSearchLike","ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().",["deleteByIds","getByIds","query","upsert","upsertMany","upsertNow"]):"",s=t?` const vectorShardKey = this.currentShardKey();
1081
+ `:"",d=t?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",w=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...t?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${e.map(S=>JSON.stringify(S)).join(", ")}]`]:[]].join(", ")} }`,c=a?`
1074
1082
  const vectorSync = this.vectorSync(env);
1075
1083
  // Vectorize lives outside this shard's SQLite, so a query whose result
1076
1084
  // depends on a similarity search cannot be proven current on reconnect —
@@ -1080,14 +1088,14 @@ const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1080
1088
  const bareVectors = vectorSync?.vectors ?? vectorsStub;
1081
1089
  const vectors = markUnvouchableReads(bareVectors, options.onRead, ["getByIds", "query"]);
1082
1090
  const onWrite = vectorSync?.onWrite;
1083
- `:"";return{vectorSyncMethod:n?`
1091
+ `:"";return{vectorSyncMethod:a?`
1084
1092
  private vectorSync(env: Record<string, unknown>): { backfill: VectorBackfillSync; onWrite: WriteHook; vectors: VectorSearchLike } | undefined {
1085
1093
  if (!config.vectors) {
1086
1094
  return undefined;
1087
1095
  }
1088
1096
 
1089
1097
  const lunora = createVectors({ indexes: config.vectors(env) });
1090
- ${s} const vectors = createContextVectors(lunora${f});
1098
+ ${s} const vectors = createContextVectors(lunora${w});
1091
1099
 
1092
1100
  return {
1093
1101
  backfill: createVectorBackfillSync({ ${d}schema: schema as unknown as VectorSchemaLike, upsertMany: lunora.upsertMany, vectors }),
@@ -1113,14 +1121,14 @@ ${s} const vectors = createContextVectors(lunora${f});
1113
1121
  ordered: async (read, work) => this.runOrderedAfterWrites(read, work),
1114
1122
  });
1115
1123
  }
1116
- `:"",vectorsBuild:c,vectorsStub:r}},Dr=({advisories:n=[],advisorProcedures:e=[],agents:t=[],capabilities:a=new Set,containers:r=[],env:s,flagKeys:d=[],hasFlags:m=!1,hasNotify:f=!1,hasVectors:c=!0,maskMetadata:y,mutators:S=[],queues:w=[],rlsMetadata:C,schema:i,schemaSnapshot:g,shapes:I=[],storageRules:_,studioFeatures:M,services:A=[],topics:P=[],useUmbrella:N=!1,workflows:R=[]})=>{const l=Qt(N),O=S.length>0,v=I.length>0,k=g===void 0?"":xt(g),re=g===void 0?"":`
1124
+ `:"",vectorsBuild:c,vectorsStub:r}},Lr=({advisories:a=[],advisorProcedures:e=[],agents:t=[],capabilities:n=new Set,containers:r=[],env:s,flagKeys:d=[],hasFlags:g=!1,hasNotify:w=!1,hasRooms:c=!1,hasVectors:y=!0,maskMetadata:S,mutators:E=[],queues:v=[],rlsMetadata:C,schema:i,schemaSnapshot:f,shapes:L=[],storageRules:_,studioFeatures:I,services:x=[],topics:M=[],useUmbrella:P=!1,workflows:k=[]})=>{const l=Jt(P),N=E.length>0,u=L.length>0,re=f===void 0?"":Ot(f),ae=f===void 0?"":`
1117
1125
  /** 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. */
1118
- const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(At(g))}, json: ${JSON.stringify(k)} };
1119
- `,ae=g===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",b=Et(a),D=Lt(m,l.flags),$=Ct(d,m,l.flags),q=Vt(f),F=It(s),{build:ne,contextField:se,importLines:oe,specs:ie}=_t(zt(w)),{build:de,contextField:ce,importLines:le,specs:he}=Mt(P,w),U=Pt(A,l.server),{build:ue,contextField:pe,importLines:me,specs:ge}=Nt(r,i.jurisdiction),{build:be,contextField:fe,importLines:ye,specs:we}=$t(R),{build:ve,contextField:ke,importLines:Se,specs:Re}=qt(t),{build:xe,configField:Ae,contextField:Oe,imports:De,stub:Te}=Ft(a.has("payments")),Ee=n,{advisoryRules:Le,advisoryRows:Ce}=Yt(Ee),Ie=e,G=C??{policies:[],roles:[]},_e=y??{columns:[]},Me=_??{rules:[]},Pe=M??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,privacy:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:Ne,override:$e}=Ut(R),{constant:qe,override:Fe}=Bt(w),u=c&&i.vectorIndexes.length>0,B=new Set(i.tables.filter(o=>Jt(o)).map(o=>o.name)),Q=u&&i.vectorIndexes.some(o=>B.has(o.table)),x=i.tables.some(o=>o.shardMode==="global"),W=Wt(B),j=i.tables.some(o=>Ot(o)),z=i.tables.some(o=>Dt(o)),T=i.tables.some(o=>o.externalSource!==void 0),J=i.tables.some(o=>o.memory===!0),H=i.tables.some(o=>o.shardMode!=="global"&&o.searchIndexes.length>0);if(z&&j)throw new Rt("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const V=i.tables.length>0,Ue=nr(i),Be=or(i),We=lr(i),je=sr(i),Y=ir(i),X=jt(u,R.length>0,w.length>0,m,H);v&&X.push("WhereInput");const Z=Ht(x),{customMutatorOverride:He,shapeGuardImport:Ve,shapeReadPolicyAssertion:Ke,shapeReadPolicyImport:Ge,shapeResolveOverride:Qe}=hr({hasMutators:O,hasShapes:v,rlsData:G}),E=[`import type { ${X.join(", ")} } from "${l.do}";`,`import { applyCdcChanges, createStableIdFactory, ${H?"backfillSearchIndexes, ":""}${u?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${J?"clearMemoryTables, ":""}${Ve}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${T?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${Q?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${Z.importFragment}ShardDO as ShardDOBase } from "${l.do}";`,...T?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${l.do}";`]:[],v?`import { asBucketStorage, ${Ge}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`];V&&E.push(`import { bindOrm, bindTableFacade } from "${l.server}";`),u&&E.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),E.push(...b.importLines,...D.importLines,...q.importLines,...F.importLines,...me,...ye,...oe,...le,...U.importLines,...Se,...De,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...O?["LUNORA_MUTATOR_PATHS"]:[],...v?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const ze=u?`
1120
- vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",Je=z?`
1121
- d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",Ye=j?`
1122
- hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Xe=T?`
1123
- sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",Ze="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",et="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",tt="ctx.storage: no storage configured. Pass `storage` to createShardDO().",rt=x?L("globalDbStub: DatabaseWriterLike",Ze,["aggregate","count","delete","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:at,vectorsBuild:nt,vectorsStub:st}=mr(u,Q?i.vectorIndexes.filter(o=>B.has(o.table)).map(o=>o.name):[]),ot=`{
1126
+ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(Dt(f))}, json: ${JSON.stringify(re)} };
1127
+ `,ne=f===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",b=Lt(n),A=_t(g,l.flags),$=It(d,g,l.flags),q=Gt(w),F=Mt(s),{build:se,contextField:oe,importLines:ie,specs:de}=Pt(Yt(v)),{build:ce,contextField:le,importLines:he,specs:ue}=Nt(M,v),U=$t(x,l.server),{build:pe,contextField:me,importLines:ge,specs:fe}=qt(r,i.jurisdiction),{build:be,contextField:we,importLines:ye,specs:ve}=Ft(k),{build:ke,contextField:Se,importLines:Re,specs:xe}=Ut(t),{build:Ae,configField:Oe,contextField:De,imports:Te,stub:Ee}=Bt(n.has("payments")),Ce=a,{advisoryRules:Le,advisoryRows:_e}=Zt(Ce),Ie=e,G=C??{policies:[],roles:[]},Me=S??{columns:[]},Pe=_??{rules:[]},Ne=I??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,privacy:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:$e,override:qe}=Wt(k),{constant:Fe,override:Ue}=jt(v),p=y&&i.vectorIndexes.length>0,B=new Set(i.tables.filter(o=>Xt(o)).map(o=>o.name)),Q=p&&i.vectorIndexes.some(o=>B.has(o.table)),R=i.tables.some(o=>o.shardMode==="global"),W=Ht(B),j=i.tables.some(o=>Tt(o)),z=i.tables.some(o=>Et(o)),O=i.tables.some(o=>o.externalSource!==void 0),J=i.tables.some(o=>o.memory===!0),H=i.tables.some(o=>o.shardMode!=="global"&&o.searchIndexes.length>0);if(z&&j)throw new At("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const V=i.tables.length>0,Be=dr(i),We=lr(i),je=mr(i),He=cr(i),Y=hr(i),X=Vt(p,k.length>0,v.length>0,g,H);u&&X.push("WhereInput");const Z=Kt(R),{customMutatorOverride:Ve,shapeGuardImport:Ke,shapeReadPolicyAssertion:Ge,shapeReadPolicyImport:Qe,shapeResolveOverride:ze}=gr({hasMutators:N,hasShapes:u,rlsData:G}),D=[`import type { ${X.join(", ")} } from "${l.do}";`,`import { applyCdcChanges, createStableIdFactory, ${H?"backfillSearchIndexes, ":""}${p?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${J?"clearMemoryTables, ":""}${Ke}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${O?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${Q?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${Z.importFragment}ShardDO as ShardDOBase } from "${l.do}";`,...O?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${l.do}";`]:[],u?`import { asBucketStorage, ${Qe}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`];V&&D.push(`import { bindOrm, bindTableFacade } from "${l.server}";`),p&&D.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),D.push(...b.importLines,...A.importLines,...q.importLines,...F.importLines,...ge,...ye,...ie,...he,...U.importLines,...Re,...Te,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...N?["LUNORA_MUTATOR_PATHS"]:[],...c?["LUNORA_ROOMS"]:[],...u?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const Je=p?`
1128
+ vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",Ye=z?`
1129
+ d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",Xe=j?`
1130
+ hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Ze=O?`
1131
+ sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",et="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",tt="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",rt="ctx.storage: no storage configured. Pass `storage` to createShardDO().",at=R?T("globalDbStub: DatabaseWriterLike",et,["aggregate","count","delete","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:nt,vectorsBuild:st,vectorsStub:ot}=wr(p,Q?i.vectorIndexes.filter(o=>B.has(o.table)).map(o=>o.name):[]),it=`{
1124
1132
  ...this.ctxDbTuning(),
1125
1133
  auth: { identity: identity ?? null, userId: userId ?? null },
1126
1134
  broadcast: (delta) => {
@@ -1158,7 +1166,7 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
1158
1166
  // Left \`undefined\` when there is no scope so \`createShardCtxDb\`
1159
1167
  // keeps its own "degrade a provable slice to a whole-table dep"
1160
1168
  // fallback rather than reporting into a no-op.
1161
- onReadRange: options.onReadRange ?? (options.scope === undefined ? undefined : this.getCtxDbReadRangeHook(options.scope)),${u?`
1169
+ onReadRange: options.onReadRange ?? (options.scope === undefined ? undefined : this.getCtxDbReadRangeHook(options.scope)),${p?`
1162
1170
  // Vectorize is outside this shard's SQLite and cannot roll back, so
1163
1171
  // the sync is held until the mutation's transaction has COMMITTED
1164
1172
  // (\`deferAfterCommit\`) instead of running inline. Inline, a write
@@ -1170,24 +1178,28 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
1170
1178
  scheduler,
1171
1179
  schema: schema as unknown as SchemaLike,
1172
1180
  sql: this.sql as SqlExec,
1173
- storage,${x?`
1181
+ storage,${R?`
1174
1182
  globalDb,`:""}
1175
- }`,it=u?`
1176
- vectors,`:"",dt=V?`
1177
- orm: bindOrm(facade),`:"",ee=j?"config.hyperdriveGlobal":"config.d1",ct=x?` const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark(), identity, onBookmark: (bookmarkValue: string | undefined) => { if (options.bookmarks !== undefined) { options.bookmarks.value = bookmarkValue; } }, userId };
1183
+ }`,dt=p?`
1184
+ vectors,`:"",ct=V?`
1185
+ orm: bindOrm(facade),`:"",ee=j?"config.hyperdriveGlobal":"config.d1",lt=R?` const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark(), identity, onBookmark: (bookmarkValue: string | undefined) => { if (options.bookmarks !== undefined) { options.bookmarks.value = bookmarkValue; } }, userId };
1178
1186
  const globalDb: DatabaseWriterLike = ${ee}?.(env, globalRequest) ?? globalDbStub;
1179
- `:"",lt=ur(v&&x,ee),{externalSourceOverride:ht,sourceBootstrap:ut,sourceClientCacheConst:pt}=pr(T),mt=`
1187
+ `:"",ht=fr(u&&R,ee),ut=c?` protected override roomHandlerPath(topic: string): string | undefined {
1188
+ // Own properties only: a plain object would resolve \`toString\` and the like to inherited functions.
1189
+ return Object.hasOwn(LUNORA_ROOMS, topic) ? LUNORA_ROOMS[topic] : undefined;
1190
+ }
1191
+ `:"",{externalSourceOverride:pt,sourceBootstrap:mt,sourceClientCacheConst:gt}=br(O),ft=`
1180
1192
  protected override async runShardInit(): Promise<void> {
1181
1193
  this.ensureMigrated();
1182
1194
  ${J?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
1183
1195
  `:""}
1184
1196
  await this.dispatchShardInit();
1185
1197
  }
1186
- `,gt=Y.length>0?`
1198
+ `,bt=Y.length>0?`
1187
1199
  if (LUNORA_TTL_SWEEPS.length > 0) {
1188
1200
  void this.scheduleTtlSweep();
1189
1201
  }
1190
- `:"",bt=`
1202
+ `:"",wt=`
1191
1203
  public constructor(state: ShardDOState, env: unknown) {
1192
1204
  super(state, env, {
1193
1205
  // Every writer this file builds spreads the ctxDbTuning() slice —
@@ -1203,7 +1215,7 @@ ${J?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sch
1203
1215
  // exists — a trigger that fails first still flushes and fuses.
1204
1216
  ...(config.observability === undefined ? {} : { telemetrySink: () => config.observability?.((env ?? {}) as Record<string, unknown>) }),
1205
1217
  });
1206
- ${ut}${gt} }
1218
+ ${mt}${bt} }
1207
1219
 
1208
1220
  protected override isCacheableQuery(functionPath: string): boolean {
1209
1221
  // NOT \`kind === "query"\` alone. A cache hit answers without running
@@ -1227,14 +1239,14 @@ ${ut}${gt} }
1227
1239
  protected override isPaidFunction(functionPath: string): boolean {
1228
1240
  return LUNORA_FUNCTIONS[functionPath]?.x402 !== undefined;
1229
1241
  }
1230
- `,ft=V?`
1242
+ `,yt=V?`
1231
1243
  const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
1232
1244
  ${i.tables.map(o=>` facade[${JSON.stringify(o.name)}] = bindTableFacade(db, ${JSON.stringify(o.name)});`).join(`
1233
1245
  `)}
1234
- `:"",yt=`${b.everyBuild}${D.build}${F.build}
1246
+ `:"",vt=`${b.everyBuild}${A.build}${F.build}
1235
1247
  const secrets = createSecrets(env);
1236
- `,wt=`${b.everyFields}${D.contextField}${q.contextField}${F.contextField}
1237
- secrets,`,vt=q.build,kt=[...b.actionFields,...A.length>0?["services"]:[]],St=`${b.actionBuild}${U.build}`;return`${Gt}${E.join(`
1248
+ `,kt=`${b.everyFields}${A.contextField}${q.contextField}${F.contextField}
1249
+ secrets,`,St=q.build,Rt=[...b.actionFields,...x.length>0?["services"]:[]],xt=`${b.actionBuild}${U.build}`;return`${zt}${D.join(`
1238
1250
  `)}
1239
1251
 
1240
1252
  type FunctionKind = "action" | "mutation" | "query";
@@ -1244,13 +1256,13 @@ interface FunctionReference {
1244
1256
  }
1245
1257
 
1246
1258
  /** Foreign-key columns per table (\`v.id("target")\` fields) for the data browser. */
1247
- const LUNORA_TABLE_REFS = ${h(Ue,"Record<string, Record<string, string>>")};
1259
+ const LUNORA_TABLE_REFS = ${h(Be,"Record<string, Record<string, string>>")};
1248
1260
 
1249
1261
  /** Declared indexes per table (secondary, search, geo, rank, vector) for the schema viewer. */
1250
- const LUNORA_TABLE_INDEXES = ${h(Be,'Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>>')};
1262
+ const LUNORA_TABLE_INDEXES = ${h(We,'Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>>')};
1251
1263
 
1252
1264
  /** Columns per table (typed, with PK/FK markers) for the studio's schema diagram, served via \`__lunora_admin__:describeTable\`. */
1253
- const LUNORA_TABLE_COLUMNS = ${h(We,`Record<
1265
+ const LUNORA_TABLE_COLUMNS = ${h(je,`Record<
1254
1266
  string,
1255
1267
  Array<{
1256
1268
  bucket?: string;
@@ -1267,16 +1279,16 @@ const LUNORA_TABLE_COLUMNS = ${h(We,`Record<
1267
1279
  >`)};
1268
1280
 
1269
1281
  /** Storage-key columns per table (\`v.storage(...)\` fields) for the file browser's records↔files join. */
1270
- const LUNORA_STORAGE_COLUMNS = ${h(je,"Record<string, string[]>")};
1282
+ const LUNORA_STORAGE_COLUMNS = ${h(He,"Record<string, string[]>")};
1271
1283
 
1272
1284
  /** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
1273
- const LUNORA_TTL_SWEEPS = ${Tt(Y,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
1285
+ const LUNORA_TTL_SWEEPS = ${Ct(Y,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
1274
1286
 
1275
1287
  /** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
1276
1288
  const LUNORA_ADVISORY_RULES = ${h(Le,"Record<string, Partial<AdvisoryFinding>>")};
1277
1289
 
1278
1290
  /** Per-finding rows; rule-level text lives once in \`LUNORA_ADVISORY_RULES\` and is merged back on first read. */
1279
- const LUNORA_ADVISORY_ROWS = ${h(Ce,"Array<Partial<AdvisoryFinding> & { name: string }>")};
1291
+ const LUNORA_ADVISORY_ROWS = ${h(_e,"Array<Partial<AdvisoryFinding> & { name: string }>")};
1280
1292
 
1281
1293
  const LUNORA_ADVISORIES = ((): (() => AdvisoryFinding[]) => {
1282
1294
  let cached: AdvisoryFinding[] | undefined;
@@ -1288,16 +1300,16 @@ const LUNORA_ADVISOR_PROCEDURES = ${h(Ie,"AdvisorProcedure[]")};
1288
1300
 
1289
1301
  /** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
1290
1302
  const LUNORA_RLS_METADATA = ${h(G,"RlsPoliciesResult")};
1291
- ${Ke}
1303
+ ${Ge}
1292
1304
  /** Read-only masking metadata (table + column + strategy discovered from \`.use(mask(...))\` chains) served via \`__lunora_admin__:maskPolicies\` for the studio's data-browser mask preview. */
1293
- const LUNORA_MASK_METADATA = ${h(_e,"MaskPoliciesResult")};
1305
+ const LUNORA_MASK_METADATA = ${h(Me,"MaskPoliciesResult")};
1294
1306
 
1295
1307
  /** Read-only storage access-rule metadata (discovered from \`.use(storageRules(...))\` chains) served via \`__lunora_admin__:storageRules\` for the studio's access-rules view. */
1296
- const LUNORA_STORAGE_RULES = ${h(Me,"StorageRulesResult")};
1308
+ const LUNORA_STORAGE_RULES = ${h(Pe,"StorageRulesResult")};
1297
1309
 
1298
1310
  /** 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. */
1299
- const LUNORA_STUDIO_FEATURES = ${h(Pe,"StudioFeaturesResult")};
1300
- ${re}${W.constant}${$.constant}${Ne}${qe}${ge}${we}${ie}${he}${U.specs}${Re}
1311
+ const LUNORA_STUDIO_FEATURES = ${h(Ne,"StudioFeaturesResult")};
1312
+ ${ae}${W.constant}${$.constant}${$e}${Fe}${fe}${ve}${de}${ue}${U.specs}${xe}
1301
1313
  export interface ShardDOConfig {
1302
1314
  /** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
1303
1315
  cdc?: boolean;
@@ -1312,27 +1324,27 @@ export interface ShardDOConfig {
1312
1324
  /** \`unknown\` because \`@lunora/scheduler\`'s \`Scheduler\` is not assignable to \`SchedulerLike\`; the shard casts it. */
1313
1325
  scheduler?: (env: Record<string, unknown>) => unknown;
1314
1326
  /** \`origin\` is the origin the current \`/rpc\` request reached the worker on — the fallback base for signed object URLs when no \`publicBaseUrl\` is configured. \`undefined\` off the synchronous dispatch path. */
1315
- storage?: (env: Record<string, unknown>, origin?: string) => unknown;${ze}${b.configFields}${D.configField}${Ae}${Je}${Ye}${Xe}${W.configField}
1327
+ storage?: (env: Record<string, unknown>, origin?: string) => unknown;${Je}${b.configFields}${A.configField}${Oe}${Ye}${Xe}${Ze}${W.configField}
1316
1328
  }
1317
- ${L("schedulerStub",et,["cancel","runAfter","runAt"])}${L("storageStub",tt,["createMultipartUpload","delete","download","generateUploadUrl","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","list","resumeMultipartUpload","store","upload"],{sync:["getUrl","resumeMultipartUpload"]})}${rt}${pt}${st}${b.stubs}${Te}
1318
- ${tr}
1329
+ ${T("schedulerStub",tt,["cancel","runAfter","runAt"])}${T("storageStub",rt,["createMultipartUpload","delete","download","generateUploadUrl","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","list","resumeMultipartUpload","store","upload"],{sync:["getUrl","resumeMultipartUpload"]})}${at}${gt}${ot}${b.stubs}${Ee}
1330
+ ${ar}
1319
1331
 
1320
1332
  /**
1321
1333
  * Build the project's shard Durable Object. Export the result as \`ShardDO\`
1322
1334
  * from the worker entry so wrangler binds it by name.
1323
1335
  */
1324
1336
  export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase =>
1325
- class extends ShardDOBase {${bt}
1337
+ class extends ShardDOBase {${wt}
1326
1338
  private migrated = false;
1327
1339
 
1328
- ${rr}
1340
+ ${ir(c)}
1329
1341
  ${Z.override}
1330
- ${ar}
1331
- ${He}${Qe}${lt}${ht}
1342
+ ${sr}
1343
+ ${Ve}${ze}${ht}${pt}
1332
1344
  protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor" | "whisper"): readonly string[] {
1333
1345
  return LUNORA_LIFECYCLE_HOOKS[event];
1334
1346
  }
1335
- ${W.override}${mt}
1347
+ ${ut}${W.override}${ft}
1336
1348
  // One \`onQueryChange\` dispatch. Mirrors \`executeSubscription\` — the
1337
1349
  // socket-terminated half of the same reactivity — and differs only in who
1338
1350
  // consumes the result: the base's \`dispatchReactors\` stores the digest as
@@ -1420,7 +1432,7 @@ ${W.override}${mt}
1420
1432
  protected override studioFeatures(): StudioFeaturesResult {
1421
1433
  return LUNORA_STUDIO_FEATURES();
1422
1434
  }
1423
- ${$.evaluateOverride}${$.subscriptionOverride}${$e}${Fe}
1435
+ ${$.evaluateOverride}${$.subscriptionOverride}${qe}${Ue}
1424
1436
  protected override advisories(): AdvisoryFinding[] {
1425
1437
  return LUNORA_ADVISORIES();
1426
1438
  }
@@ -1429,14 +1441,14 @@ ${$.evaluateOverride}${$.subscriptionOverride}${$e}${Fe}
1429
1441
  return LUNORA_ADVISOR_PROCEDURES();
1430
1442
  }
1431
1443
 
1432
- ${Zt}
1444
+ ${tr}
1433
1445
 
1434
1446
  protected override ensureMigrated(): void {
1435
1447
  if (this.migrated) {
1436
1448
  return;
1437
1449
  }
1438
1450
 
1439
- runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${ae} });
1451
+ runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${ne} });
1440
1452
  this.migrated = true;
1441
1453
  }
1442
1454
  ${H?`
@@ -1448,7 +1460,7 @@ ${H?`
1448
1460
 
1449
1461
  return backfillSearchIndexes(this.sql as SqlExec, schema as unknown as SchemaLike, options);
1450
1462
  }
1451
- `:""}${at}
1452
- ${er({actionOnlyFields:kt,agentsBuild:ve,agentsContextField:ke,containersBuild:ue,containersContextField:pe,databaseOptions:ot,everyContextBuild:yt,everyContextField:wt,facadeBlock:ft,globalDatabaseLine:ct,notifyBuild:vt,ormContextField:dt,paymentsBuild:xe,paymentsContextField:Oe,queuesBuild:ne,queuesContextField:se,topicsBuild:de,topicsContextField:ce,vectorsBuild:nt,vectorsContextField:it,workflowsBuild:be,workflowsContextField:fe,actionOnlyBuild:St})}
1463
+ `:""}${nt}
1464
+ ${rr({actionOnlyFields:Rt,agentsBuild:ke,agentsContextField:Se,containersBuild:pe,containersContextField:me,databaseOptions:it,everyContextBuild:vt,everyContextField:kt,facadeBlock:yt,globalDatabaseLine:lt,notifyBuild:St,ormContextField:ct,paymentsBuild:Ae,paymentsContextField:De,queuesBuild:se,queuesContextField:oe,topicsBuild:ce,topicsContextField:le,vectorsBuild:st,vectorsContextField:dt,workflowsBuild:be,workflowsContextField:we,actionOnlyBuild:xt})}
1453
1465
  };
1454
- `};export{sr as b,Dr as e};
1466
+ `};export{cr as b,Lr as e};
@@ -1 +1 @@
1
- import{posix as w,dirname as h,join as F}from"node:path";import{Node as l,SyntaxKind as g,DiagnosticCategory as K}from"ts-morph";import{lunoraRelativePath as B}from"./isTestPath-B81lOULB.mjs";let p,v;const Oe=e=>{const t=p,n=[];p=n;try{return{erased:n,value:e()}}finally{p=t}},Ue=e=>{p?.push(...e)},V=e=>{for(const t of e.getAncestors())if(l.isVariableDeclaration(t))return t.getName()},E=(e,t)=>{p?.push({exportName:V(e),filePath:e.getSourceFile().getFilePath(),line:e.getStartLineNumber(),rendered:t})},Pe=e=>{v!==void 0&&E(v,e)},Le=(e,t)=>{const n=v;v=e;try{return t()}finally{v=n}},W=(e,t)=>{const n=e.exportName??`line ${e.line.toString()}`;return{cacheKey:`procedure_return_type_erased:${t}:${n}`,categories:["SCHEMA"],description:"Codegen renders a procedure's return type into `_generated/`, where only names that resolve from that directory may appear. A type it can neither name nor reproduce structurally — a class instance, a call or index signature, a recursive or very deeply nested shape — is emitted as `unknown` instead, so callers lose the shape while the runtime still returns it.",detail:`\`${n}\` in \`${t}\` (line ${e.line.toString()}) returns \`${e.rendered}\`, which codegen could not reproduce — its generated type is \`unknown\`.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,filePath:t,line:e.line,rendered:e.rendered},name:"procedure_return_type_erased",remediation:"Declare the shape explicitly with `.output(...)`, or export the type from the module that declares it so codegen can name it. A class instance cannot cross the wire at all — return a plain object.",title:"Procedure return type is missing from the generated type"}},Fe=(e,t)=>{const n=new Map;for(const r of e){const s=W(r,B(t,r.filePath));n.set(s.cacheKey,s)}return[...n.values()].toSorted((r,s)=>r.cacheKey.localeCompare(s.cacheKey))},q=/\bany\b(?!\s*(?:\?\s*)?:)/u,G=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,X=e=>q.test(e.replaceAll(G,"")),H="/_generated/",J=e=>{const t=[e.getSymbol(),e.getAliasSymbol()].flatMap(n=>n?.getDeclarations()??[]);return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},Y=/^(?<quote>["'])(?<specifier>.*)\k<quote>$/su,x=e=>{for(const t of e.getAncestors())if(l.isModuleDeclaration(t)){const n=Y.exec(t.getName());if(n?.groups?.specifier!==void 0)return n.groups.specifier}},M=new WeakMap,z=(e,t)=>{const n=e.getSymbol();if(n===void 0)return;let r=M.get(n.compilerSymbol);return r===void 0&&(r=new Map,M.set(n.compilerSymbol,r)),r.has(t)||r.set(t,n.getExport(t)??e.getExportSymbols().find(s=>s.getName()===t)),r.get(t)},C=(e,t)=>e.getNamespaceImport()!==void 0||e.getNamedImports().some(n=>n.getName()===t),Q=(e,t,n)=>e.getModuleSpecifierValue()===t&&C(e,n)?n:void 0,Z=(e,t)=>{const n=e.getDefaultImport();if(n===void 0)return;const r=n.getSymbol();return(r?.getAliasedSymbol()??r)?.getDeclarations().includes(t)===!0?"default":void 0},ee=(e,t,n)=>{if(!C(e,n))return;const r=e.getModuleSpecifierSourceFile(),s=r===void 0?void 0:z(r,n);return(s?.getAliasedSymbol()??s)?.getDeclarations().includes(t)===!0?n:void 0},te=/^\.\.?(?:$|\/)/u,ne=new Map([[".cjs",".cjs"],[".cts",".cjs"],[".d.ts",".js"],[".js",".js"],[".jsx",".jsx"],[".mjs",".mjs"],[".mts",".mjs"],[".ts",".js"],[".tsx",".js"]]),re=(e,t)=>{const n=t.getModuleSpecifierValue();if(!te.test(n))return;const r=t.getModuleSpecifierSourceFile(),s=r===void 0?void 0:ne.get(r.getExtension());if(r===void 0||s===void 0)return;const i=`${w.join(r.getDirectoryPath(),r.getBaseNameWithoutExtension())}${s}`,o=w.relative(e.getDirectoryPath(),i);return o.startsWith(".")?o:`./${o}`},se=(e,t,n)=>{const r=x(t);for(const s of e.getImportDeclarations()){const i=r===void 0?Z(s,t)??ee(s,t,n):Q(s,r,n);if(i!==void 0)return{exportName:i,specifier:re(e,s)??s.getModuleSpecifierValue()}}},oe=(e,t)=>Object.keys(t.getProject().getCompilerOptions().paths??{}).some(n=>{const r=n.indexOf("*");return r===-1?e===n:e.startsWith(n.slice(0,r))&&e.endsWith(n.slice(r+1))}),f={kind:"verbatim"},S={kind:"expand"},ie=new Set([g.ClassDeclaration,g.EnumDeclaration,g.EnumMember,g.InterfaceDeclaration,g.TypeAliasDeclaration]),ae=e=>x(e)!==void 0||l.isExportable(e)&&e.isExported(),ce=(e,t)=>new RegExp(String.raw`(?<![$\w])${t.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`)}(?![$\w])`,"u").test(e),O=(e,t,n,r)=>{const s=e.getSourceFile();if(s.getSymbol()===void 0&&x(e)===void 0||!ie.has(e.getKind()))return f;const i=s.getFilePath();if(i.includes(H))return f;if(i===n)return S;const o=l.isEnumMember(e)?e.getParent():e;if(!l.hasName(o))return S;const c=se(t.getSourceFile(),o,o.getName());return c===void 0?ae(o)||!ce(r(),o.getName())?f:S:oe(c.specifier,t)?S:{kind:"qualify",qualified:c}},ue=new Set([g.ClassDeclaration,g.EnumDeclaration,g.FunctionDeclaration,g.ModuleDeclaration]),_=e=>{const t=e?.getDeclarations()??[];return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},le=e=>{for(const t of e.getDeclarations()){const n=t.getFirstChildByKind(g.ComputedPropertyName);if(n!==void 0){let r=n.getExpression();for(;l.isPropertyAccessExpression(r);)r=r.getExpression();return r}}},ge=(e,t)=>{if(e.getProperties().some(s=>{if(!s.getName().startsWith("__@"))return!1;const i=le(s);return i===void 0||!_(i.getSymbol())}))return!0;const r=e.getSymbol();return r!==void 0&&r.getDeclarations().some(s=>ue.has(s.getKind()))&&!_(r)&&t().startsWith("typeof ")},U=(e,t,n)=>{const r=e.getAliasSymbol(),s=e.getSymbol(),i=new Set((r??s)?.getDeclarations());let o=!1,c;const a=()=>(c??=e.getText(t),c);for(const u of[s,r].flatMap(d=>d?.getDeclarations()??[])){const d=O(u,t,n,a);if(d.kind==="qualify"&&i.has(u))return d;o||=d.kind!=="verbatim"}return o||ge(e,a)?S:f},de=(e,t,n)=>{const r=l.isPropertySignature(e)||l.isPropertyDeclaration(e)?e.getTypeNode():void 0;if(r===void 0)return f;let s=!1;for(const i of[r,...r.getDescendantsOfKind(g.TypeReference)].filter(o=>l.isTypeReference(o))){const o=i.getTypeName().getSymbol();for(const c of(o?.getAliasedSymbol()??o)?.getDeclarations()??[]){const a=O(c,t,n,()=>i.getText());if(a.kind==="qualify")return a;s||=a.kind!=="verbatim"}}return s?S:f},fe=/^[A-Za-z_$][\w$]*$/u,me=e=>fe.test(e)?e:JSON.stringify(e),P=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},A=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0&&!e.getProperties().some(t=>t.getName().startsWith("__@")),T=(e,t,n,r=new Set)=>r.has(e)?!1:(r.add(e),U(e,t,n).kind!=="verbatim"||P(e).some(s=>T(s,t,n,r))?!0:A(e)?e.getProperties().some(s=>s.getDeclarations().some(i=>de(i,t,n).kind!=="verbatim")?!0:T(s.getTypeAtLocation(t),t,n,r)):!1),Se=(e,t)=>{const n=e.getValueDeclaration()??e.getDeclarations()[0];return n&&(l.isPropertySignature(n)||l.isPropertyDeclaration(n))&&n.hasQuestionToken()?!0:t.isUnion()&&t.getUnionTypes().some(r=>r.isUndefined())},L=(e,t)=>e!==void 0&&(A(e)||e.isString()||e.isNumber()||e.isBigInt()||e.isBoolean()||e.isLiteral()||e.isBooleanLiteral()||e.isEnumLiteral()||e.isTemplateLiteral()||e.isNull()||e.isUndefined()||e.isAny()||e.isUnknown()||e.isNever()||e.isVoid())?t:`(${t})`,pe=32,ve=8,Ee=(e,t,n,r,s,i)=>{const o=e.getArrayElementType(),c=o?i(o,t,n,r,s):void 0;if(c!==void 0)return`${L(o,c)}[]`},ye=(e,t,n,r,s,i)=>{const o=[];for(const c of e.getUnionTypes()){const a=i(c,t,n,r,s);if(a===void 0)return;o.push(a)}return o.join(" | ")},be=(e,t,n,r,s,i)=>{const o=[];for(const c of e.getIntersectionTypes()){const a=i(c,t,n,r,s);if(a===void 0)return;o.push(L(c,a))}return o.join(" & ")},Te=(e,t,n,r,s,i)=>{if(!A(e))return;const o=[];for(const c of e.getProperties()){const a=c.getTypeAtLocation(t),u=Se(c,a),d=u&&a.isUnion()?a.getUnionTypes().filter(N=>!N.isUndefined()):[a],D=[];for(const N of d){const I=i(N,t,n,r+1,s);if(I===void 0)return;D.push(I)}o.push(`${me(c.getName())}${u?"?":""}: ${D.join(" | ")}`)}return o.length>0?`{ ${o.join("; ")} }`:"{}"},Ae=e=>{const t=e.getLiteralValue();return typeof t=="string"?JSON.stringify(t):typeof t=="number"?String(t):void 0},Ne=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isClassDeclaration(t)||l.isClassExpression(t)),y=(e,t,n,r,s=new Set)=>{if(r.has(e)||s.has(e))return!1;if(n>pe)return!0;const i=new Set(r).add(e);if(P(e).some(u=>y(u,t,n+1,i,s)))return!0;const o=e.getArrayElementType();if(o!==void 0)return y(o,t,n+1,i,s);if(J(e))return s.add(e),!1;if(e.getCallSignatures().length>0||e.getConstructSignatures().length>0||[e.getSymbol(),e.getAliasSymbol()].flatMap(u=>u?.getDeclarations()??[]).some(u=>l.isClassDeclaration(u)||l.isClassExpression(u)))return!0;const a=A(e)&&e.getProperties().some(u=>y(u.getTypeAtLocation(t),t,n+1,i,s));return a||s.add(e),a},xe=(e,t,n,r,s,i,o)=>{const c=[];for(const a of t.getAliasSymbol()===void 0?t.getTypeArguments():t.getAliasTypeArguments()){const u=o(a,n,r,s+1,i);if(u===void 0)return;c.push(u)}return`import("${e.specifier}").${e.exportName}${c.length>0?`<${c.join(", ")}>`:""}`},De=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isEnumDeclaration(t)||l.isEnumMember(t)),m=(e,t,n,r,s)=>{if(r>ve||s.has(e))return;const i=U(e,t,n);if(i.kind==="verbatim"&&!T(e,t,n))return e.getText(t);const o=new Set(s).add(e);if(!Ne(e)){if(e.isEnumLiteral())return Ae(e);if(i.kind==="qualify"&&!De(e)){const c=xe(i.qualified,e,t,n,r,o,m);if(c!==void 0)return c}return e.isArray()?Ee(e,t,n,r,o,m):e.isUnion()?ye(e,t,n,r,o,m):e.isIntersection()?be(e,t,n,r,o,m):Te(e,t,n,r,o,m)}},R=new WeakMap,Ie=e=>{const t=R.get(e.compilerNode);if(t)return t;const n=e.getPreEmitDiagnostics().filter(r=>r.getCategory()===K.Error);return R.set(e.compilerNode,n),n},b=e=>{const t=e.getMessageText();return typeof t=="string"?t:t.getMessageText()},we=/is of type 'unknown'|on type '\{\}'/,he=e=>we.test(e),Me=/has no exported member '([^']+)'/,_e=(e,t,n,r)=>{const s=e.getSourceFile();for(const i of e.getDescendantsOfKind(g.Identifier))for(const o of i.getSymbol()?.getDeclarations()??[]){const c=o.getStart();if(o.getSourceFile()!==s||c>=n&&c<=r)continue;const a=t.find(u=>{const d=u.getStart();return d!==void 0&&d>=o.getStart()&&d<=o.getEnd()});if(a!==void 0)return b(a)}},$=e=>{const t=e.getStart(),n=e.getEnd(),r=Ie(e.getSourceFile()),s=r.find(a=>{const u=a.getStart();return u!==void 0&&u>=t&&u<=n});if(s===void 0){const a=_e(e,r,t,n);return a===void 0?void 0:{derivative:!0,message:a}}const i=b(s);if(!he(i))return{derivative:!1,message:i};const o=new Set(e.getDescendantsOfKind(g.Identifier).map(a=>a.getText())),c=r.find(a=>{const u=Me.exec(b(a))?.[1];return u!==void 0&&o.has(u)});return{derivative:!0,message:c?`${i}; caused by: ${b(c)}`:i}},Re=e=>{const t=e.getProject().getFileSystem();let n=h(e.getFilePath());for(;;){const r=F(n,"package.json");if(t.fileExistsSync(r)){const{name:i}=JSON.parse(t.readFileSync(r));return typeof i=="string"?i:void 0}const s=h(n);if(s===n)return;n=s}},k=e=>{const t=e.getSymbol()??e.getAliasSymbol(),n=t?.getName()==="SseEvent"?t.getDeclarations()[0]:void 0;return n!==void 0&&Re(n.getSourceFile())==="@lunora/server"},$e=e=>{const t=e.isUnion()?e.getUnionTypes():[e];if(t.some(n=>k(n)))return t.flatMap(n=>{const r=k(n)?n.getTypeArguments()[0]??n:n;return r.isUnion()?r.getUnionTypes():[r]})},j=(e,t)=>{const n=e.getText(t);if(!n||n==="any"||n==="never"||n==="unknown"){const s=$(t);return s!==void 0&&(n!=="unknown"||s.derivative)&&E(t,`${n||"any"} (${s.message})`),"unknown"}if(X(n)){const s=$(t);return s!==void 0&&E(t,`${n} (${s.message})`),"unknown"}if(y(e,t,0,new Set))return"unknown";const r=t.getSourceFile().getFilePath();if(T(e,t,r)){const s=m(e,t,r,0,new Set);return s===void 0&&E(t,n),s??"unknown"}return n},Ke=(e,t=!1)=>{const n=e.getType().getCallSignatures()[0];if(!n)return"unknown";let r=n.getReturnType();const i=(r.getSymbol()??r.getAliasSymbol())?.getName();if(i==="Promise"||i==="AsyncIterable"||i==="AsyncIterableIterator"||i==="AsyncGenerator"){const a=r.getTypeArguments()[0];a&&(r=a)}const o=t?$e(r):void 0;if(o===void 0)return j(r,e);const c=o.map(a=>j(a,e));return c.includes("unknown")?"unknown":[...new Set(c)].join(" | ")};export{T as a,Pe as b,Oe as c,Fe as d,m as e,X as i,Le as p,Ue as r,Ke as u};
1
+ import{posix as h,dirname as w,join as F}from"node:path";import{Node as l,SyntaxKind as g,DiagnosticCategory as K}from"ts-morph";import{lunoraRelativePath as B}from"./isTestPath-B81lOULB.mjs";let v,S;const Oe=e=>{const t=v,n=[];v=n;try{return{erased:n,value:e()}}finally{v=t}},Ue=e=>{v?.push(...e)},V=e=>{for(const t of e.getAncestors())if(l.isVariableDeclaration(t))return t.getName()},y=(e,t)=>{v?.push({exportName:V(e),filePath:e.getSourceFile().getFilePath(),line:e.getStartLineNumber(),rendered:t})},Pe=e=>{S!==void 0&&y(S,e)},Le=(e,t)=>{const n=S;S=e;try{return t()}finally{S=n}},W=(e,t)=>{const n=e.exportName??`line ${e.line.toString()}`;return{cacheKey:`procedure_return_type_erased:${t}:${n}`,categories:["SCHEMA"],description:"Codegen renders a procedure's return type into `_generated/`, where only names that resolve from that directory may appear. A type it can neither name nor reproduce structurally — a class instance, a call or index signature, a recursive or very deeply nested shape — is emitted as `unknown` instead, so callers lose the shape while the runtime still returns it.",detail:`\`${n}\` in \`${t}\` (line ${e.line.toString()}) returns \`${e.rendered}\`, which codegen could not reproduce — its generated type is \`unknown\`.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,filePath:t,line:e.line,rendered:e.rendered},name:"procedure_return_type_erased",remediation:"Declare the shape explicitly with `.output(...)`, or export the type from the module that declares it so codegen can name it. A class instance cannot cross the wire at all — return a plain object.",title:"Procedure return type is missing from the generated type"}},Fe=(e,t)=>{const n=new Map;for(const r of e){const s=W(r,B(t,r.filePath));n.set(s.cacheKey,s)}return[...n.values()].toSorted((r,s)=>r.cacheKey.localeCompare(s.cacheKey))},q=/\bany\b(?!\s*(?:\?\s*)?:)/u,G=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,X=e=>q.test(e.replaceAll(G,"")),H="/_generated/",J=e=>{const t=[e.getSymbol(),e.getAliasSymbol()].flatMap(n=>n?.getDeclarations()??[]);return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},Y=/^(?<quote>["'])(?<specifier>.*)\k<quote>$/su,x=e=>{for(const t of e.getAncestors())if(l.isModuleDeclaration(t)){const n=Y.exec(t.getName());if(n?.groups?.specifier!==void 0)return n.groups.specifier}},M=new WeakMap,z=(e,t)=>{const n=e.getSymbol();if(n===void 0)return;let r=M.get(n.compilerSymbol);return r===void 0&&(r=new Map,M.set(n.compilerSymbol,r)),r.has(t)||r.set(t,n.getExport(t)??e.getExportSymbols().find(s=>s.getName()===t)),r.get(t)},C=(e,t)=>e.getNamespaceImport()!==void 0||e.getNamedImports().some(n=>n.getName()===t),Q=(e,t,n)=>e.getModuleSpecifierValue()===t&&C(e,n)?n:void 0,Z=(e,t)=>{const n=e.getDefaultImport();if(n===void 0)return;const r=n.getSymbol();return(r?.getAliasedSymbol()??r)?.getDeclarations().includes(t)===!0?"default":void 0},ee=(e,t,n)=>{if(!C(e,n))return;const r=e.getModuleSpecifierSourceFile(),s=r===void 0?void 0:z(r,n);return(s?.getAliasedSymbol()??s)?.getDeclarations().includes(t)===!0?n:void 0},te=/^\.\.?(?:$|\/)/u,ne=new Map([[".cjs",".cjs"],[".cts",".cjs"],[".d.ts",".js"],[".js",".js"],[".jsx",".jsx"],[".mjs",".mjs"],[".mts",".mjs"],[".ts",".js"],[".tsx",".js"]]),re=(e,t)=>{const n=t.getModuleSpecifierValue();if(!te.test(n))return;const r=t.getModuleSpecifierSourceFile(),s=r===void 0?void 0:ne.get(r.getExtension());if(r===void 0||s===void 0)return;const i=`${h.join(r.getDirectoryPath(),r.getBaseNameWithoutExtension())}${s}`,o=h.relative(e.getDirectoryPath(),i);return o.startsWith(".")?o:`./${o}`},se=(e,t,n)=>{const r=x(t);for(const s of e.getImportDeclarations()){const i=r===void 0?Z(s,t)??ee(s,t,n):Q(s,r,n);if(i!==void 0)return{exportName:i,specifier:re(e,s)??s.getModuleSpecifierValue()}}},oe=(e,t)=>Object.keys(t.getProject().getCompilerOptions().paths??{}).some(n=>{const r=n.indexOf("*");return r===-1?e===n:e.startsWith(n.slice(0,r))&&e.endsWith(n.slice(r+1))}),f={kind:"verbatim"},p={kind:"expand"},ie=new Set([g.ClassDeclaration,g.EnumDeclaration,g.EnumMember,g.InterfaceDeclaration,g.TypeAliasDeclaration]),ae=e=>x(e)!==void 0||l.isExportable(e)&&e.isExported(),ce=(e,t)=>new RegExp(String.raw`(?<![$\w])${t.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`)}(?![$\w])`,"u").test(e),O=(e,t,n,r)=>{const s=e.getSourceFile();if(s.getSymbol()===void 0&&x(e)===void 0||!ie.has(e.getKind()))return f;const i=s.getFilePath();if(i.includes(H))return f;if(i===n)return p;const o=l.isEnumMember(e)?e.getParent():e;if(!l.hasName(o))return p;const c=se(t.getSourceFile(),o,o.getName());return c===void 0?ae(o)||!ce(r(),o.getName())?f:p:oe(c.specifier,t)?p:{kind:"qualify",qualified:c}},ue=new Set([g.ClassDeclaration,g.EnumDeclaration,g.FunctionDeclaration,g.ModuleDeclaration]),_=e=>{const t=e?.getDeclarations()??[];return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},le=e=>{for(const t of e.getDeclarations()){const n=t.getFirstChildByKind(g.ComputedPropertyName);if(n!==void 0){let r=n.getExpression();for(;l.isPropertyAccessExpression(r);)r=r.getExpression();return r}}},ge=(e,t)=>{if(e.getProperties().some(s=>{if(!s.getName().startsWith("__@"))return!1;const i=le(s);return i===void 0||!_(i.getSymbol())}))return!0;const r=e.getSymbol();return r!==void 0&&r.getDeclarations().some(s=>ue.has(s.getKind()))&&!_(r)&&t().startsWith("typeof ")},U=(e,t,n)=>{const r=e.getAliasSymbol(),s=e.getSymbol(),i=new Set((r??s)?.getDeclarations());let o=!1,c;const a=()=>(c??=e.getText(t),c);for(const u of[s,r].flatMap(d=>d?.getDeclarations()??[])){const d=O(u,t,n,a);if(d.kind==="qualify"&&i.has(u))return d;o||=d.kind!=="verbatim"}return o||ge(e,a)?p:f},de=(e,t,n)=>{const r=l.isPropertySignature(e)||l.isPropertyDeclaration(e)?e.getTypeNode():void 0;if(r===void 0)return f;let s=!1;for(const i of[r,...r.getDescendantsOfKind(g.TypeReference)].filter(o=>l.isTypeReference(o))){const o=i.getTypeName().getSymbol();for(const c of(o?.getAliasedSymbol()??o)?.getDeclarations()??[]){const a=O(c,t,n,()=>i.getText());if(a.kind==="qualify")return a;s||=a.kind!=="verbatim"}}return s?p:f},fe=/^[A-Za-z_$][\w$]*$/u,me=e=>fe.test(e)?e:JSON.stringify(e),P=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},A=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0&&!e.getProperties().some(t=>t.getName().startsWith("__@")),T=(e,t,n,r=new Set)=>r.has(e)?!1:(r.add(e),U(e,t,n).kind!=="verbatim"||P(e).some(s=>T(s,t,n,r))?!0:A(e)?e.getProperties().some(s=>s.getDeclarations().some(i=>de(i,t,n).kind!=="verbatim")?!0:T(s.getTypeAtLocation(t),t,n,r)):!1),pe=(e,t)=>{const n=e.getValueDeclaration()??e.getDeclarations()[0];return n&&(l.isPropertySignature(n)||l.isPropertyDeclaration(n))&&n.hasQuestionToken()?!0:t.isUnion()&&t.getUnionTypes().some(r=>r.isUndefined())},L=(e,t)=>e!==void 0&&(A(e)||e.isString()||e.isNumber()||e.isBigInt()||e.isBoolean()||e.isLiteral()||e.isBooleanLiteral()||e.isEnumLiteral()||e.isTemplateLiteral()||e.isNull()||e.isUndefined()||e.isAny()||e.isUnknown()||e.isNever()||e.isVoid())?t:`(${t})`,ve=32,Se=8,ye=(e,t,n,r,s,i)=>{const o=e.getArrayElementType(),c=o?i(o,t,n,r,s):void 0;if(c!==void 0)return`${L(o,c)}[]`},Ee=(e,t,n,r,s,i)=>{const o=[];for(const c of e.getUnionTypes()){const a=i(c,t,n,r,s);if(a===void 0)return;o.push(a)}return o.join(" | ")},be=(e,t,n,r,s,i)=>{const o=[];for(const c of e.getIntersectionTypes()){const a=i(c,t,n,r,s);if(a===void 0)return;o.push(L(c,a))}return o.join(" & ")},Te=(e,t,n,r,s,i)=>{if(!A(e))return;const o=[];for(const c of e.getProperties()){const a=c.getTypeAtLocation(t),u=pe(c,a),d=u&&a.isUnion()?a.getUnionTypes().filter(N=>!N.isUndefined()):[a],D=[];for(const N of d){const I=i(N,t,n,r+1,s);if(I===void 0)return;D.push(I)}o.push(`${me(c.getName())}${u?"?":""}: ${D.join(" | ")}`)}return o.length>0?`{ ${o.join("; ")} }`:"{}"},Ae=e=>{const t=e.getLiteralValue();return typeof t=="string"?JSON.stringify(t):typeof t=="number"?String(t):void 0},Ne=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isClassDeclaration(t)||l.isClassExpression(t)),E=(e,t,n,r,s=new Set)=>{if(r.has(e)||s.has(e))return!1;if(n>ve)return!0;const i=new Set(r).add(e);if(P(e).some(u=>E(u,t,n+1,i,s)))return!0;const o=e.getArrayElementType();if(o!==void 0)return E(o,t,n+1,i,s);if(J(e))return s.add(e),!1;if(e.getCallSignatures().length>0||e.getConstructSignatures().length>0||[e.getSymbol(),e.getAliasSymbol()].flatMap(u=>u?.getDeclarations()??[]).some(u=>l.isClassDeclaration(u)||l.isClassExpression(u)))return!0;const a=A(e)&&e.getProperties().some(u=>E(u.getTypeAtLocation(t),t,n+1,i,s));return a||s.add(e),a},xe=(e,t,n,r,s,i,o)=>{const c=[];for(const a of t.getAliasSymbol()===void 0?t.getTypeArguments():t.getAliasTypeArguments()){const u=o(a,n,r,s+1,i);if(u===void 0)return;c.push(u)}return`import("${e.specifier}").${e.exportName}${c.length>0?`<${c.join(", ")}>`:""}`},De=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isEnumDeclaration(t)||l.isEnumMember(t)),m=(e,t,n,r,s)=>{if(r>Se||s.has(e))return;const i=U(e,t,n);if(i.kind==="verbatim"&&!T(e,t,n))return e.getText(t);const o=new Set(s).add(e);if(!Ne(e)){if(e.isEnumLiteral())return Ae(e);if(i.kind==="qualify"&&!De(e)){const c=xe(i.qualified,e,t,n,r,o,m);if(c!==void 0)return c}return e.isArray()?ye(e,t,n,r,o,m):e.isUnion()?Ee(e,t,n,r,o,m):e.isIntersection()?be(e,t,n,r,o,m):Te(e,t,n,r,o,m)}},R=new WeakMap,Ie=e=>{const t=R.get(e.compilerNode);if(t)return t;const n=e.getPreEmitDiagnostics().filter(r=>r.getCategory()===K.Error);return R.set(e.compilerNode,n),n},b=e=>{const t=e.getMessageText();return typeof t=="string"?t:t.getMessageText()},he=/is of type 'unknown'|on type '\{\}'/,we=e=>he.test(e),Me=/has no exported member '([^']+)'/,_e=(e,t,n,r)=>{const s=e.getSourceFile();for(const i of e.getDescendantsOfKind(g.Identifier))for(const o of i.getSymbol()?.getDeclarations()??[]){const c=o.getStart();if(o.getSourceFile()!==s||c>=n&&c<=r)continue;const a=t.find(u=>{const d=u.getStart();return d!==void 0&&d>=o.getStart()&&d<=o.getEnd()});if(a!==void 0)return b(a)}},$=e=>{const t=e.getStart(),n=e.getEnd(),r=Ie(e.getSourceFile()),s=r.find(a=>{const u=a.getStart();return u!==void 0&&u>=t&&u<=n});if(s===void 0){const a=_e(e,r,t,n);return a===void 0?void 0:{derivative:!0,message:a}}const i=b(s);if(!we(i))return{derivative:!1,message:i};const o=new Set(e.getDescendantsOfKind(g.Identifier).map(a=>a.getText())),c=r.find(a=>{const u=Me.exec(b(a))?.[1];return u!==void 0&&o.has(u)});return{derivative:!0,message:c?`${i}; caused by: ${b(c)}`:i}},Re=e=>{const t=e.getProject().getFileSystem();let n=w(e.getFilePath());for(;;){const r=F(n,"package.json");if(t.fileExistsSync(r)){let i;try{i=JSON.parse(t.readFileSync(r))}catch{return}const o=typeof i=="object"&&i!==null?i.name:void 0;return typeof o=="string"?o:void 0}const s=w(n);if(s===n)return;n=s}},k=e=>{const t=e.getSymbol()??e.getAliasSymbol(),n=t?.getName()==="SseEvent"?t.getDeclarations()[0]:void 0;return n!==void 0&&Re(n.getSourceFile())==="@lunora/server"},$e=e=>{const t=e.isUnion()?e.getUnionTypes():[e];if(t.some(n=>k(n)))return t.flatMap(n=>{const r=k(n)?n.getTypeArguments()[0]??n:n;return r.isUnion()?r.getUnionTypes():[r]})},j=(e,t)=>{const n=e.getText(t);if(!n||n==="any"||n==="never"||n==="unknown"){const s=$(t);return s!==void 0&&(n!=="unknown"||s.derivative)&&y(t,`${n||"any"} (${s.message})`),"unknown"}if(X(n)){const s=$(t);return s!==void 0&&y(t,`${n} (${s.message})`),"unknown"}if(E(e,t,0,new Set))return"unknown";const r=t.getSourceFile().getFilePath();if(T(e,t,r)){const s=m(e,t,r,0,new Set);return s===void 0&&y(t,n),s??"unknown"}return n},Ke=(e,t=!1)=>{const n=e.getType().getCallSignatures()[0];if(!n)return"unknown";let r=n.getReturnType();const i=(r.getSymbol()??r.getAliasSymbol())?.getName();if(i==="Promise"||i==="AsyncIterable"||i==="AsyncIterableIterator"||i==="AsyncGenerator"){const a=r.getTypeArguments()[0];a&&(r=a)}const o=t?$e(r):void 0;if(o===void 0)return j(r,e);const c=o.map(a=>j(a,e));return c.includes("unknown")?"unknown":[...new Set(c)].join(" | ")};export{T as a,Pe as b,Oe as c,Fe as d,m as e,X as i,Le as p,Ue as r,Ke as u};