@lunora/codegen 1.0.0-alpha.400 → 1.0.0-alpha.402

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 (80) hide show
  1. package/dist/index.d.mts +86 -1
  2. package/dist/index.d.ts +86 -1
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/{AGENTS_FILENAME-Cli3X44r.mjs → AGENTS_FILENAME-BiSJTXnu.mjs} +1 -1
  5. package/dist/packem_shared/{ALL_NOTIFY_CHANNELS-D1SaOfnm.mjs → ALL_NOTIFY_CHANNELS-_xAn-jI3.mjs} +1 -1
  6. package/dist/packem_shared/{CONTAINERS_FILENAME-BX1_ALLp.mjs → CONTAINERS_FILENAME-Bj3hFBa-.mjs} +1 -1
  7. package/dist/packem_shared/DEFAULT_TARGET-BfJ7upI0.mjs +1 -0
  8. package/dist/packem_shared/{FLAGS_FILENAME-DY3yo1u_.mjs → FLAGS_FILENAME-BW7MzS9C.mjs} +1 -1
  9. package/dist/packem_shared/{GENERATED_HEADER-B-tYRlRG.mjs → GENERATED_HEADER-DgrhC3Iv.mjs} +1 -1
  10. package/dist/packem_shared/{LUNORA_ERROR_CODES-CjACC-MQ.mjs → LUNORA_ERROR_CODES-D7AVT7qF.mjs} +1 -1
  11. package/dist/packem_shared/{MUTATORS_FILENAME-Ck_l1lz7.mjs → MUTATORS_FILENAME-tPpN_a00.mjs} +1 -1
  12. package/dist/packem_shared/{OPENRPC_VERSION-Dr6Xjldk.mjs → OPENRPC_VERSION-DI_G2H0Q.mjs} +1 -1
  13. package/dist/packem_shared/{QUEUES_FILENAME-C5xotY-M.mjs → QUEUES_FILENAME-Cpp-0QI9.mjs} +1 -1
  14. package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-CxmZ2igT.mjs → SCHEMA_SNAPSHOT_FILENAME-CoCuKo3b.mjs} +11 -11
  15. package/dist/packem_shared/{SHAPES_FILENAME-DCtGHMEm.mjs → SHAPES_FILENAME-cHL4n_Co.mjs} +1 -1
  16. package/dist/packem_shared/{WORKFLOWS_FILENAME-CyV1HQaP.mjs → WORKFLOWS_FILENAME-BXjKKAmj.mjs} +1 -1
  17. package/dist/packem_shared/{attribution-DjweYNgJ.mjs → attribution-C6VQNs-V.mjs} +1 -1
  18. package/dist/packem_shared/{buildOpenApiDocument-BTp9vkHw.mjs → buildOpenApiDocument-aAAsKnsY.mjs} +1 -1
  19. package/dist/packem_shared/{capabilitiesUsedBy-SSrieNZ1.mjs → capabilitiesUsedBy-t-UvdnZl.mjs} +1 -1
  20. package/dist/packem_shared/chain-BvRxehwv.mjs +1 -0
  21. package/dist/packem_shared/{classify-procedure-call-BuF5PNwV.mjs → classify-procedure-call-DwWrpCoX.mjs} +1 -1
  22. package/dist/packem_shared/companionServiceBinding-CnEUhH0Z.mjs +1 -0
  23. package/dist/packem_shared/{context-property-calls-BcUYQ6ph.mjs → context-property-calls-RsCkfFCU.mjs} +1 -1
  24. package/dist/packem_shared/{context-root-2wag3akK.mjs → context-root-CY5kkBER.mjs} +1 -1
  25. package/dist/packem_shared/{createCodegenProject-C8N4Zm8h.mjs → createCodegenProject-BC4GwdnG.mjs} +1 -1
  26. package/dist/packem_shared/{database-calls-B_85LJIk.mjs → database-calls-HP2mxQAR.mjs} +1 -1
  27. package/dist/packem_shared/{discoverAuthApiCalls-f8_WRQEA.mjs → discoverAuthApiCalls-CHytF_NH.mjs} +1 -1
  28. package/dist/packem_shared/{discoverCrons-DTqSuSDh.mjs → discoverCrons-C6Y1u_kI.mjs} +1 -1
  29. package/dist/packem_shared/discoverFunctions-B-051l15.mjs +1 -0
  30. package/dist/packem_shared/{discoverHttpRoutes-2gxHuLgt.mjs → discoverHttpRoutes-BccPlGZb.mjs} +1 -1
  31. package/dist/packem_shared/discoverHyperdriveCalls-DmUuhUoL.mjs +1 -0
  32. package/dist/packem_shared/{discoverInserts-CLh70kVu.mjs → discoverInserts-z7jg8LD3.mjs} +1 -1
  33. package/dist/packem_shared/discoverMaskProcedures-CrkT80jO.mjs +1 -0
  34. package/dist/packem_shared/{discoverMigrations-e5_NQdf-.mjs → discoverMigrations-B6u2Do9_.mjs} +1 -1
  35. package/dist/packem_shared/{discoverNondeterministicCalls-CrXAegUc.mjs → discoverNondeterministicCalls-Dei7EUFX.mjs} +1 -1
  36. package/dist/packem_shared/{discoverQueries-T8b_7ZZ-.mjs → discoverQueries-D4mihML_.mjs} +1 -1
  37. package/dist/packem_shared/discoverR2sqlCalls-Ej8oRuVk.mjs +1 -0
  38. package/dist/packem_shared/{discoverRlsMetadata-CnVvP2Ps.mjs → discoverRlsMetadata-CNn4cdfy.mjs} +1 -1
  39. package/dist/packem_shared/{discoverRlsProcedures-DttY0Jld.mjs → discoverRlsProcedures-CsczAow2.mjs} +1 -1
  40. package/dist/packem_shared/{discoverSandboxUsage-X0SECo-x.mjs → discoverSandboxUsage-EKZOCCPU.mjs} +1 -1
  41. package/dist/packem_shared/discoverSchema-BcyKCBIw.mjs +1 -0
  42. package/dist/packem_shared/{discoverStorageRulesMetadata-t_oMSn0L.mjs → discoverStorageRulesMetadata-yCB6MdrA.mjs} +1 -1
  43. package/dist/packem_shared/{emitAgents-ChXyTTzS.mjs → emitAgents-ec5ov78B.mjs} +1 -1
  44. package/dist/packem_shared/{emitApi-Cdc8MeNK.mjs → emitApi-lwadq5G7.mjs} +1 -1
  45. package/dist/packem_shared/{emitApp-xunr1-_c.mjs → emitApp-C3IUdkkt.mjs} +37 -28
  46. package/dist/packem_shared/{emitCrons-BQjDleCe.mjs → emitCrons-CCRKs482.mjs} +1 -1
  47. package/dist/packem_shared/{emitDataModel-MjAOi3KM.mjs → emitDataModel-BvCZS4Yq.mjs} +1 -1
  48. package/dist/packem_shared/{emitDrizzleSchema-Dszoyymv.mjs → emitDrizzleSchema-BzOChEYW.mjs} +1 -1
  49. package/dist/packem_shared/{emitFunctions-BIMKBLQ8.mjs → emitFunctions-ppMX7E3X.mjs} +1 -1
  50. package/dist/packem_shared/{emitServer-DNwuNiay.mjs → emitServer-DsSAaZaT.mjs} +1 -1
  51. package/dist/packem_shared/{emitShard-CueduzG1.mjs → emitShard-Dhy_F7iF.mjs} +1 -1
  52. package/dist/packem_shared/{exported-procedure-chains-BaxQ8C-S.mjs → exported-procedure-chains-DiNvW1Wl.mjs} +1 -1
  53. package/dist/packem_shared/{fingerprintSchemaSources-PmhepCVj.mjs → fingerprintSchemaSources-Cpom_87X.mjs} +1 -1
  54. package/dist/packem_shared/{handler-reference-D2EE2q-4.mjs → handler-reference-BqSXtjJ6.mjs} +1 -1
  55. package/dist/packem_shared/index-BPg6e1oa.mjs +1 -0
  56. package/dist/packem_shared/{index-Dd6T5nSP.mjs → index-DgHhQfpm.mjs} +1 -1
  57. package/dist/packem_shared/{ip-reads-WFubgB1G.mjs → ip-reads-Bn9qvrMD.mjs} +1 -1
  58. package/dist/packem_shared/isTestPath-B357_sbh.mjs +1 -0
  59. package/dist/packem_shared/loadProjectConfig-D4_s2UFp.mjs +1 -0
  60. package/dist/packem_shared/{modules-DE0ksIeR.mjs → modules-BgublqiK.mjs} +1 -1
  61. package/dist/packem_shared/project-config-file-DBVmBpin.mjs +1 -0
  62. package/dist/packem_shared/{qualifiers-ClaCHu0X.mjs → qualifiers-qqH8fRTo.mjs} +1 -1
  63. package/dist/packem_shared/{server-C4h6-BZx.mjs → server-CRFaUMKQ.mjs} +1 -1
  64. package/dist/packem_shared/{shard-DNpjvEod.mjs → shard-Csztu3jG.mjs} +57 -45
  65. package/dist/packem_shared/{shard-runtime-knn-ER8x.mjs → shard-runtime-D0xuE0pX.mjs} +1 -1
  66. package/dist/packem_shared/{shared-DhqnD5R3.mjs → shared-Cn7dMQ_u.mjs} +1 -1
  67. package/dist/packem_shared/{unwrap-handler-return-BpigsVD6.mjs → unwrap-handler-return-zNStZJ4K.mjs} +1 -1
  68. package/package.json +1 -1
  69. package/dist/packem_shared/DEFAULT_TARGET-C-gcdslJ.mjs +0 -1
  70. package/dist/packem_shared/chain-DWwd9wXd.mjs +0 -1
  71. package/dist/packem_shared/companionServiceBinding-ChINWo8k.mjs +0 -1
  72. package/dist/packem_shared/discoverFunctions-D4GIaVIP.mjs +0 -1
  73. package/dist/packem_shared/discoverHyperdriveCalls-DaJLewG0.mjs +0 -1
  74. package/dist/packem_shared/discoverMaskProcedures-C0VcUGpb.mjs +0 -1
  75. package/dist/packem_shared/discoverR2sqlCalls-CY0xmIWX.mjs +0 -1
  76. package/dist/packem_shared/discoverSchema-DDvMQheA.mjs +0 -1
  77. package/dist/packem_shared/index-fVYBrxkP.mjs +0 -1
  78. package/dist/packem_shared/isTestPath-ClgKgMYM.mjs +0 -1
  79. package/dist/packem_shared/loadProjectConfig-CtcJHHKS.mjs +0 -1
  80. package/dist/packem_shared/static-literal-BwDHHjEJ.mjs +0 -1
@@ -1,4 +1,4 @@
1
- import{AGENT_RUNTIME_FUNCTIONS as N}from"@lunora/agent/naming";import{LunoraError as R}from"@lunora/errors";import{r as d,a as w,b as P,c as L}from"./qualifiers-ClaCHu0X.mjs";import{a as A,r as y,p as $,G as x,b as k,c as m,d as S,e as O,i as T}from"./shared-DhqnD5R3.mjs";import{s as g}from"./dispatch-namespace-DwTjD7BU.mjs";const j=t=>k(t,e=>{const s=d(y(e.args),e.filePath),n=d(L(e),e.filePath),o=`FunctionReference<"${e.kind}", ${s}, ${n}>`;return`${e.exportName}: ${T(e)?`${o} & { readonly sensitive: true }`:o};`},"type"),I=(t,e)=>{if(t.length===0&&e.length===0)return{block:"",importLine:""};const s=[];let n="";if(t.length>0&&(n+="\n/** Params type carried by a `defineWorkflow` definition (its phantom `__params`). */\ntype WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params } ? (unknown extends Params ? Record<string, unknown> : Params) : Record<string, unknown>;\n"),n+=`
1
+ import{AGENT_RUNTIME_FUNCTIONS as N}from"@lunora/agent/naming";import{LunoraError as R}from"@lunora/errors";import{r as d,a as w,b as P,c as L}from"./qualifiers-qqH8fRTo.mjs";import{a as A,r as y,p as $,G as x,b as k,c as m,d as S,e as O,i as T}from"./shared-Cn7dMQ_u.mjs";import{s as g}from"./dispatch-namespace-DwTjD7BU.mjs";const j=t=>k(t,e=>{const s=d(y(e.args),e.filePath),n=d(L(e),e.filePath),o=`FunctionReference<"${e.kind}", ${s}, ${n}>`;return`${e.exportName}: ${T(e)?`${o} & { readonly sensitive: true }`:o};`},"type"),I=(t,e)=>{if(t.length===0&&e.length===0)return{block:"",importLine:""};const s=[];let n="";if(t.length>0&&(n+="\n/** Params type carried by a `defineWorkflow` definition (its phantom `__params`). */\ntype WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params } ? (unknown extends Params ? Record<string, unknown> : Params) : Record<string, unknown>;\n"),n+=`
2
2
  /** A typed reference to a durable workflow, addressable for \`cronJobs()\` targets. Mirrors \`@lunora/scheduler\`'s \`WorkflowReference\` structurally. */
3
3
  export interface WorkflowReference<Params = Record<string, unknown>> {
4
4
  readonly isLunoraWorkflow: true;
@@ -1,11 +1,11 @@
1
- import{APP_METHOD_CAPABILITIES as q}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{i as N}from"./schema-BgM8A3XV.mjs";import{a as I,I as L,G as y}from"./shared-DhqnD5R3.mjs";const j={configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},f=e=>[...q.filter(({key:r})=>e.capabilities.has(r)).map(({appMethod:r})=>r),...e.hasVectors?[j]:[]],w=e=>f(e).length>0,k=e=>(e.emailAgents?.length??0)>0,l=e=>e.tables.some(r=>N(r)),p=e=>e.liveStreams===!0&&(e.liveStreamDeclarations?.length??0)>0,$=e=>e.hasScheduler?`
1
+ import{APP_METHOD_CAPABILITIES as N}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{i as q}from"./schema-BgM8A3XV.mjs";import{a as I,I as L,G as y}from"./shared-Cn7dMQ_u.mjs";const j={configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},f=e=>[...N.filter(({key:r})=>e.capabilities.has(r)).map(({appMethod:r})=>r),...e.hasVectors?[j]:[]],w=e=>f(e).length>0,k=e=>(e.emailAgents?.length??0)>0,l=e=>e.tables.some(r=>q(r)),p=e=>e.liveStreams===!0&&(e.liveStreamDeclarations?.length??0)>0,$=e=>e.hasScheduler?`
2
2
  /** Resolve the \`SchedulerDO\`-backed scheduler for this env; \`undefined\` until the namespace is wired. */
3
3
  private resolveScheduler(env: Env): ReturnType<typeof createScheduler> | undefined {
4
4
  const namespace = this.schedulerDeclaration?.namespace(env);
5
5
 
6
6
  return namespace ? createScheduler({${e.jurisdiction?` jurisdiction: ${JSON.stringify(e.jurisdiction)},`:""} namespace }) : undefined;
7
7
  }
8
- `:"",G=e=>e?`
8
+ `:"",P=e=>e?`
9
9
  /**
10
10
  * One bucket's \`Storage\`, signing under the name it is registered as.
11
11
  *
@@ -114,7 +114,7 @@ import{APP_METHOD_CAPABILITIES as q}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";impor
114
114
  storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string; sha256?: string }) => pick(opts?.bucket).upload(key, body, opts),
115
115
  };
116
116
  }
117
- `:"",P=e=>e?`
117
+ `:"",G=e=>e?`
118
118
  /**
119
119
  * Adapt the raw D1 binding to \`@lunora/d1\`'s \`D1Exec\` (reads via \`all\`, writes via \`run\`, and — when the binding exposes it — several writes in one round trip via \`batch\`).
120
120
  *
@@ -382,7 +382,7 @@ const buildGlobalCdcApplier =
382
382
 
383
383
  return request.changes.length;
384
384
  };
385
- `:"",M=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. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket(\"name\")` and the studio's bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. Omit it and `ctx.storage` in a mutation, action or HTTP handler (and the studio's copy-URL) signs against the origin the request reached the worker on — no per-environment value to ship. Queries get no such fallback (a live query re-runs with no request behind it), so a query that signs URLs needs this set. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}"]:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(async () => (await import("postgres")).default(env.HYPERDRIVE.connectionString, { fetch_types: false, max: 5 })))`. Called per request, by the shard and by the stateless worker\'s admin plane, so return an exec on a connection opened for that call: never cache a driver or socket at module scope, since Workers refuse I/O across requests. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],_=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[],...e.hasAdminRevocations===!1?[]:[" private adminRevocationsSelector?: Selector<Env, ShardNamespaceLike>;"]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;",...e.hasDeliveryAuthorization===!1?[]:[' private deliveryAuthorizationSelector?: ShardConfig["deliveryAuthorization"];']," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;",' private maxRelationKeysLimit?: ShardConfig["maxRelationKeys"];',' private observabilitySink?: ShardConfig["observability"];',' private relationExistsPushDownMode?: ShardConfig["relationExistsPushDown"];'," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...w(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[],...l(e)?[" private shardRegistrySelector?: Selector<Env, ShardNamespaceLike | ShardRegistryRpc>;"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasSourcedTables?[' private sourceClientFactory?: NonNullable<ShardConfig["sourceClient"]>;']:[],...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],W=e=>f(e).map(({configKey:r,doc:t,method:a})=>` /** ${t} */
385
+ `:"",_=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. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket(\"name\")` and the studio's bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. Omit it and `ctx.storage` in a mutation, action or HTTP handler (and the studio's copy-URL) signs against the origin the request reached the worker on — no per-environment value to ship. Queries get no such fallback (a live query re-runs with no request behind it), so a query that signs URLs needs this set. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}"]:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(async () => (await import("postgres")).default(env.HYPERDRIVE.connectionString, { fetch_types: false, max: 5 })))`. Called per request, by the shard and by the stateless worker\'s admin plane, so return an exec on a connection opened for that call: never cache a driver or socket at module scope, since Workers refuse I/O across requests. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],M=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[],...e.hasAdminRevocations===!1?[]:[" private adminRevocationsSelector?: Selector<Env, ShardNamespaceLike>;"]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;",...e.hasDeliveryAuthorization===!1?[]:[' private deliveryAuthorizationSelector?: ShardConfig["deliveryAuthorization"];']," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;",' private maxRelationKeysLimit?: ShardConfig["maxRelationKeys"];',' private observabilitySink?: ShardConfig["observability"];',' private relationExistsPushDownMode?: ShardConfig["relationExistsPushDown"];'," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...w(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[],...l(e)?[" private shardRegistrySelector?: Selector<Env, ShardNamespaceLike | ShardRegistryRpc>;"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasSourcedTables?[' private sourceClientFactory?: NonNullable<ShardConfig["sourceClient"]>;']:[],...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],W=e=>f(e).map(({configKey:r,doc:t,method:a})=>` /** ${t} */
386
386
  public ${a}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${r}"]>>): this {
387
387
  this.shardExtras.${r} = factory as NonNullable<ShardConfig["${r}"]>;
388
388
 
@@ -567,7 +567,7 @@ const buildGlobalCdcApplier =
567
567
  : {}),`]:[],...l(e)?[" ...(this.shardRegistrySelector ? { shardRegistry: (rawEnv: Record<string, unknown>) => this.shardRegistrySelector?.(rawEnv as Env) } : {}),"]:[],...e.hasSourcedTables?[" ...(this.sourceClientFactory === undefined ? {} : { sourceClient: this.sourceClientFactory }),"]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>, origin?: string) => this.resolveStorage(rawEnv as Env, origin) } : {}),"]:[],...w(e)?[" ...this.shardExtras,"]:[]];return t.length>0?`
568
568
  ${t.join(`
569
569
  `)}
570
- `:""},F=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],U=(e,r)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${r?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],z=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],Q=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],J=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],K=e=>e?['import notifyConfig from "../notify.js";']:[],V=e=>k(e)?e.lazyFunctions===!0?['import type { dispatchAgentEmail } from "@lunora/agent/inbound";']:['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],Y=e=>k(e)&&e.lazyFunctions!==!0?['import * as lunoraAgentDefinitions from "../agents.js";']:[],X=e=>{const{hasFramework:r,hasGlobal:t,hasHyperdriveGlobal:a,hasQueue:n,useUmbrella:s}=e,i=s?"lunorash/runtime":"@lunora/runtime",d=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike",...l(e)?["ShardRegistryRpc"]:[],"WorkerOptions",...n?["TriggerTrace"]:[],...t?["GlobalIntrospector"]:[],...e.tables.length>0?["ShardingInfo"]:[],...r?["FrameworkHostHandler"]:[]],c=[...t||a?["createCrossShardRelationCapabilities"]:[],...l(e)?["createDynamicShardRegistry","createQueryCoordinator"]:[],"createWorker",...e.jurisdiction?["declareAppJurisdiction"]:[],"resolveLogArchiveFromEnv",...e.hasAuth?["memoizeIdentity"]:[],...r?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...d].toSorted((o,u)=>o.localeCompare(u)).join(", ")} } from "${i}";`,`import { ${c} } from "${i}";`]},Z=e=>{const{hasAccess:r,hasAuth:t,hasGlobal:a,hasHyperdriveGlobal:n,hasKvIntrospector:s,hasQueue:i,hasScheduler:d,hasStorage:c,hasWorkflow:o}=e;return[...t?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import type * as LunoraAuthModule from "./authModule.js";']:[],...U(r,t),...J(a),...n?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { applyHyperdriveGlobalCdc, createHyperdriveGlobalCtxDb, createHyperdriveGlobalIntrospector, exportHyperdriveGlobalRows, importHyperdriveGlobalRows, readHyperdriveGlobalCdc } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...z(s),...Q(e.hasVectors),...d?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...c?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...o?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...V(e),...X(e),"",...F(e.identity),...Y(e),...a||n?['import schema from "../schema.js";']:[],...K(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...i?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";',...e.lazyFunctions===!0?[]:['import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']]:[],'import { createShardDO } from "./shard.js";',...p(e)?[`import { liveStreamRouter } from "${e.useUmbrella?"lunorash/server":"@lunora/server"}";`]:[],...e.hasVectors?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},ee=e=>e.jurisdiction&&e.jurisdictionPinsAuth===!0?`
570
+ `:""},U=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],F=(e,r)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${r?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],z=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],Q=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],J=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],K=e=>e?['import notifyConfig from "../notify.js";']:[],V=e=>k(e)?e.lazyFunctions===!0?['import type { dispatchAgentEmail } from "@lunora/agent/inbound";']:['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],Y=e=>k(e)&&e.lazyFunctions!==!0?['import * as lunoraAgentDefinitions from "../agents.js";']:[],X=e=>{const{hasFramework:r,hasGlobal:t,hasHyperdriveGlobal:a,hasQueue:s,useUmbrella:n}=e,i=n?"lunorash/runtime":"@lunora/runtime",d=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","SecurityOptions","ShardNamespaceLike",...l(e)?["ShardRegistryRpc"]:[],"WorkerOptions",...s?["TriggerTrace"]:[],...t?["GlobalIntrospector"]:[],...e.tables.length>0?["ShardingInfo"]:[],...r?["FrameworkHostHandler"]:[]],c=[...t||a?["createCrossShardRelationCapabilities"]:[],...l(e)?["createDynamicShardRegistry","createQueryCoordinator"]:[],"createWorker",...e.jurisdiction?["declareAppJurisdiction"]:[],"resolveLogArchiveFromEnv",...e.hasAuth?["memoizeIdentity"]:[],...r?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...d].toSorted((o,u)=>o.localeCompare(u)).join(", ")} } from "${i}";`,`import { ${c} } from "${i}";`]},Z=e=>{const{hasAccess:r,hasAuth:t,hasGlobal:a,hasHyperdriveGlobal:s,hasKvIntrospector:n,hasQueue:i,hasScheduler:d,hasStorage:c,hasWorkflow:o}=e;return[...t?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import type * as LunoraAuthModule from "./authModule.js";']:[],...F(r,t),...J(a),...s?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { applyHyperdriveGlobalCdc, createHyperdriveGlobalCtxDb, createHyperdriveGlobalIntrospector, exportHyperdriveGlobalRows, importHyperdriveGlobalRows, readHyperdriveGlobalCdc } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...z(n),...Q(e.hasVectors),...d?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...c?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...o?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...V(e),...X(e),"",...U(e.identity),...Y(e),...a||s?['import schema from "../schema.js";']:[],...K(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...i?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";',...e.lazyFunctions===!0?[]:['import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']]:[],'import { createShardDO } from "./shard.js";',...p(e)?[`import { liveStreamRouter } from "${e.useUmbrella?"lunorash/server":"@lunora/server"}";`]:[],...e.hasVectors?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},ee=e=>e.jurisdiction&&e.jurisdictionPinsAuth===!0?`
571
571
  // The schema's jurisdiction pins the auth object like every other DO.
572
572
  jurisdiction: ${JSON.stringify(e.jurisdiction)},`:"",te=e=>typeof e=="string"?`{ mode: { kind: ${JSON.stringify(e)} } }`:`{ mode: { field: ${JSON.stringify(e.field)}, kind: "shardBy" } }`,re=e=>[...e.tables.length>0?[` const tableSharding = new Map<string, ShardingInfo>([
573
573
  ${e.tables.map(r=>` [${JSON.stringify(r.name)}, ${te(r.shardMode)}],`).join(`
@@ -583,7 +583,7 @@ ${e.tables.map(r=>` [${JSON.stringify(r.name)}, ${te(r.shardMode)}],`
583
583
 
584
584
  if (adminRevocations) {
585
585
  options.adminRevocations = adminRevocations;
586
- }`],S=e=>(e.liveStreamDeclarations??[]).map(r=>{if(I(r.exportName,"live stream export name"),!L.test(r.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(r.filePath)}`);return` { id: ${JSON.stringify(r.id)}, load: () => import("../${r.filePath}.js").then((m) => m.${r.exportName}) },`}),ne=e=>p(e)?[" httpRouter: liveStreamRouter([",...S(e)," ], this.httpRouterApp),"]:[" ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"],se=e=>p(e)?[" liveStreamRoutes: [",...(e.liveStreamDeclarations??[]).flatMap(r=>[` ${JSON.stringify(`GET /live/${r.id}/connect`)},`,` ${JSON.stringify(`POST /live/${r.id}/control`)},`])," ],"]:[],oe=e=>p(e)?`liveStreamRouter([
586
+ }`],S=e=>(e.liveStreamDeclarations??[]).map(r=>{if(I(r.exportName,"live stream export name"),!L.test(r.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(r.filePath)}`);return` { id: ${JSON.stringify(r.id)}, load: () => import("../${r.filePath}.js").then((m) => m.${r.exportName}) },`}),se=e=>p(e)?[" httpRouter: liveStreamRouter([",...S(e)," ], this.httpRouterApp),"]:[" ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"],ne=e=>p(e)?[" liveStreamRoutes: [",...(e.liveStreamDeclarations??[]).flatMap(r=>[` ${JSON.stringify(`GET /live/${r.id}/connect`)},`,` ${JSON.stringify(`POST /live/${r.id}/control`)},`])," ],"]:[],oe=e=>p(e)?`liveStreamRouter([
587
587
  ${S(e).join(`
588
588
  `)}
589
589
  ], host)`:"host",ie=e=>e.agentWorkflows===void 0?[]:[` options.agentWorkflows = ${JSON.stringify(e.agentWorkflows)};`],ce=e=>[...re(e),...e.hasAdminRevocations===!1?[]:ae,...e.hasScheduler?[` if (this.schedulerDeclaration) {
@@ -855,13 +855,13 @@ ${S(e).join(`
855
855
  }`]:[],...ie(e),...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
856
856
  ${e.voiceAgents.map(r=>` ${JSON.stringify(r.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(r.bindingName)}] as ShardNamespaceLike,`).join(`
857
857
  `)}
858
- };`]:[]],le=e=>e.hasQueue?[` queue: ${e.lazyFunctions===!0?"async ":""}(batch: unknown, queueEnv: unknown, _context: ExecutionContextLike, trigger: TriggerTrace, ${e.liveStreams?"queueLive":"_live"}: Parameters<typeof dispatchQueueBatch>[2]["live"], queueFetch: Parameters<typeof dispatchQueueBatch>[2]["fetchImpl"]): Promise<void> =>`,` dispatchQueueBatch(batch as Parameters<typeof dispatchQueueBatch>[0], ${e.lazyFunctions===!0?'(await import("./queues.js")).LUNORA_QUEUE_REGISTRY':"LUNORA_QUEUE_REGISTRY"}, {`," capture: shouldCaptureQueue(queueEnv as Record<string, unknown>)",` ? createQueueCaptureSink(queueEnv as Record<string, unknown>${e.jurisdiction?`, { jurisdiction: ${JSON.stringify(e.jurisdiction)} }`:""})`," : undefined,"," env: queueEnv as Record<string, unknown>,"," holdSeconds: trigger.holdSeconds,"," traceparent: trigger.traceparent,"," fetchImpl: queueFetch,",...e.liveStreams?[" live: queueLive,"]:[]," }),"]:[],de=e=>[' aiChatBinding: (env as Record<string, unknown>)["AI"] as WorkerOptions["aiChatBinding"],',' aiOptInLevel: (env as Record<string, unknown>)["LUNORA_AI_OPT_IN"] as WorkerOptions["aiOptInLevel"],'," cronJobs: LUNORA_CRONS,"," functions: LUNORA_FUNCTIONS,",...e.identity?[` identity: lunoraIdentityContract.${e.identity.exportName},`]:[],...e.jurisdiction?[` jurisdiction: ${JSON.stringify(e.jurisdiction)},`]:[],...e.wantsArchitecture?[" architecture: deferred.architecture,"]:[],...e.wantsOpenApi?[" openApiSpec: deferred.openApiSpec,"]:[],...e.wantsOpenRpc?[" openRpcSpec: deferred.openRpcSpec,"]:[],...le(e),...ne(e),...se(e)," routes: this.routeMap,",...e.liveStreamsWithheld?[" liveStreams: false,"]:[]," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),"],he=e=>e?`
858
+ };`]:[]],le=e=>e.hasQueue?[` queue: ${e.lazyFunctions===!0?"async ":""}(batch: unknown, queueEnv: unknown, _context: ExecutionContextLike, trigger: TriggerTrace, ${e.liveStreams?"queueLive":"_live"}: Parameters<typeof dispatchQueueBatch>[2]["live"], queueFetch: Parameters<typeof dispatchQueueBatch>[2]["fetchImpl"]): Promise<void> =>`,` dispatchQueueBatch(batch as Parameters<typeof dispatchQueueBatch>[0], ${e.lazyFunctions===!0?'(await import("./queues.js")).LUNORA_QUEUE_REGISTRY':"LUNORA_QUEUE_REGISTRY"}, {`," capture: shouldCaptureQueue(queueEnv as Record<string, unknown>)",` ? createQueueCaptureSink(queueEnv as Record<string, unknown>${e.jurisdiction?`, { jurisdiction: ${JSON.stringify(e.jurisdiction)} }`:""})`," : undefined,"," env: queueEnv as Record<string, unknown>,"," holdSeconds: trigger.holdSeconds,"," traceparent: trigger.traceparent,"," fetchImpl: queueFetch,",...e.liveStreams?[" live: queueLive,"]:[]," }),"]:[],de=e=>[' aiChatBinding: (env as Record<string, unknown>)["AI"] as WorkerOptions["aiChatBinding"],',' aiOptInLevel: (env as Record<string, unknown>)["LUNORA_AI_OPT_IN"] as WorkerOptions["aiOptInLevel"],'," cronJobs: LUNORA_CRONS,"," functions: LUNORA_FUNCTIONS,",...e.identity?[` identity: lunoraIdentityContract.${e.identity.exportName},`]:[],...e.jurisdiction?[` jurisdiction: ${JSON.stringify(e.jurisdiction)},`]:[],...e.wantsArchitecture?[" architecture: deferred.architecture,"]:[],...e.wantsOpenApi?[" openApiSpec: deferred.openApiSpec,"]:[],...e.wantsOpenRpc?[" openRpcSpec: deferred.openRpcSpec,"]:[],...le(e),...se(e),...ne(e)," routes: this.routeMap,",...e.liveStreamsWithheld?[" liveStreams: false,"]:[]," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),",...e.spaAssetsBindings===void 0||e.spaAssetsBindings.length===0?[]:[` spaAssets: (${e.spaAssetsBindings.map(r=>`(env as Record<string, unknown>)[${JSON.stringify(r)}]`).join(" ?? ")}) as WorkerOptions["spaAssets"],`]],he=e=>e?`
859
859
  /** The identity memo per \`env\` object, owned by one assembled worker. */
860
860
  type IdentityMemoStore = WeakMap<object, ReturnType<typeof memoizeIdentity>>;
861
- `:"",E=e=>e.hasAuth||e.wantsArchitecture||e.wantsOpenApi||e.wantsOpenRpc,ue=e=>{if(!E(e))return"";const t=[[e.wantsArchitecture,"architecture","unknown",'(await import("./architecture.js")).architecture'],[e.hasAuth,"auth","typeof LunoraAuthModule",'await import("./authModule.js")'],[e.wantsOpenApi,"openApiSpec","unknown",'(await import("./openapi.js")).openApiSpec'],[e.wantsOpenRpc,"openRpcSpec","unknown",'(await import("./openrpc.js")).openRpcSpec']].filter(([a])=>a).map(([,a,n,s])=>[a,n,s]);return`
861
+ `:"",E=e=>e.hasAuth||e.wantsArchitecture||e.wantsOpenApi||e.wantsOpenRpc,ue=e=>{if(!E(e))return"";const t=[[e.wantsArchitecture,"architecture","unknown",'(await import("./architecture.js")).architecture'],[e.hasAuth,"auth","typeof LunoraAuthModule",'await import("./authModule.js")'],[e.wantsOpenApi,"openApiSpec","unknown",'(await import("./openapi.js")).openApiSpec'],[e.wantsOpenRpc,"openRpcSpec","unknown",'(await import("./openrpc.js")).openRpcSpec']].filter(([a])=>a).map(([,a,s,n])=>[a,s,n]);return`
862
862
  /** What the worker reads only once a request arrives: loaded then, not at isolate startup (Cloudflare caps startup at 1 s of CPU). */
863
863
  interface DeferredModules {
864
- ${t.map(([a,n])=>` ${a}: ${n};`).join(`
864
+ ${t.map(([a,s])=>` ${a}: ${s};`).join(`
865
865
  `)}
866
866
  }
867
867
 
@@ -871,17 +871,17 @@ let deferredModules: Promise<DeferredModules> | undefined;
871
871
  const loadDeferredModules = (): Promise<DeferredModules> =>
872
872
  (deferredModules ??= (async (): Promise<DeferredModules> => {
873
873
  return {
874
- ${t.map(([a,,n])=>` ${a}: ${n},`).join(`
874
+ ${t.map(([a,,s])=>` ${a}: ${s},`).join(`
875
875
  `)}
876
876
  };
877
877
  })());
878
878
  `},pe=(e,r)=>{const t=`buildWorker(rawEnv as Env${r})`,a=e?`
879
- await ensureAuth(env);`:"",n=e?`
880
- await ensureAuth(rawEnv as Env);`:"";return e?{ensureAuthCall:a,ensureRawAuthCall:n,eventWorker:"target",eventWorkerLine:`
881
- const target = (await authReady(rawEnv as Env)) ? (worker ??= ${t}) : ${t};`}:{ensureAuthCall:a,ensureRawAuthCall:n,eventWorker:"worker",eventWorkerLine:`
879
+ await ensureAuth(env);`:"",s=e?`
880
+ await ensureAuth(rawEnv as Env);`:"";return e?{ensureAuthCall:a,ensureRawAuthCall:s,eventWorker:"target",eventWorkerLine:`
881
+ const target = (await authReady(rawEnv as Env)) ? (worker ??= ${t}) : ${t};`}:{ensureAuthCall:a,ensureRawAuthCall:s,eventWorker:"worker",eventWorkerLine:`
882
882
  worker ??= ${t};`}},me=e=>E(e)?{asyncIfDeferred:"async ",deferredArgument:", deferred",deferredParameter:", deferred: DeferredModules",loadDeferredLine:`
883
- const deferred = await loadDeferredModules();`}:{asyncIfDeferred:"",deferredArgument:"",deferredParameter:"",loadDeferredLine:""},we=e=>e?`${y}export { authDiscoveryPathsFor, createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, handleAuthDiscoveryRequest, handleAuthRequest, lunoraD1Adapter, resolveSessionIdentity } from "@lunora/auth/worker";
884
- `:"",be=e=>{const r=e.emailAgents??[];if(r.length===0)return"";const t=a=>r.map(n=>`${a}{ agent: lunoraAgentDefinitions.${n.exportName}, className: ${JSON.stringify(n.className)} },`).join(`
883
+ const deferred = await loadDeferredModules();`}:{asyncIfDeferred:"",deferredArgument:"",deferredParameter:"",loadDeferredLine:""},ke=e=>e?`${y}export { authDiscoveryPathsFor, createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, handleAuthDiscoveryRequest, handleAuthRequest, lunoraD1Adapter, resolveSessionIdentity } from "@lunora/auth/worker";
884
+ `:"",be=e=>{const r=e.emailAgents??[];if(r.length===0)return"";const t=a=>r.map(s=>`${a}{ agent: lunoraAgentDefinitions.${s.exportName}, className: ${JSON.stringify(s.className)} },`).join(`
885
885
  `);return e.lazyFunctions!==!0?` composed.email = dispatchAgentEmail([
886
886
  ${t(" ")}
887
887
  ]);
@@ -900,7 +900,14 @@ ${t(" ")}
900
900
  return agentEmail(message, rawEnv, context);
901
901
  };
902
902
 
903
- `},ge=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((r,t)=>r.localeCompare(t)).join(", "),ke=e=>{const r=(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0,t={...e,hasVectors:r},{hasAuth:a}=t,n=M(t),s=ce(t),i=a?` let auth: LunoraAuth | null = null;
903
+ `},ge=e=>e.securityHeaders===void 0?"":`
904
+ /**
905
+ * \`security.headers\` from \`lunora.config\`: the baseline security headers the Worker sends, and the same values
906
+ * the build writes into the static assets' \`_headers\`. An app that calls \`createWorker\` itself passes it as
907
+ * \`security: { headers: LUNORA_SECURITY_HEADERS }\`.
908
+ */
909
+ const LUNORA_SECURITY_HEADERS: SecurityOptions["headers"] = ${JSON.stringify(e.securityHeaders)};
910
+ `,ve=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((r,t)=>r.localeCompare(t)).join(", "),Se=e=>{const r=(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0,t={...e,hasVectors:r},{hasAuth:a}=t,s=_(t),n=ce(t),i=a?` let auth: LunoraAuth | null = null;
904
911
  let authInit: Promise<void> | null = null;
905
912
  // One memo per env for THIS assembled worker: every worker it builds reuses it, but a second
906
913
  // \`assemble()\` has its own auth closure and must not share.
@@ -983,15 +990,15 @@ type Selector<Env, T> = (env: Env) => T | undefined;
983
990
 
984
991
  /** The generated \`createShardDO\` config — \`.observability()\`, \`.maxRelationKeys()\` and the long-tail \`.ai()\` / \`.kv()\` / … methods pass straight through to it. */
985
992
  type ShardConfig = NonNullable<Parameters<typeof createShardDO>[0]>;
986
- ${he(a)}${ue(t)}${t.jurisdiction?`
993
+ ${ge(t)}${he(a)}${ue(t)}${t.jurisdiction?`
987
994
  // Module scope, so every isolate loading this script (the worker and each Durable
988
995
  // Object class it exports) knows the schema's jurisdiction before a request runs.
989
996
  // \`@lunora/mail\` reads it to pin its shard RPC like every other DO path.
990
997
  declareAppJurisdiction(${JSON.stringify(t.jurisdiction)});
991
998
  `:""}
992
- ${n.join(`
999
+ ${s.join(`
993
1000
 
994
- `)}${n.length>0?`
1001
+ `)}${s.length>0?`
995
1002
 
996
1003
  `:""}/** The composed app: a Cloudflare module worker (\`fetch\` / \`scheduled\` / optional \`email\`) plus the \`ShardDO\` class binding. */
997
1004
  interface ComposedApp extends LunoraWorker {
@@ -1008,7 +1015,7 @@ interface ComposedApp extends LunoraWorker {
1008
1015
  * first request so per-isolate singletons are built once.
1009
1016
  */
1010
1017
  class AppBuilder<Env extends object> {
1011
- ${_(t).join(`
1018
+ ${M(t).join(`
1012
1019
  `)}
1013
1020
 
1014
1021
  private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
@@ -1072,7 +1079,7 @@ ${t.hasFramework?`
1072
1079
  `:""}
1073
1080
  return composed;
1074
1081
  }
1075
- ${$(t)}${G(t.hasStorage)}
1082
+ ${$(t)}${P(t.hasStorage)}
1076
1083
  /** Fan the recorded declarations into the worker-side \`createWorker\` options. */
1077
1084
  private buildWorkerOptions(env: Env, ${A}): WorkerOptions {
1078
1085
  const options: WorkerOptions = {
@@ -1086,18 +1093,18 @@ ${de(t).join(`
1086
1093
  options.adminToken = adminToken;
1087
1094
  }
1088
1095
 
1089
- ${s.join(`
1096
+ ${n.join(`
1090
1097
 
1091
- `)}${s.length>0?`
1098
+ `)}${n.length>0?`
1092
1099
 
1093
1100
  `:""} for (const fn of this.extendFns) {
1094
1101
  Object.assign(options, fn(env, { ...options }));
1095
1102
  }
1096
-
1103
+ ${t.securityHeaders===void 0?"":"\n // `security.headers` from lunora.config, unless code set its own. After `.extend()`, whose shallow\n // assign would otherwise drop it when an extension sets only `security.cors`.\n if (options.security?.headers === undefined) {\n options.security = { ...options.security, headers: LUNORA_SECURITY_HEADERS };\n }\n"}
1097
1104
  return options;
1098
1105
  }
1099
1106
  }
1100
- ${P(t.hasGlobal)}
1107
+ ${G(t.hasGlobal)}
1101
1108
  /**
1102
1109
  * Shape of the project's root \`lunora.config.*\`.
1103
1110
  *
@@ -1119,6 +1126,8 @@ interface LunoraConfig<Env extends object = object> {
1119
1126
  remote?: boolean;
1120
1127
  /** Sibling Workers the app calls through service bindings — key → its folder and, for RPC, the exported \`WorkerEntrypoint\` class (\`rpc: false\` binds that class but calls it with plain \`fetch\`, without importing the service's sources). Becomes \`ctx.services.<key>\` in actions, a wrangler \`services[]\` entry, one \`lunora dev\` session and a services-first \`lunora deploy\`. Literals, for the same reason as \`target\`. */
1121
1128
  services?: Record<string, { dir: string; entrypoint?: string; rpc?: false }>;
1129
+ /** Baseline security headers for the Worker AND the static assets' generated \`_headers\` (\`crossOriginOpenerPolicy\`, \`frameAncestors\`, \`csp\`, …; \`false\` omits a header, \`headers: false\` all of them). A \`security.headers\` set in code wins. Literals, for the same reason as \`target\`. */
1130
+ security?: { headers?: SecurityOptions["headers"] };
1122
1131
  /** Studio settings. \`companion: true\` emits the companion Worker that serves the advisor procedure list to a hosted Studio, bound to the app as \`ADVISOR_COMPANION\`. A literal, for the same reason as \`target\`. */
1123
1132
  studio?: { companion?: boolean };
1124
1133
  /** Deploy target id — \`lunora deploy\`/\`verify\` read it when no \`--target\` is passed. Must be a literal: \`runCodegen\` resolves it synchronously by PARSING this file, so a computed value is not seen — \`lunora verify\` reports \`platform_unreadable_target\` rather than defaulting in silence. */
@@ -1137,6 +1146,6 @@ interface LunoraConfig<Env extends object = object> {
1137
1146
  */
1138
1147
  const defineApp = <Env extends object>(): AppBuilder<Env> => new AppBuilder<Env>();
1139
1148
 
1140
- export { AppBuilder, defineApp };
1141
- export type { ${ge(t)} };
1142
- `};export{ke as emitApp,we as emitAuthModule};
1149
+ export { AppBuilder, defineApp${t.securityHeaders===void 0?"":", LUNORA_SECURITY_HEADERS"} };
1150
+ export type { ${ve(t)} };
1151
+ `};export{Se as emitApp,ke as emitAuthModule};
@@ -1,4 +1,4 @@
1
- import{G as i,d as c}from"./shared-DhqnD5R3.mjs";import{i as g}from"./schema-BgM8A3XV.mjs";const f=r=>r?`${i}/**
1
+ import{G as i,d as c}from"./shared-Cn7dMQ_u.mjs";import{i as g}from"./schema-BgM8A3XV.mjs";const f=r=>r?`${i}/**
2
2
  * The \`SchedulerDO\` Durable Object class, re-exported so a worker entry can
3
3
  * forward it — wrangler binds only what the entry exports:
4
4
  *
@@ -1,4 +1,4 @@
1
- import{r as k}from"./qualifiers-ClaCHu0X.mjs";import{a as i,e as o,v as d,f as v,G as M}from"./shared-DhqnD5R3.mjs";const _="schema",w=a=>{for(const e of a.tables)i(e.name,"table name");const l=a.tables.map(e=>`"${e.name}"`).join(" | ")||"never",m=a.tables.filter(e=>e.extensionKey===void 0).map(e=>`"${e.name}"`).join(" | ")||"never",p=a.tables.map(e=>{const t=Object.entries(e.shape).map(([g,r])=>{const s=o(g);if(r.kind==="optional"){const h=r.inner?d(r.inner):"unknown";return` ${s}?: ${h};`}return` ${s}: ${d(r)};`}).join(`
1
+ import{r as k}from"./qualifiers-qqH8fRTo.mjs";import{a as i,e as o,v as d,f as v,G as M}from"./shared-Cn7dMQ_u.mjs";const _="schema",w=a=>{for(const e of a.tables)i(e.name,"table name");const l=a.tables.map(e=>`"${e.name}"`).join(" | ")||"never",m=a.tables.filter(e=>e.extensionKey===void 0).map(e=>`"${e.name}"`).join(" | ")||"never",p=a.tables.map(e=>{const t=Object.entries(e.shape).map(([g,r])=>{const s=o(g);if(r.kind==="optional"){const h=r.inner?d(r.inner):"unknown";return` ${s}?: ${h};`}return` ${s}: ${d(r)};`}).join(`
2
2
  `),n=t?`
3
3
  ${t}
4
4
  `:"",N=e.commitOrdered===!0?`
@@ -1,4 +1,4 @@
1
- import{SCHEMA_MODULE_PATH as c}from"./emitDataModel-MjAOi3KM.mjs";import{r as m}from"./qualifiers-ClaCHu0X.mjs";import{G as b,a as z,d as T,v as f,u as A,g as x,c as h}from"./shared-DhqnD5R3.mjs";const d=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:f(e)};case"bigint":return{builder:"blob",mode:"bigint",notNull:!0};case"boolean":return{builder:"integer",mode:"boolean",notNull:!0};case"bytes":return{builder:"blob",mode:"buffer",notNull:!0};case"date":case"timestamp":return{builder:"integer",notNull:!0};case"from":return{builder:"text",notNull:!0,typeAnnotation:f(e)};case"id":return{builder:"text",notNull:!0};case"literal":{const t=e.literalValue??"";return t.startsWith('"')||t.startsWith("'")?{builder:"text",notNull:!0}:t==="true"||t==="false"?{builder:"integer",mode:"boolean",notNull:!0}:t==="null"?{builder:"text",notNull:!0}:{builder:"real",notNull:!0}}case"null":return{builder:"text",notNull:!0};case"number":return{builder:"real",notNull:!0};case"optional":return{...e.inner?d(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},N=(e,t)=>{const r=A(e);return r.kind==="id"&&r.tableName!==void 0&&t.has(r.tableName)?r.tableName:void 0},j=(e,t,r)=>{x(e,"drizzle column name");const n=d(t),o=n.mode?`, { mode: "${n.mode}" }`:"";let l=`${n.builder}("${e}"${o})`;n.typeAnnotation&&(l+=`.$type<${n.typeAnnotation}>()`);const s=N(t,r);return s!==void 0&&(l+=`.references((): AnySQLiteColumn => ${s}._id)`),n.notNull&&t.column?.notNull!==!1&&(l+=".notNull()"),l},I=e=>{const t=e.unique?"uniqueIndex":"index",r=e.fields.map(n=>(x(n,"drizzle index field"),`t.${n}`)).join(", ");return` ${h(e.name)}: ${t}(${JSON.stringify(e.name)}).on(${r}),`},S=(e,t)=>{z(e.name,"table name");const r=[' _id: text("_id").primaryKey(),',' _creationTime: integer("_creationTime").notNull(),',...Object.entries(e.shape).map(([o,l])=>` ${o}: ${j(o,l,t)},`)].join(`
1
+ import{SCHEMA_MODULE_PATH as c}from"./emitDataModel-BvCZS4Yq.mjs";import{r as m}from"./qualifiers-qqH8fRTo.mjs";import{G as b,a as z,d as T,v as f,u as A,g as x,c as h}from"./shared-Cn7dMQ_u.mjs";const d=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:f(e)};case"bigint":return{builder:"blob",mode:"bigint",notNull:!0};case"boolean":return{builder:"integer",mode:"boolean",notNull:!0};case"bytes":return{builder:"blob",mode:"buffer",notNull:!0};case"date":case"timestamp":return{builder:"integer",notNull:!0};case"from":return{builder:"text",notNull:!0,typeAnnotation:f(e)};case"id":return{builder:"text",notNull:!0};case"literal":{const t=e.literalValue??"";return t.startsWith('"')||t.startsWith("'")?{builder:"text",notNull:!0}:t==="true"||t==="false"?{builder:"integer",mode:"boolean",notNull:!0}:t==="null"?{builder:"text",notNull:!0}:{builder:"real",notNull:!0}}case"null":return{builder:"text",notNull:!0};case"number":return{builder:"real",notNull:!0};case"optional":return{...e.inner?d(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},N=(e,t)=>{const r=A(e);return r.kind==="id"&&r.tableName!==void 0&&t.has(r.tableName)?r.tableName:void 0},j=(e,t,r)=>{x(e,"drizzle column name");const n=d(t),o=n.mode?`, { mode: "${n.mode}" }`:"";let l=`${n.builder}("${e}"${o})`;n.typeAnnotation&&(l+=`.$type<${n.typeAnnotation}>()`);const s=N(t,r);return s!==void 0&&(l+=`.references((): AnySQLiteColumn => ${s}._id)`),n.notNull&&t.column?.notNull!==!1&&(l+=".notNull()"),l},I=e=>{const t=e.unique?"uniqueIndex":"index",r=e.fields.map(n=>(x(n,"drizzle index field"),`t.${n}`)).join(", ");return` ${h(e.name)}: ${t}(${JSON.stringify(e.name)}).on(${r}),`},S=(e,t)=>{z(e.name,"table name");const r=[' _id: text("_id").primaryKey(),',' _creationTime: integer("_creationTime").notNull(),',...Object.entries(e.shape).map(([o,l])=>` ${o}: ${j(o,l,t)},`)].join(`
2
2
  `),n=e.indexes.length>0?`, (t) => ({
3
3
  ${e.indexes.map(o=>I(o)).join(`
4
4
  `)}
@@ -1,4 +1,4 @@
1
- import{LunoraError as L}from"@lunora/errors";import{L as pe,i as ge,G as U,d as J,I as F,s as fe,b as C,r as ye,c as $e}from"./shared-DhqnD5R3.mjs";import{v as we}from"./parse-validator-BisfC8bR.mjs";import{renderAgentFunctionRegistry as be,renderSandboxFunctionRegistry as Re}from"./emitApi-Cdc8MeNK.mjs";import{b as ke,a as Ne,r as j,c as ve}from"./qualifiers-ClaCHu0X.mjs";import{s as g}from"./dispatch-namespace-DwTjD7BU.mjs";const Oe=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),B=t=>t.column!==void 0,Se=(t,r)=>{switch(t){case"bigint":return`if (typeof ${r} !== "bigint") return DEFER;
1
+ import{LunoraError as L}from"@lunora/errors";import{L as pe,i as ge,G as U,d as J,I as F,s as fe,b as C,r as ye,c as $e}from"./shared-Cn7dMQ_u.mjs";import{v as we}from"./parse-validator-BisfC8bR.mjs";import{renderAgentFunctionRegistry as be,renderSandboxFunctionRegistry as Re}from"./emitApi-lwadq5G7.mjs";import{b as ke,a as Ne,r as j,c as ve}from"./qualifiers-qqH8fRTo.mjs";import{s as g}from"./dispatch-namespace-DwTjD7BU.mjs";const Oe=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),B=t=>t.column!==void 0,Se=(t,r)=>{switch(t){case"bigint":return`if (typeof ${r} !== "bigint") return DEFER;
2
2
  `;case"boolean":return`if (typeof ${r} !== "boolean") return DEFER;
3
3
  `;case"date":case"number":case"timestamp":return`if (typeof ${r} !== "number" || !Number.isFinite(${r})) return DEFER;
4
4
  `;case"null":return`if (${r} !== null) return DEFER;
@@ -1 +1 @@
1
- import"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{e}from"./server-C4h6-BZx.mjs";import"./shared-DhqnD5R3.mjs";import"./platform-8oj7iXQy.mjs";export{e as default};
1
+ import"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{e}from"./server-CRFaUMKQ.mjs";import"./shared-Cn7dMQ_u.mjs";import"./platform-8oj7iXQy.mjs";export{e as default};
@@ -1 +1 @@
1
- import"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-DNpjvEod.mjs";import"./shard-runtime-knn-ER8x.mjs";import"./shared-DhqnD5R3.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
1
+ import"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-Csztu3jG.mjs";import"./shard-runtime-D0xuE0pX.mjs";import"./shared-Cn7dMQ_u.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
@@ -1 +1 @@
1
- import{Node as s}from"ts-morph";import{j as t,h as c}from"./attribution-DjweYNgJ.mjs";import{c as n}from"./classify-procedure-call-BuF5PNwV.mjs";const m=a=>{const i=[];for(const e of t(a)){const r=e.getInitializer(),o=r&&s.isCallExpression(r)?n(r):void 0;o?.receiver&&i.push({name:c(e)??e.getName(),receiver:o.receiver})}return i};export{m as e};
1
+ import{Node as s}from"ts-morph";import{j as t,h as c}from"./attribution-C6VQNs-V.mjs";import{c as n}from"./classify-procedure-call-DwWrpCoX.mjs";const m=a=>{const i=[];for(const e of t(a)){const r=e.getInitializer(),o=r&&s.isCallExpression(r)?n(r):void 0;o?.receiver&&i.push({name:c(e)??e.getName(),receiver:o.receiver})}return i};export{m as e};
@@ -1 +1 @@
1
- import{createHash as i}from"node:crypto";import{existsSync as s,readFileSync as c}from"node:fs";import{join as u}from"node:path";import{listLunoraSourceFiles as h}from"./isTestPath-ClgKgMYM.mjs";const S=t=>{if(!s(t))return"unreadable";const e=h(t,{includeSkipped:!0}),o=u(t,"schema.ts");s(o)&&e.push(o);const r=i("sha256");for(const a of e.toSorted((n,p)=>n.localeCompare(p)))try{r.update(a).update("\0").update(c(a))}catch{}return r.digest("hex")};export{S as default};
1
+ import{createHash as i}from"node:crypto";import{existsSync as s,readFileSync as c}from"node:fs";import{join as u}from"node:path";import{listLunoraSourceFiles as h}from"./isTestPath-B357_sbh.mjs";const S=t=>{if(!s(t))return"unreadable";const e=h(t,{includeSkipped:!0}),o=u(t,"schema.ts");s(o)&&e.push(o);const r=i("sha256");for(const a of e.toSorted((n,p)=>n.localeCompare(p)))try{r.update(a).update("\0").update(c(a))}catch{}return r.digest("hex")};export{S as default};
@@ -1 +1 @@
1
- import{dirname as F}from"node:path";import{Node as e}from"ts-morph";import{unwrapExpression as m,lunoraRelativePath as u}from"./isTestPath-ClgKgMYM.mjs";import{r as v,h}from"./attribution-DjweYNgJ.mjs";const b=i=>e.isPropertyAssignment(i)?m(i.getInitializer()):e.isShorthandPropertyAssignment(i)?i.getNameNode():void 0,A=(i,s)=>{const o=i===void 0?void 0:b(i);if(o===void 0||!e.isIdentifier(o))return;const a=v(o),g=a?.getAliasedSymbol()??a;for(const t of g?.getDeclarations()??[]){const n=e.isVariableDeclaration(t)?m(t.getInitializer()):t;if(!(e.isFunctionDeclaration(n)||e.isArrowFunction(n)||e.isFunctionExpression(n))||!(e.isFunctionDeclaration(t)||e.isVariableDeclaration(t)))continue;const r=t.getSourceFile(),c=u(s,r.getFilePath()),l=!c.startsWith("../"),d=l?c:u(F(s),r.getFilePath()),f=h(t);return{body:n,...r===o.getSourceFile()?{}:{file:d},...l&&f!==void 0?{site:{exportName:f,file:d}}:{}}}};export{A as r};
1
+ import{dirname as F}from"node:path";import{Node as e}from"ts-morph";import{unwrapExpression as m,lunoraRelativePath as u}from"./isTestPath-B357_sbh.mjs";import{r as v,h}from"./attribution-C6VQNs-V.mjs";const b=i=>e.isPropertyAssignment(i)?m(i.getInitializer()):e.isShorthandPropertyAssignment(i)?i.getNameNode():void 0,A=(i,s)=>{const o=i===void 0?void 0:b(i);if(o===void 0||!e.isIdentifier(o))return;const a=v(o),g=a?.getAliasedSymbol()??a;for(const t of g?.getDeclarations()??[]){const n=e.isVariableDeclaration(t)?m(t.getInitializer()):t;if(!(e.isFunctionDeclaration(n)||e.isArrowFunction(n)||e.isFunctionExpression(n))||!(e.isFunctionDeclaration(t)||e.isVariableDeclaration(t)))continue;const r=t.getSourceFile(),c=u(s,r.getFilePath()),l=!c.startsWith("../"),d=l?c:u(F(s),r.getFilePath()),f=h(t);return{body:n,...r===o.getSourceFile()?{}:{file:d},...l&&f!==void 0?{site:{exportName:f,file:d}}:{}}}};export{A as r};
@@ -0,0 +1 @@
1
+ import{LunoraError as g}from"@lunora/errors";import{Node as s,SyntaxKind as B}from"ts-morph";import{d as z}from"./declared-output-Iaar469J.mjs";import{findObjectProperty as h,bindingKeyName as H,listLunoraSourceFiles as M,lunoraRelativePath as W}from"./isTestPath-B357_sbh.mjs";import{e as K,i as O}from"./attribution-C6VQNs-V.mjs";import{u as R,p as q,r as Y,c as w,a as G}from"./unwrap-handler-return-zNStZJ4K.mjs";import{m as J}from"./ip-reads-Bn9qvrMD.mjs";import{b as L,s as X,c as Q}from"./classify-procedure-call-DwWrpCoX.mjs";import{r as D,p as C,a as Z}from"./parse-validator-BisfC8bR.mjs";import{N as ee,l as te}from"./project-config-file-DBVmBpin.mjs";import{s as ie}from"./dispatch-namespace-DwTjD7BU.mjs";const I=e=>e!==void 0&&(s.isArrowFunction(e)||s.isFunctionExpression(e))?e:void 0,ne=e=>{const i=e.getArguments()[0],t=I(i);if(t!==void 0)return t;if(i===void 0||!s.isObjectLiteralExpression(i))return;const n=h(i,"handler");return n!==void 0&&s.isPropertyAssignment(n)?I(n.getInitializer()):void 0},re=e=>{const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return"unknown";const t=h(i,"handler");if(!t||!s.isPropertyAssignment(t))return"unknown";const n=t.getInitializer();return!n||!(s.isArrowFunction(n)||s.isFunctionExpression(n))?"unknown":R(n)},oe=e=>{const i=e.getArguments()[0];return!i||!(s.isArrowFunction(i)||s.isFunctionExpression(i))?"unknown":R(i)},se=e=>{let i={};for(const t of L(e)){if(t.name!=="input")continue;const n=t.call.getArguments()[0],o=n!==void 0&&s.isExpression(n)?D(n):void 0;o!==void 0&&(i={...C(o),...i})}return i},ae=e=>{const i=L(e).find(n=>n.name==="output");if(!i)return;const t=i.call.getArguments()[0];return t&&s.isExpression(t)?q(i.call,()=>Z(t)):void 0},E=(e,i)=>{const t=h(e,i);if(t===void 0||!s.isPropertyAssignment(t))return;const n=t.getInitializer();return n!==void 0&&s.isStringLiteral(n)?n.getLiteralValue():void 0},k=(e,i)=>{const t=h(e,i);if(t===void 0||!s.isPropertyAssignment(t))return;const n=t.getInitializer();return n!==void 0&&s.isNumericLiteral(n)?n.getLiteralValue():void 0},ce=e=>{const i=h(e,"cache");if(i===void 0||!s.isPropertyAssignment(i))return;const t=i.getInitializer();if(t===void 0||!s.isObjectLiteralExpression(t))return;const n=E(t,"scope"),o=k(t,"maxAge"),r=k(t,"staleWhileRevalidate"),a=E(t,"tag"),c=E(t,"vary"),l={...o===void 0?{}:{maxAge:o},...n==="private"||n==="public"?{scope:n}:{},...r===void 0?{}:{staleWhileRevalidate:r},...a===void 0?{}:{tag:a},...c===void 0?{}:{vary:c}};return Object.keys(l).length===0?void 0:l},le=e=>{if(e===void 0||!s.isObjectLiteralExpression(e))return{};const i=ce(e),t=h(e,"rest");return t!==void 0&&s.isPropertyAssignment(t)?{...i===void 0?{}:{cache:i},rest:t.getInitializer()?.getText()==="true"}:i===void 0?{}:{cache:i}},ue=e=>{const i=L(e).find(t=>t.name==="expose");return i?le(i.call.getArguments()[0]):void 0},de=e=>{const i=L(e).find(r=>r.name==="x402");if(!i)return;const t=i.call.getArguments()[0];if(t===void 0||!s.isObjectLiteralExpression(t))return{};const n=h(t,"price");if(n===void 0||!s.isPropertyAssignment(n))return{};const o=n.getInitializer();return o===void 0?{}:s.isStringLiteral(o)?{price:o.getLiteralValue()}:s.isNumericLiteral(o)?{price:o.getLiteralValue()}:{}},ge=e=>{const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return{};const t=h(i,"args");if(!t||!s.isPropertyAssignment(t))return{};const n=t.getInitializer(),o=n===void 0?void 0:D(n);return o===void 0?{}:C(o)},f=(e,i)=>{throw new g("INTERNAL",`@lunora/codegen: lazy function registry needs literal ${i} in ${e.getSourceFile().getFilePath()}:${String(e.getStartLineNumber())}`)},S=(e,i,t)=>{if(!e||!s.isObjectLiteralExpression(e))return f(i,"metadata objects");const n=new Set;for(const o of e.getProperties()){if(!s.isPropertyAssignment(o))return f(o,"metadata fields without spreads, getters, or shorthand");const r=o.getNameNode(),a=s.isStringLiteral(r)?r.getLiteralValue():r.getText();if(!s.isIdentifier(r)&&!s.isStringLiteral(r)||!t.includes(a)||n.has(a))return f(o,"supported, unique metadata fields");n.add(a)}return e},y=(e,i)=>{const t=e.getProperty(i);return t&&s.isPropertyAssignment(t)?t.getInitializer():void 0},pe=e=>{const i=S(e,e,["credentialHeaders","maxAge","scope","staleWhileRevalidate","tag","vary"]),t={};for(const r of["maxAge","staleWhileRevalidate"]){const a=y(i,r);if(!(a===void 0&&r!=="maxAge")){if(!a||!s.isNumericLiteral(a))return f(e,`cache.${r}`);t[r]=a.getLiteralValue()}}const n=y(i,"scope");if(!n||!s.isStringLiteral(n)||!["private","public"].includes(n.getLiteralValue()))return f(e,"cache.scope");t.scope=n.getLiteralValue();for(const r of["tag","vary"]){const a=y(i,r);if(a!==void 0){if(!s.isStringLiteral(a))return f(a,`cache.${r}`);t[r]=a.getLiteralValue()}}const o=y(i,"credentialHeaders");if(o!==void 0){if(!s.isArrayLiteralExpression(o))return f(o,"cache.credentialHeaders");t.credentialHeaders=o.getElements().map(r=>s.isStringLiteral(r)?r.getLiteralValue():f(r,"cache.credentialHeaders string entries"))}return t},fe=e=>{const i=S(e.getArguments()[0],e,["rest","cache"]),t=y(i,"rest"),n=y(i,"cache");return t!==void 0&&!s.isTrueLiteral(t)&&!s.isFalseLiteral(t)?f(t,".expose({ rest })"):{...t?{rest:s.isTrueLiteral(t)}:{},...n?{cache:pe(n)}:{}}},me=e=>{const i=S(e.getArguments()[0],e,["price"]),t=y(i,"price");return!t||!s.isStringLiteral(t)&&!s.isNumericLiteral(t)?f(e,"`.x402({ price })` value"):{price:t.getLiteralValue()}},he=e=>{const i=e.map(o=>{const r=o.getArguments()[0];return r===void 0?ee:te(r)}),t=i.every(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)),n=i.reduce((o,r)=>({...r,...o}),{});return t?n:"unloaded"},ye=e=>{const{factory:i,steps:t}=X(e);if(!i)return f(e,"metadata from a resolvable Lunora factory root");const n={visibility:i.startsWith("internal")?"internal":"public"};for(const{call:r,name:a}of t){if(!["expose","input","meta","output","use","x402"].includes(a))return f(r,`known builder modifiers, got .${a}()`);a==="expose"&&n.expose===void 0&&(n.expose=fe(r)),a==="x402"&&n.x402===void 0&&(n.x402=me(r))}const o=t.filter(r=>r.name==="meta").map(r=>r.call);return o.length===0?n:{...n,meta:he(o)}},ve=new Set(["action","mutation","query","stream"]),N=(e,i,t)=>{const n=e.getProperty(i)?.getTypeAtLocation(t);if(n===void 0)return;const o=n.isUnion()?n.getUnionTypes().filter(a=>!a.isUndefined()):[n],r=o.length===1?o[0]?.getLiteralValue():void 0;return typeof r=="string"?r:void 0},U=(e,i)=>{const t=N(e,"kind",i);return t!==void 0&&ve.has(t)&&e.getProperty("handler")!==void 0?t:void 0},be=e=>{const i=e.getParent();if(s.isPropertyAccessExpression(i)&&i.getExpression()===e)return i.getName()==="functions";if(s.isElementAccessExpression(i)&&i.getExpression()===e){const n=i.getArgumentExpression();return n!==void 0&&s.isStringLiteral(n)&&n.getLiteralValue()==="functions"}const t=s.isVariableDeclaration(i)&&i.getNameNode()!==e?i.getNameNode():void 0;return t!==void 0&&s.isObjectBindingPattern(t)&&t.getElements().some(n=>(n.getPropertyNameNode()?.getText()??n.getName())==="functions")},it=(e,i)=>{for(const t of e)for(const n of t.getVariableDeclarations()){const o=n.getNameNode();if(!n.isExported()||!s.isIdentifier(o))continue;const a=(n.getType().getProperty("functions")?.getTypeAtLocation(n)?.getProperties()??[]).filter(u=>U(u.getTypeAtLocation(n),n)!==void 0);if(a.length===0||o.findReferencesAsNodes().some(u=>be(u)))continue;const l=n.getName(),d=a.map(u=>u.getName()).join(", ");console.warn(`@lunora/codegen: ${i(t)}:${l} ships functions (${d}) that nothing re-exports, so none is in the generated api. Add \`export const { ${d} } = ${l}.functions;\` (or export your own wrappers of them).`)}},Ne=new Set(["connect","disconnect","init","reactor","whisper"]),Le={ArrayBuffer:"bytes",GeoPoint:"geoPoint"},Ae=8,P=(e,i)=>{const t=e.getText(i);return t===""?{kind:"from"}:{kind:"from",tsType:t}},Ee=new Set(["false","true"]),Pe=[[e=>e.isAny()||e.isUnknown(),"any"],[e=>e.isString(),"string"],[e=>e.isNumber(),"number"],[e=>e.isBoolean(),"boolean"],[e=>e.isNull(),"null"],[e=>e.isBigInt(),"bigint"]],Te=(e,i,t)=>{if(!e.isObject()||e.isIntersection()||e.getCallSignatures().length>0||e.isClass())return;const n=e.getProperties();if(n.some(r=>r.getTypeAtLocation(i).getCallSignatures().length>0))return;const o=e.getStringIndexType();if(o!==void 0&&n.length===0)return{keyType:{kind:"string"},kind:"record",valueType:b(o,i,t+1)};if(!(o!==void 0||n.length===0))return{kind:"object",shape:Object.fromEntries(n.map(r=>[r.getName(),$(r.getTypeAtLocation(i),r.isOptional(),i,t+1)]))}},b=(e,i,t)=>{if(t>Ae)return P(e,i);const n=Pe.find(([a])=>a(e));if(n!==void 0)return{kind:n[1]};const o=Le[(e.getSymbol()??e.getAliasSymbol())?.getName()??""];if(o!==void 0)return{kind:o};if(e.isStringLiteral()||e.isNumberLiteral()||e.isBooleanLiteral()||e.isBigIntLiteral())return{kind:"literal",literalValue:e.getText(i),sensitive:!0};const r=e.isIntersection()?N(e,"__table",i):void 0;if(r!==void 0)return{kind:"id",tableName:r};if(e.isUnion())return F(e.getUnionTypes(),i,t);if(e.isArray()){const a=e.getArrayElementType();return a===void 0?P(e,i):{inner:b(a,i,t+1),kind:"array"}}return Te(e,i,t)??P(e,i)},F=(e,i,t)=>{const o=new Set(e.filter(l=>l.isBooleanLiteral()).map(l=>l.getText(i))).size===Ee.size,r=e.filter(l=>!(o&&l.isBooleanLiteral())).map(l=>b(l,i,t+1)),a=o?[...r,{kind:"boolean"}]:r,[c]=a;return a.length===1&&c!==void 0?c:{kind:"union",members:a}},$=(e,i,t,n)=>{const o=e.isUnion()?e.getUnionTypes():[e],r=o.filter(l=>!l.isUndefined());if(!i&&r.length===o.length)return b(e,t,n);if(r.length===0)return{inner:{kind:"any"},kind:"optional"};const[a]=r;return{inner:r.length===1&&a!==void 0?b(a,t,n):F(r,t,n),kind:"optional"}},xe=(e,i)=>{const t=e.getProperty("__type")?.getTypeAtLocation(i);if(t===void 0)return{kind:"from"};const n=(e.getSymbol()??e.getAliasSymbol())?.getName();return n==="TimestampColumnValidator"?{kind:"timestamp"}:n==="ObjectColumnValidator"&&t.getProperties().length===0?{kind:"object",shape:{}}:$(t,!1,i,0)},Se=new Set(["AsyncGenerator","AsyncIterable","AsyncIterableIterator"]),Oe=(e,i)=>{const t=e.getProperty("handler")?.getTypeAtLocation(i).getCallSignatures()[0]?.getReturnType();if(t===void 0)return[];if(Se.has((t.getSymbol()??t.getAliasSymbol())?.getName()??"")){const[n]=t.getTypeArguments();return n===void 0?[]:[n]}return(t.isUnion()?t.getUnionTypes():[t]).map(n=>n.getSymbol()?.getName()==="Promise"?n.getTypeArguments()[0]??n:n)},we=(e,i)=>{const t=[...new Set(e.map(n=>Y(n,i)))];return t.length===0||t.includes("unknown")?"unknown":t.join(" | ")},Ie=(e,i,t,n)=>{const o=e.getType(),r=U(o,e);if(r===void 0)return;const a={...n?{description:n}:{},exportName:i,filePath:t,kind:r};if(o.getProperty("channel")?.isOptional()===!1)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a room from a published package; its name is not in the declared type, so codegen cannot route it. Declare the room with \`defineRoom\` in this file instead.`);const c=N(o,"lifecycle",e),l=o.getProperty("lifecycle");if(c===void 0&&l!==void 0&&!l.isOptional())throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a lifecycle hook from a published package whose type does not say which moment it runs at. Declare it with its moment, e.g. \`RegisteredLifecycleHook & { readonly lifecycle: "disconnect" }\` (what \`onDisconnect\` returns).`);if(c!==void 0){if(!Ne.has(c))throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a "${c}" lifecycle hook from a published package; only a locally declared hook can carry its route. Declare it in this file instead.`);return{...a,args:{},lifecycle:c,returnType:"void",visibility:"internal"}}const d=N(o,"visibility",e);if(d!=="internal"&&d!=="public")throw new g("PUBLISHED_FUNCTION_VISIBILITY_UNKNOWN",`${t}:${i} re-exports a function from a published package whose type does not say whether it is internal or public. Declare it in that package as \`RegisteredQuery\` / \`RegisteredMutation\` / \`RegisteredAction\` (public) or their \`RegisteredInternal*\` counterparts, not the bare \`RegisteredFunction\`, so codegen does not list an internal function in the client \`api\`.`);if(d==="internal"&&o.getProperty("visibility")?.isOptional()!==!1)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports an internal function from a published package whose type makes \`visibility\` optional, so the value may not carry it. Declare it with a \`RegisteredInternal*\` type, which requires \`visibility: "internal"\`.`);const u=o.getProperty("args")?.getTypeAtLocation(e);if(u===void 0||u.isAny()||u.isUnknown()||u.getStringIndexType()!==void 0||u.getNumberIndexType()!==void 0)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a function from a published package whose type does not list its arguments. Declare its validator map with one key per argument (an empty \`{}\` for none) so codegen can type the client call.`);const m=Object.fromEntries(u.getProperties().map(p=>[p.getName(),xe(p.getTypeAtLocation(e),e)]));return{...a,args:m,...r==="query"?{readsIp:!0}:{},returnType:we(Oe(o,e),e),typeDerivedArgs:!0,visibility:d}},ke=8,A=(e,i=0)=>{if(i>ke)return;if(s.isCallExpression(e))return{call:e};if(s.isParenthesizedExpression(e)||s.isAsExpression(e)||s.isSatisfiesExpression(e)||s.isNonNullExpression(e))return A(e.getExpression(),i+1);if(!s.isIdentifier(e)&&!s.isPropertyAccessExpression(e))return;const t=e.getSymbol()?.getValueDeclaration();return t?T(t,i+1):void 0},T=(e,i)=>{if(s.isVariableDeclaration(e)||s.isPropertyAssignment(e)){const t=e.getInitializer();return t?A(t,i):{deadEnd:e}}if(s.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol()?.getValueDeclaration();return t?T(t,i+1):void 0}if(s.isBindingElement(e)){const t=H(e),r=e.getFirstAncestorByKind(B.VariableDeclaration)?.getInitializer()?.getType().getProperty(t)?.getValueDeclaration();return r?T(r,i+1):void 0}return{deadEnd:e}},x=e=>{const i=A(e);return i!==void 0&&"call"in i?i.call:void 0},_=e=>{const i=A(e);return i!==void 0&&"deadEnd"in i&&i.deadEnd.getSourceFile().isDeclarationFile()},_e=(e,i=()=>!0)=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t)){const r=[];for(const a of t.getElements().filter(c=>i(c.getName()))){const c=x(a.getNameNode());c&&r.push([a.getName(),c])}return r}if(!i(e.getName()))return[];const n=e.getInitializer(),o=n&&(s.isCallExpression(n)?n:x(n));return o?[[e.getName(),o]]:[]},Re=(e,i)=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t))return t.getElements().filter(o=>i(o.getName())&&_(o.getNameNode())).map(o=>[o.getName(),o.getNameNode()]);const n=e.getInitializer();return i(e.getName())&&n!==void 0&&_(n)?[[e.getName(),t]]:[]},De=e=>{const i=e.getArguments()[0],t=s.isObjectLiteralExpression(i)?i.getProperty("name"):void 0,n=s.isPropertyAssignment(t)?t.getInitializer():void 0;if(!n||!s.isStringLiteral(n))throw new g("ROOM_NAME_NOT_LITERAL",'defineRoom needs a string-literal `name` (e.g. `defineRoom({ name: "chat", … })`) so codegen can type its reference.');return n.getLiteralValue()},Ce=e=>e.startsWith("/")&&new URL(e,"https://lunora.invalid").pathname===e&&e!=="/_lunora"&&!e.startsWith("/_lunora/"),Ue=e=>{const i=e.getArguments()[0];if(!s.isObjectLiteralExpression(i))throw new g("SOCKET_PATH_NOT_LITERAL","defineWebSocket needs an object-literal options argument so codegen can read its `path` and `auth`.");const t=i.getProperty("path"),n=s.isPropertyAssignment(t)?t.getInitializer():void 0;if(!n||!s.isStringLiteral(n))throw new g("SOCKET_PATH_NOT_LITERAL",'defineWebSocket needs a string-literal `path` (e.g. `defineWebSocket({ path: "/chat", … })`) so codegen can route its upgrade.');const o=n.getLiteralValue();if(!Ce(o))throw new g("SOCKET_PATH_INVALID",`defineWebSocket path "${o}" must be a plain URL path starting with "/" (no "?", "#", ".." or unencoded characters) and not under "/_lunora".`);if(i.getProperties().some(l=>s.isSpreadAssignment(l)||s.isPropertyAssignment(l)&&s.isComputedPropertyName(l.getNameNode())))throw new g("SOCKET_AUTH_NOT_LITERAL","defineWebSocket cannot spread its options or use a computed key: codegen must read `auth` as a literal `auth: true` or `auth: false`.");const a=i.getProperty("auth");if(a===void 0)return{auth:!1,path:o};const c=s.isPropertyAssignment(a)?a.getInitializer():void 0;if(c===void 0||!(s.isTrueLiteral(c)||s.isFalseLiteral(c)))throw new g("SOCKET_AUTH_NOT_LITERAL","defineWebSocket needs a literal `auth: true` or `auth: false`, so codegen can read whether the route requires a session. A shorthand or a variable is not read.");return{auth:s.isTrueLiteral(c),path:o}},Fe=(e,i,t,n)=>{const o=n?ye(i):void 0,r=n?o?.expose:ue(i),a=n?o?.x402:de(i),c=w(()=>ae(i)),l=w(()=>oe(e)),d=z({kind:t.kind,output:c.value});return G(d?c.erased:l.erased),{args:se(i),...r?{expose:r}:{},...a?{x402:a}:{},...o?.meta===void 0?{}:{meta:o.meta},...t.adminOnly?{adminOnly:!0}:{},kind:t.kind,...c.value?{output:c.value}:{},returnType:l.value,visibility:o?.visibility==="internal"||t.visibility==="internal"?"internal":"public"}},$e=(e,i)=>{const t=Q(e,i);if(!t)return;if(t.channel)return{args:{},channel:{kind:t.channel,name:De(e)},kind:t.kind,returnType:"void",visibility:t.visibility};const{receiver:n}=t;return n?Fe(e,n,t,i):t.lifecycle?{args:{},kind:t.kind,lifecycle:t.lifecycle,returnType:"void",...t.lifecycle==="socket"?{socket:{...Ue(e),origin:`${e.getSourceFile().getFilePath()}@${String(e.getStart())}`}}:{},visibility:t.visibility}:{args:ge(e),kind:t.kind,returnType:re(e),visibility:t.visibility}},V=e=>{const i=e?.getJsDocs().at(-1)?.getDescription().trim();return i===""?void 0:i},Ve=e=>V(e.getFirstAncestor(i=>s.isVariableStatement(i))),je=e=>{const i=new Map;for(const t of e.getVariableStatements())if(t.isExported())for(const n of t.getDeclarations())i.has(n.getName())||i.set(n.getName(),t);return t=>V(i.get(t))},j=(e,i,t,n,o)=>{const r=$e(e,n);if(!r)return;const a=o??Ve(e);return{args:r.args,...a?{description:a}:{},exportName:i,filePath:t,kind:r.kind,returnType:r.returnType,...r.output?{output:r.output}:{},...r.meta===void 0?{}:{meta:r.meta},visibility:r.visibility,...r.adminOnly?{adminOnly:!0}:{},...r.kind==="query"&&(ne(e)===void 0||J(e))?{readsIp:!0}:{},...r.expose?{expose:r.expose}:{},...r.x402?{x402:r.x402}:{},...r.lifecycle?{lifecycle:r.lifecycle}:{},...r.channel?{channel:r.channel}:{},...r.socket?{socket:r.socket}:{}}},Be=(e,i,t)=>{const n=[];for(const o of e.getExportAssignments()){if(o.isExportEquals())continue;const r=x(o.getExpression()),a=r?j(r,"default",i,t):void 0;r&&a&&n.push({call:r,entry:a})}return n},ze=(e,i,t)=>{const n=K(e),o=je(e),r=new Map,a=(d,u)=>{if(d?.channel?.kind!=="room")return;const m=r.get(d.channel.name);if(m!==void 0&&m!==u)throw new g("DUPLICATE_ROOM_NAME",`Duplicate room name "${d.channel.name}" in ${i}: two defineRoom calls share it. Room names must be unique.`);r.set(d.channel.name,u)},c=e.getVariableStatements().flatMap(d=>d.getDeclarations()).flatMap(d=>_e(d,u=>n.has(u))).flatMap(([d,u])=>(n.get(d)??[]).filter(m=>O(m)).flatMap(m=>{const p=j(u,m,i,t,o(m));return a(p,u),p?[p]:[]})),l=new Set(c.map(d=>d.exportName));for(const d of e.getVariableStatements().flatMap(u=>u.getDeclarations()))for(const[u,m]of Re(d,p=>n.has(p)))for(const p of(n.get(u)??[]).filter(v=>O(v)&&!l.has(v))){const v=Ie(m,p,i,o(p));v&&(c.push(v),l.add(p))}for(const{call:d,entry:u}of Be(e,i,t))l.has(u.exportName)||(a(u,d),c.push(u));return c},He=e=>{const i=new Map;for(const t of e){if(t.channel?.kind!=="room")continue;const n=i.get(t.channel.name);if(n!==void 0&&n.file!==t.filePath)throw new g("DUPLICATE_ROOM_NAME",`Duplicate room name "${t.channel.name}": defined in ${n.origin} and ${t.filePath}:${t.exportName}. Room names must be unique across the project.`);n===void 0&&i.set(t.channel.name,{file:t.filePath,origin:`${t.filePath}:${t.exportName}`})}},Me=e=>{const i=new Map;for(const t of e){const n=ie(t.filePath),o=i.get(n);if(o&&o!==t.filePath)throw Object.assign(new Error(`Namespace collision: "${o}" and "${t.filePath}" both resolve to "${n}". 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:[o,t.filePath],status:500});i.set(n,t.filePath)}},nt=(e,i,t={})=>{const n=M(i),o=[];for(const r of n){const a=e.getSourceFile(r)??e.addSourceFileAtPath(r),c=W(i,r);o.push(...ze(a,c,t.lazyFunctions===!0))}return o.sort((r,a)=>`${r.filePath}:${r.exportName}`.localeCompare(`${a.filePath}:${a.exportName}`)),Me(o),He(o),o};export{nt as d,I as i,ne as p,it as w};
@@ -1 +1 @@
1
- import{Node as r}from"ts-morph";import{listLunoraSourceFiles as u,lunoraRelativePath as f}from"./isTestPath-ClgKgMYM.mjs";import{j as m,h as p}from"./attribution-DjweYNgJ.mjs";import{t as d}from"./database-calls-B_85LJIk.mjs";import{w as g,c as h}from"./classify-procedure-call-BuF5PNwV.mjs";import{a as k}from"./property-name-7cBlgK_O.mjs";const l=e=>{if(!(!r.isPropertyAssignment(e)&&!r.isShorthandPropertyAssignment(e)&&!r.isMethodDeclaration(e)&&!r.isGetAccessorDeclaration(e)))return k(e)},v=e=>g(e,"use","mask"),D=e=>{if(r.isPropertyAssignment(e)){const s=e.getInitializer();if(s&&r.isStringLiteral(s)){const t=s.getLiteralText();if(t==="redact"||t==="hash")return t}}return"custom"},P=e=>{const s=e.getArguments()[0];if(!s||!r.isObjectLiteralExpression(s))return[];const t=[];for(const i of s.getProperties()){const o=l(i);if(o===void 0||!r.isPropertyAssignment(i))continue;const n=i.getInitializer();if(!(!n||!r.isObjectLiteralExpression(n)))for(const a of n.getProperties()){const c=l(a);c!==void 0&&t.push({column:c,table:o})}}return t},y=e=>{const s=v(e);return{maskColumns:s.flatMap(t=>P(t)),usesMask:s.length>0}},C=new Set(["explain","findFirst","findFirstOrThrow","findMany","get","query"]),M=new Set(["delete","insert","patch","replace"]),x=(e,s)=>{if(!r.isVariableDeclaration(e))return;const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const i=h(t);if(!i)return;const o=i.receiver?y(i.receiver):{maskColumns:[],usesMask:!1},{tablesRead:n,tablesWritten:a}=d(e,C,M);return{exportName:p(e)??e.getName(),file:s,maskColumns:o.maskColumns,tablesRead:n,tablesWritten:a,usesMask:o.usesMask,visibility:i.visibility}},E=(e,s)=>{const t=[];for(const i of u(s)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i),n=f(s,i);for(const a of m(o)){const c=x(a,n);c&&t.push(c)}}return t};export{l as a,E as d,v as m,D as s};
1
+ import{Node as r}from"ts-morph";import{listLunoraSourceFiles as u,lunoraRelativePath as f}from"./isTestPath-B357_sbh.mjs";import{j as m,h as p}from"./attribution-C6VQNs-V.mjs";import{t as d}from"./database-calls-HP2mxQAR.mjs";import{w as g,c as h}from"./classify-procedure-call-DwWrpCoX.mjs";import{a as k}from"./property-name-7cBlgK_O.mjs";const l=e=>{if(!(!r.isPropertyAssignment(e)&&!r.isShorthandPropertyAssignment(e)&&!r.isMethodDeclaration(e)&&!r.isGetAccessorDeclaration(e)))return k(e)},v=e=>g(e,"use","mask"),D=e=>{if(r.isPropertyAssignment(e)){const s=e.getInitializer();if(s&&r.isStringLiteral(s)){const t=s.getLiteralText();if(t==="redact"||t==="hash")return t}}return"custom"},P=e=>{const s=e.getArguments()[0];if(!s||!r.isObjectLiteralExpression(s))return[];const t=[];for(const i of s.getProperties()){const o=l(i);if(o===void 0||!r.isPropertyAssignment(i))continue;const n=i.getInitializer();if(!(!n||!r.isObjectLiteralExpression(n)))for(const a of n.getProperties()){const c=l(a);c!==void 0&&t.push({column:c,table:o})}}return t},y=e=>{const s=v(e);return{maskColumns:s.flatMap(t=>P(t)),usesMask:s.length>0}},C=new Set(["explain","findFirst","findFirstOrThrow","findMany","get","query"]),M=new Set(["delete","insert","patch","replace"]),x=(e,s)=>{if(!r.isVariableDeclaration(e))return;const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const i=h(t);if(!i)return;const o=i.receiver?y(i.receiver):{maskColumns:[],usesMask:!1},{tablesRead:n,tablesWritten:a}=d(e,C,M);return{exportName:p(e)??e.getName(),file:s,maskColumns:o.maskColumns,tablesRead:n,tablesWritten:a,usesMask:o.usesMask,visibility:i.visibility}},E=(e,s)=>{const t=[];for(const i of u(s)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i),n=f(s,i);for(const a of m(o)){const c=x(a,n);c&&t.push(c)}}return t};export{l as a,E as d,v as m,D as s};
@@ -1 +1 @@
1
- import{Node as s,SyntaxKind as i}from"ts-morph";import{i as n}from"./context-root-2wag3akK.mjs";const o=/rate|limit|\bip\b|geo|throttle/iu,a=/^run[A-Z]/u,l=t=>s.isIdentifier(t)?(t.getSymbol()?.getDeclarations()??[]).some(r=>r.getFirstAncestorByKind(i.ImportDeclaration)?.getModuleSpecifierValue().startsWith("@lunora/")===!0):!1,c=t=>{const e=s.isCallExpression(t)?t.getExpression():t;let r;return s.isIdentifier(e)?r=e:s.isPropertyAccessExpression(e)&&(r=e.getNameNode()),r!==void 0&&l(s.isPropertyAccessExpression(e)?e.getExpression():r)&&!o.test(r.getText())},p=t=>{const e=s.isCallExpression(t)?t.getExpression():void 0;if(s.isElementAccessExpression(e)){const r=e.getArgumentExpression();return(s.isStringLiteral(r)||s.isNoSubstitutionTemplateLiteral(r))&&r.getLiteralText()==="use"}return s.isPropertyAccessExpression(e)&&e.getName()==="use"},g=t=>{const e=t.getParent();return s.isPropertyAccessExpression(e)&&e.getExpression()===t?!a.test(e.getName()):s.isElementAccessExpression(e)&&e.getExpression()===t?s.isStringLiteral(e.getArgumentExpression())||s.isNoSubstitutionTemplateLiteral(e.getArgumentExpression()):s.isVariableDeclaration(e)&&e.getInitializer()?.getText()===t.getText()},u=t=>{if(s.isPropertyAccessExpression(t))return t.getName()==="ip";if(s.isElementAccessExpression(t)){const e=t.getArgumentExpression();return(s.isStringLiteral(e)||s.isNoSubstitutionTemplateLiteral(e))&&e.getLiteralText()==="ip"}return s.isBindingElement(t)?t.getDotDotDotToken()!==void 0||(t.getPropertyNameNode()?.getText()??t.getName())==="ip":s.isShorthandPropertyAssignment(t)&&t.getName()==="ip"},A=t=>{for(const e of t.getDescendants()){if(u(e)||p(e)&&!c(e.getArguments()[0]))return!0;if(s.isIdentifier(e)&&n(e)&&!g(e)){const r=e.getParent();if(!(s.isParameterDeclaration(r)||s.isBindingElement(r)||s.isVariableDeclaration(r)))return!0}}return!1};export{A as m};
1
+ import{Node as s,SyntaxKind as i}from"ts-morph";import{i as n}from"./context-root-CY5kkBER.mjs";const o=/rate|limit|\bip\b|geo|throttle/iu,a=/^run[A-Z]/u,l=t=>s.isIdentifier(t)?(t.getSymbol()?.getDeclarations()??[]).some(r=>r.getFirstAncestorByKind(i.ImportDeclaration)?.getModuleSpecifierValue().startsWith("@lunora/")===!0):!1,c=t=>{const e=s.isCallExpression(t)?t.getExpression():t;let r;return s.isIdentifier(e)?r=e:s.isPropertyAccessExpression(e)&&(r=e.getNameNode()),r!==void 0&&l(s.isPropertyAccessExpression(e)?e.getExpression():r)&&!o.test(r.getText())},p=t=>{const e=s.isCallExpression(t)?t.getExpression():void 0;if(s.isElementAccessExpression(e)){const r=e.getArgumentExpression();return(s.isStringLiteral(r)||s.isNoSubstitutionTemplateLiteral(r))&&r.getLiteralText()==="use"}return s.isPropertyAccessExpression(e)&&e.getName()==="use"},g=t=>{const e=t.getParent();return s.isPropertyAccessExpression(e)&&e.getExpression()===t?!a.test(e.getName()):s.isElementAccessExpression(e)&&e.getExpression()===t?s.isStringLiteral(e.getArgumentExpression())||s.isNoSubstitutionTemplateLiteral(e.getArgumentExpression()):s.isVariableDeclaration(e)&&e.getInitializer()?.getText()===t.getText()},u=t=>{if(s.isPropertyAccessExpression(t))return t.getName()==="ip";if(s.isElementAccessExpression(t)){const e=t.getArgumentExpression();return(s.isStringLiteral(e)||s.isNoSubstitutionTemplateLiteral(e))&&e.getLiteralText()==="ip"}return s.isBindingElement(t)?t.getDotDotDotToken()!==void 0||(t.getPropertyNameNode()?.getText()??t.getName())==="ip":s.isShorthandPropertyAssignment(t)&&t.getName()==="ip"},A=t=>{for(const e of t.getDescendants()){if(u(e)||p(e)&&!c(e.getArguments()[0]))return!0;if(s.isIdentifier(e)&&n(e)&&!g(e)){const r=e.getParent();if(!(s.isParameterDeclaration(r)||s.isBindingElement(r)||s.isVariableDeclaration(r)))return!0}}return!1};export{A as m};
@@ -0,0 +1 @@
1
+ import{statSync as A,readdirSync as P,realpathSync as D,lstatSync as I}from"node:fs";import{dirname as w,join as x,relative as F,sep as N,extname as O,basename as k}from"node:path";import{matcher as z}from"@visulima/fs";import{SyntaxKind as p,Node as s,VariableDeclarationKind as j}from"ts-morph";import{diagnosticAt as M}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{r as K}from"./project-config-file-DBVmBpin.mjs";import{findProjectConfigFile as $,findCodegenConfigFile as V}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{p as B,a as U}from"./property-name-7cBlgK_O.mjs";const W=/\.ts$/u,g=(e,t)=>F(e,t).split(N).join("/").replace(W,""),H=new Set(["_generated","node_modules"]),L=new Set(["__fixtures__","__mocks__","__snapshots__","__tests__"]),_=/\.(?:bench|e2e|e2e-spec|spec|spec-d|test|test-d)(?:\.tsx?)?$/u,ve=e=>{const t=e.split("/");return _.test(t.at(-1)??"")||t.slice(0,-1).some(i=>L.has(i))},d=(e,t,i)=>t?H.has(e)||!i&&L.has(e):!i&&_.test(e),v=new Map,E=()=>!1;let f;const X=e=>{const t=V(e),i=t===void 0?void 0:A(t,{throwIfNoEntry:!1});if(t===void 0||i===void 0)return E;const n=`${String(i.mtimeMs)}:${String(i.size)}`,r=v.get(t);if(r?.key===n)return r.isExcluded;const{codegen:o}=K(w(t));o?.unreadable&&console.warn("@lunora/codegen: `codegen.exclude` in lunora.config is not an array of string literals without `!` negations — ignoring it.");const c=o?.exclude?.length?z(o.exclude):E;return v.set(t,{isExcluded:c,key:n}),c},G=(e,t,i)=>e==="schema.ts"&&t===i,Y=e=>{try{return A(e)}catch{console.warn(`@lunora/codegen: skipping ${e} — it is a symlink that does not resolve (or vanished mid-scan).`);return}},R=(e,t,i,n,r)=>{let o,c;try{o=P(e),c=D(e)}catch{return t}if(n.has(c))return t;n.add(c);for(const l of o){const u=x(e,l),a=Y(u);a===void 0||r(l,F(i,u).split(N).join("/"),a.isDirectory())||(a.isDirectory()?R(u,t,i,n,r):a.isFile()&&O(l)===".ts"&&!G(l,e,i)&&t.push(u))}return t},C=(e,t={})=>{const i=t.includeSkipped??!1,n=`${String(i)}\0${e}`,r=f?.get(n);if(r!==void 0)return[...r];const o=i?E:X(e),c=R(e,[],e,new Set,(l,u,a)=>d(l,a,i)||o(u));return f?.set(n,c),[...c]},he=e=>{if(f!==void 0)return e();f=new Map;try{return e()}finally{f=void 0}},q=["src/server","src/index.ts","src/worker.ts"],Q=new Set([".ts",".tsx"]),T=(e,t=[])=>{let i;try{i=I(e)}catch{return t}if(i.isFile())return Q.has(O(e))&&!d(k(e),!1,!1)&&t.push(e),t;if(!i.isDirectory())return t;for(const n of P(e))d(n,!0,!1)||T(x(e,n),t);return t},J=e=>{const t=w(e),i=C(e).map(o=>({displayPath:g(e,o),filePath:o})),n=new Set(i.map(o=>o.filePath)),r=$(t);for(const o of[...q.flatMap(c=>T(x(t,c))),...r===void 0?[]:[r]])n.has(o)||(n.add(o),i.push({displayPath:g(t,o),filePath:o}));return i},Z=e=>Array.isArray(e),h=new WeakMap,ee=(e,t)=>{let i=h.get(e.compilerNode);i===void 0&&(i=new Map,h.set(e.compilerNode,i));let n=i.get(t);return n===void 0&&(n=e.getDescendantsOfKind(t),i.set(t,n)),n},b=(e,t,i,n)=>{const r=[];for(const{displayPath:o,filePath:c}of t){const l=e.getSourceFile(c)??e.addSourceFileAtPath(c);for(const u of ee(l,i)){const a=n(u,o);Z(a)?r.push(...a):a!==void 0&&r.push(a)}}return r},te=e=>C(e).map(t=>({displayPath:g(e,t),filePath:t})),ie=(e,t,i,n)=>b(e,te(t),i,n),ye=(e,t,i)=>ie(e,t,p.CallExpression,i),Ae=(e,t,i)=>b(e,J(t),p.CallExpression,i),Pe=e=>B(e.getPropertyNameNode()??e.getNameNode()),S=(e,t)=>e?.getProperties().find(i=>!s.isSpreadAssignment(i)&&U(i)===t),we=(e,t)=>{if(t){const o=e.getArguments()[0];return o&&(s.isArrowFunction(o)||s.isFunctionExpression(o))?o:void 0}const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return;const n=S(i,"handler");if(!n||!s.isPropertyAssignment(n))return;const r=n.getInitializer();return r&&(s.isArrowFunction(r)||s.isFunctionExpression(r))?r:void 0},Fe=(e,t)=>{if(!e||!s.isObjectLiteralExpression(e))return;const i=S(e,t);return i&&s.isPropertyAssignment(i)?i.getInitializer():void 0},se=e=>{const t=e?.getParent();return s.isVariableDeclaration(e)&&s.isVariableDeclarationList(t)&&t.getDeclarationKind()===j.Const},ne=e=>{let t=e,i=t.getParent();for(;i!==void 0&&(s.isParenthesizedExpression(i)||s.isAsExpression(i)||s.isSatisfiesExpression(i)||s.isTypeAssertion(i)||s.isNonNullExpression(i));)t=i,i=t.getParent();return t},y=e=>{const t=ne(e),i=t.getParent();if(i===void 0)return!1;if(s.isBinaryExpression(i)){const r=i.getOperatorToken().getKind();return i.getLeft()===t&&r>=p.FirstAssignment&&r<=p.LastAssignment}if(s.isPrefixUnaryExpression(i)||s.isPostfixUnaryExpression(i)){const r=i.getOperatorToken();return r===p.PlusPlusToken||r===p.MinusMinusToken}return s.isDeleteExpression(i)?!0:s.isForOfStatement(i)||s.isForInStatement(i)?i.getInitializer()===t:s.isPropertyAssignment(i)?i.getInitializer()===t&&y(i):(s.isShorthandPropertyAssignment(i)||s.isSpreadAssignment(i)||s.isSpreadElement(i)||s.isObjectLiteralExpression(i)||s.isArrayLiteralExpression(i))&&y(i)},re=e=>{const t=e?.getDeclarations().find(n=>s.isVariableDeclaration(n));if(!se(t))return;const i=t.getParent().getParent();return s.isVariableStatement(i)&&s.isSourceFile(i.getParent())?t.getInitializer():void 0},oe=e=>re(e.getSymbol()),Ne=e=>{if(!e)return;if(s.isObjectLiteralExpression(e))return e;if(!s.isIdentifier(e))return;const t=oe(e);return t!==void 0&&s.isObjectLiteralExpression(t)?t:void 0},m=e=>{let t=e;for(;t&&(s.isAsExpression(t)||s.isSatisfiesExpression(t)||s.isParenthesizedExpression(t)||s.isNonNullExpression(t));)t=t.getExpression();return t},ce=(e,t)=>{let i=m(e);for(;s.isAwaitExpression(i)||s.isPropertyAccessExpression(i)||s.isElementAccessExpression(i)||s.isCallExpression(i);){const n=s.isCallExpression(i)?t?.(i):void 0;if(n!==void 0)return{verdict:n};i=m(i.getExpression())}return{root:i}},Oe=e=>ce(e).root,Le=e=>s.isArrowFunction(e)||s.isConstructorDeclaration(e)||s.isFunctionDeclaration(e)||s.isFunctionExpression(e)||s.isGetAccessorDeclaration(e)||s.isMethodDeclaration(e)||s.isSetAccessorDeclaration(e),_e=(e,t)=>e?.compilerNode===t.compilerNode,Re=e=>{if(s.isPropertyAccessExpression(e))return{member:e.getName(),object:e.getExpression()};const t=s.isElementAccessExpression(e)?e.getArgumentExpression():void 0;return s.isElementAccessExpression(e)&&s.isStringLiteral(t)?{member:t.getLiteralValue(),object:e.getExpression()}:void 0},Ce=e=>{const t=e.getParent();return s.isReturnStatement(t)||s.isArrowFunction(t)&&t.getBody()===e?e.getFirstAncestor(n=>s.isFunctionLikeDeclaration(n)||s.isArrowFunction(n)):void 0},Te=e=>{const t=m(e);return t&&s.isCallExpression(t)?t:void 0},be=e=>{const t=e.getExportAssignment(r=>!r.isExportEquals());if(!t)return;const i=t.getExpression();if(!s.isIdentifier(i))return i;const n=i.getSymbol()?.getValueDeclaration();return n&&s.isVariableDeclaration(n)?n.getInitializer():i},De=e=>{const t=e.getArguments()[1];return t&&s.isStringLiteral(t)?t.getLiteralValue():""},Ie=(e,t)=>{if(!s.isObjectLiteralExpression(e))return;const i=S(e,t);if(!i||!s.isPropertyAssignment(i))return;const n=i.getInitializer();return n&&s.isStringLiteral(n)?n.getLiteralText():void 0},ae=e=>{const t=e.getStatements(),[i]=t;if(t.length!==1||i===void 0||!s.isReturnStatement(i))return;const n=i.getExpression();return n!==void 0&&s.isObjectLiteralExpression(n)?n:void 0},ke=e=>{if(s.isObjectLiteralExpression(e))return e;if(s.isParenthesizedExpression(e)){const t=e.getExpression();return s.isObjectLiteralExpression(t)?t:void 0}return s.isBlock(e)?ae(e):void 0},ze=e=>(t,i,n)=>{if(s.isStringLiteral(t)||s.isNoSubstitutionTemplateLiteral(t))return t.getLiteralValue();throw M(t,`${e} "${i}": \`${n}\` must be a static string literal — it is deploy configuration codegen writes into wrangler.jsonc`)},le=new Set(["api","internal"]),je=new Set(["run","runAction","runMutation","runQuery"]),ue=e=>{if(e===void 0||!s.isPropertyAccessExpression(e))return;const t=[];let i=e;for(;s.isPropertyAccessExpression(i);)t.unshift(i.getName()),i=i.getExpression();return s.isIdentifier(i)&&le.has(i.getText())&&t.length>=2?t:void 0},Me=e=>{const t=ue(e);return t===void 0?void 0:`${t.slice(0,-1).join("_")}:${String(t.at(-1))}`};export{je as RUN_METHODS,W as TS_EXTENSION_RE,Pe as bindingKeyName,Oe as chainRootOf,ye as collectCallRows,ie as collectNodeRows,Ae as collectSecurityCallRows,be as defaultExportExpression,ee as descendantsOfKind,S as findObjectProperty,Me as functionKeyOf,ue as functionReferenceSegments,we as handlerOf,se as isConstDeclaration,Le as isFunctionLike,_e as isSameNode,ve as isTestPath,y as isWriteTarget,De as limitNameOf,C as listLunoraSourceFiles,J as listSecurityScanFiles,g as lunoraRelativePath,Re as memberAccessOf,ke as objectLiteralFromCallbackBody,Ne as optionsObjectLiteral,ne as outermostValueWrapper,Fe as propertyInitializer,U as propertyKeyName,B as propertyNameText,Ce as returningFunctionOf,ze as stringPropertyFor,Ie as stringPropertyOf,re as symbolConstInitializer,m as unwrapExpression,Te as unwrapToCallExpression,ce as walkChain,he as withSourceListMemo};
@@ -0,0 +1 @@
1
+ import{b as a,e as t,r as i,c,d,a as s}from"./project-config-file-DBVmBpin.mjs";import"./property-name-7cBlgK_O.mjs";import{PROJECT_CONFIG_FILENAMES as j,findProjectConfigFile as P}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";export{j as PROJECT_CONFIG_FILENAMES,P as findProjectConfigFile,a as loadProjectConfig,t as readMergeDurableObjects,i as readProjectConfigLiterals,c as readProjectLazyFunctions,d as readProjectSecurityHeaders,s as readProjectStudioCompanion};
@@ -1 +1 @@
1
- import{basename as b}from"node:path";import{Node as d}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{listLunoraSourceFiles as $,lunoraRelativePath as v,unwrapToCallExpression as E,defaultExportExpression as S,findObjectProperty as M}from"./isTestPath-ClgKgMYM.mjs";import{s as g}from"./dispatch-namespace-DwTjD7BU.mjs";const h=(e,o)=>e.find(t=>t.ownsFolder!==!1&&o.startsWith(`${t.name}/`))?.name,F="module.ts",w=(e,o,t)=>{if(d.isStringLiteral(e)||d.isNoSubstitutionTemplateLiteral(e))return e.getLiteralValue();throw c(e,`module "${o}": \`${t}\` must be a static string literal — codegen reads it without running the file`)},L=(e,o,t)=>{if(!d.isArrayLiteralExpression(e))throw c(e,`module "${o}": \`${t}\` must be an inline array of table names`);return e.getElements().map(n=>w(n,o,t))},p=(e,o,t)=>{const n=M(e,o);if(n!==void 0){if(!d.isPropertyAssignment(n))throw c(n,`module "${t}": write \`${o}\` inline as \`${o}: …\` — codegen reads it without running the file`);return n.getInitializerOrThrow()}},A=(e,o,t)=>{const n=e.getSourceFile(o)??e.addSourceFileAtPath(o),s=E(S(n)),a=s?.getExpression();if(!s||!a||!d.isIdentifier(a)||a.getText()!=="defineModule")return;if(t==="")throw c(s,"defineModule: lunora/module.ts would make the whole app one module — move it into the folder it describes (lunora/<module>/module.ts)");const i=s.getArguments()[0],m={name:t,tables:[]};if(i===void 0)return m;if(!d.isObjectLiteralExpression(i))throw c(i,`module "${t}": defineModule must be passed an inline object literal`);const r=p(i,"description",t);r!==void 0&&(m.description=w(r,t,"description"));const l=p(i,"tables",t);return l!==void 0&&(m.tables=L(l,t,"tables")),m},k=(e,o)=>{const t=[];for(const n of $(o)){if(b(n)!==F)continue;const s=v(o,n),a=A(e,n,s==="module"?"":s.slice(0,-7));a&&t.push(a)}return t.toSorted((n,s)=>n.name.localeCompare(s.name))},T=(e,o)=>{const t=new Set(e.map(r=>r.name)),n=new Set(e.flatMap(r=>r.tables)),s=o.tables.filter(r=>r.extensionKey!==void 0&&!n.has(r.name)),a=Map.groupBy(s,r=>String(r.extensionKey)),i=e.map(r=>{const l=a.get(r.name);return l===void 0?r:{...r,tables:[...r.tables,...l.map(u=>u.name)]}}),m=[...a].filter(([r])=>!t.has(r)).map(([r,l])=>{const u=l.every(f=>f.extensionFromPackage===!0);return{installed:!0,name:r,...u?{ownsFolder:!1}:{},tables:l.map(f=>f.name)}});return[...i,...m].toSorted((r,l)=>r.name.localeCompare(l.name))},x=e=>{for(const o of e){const t=e.find(n=>n.name.startsWith(`${o.name}/`));if(t)throw new Error(`@lunora/codegen: module "${t.name}" is nested inside ${o.installed===!0?"installed component":"module"} "${o.name}" — a file can belong to one module only, so move one of the two`)}},y=(e,o)=>{const t=new Set(o.tables.map(s=>s.name)),n=new Map;for(const s of e)for(const a of s.tables){if(!t.has(a))throw new Error(`@lunora/codegen: module "${s.name}" declares table "${a}", which lunora/schema.ts does not define`);const i=n.get(a);if(i!==void 0)throw new Error(`@lunora/codegen: table "${a}" is claimed by both module "${i}" and module "${s.name}" — a table has one owner`);n.set(a,s.name)}},C=(e,o,t)=>{if(e.length===0)return;const n=new Set(o.map(s=>s.name));for(const s of t){const a=g(s);if(h(o,s)===void 0&&n.has(a))throw new Error(`@lunora/codegen: lunora/${s}.ts sits beside module "${a}" and shares its name — move it into lunora/${a}/ or rename one of them`)}},z=(e,o,t)=>{const n=T(e,o);return x(n),y(n,o),C(e,n,t),n},K=(e,o)=>h(e,o)??g(o);export{h as a,k as d,K as m,z as r};
1
+ import{basename as b}from"node:path";import{Node as d}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{listLunoraSourceFiles as $,lunoraRelativePath as v,unwrapToCallExpression as E,defaultExportExpression as S,findObjectProperty as M}from"./isTestPath-B357_sbh.mjs";import{s as g}from"./dispatch-namespace-DwTjD7BU.mjs";const h=(e,o)=>e.find(t=>t.ownsFolder!==!1&&o.startsWith(`${t.name}/`))?.name,F="module.ts",w=(e,o,t)=>{if(d.isStringLiteral(e)||d.isNoSubstitutionTemplateLiteral(e))return e.getLiteralValue();throw c(e,`module "${o}": \`${t}\` must be a static string literal — codegen reads it without running the file`)},L=(e,o,t)=>{if(!d.isArrayLiteralExpression(e))throw c(e,`module "${o}": \`${t}\` must be an inline array of table names`);return e.getElements().map(n=>w(n,o,t))},p=(e,o,t)=>{const n=M(e,o);if(n!==void 0){if(!d.isPropertyAssignment(n))throw c(n,`module "${t}": write \`${o}\` inline as \`${o}: …\` — codegen reads it without running the file`);return n.getInitializerOrThrow()}},A=(e,o,t)=>{const n=e.getSourceFile(o)??e.addSourceFileAtPath(o),s=E(S(n)),a=s?.getExpression();if(!s||!a||!d.isIdentifier(a)||a.getText()!=="defineModule")return;if(t==="")throw c(s,"defineModule: lunora/module.ts would make the whole app one module — move it into the folder it describes (lunora/<module>/module.ts)");const i=s.getArguments()[0],m={name:t,tables:[]};if(i===void 0)return m;if(!d.isObjectLiteralExpression(i))throw c(i,`module "${t}": defineModule must be passed an inline object literal`);const r=p(i,"description",t);r!==void 0&&(m.description=w(r,t,"description"));const l=p(i,"tables",t);return l!==void 0&&(m.tables=L(l,t,"tables")),m},k=(e,o)=>{const t=[];for(const n of $(o)){if(b(n)!==F)continue;const s=v(o,n),a=A(e,n,s==="module"?"":s.slice(0,-7));a&&t.push(a)}return t.toSorted((n,s)=>n.name.localeCompare(s.name))},T=(e,o)=>{const t=new Set(e.map(r=>r.name)),n=new Set(e.flatMap(r=>r.tables)),s=o.tables.filter(r=>r.extensionKey!==void 0&&!n.has(r.name)),a=Map.groupBy(s,r=>String(r.extensionKey)),i=e.map(r=>{const l=a.get(r.name);return l===void 0?r:{...r,tables:[...r.tables,...l.map(u=>u.name)]}}),m=[...a].filter(([r])=>!t.has(r)).map(([r,l])=>{const u=l.every(f=>f.extensionFromPackage===!0);return{installed:!0,name:r,...u?{ownsFolder:!1}:{},tables:l.map(f=>f.name)}});return[...i,...m].toSorted((r,l)=>r.name.localeCompare(l.name))},x=e=>{for(const o of e){const t=e.find(n=>n.name.startsWith(`${o.name}/`));if(t)throw new Error(`@lunora/codegen: module "${t.name}" is nested inside ${o.installed===!0?"installed component":"module"} "${o.name}" — a file can belong to one module only, so move one of the two`)}},y=(e,o)=>{const t=new Set(o.tables.map(s=>s.name)),n=new Map;for(const s of e)for(const a of s.tables){if(!t.has(a))throw new Error(`@lunora/codegen: module "${s.name}" declares table "${a}", which lunora/schema.ts does not define`);const i=n.get(a);if(i!==void 0)throw new Error(`@lunora/codegen: table "${a}" is claimed by both module "${i}" and module "${s.name}" — a table has one owner`);n.set(a,s.name)}},C=(e,o,t)=>{if(e.length===0)return;const n=new Set(o.map(s=>s.name));for(const s of t){const a=g(s);if(h(o,s)===void 0&&n.has(a))throw new Error(`@lunora/codegen: lunora/${s}.ts sits beside module "${a}" and shares its name — move it into lunora/${a}/ or rename one of them`)}},z=(e,o,t)=>{const n=T(e,o);return x(n),y(n,o),C(e,n,t),n},K=(e,o)=>h(e,o)??g(o);export{h as a,k as d,K as m,z as r};
@@ -0,0 +1 @@
1
+ import{statSync as z,readFileSync as $}from"node:fs";import{basename as D}from"node:path";import{createJiti as M}from"jiti";import{Node as n,SyntaxKind as p,Project as _,VariableDeclarationKind as R}from"ts-morph";import{a as b}from"./property-name-7cBlgK_O.mjs";import{findProjectConfigFile as I,findCodegenConfigFile as O}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";const F=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},U=/^[a-z][\d+.a-z-]*:\/\/(?:\*\.)?[\d.a-z-]+(?::\d{1,5})?$/iu,C=e=>[...e].every(t=>t===" "||t>=" "&&t!==""&&t<="ÿ"),K=["same-origin","same-origin-allow-popups","unsafe-none"],H=["DENY","SAMEORIGIN"],L=["includeSubDomains","maxAge","preload"],w=["csp","permissionsPolicy","referrerPolicy"],A=[...w,"crossOriginOpenerPolicy","frameAncestors","frameOptions","hsts"],S=e=>e.map(t=>JSON.stringify(t)).join(", "),J=(e,t)=>{if(typeof e=="boolean")return e;if(!F(e)){t.push("security.headers.hsts must be a boolean or an object { maxAge?, includeSubDomains?, preload? }");return}for(const o of Object.keys(e).filter(a=>!L.includes(a)))t.push(`security.headers.hsts.${o} is not an option (expected ${S(L)})`);const{includeSubDomains:r,maxAge:i,preload:s}=e;i!==void 0&&!(typeof i=="number"&&Number.isSafeInteger(i)&&i>=0)&&t.push(`security.headers.hsts.maxAge must be a whole number of seconds (got ${JSON.stringify(i)})`);for(const[o,a]of[["includeSubDomains",r],["preload",s]])a!==void 0&&typeof a!="boolean"&&t.push(`security.headers.hsts.${o} must be a boolean`);return{...r===void 0?{}:{includeSubDomains:r},...i===void 0?{}:{maxAge:i},...s===void 0?{}:{preload:s}}},P=(e,t,r,i)=>{if(t===void 0||t===!1||r.includes(t))return t;i.push(`security.headers.${e} must be one of ${S(r)} or false (got ${JSON.stringify(t)})`)},Y=(e,t)=>{if(e!==void 0){if(!Array.isArray(e)){t.push('security.headers.frameAncestors must be an array of origins like ["https://partner.example"]');return}for(const r of e)(typeof r!="string"||!U.test(r)||!C(r))&&t.push(`security.headers.frameAncestors entry ${JSON.stringify(r)} is not an origin like "https://partner.example"`);return[...e]}},W=e=>{if(e===void 0||typeof e=="boolean")return{ok:!0,value:e};if(!F(e))return{ok:!1,problems:[`security.headers must be a boolean or an object (got ${Array.isArray(e)?"an array":JSON.stringify(e)})`]};const t=Object.keys(e).filter(i=>!A.includes(i)).map(i=>`security.headers.${i} is not an option (expected ${S(A)})`),r={};for(const i of w){const s=e[i];s===void 0||s===!1?r[i]=s:typeof s!="string"?t.push(`security.headers.${i} must be a string or false`):C(s)?r[i]=s:t.push(`security.headers.${i} contains a line break or control character`)}return r.crossOriginOpenerPolicy=P("crossOriginOpenerPolicy",e.crossOriginOpenerPolicy,K,t),r.frameOptions=P("frameOptions",e.frameOptions,H,t),r.frameAncestors=Y(e.frameAncestors,t),r.hsts=e.hsts===void 0?void 0:J(e.hsts,t),r.frameAncestors!==void 0&&typeof r.csp=="string"&&t.push("security.headers.frameAncestors cannot be combined with a csp string: put the frame-ancestors directive in the csp"),r.frameAncestors!==void 0&&r.frameOptions==="DENY"&&t.push('security.headers.frameAncestors cannot be combined with frameOptions: "DENY"'),r.frameAncestors!==void 0&&r.csp===!1&&t.push("security.headers.frameAncestors needs the Content-Security-Policy that carries it; it cannot be combined with csp: false"),t.length>0?{ok:!1,problems:t}:{ok:!0,value:Object.fromEntries(Object.entries(r).filter(([,i])=>i!==void 0))}},d=Symbol("not-literal"),N=e=>Number(e.getText().replaceAll("_","")),G=e=>n.isStringLiteral(e)||n.isNoSubstitutionTemplateLiteral(e)?e.getLiteralValue():n.isNumericLiteral(e)?N(e):n.isPrefixUnaryExpression(e)&&e.getOperatorToken()===p.MinusToken&&n.isNumericLiteral(e.getOperand())?-N(e.getOperand()):n.isTrueLiteral(e)||n.isFalseLiteral(e)?e.getLiteralValue():n.isBinaryExpression(e)?B(e):n.isNullLiteral(e)?null:d,q={[p.AsteriskAsteriskToken]:(e,t)=>e**t,[p.AsteriskToken]:(e,t)=>e*t,[p.MinusToken]:(e,t)=>e-t,[p.PercentToken]:(e,t)=>e%t,[p.PlusToken]:(e,t)=>e+t,[p.SlashToken]:(e,t)=>e/t},B=e=>{const t=q[e.getOperatorToken().getKind()],[r,i]=[y(e.getLeft()),y(e.getRight())];return t!==void 0&&typeof r=="number"&&typeof i=="number"&&Number.isFinite(r)&&Number.isFinite(i)?t(r,i):d},y=e=>{if(n.isParenthesizedExpression(e)||n.isAsExpression(e)||n.isSatisfiesExpression(e))return y(e.getExpression());if(n.isArrayLiteralExpression(e)){const t=e.getElements().map(r=>y(r));return t.includes(d)?d:t}return n.isObjectLiteralExpression(e)?Q(e):G(e)},Q=e=>{const t=[];for(const r of e.getProperties()){const i=n.isPropertyAssignment(r)?r.getNameNode():void 0,s=n.isPropertyAssignment(r)?r.getInitializer():void 0,o=s===void 0?d:y(s);if(i===void 0||o===d||!(n.isIdentifier(i)||n.isStringLiteral(i)))return d;const a=n.isStringLiteral(i)?i.getLiteralValue():i.getText();if(a==="__proto__")return d;t.push([a,o])}return Object.fromEntries(t)},E=new Map,Ae=async e=>{const t=I(e);if(t===void 0)return{};let r;try{const o=z(t);r=`${String(o.mtimeMs)}:${String(o.size)}`}catch{return{}}const i=E.get(t);if(i?.key===r)return i.value;const s=(async()=>{try{const a=(await M(t,{interopDefault:!1,moduleCache:!1}).import(t))?.default;return{config:a!==null&&typeof a=="object"?a:void 0}}catch(o){return{error:o instanceof Error?o.message:String(o)}}})();return E.set(t,{key:r,value:s}),s},u=e=>{let t=e;for(;t!==void 0&&(n.isSatisfiesExpression(t)||n.isAsExpression(t)||n.isParenthesizedExpression(t));)t=t.getExpression();return t},X=e=>{const t=e.getExportAssignments().find(i=>!i.isExportEquals());let r=u(t?.getExpression());return r!==void 0&&n.isIdentifier(r)&&(r=u(e.getVariableDeclaration(r.getText())?.getInitializer())),r!==void 0&&n.isObjectLiteralExpression(r)?r:void 0},m=(e,t)=>n.isPropertyAssignment(e)?e.getInitializer():t.getVariableDeclaration(b(e))?.getInitializer(),g=(e,t,r)=>{const i=u(e);if(i===void 0||!n.isObjectLiteralExpression(i))return{unreadable:!0};const s=i.getProperties(),o=s.filter(l=>n.isPropertyAssignment(l)&&!n.isComputedPropertyName(l.getNameNode())||n.isShorthandPropertyAssignment(l));if(o.length!==s.length)return{unreadable:!0};const a=o.findLast(l=>b(l)===r);if(a===void 0)return{absent:!0};const c=m(a,t);return c===void 0?{unreadable:!0}:{literal:c}},Z=["exportName","file","reason","rule"],ee=e=>{const t=u(e);if(t===void 0||!n.isObjectLiteralExpression(t))return;const r={};for(const c of t.getProperties()){if(!n.isPropertyAssignment(c)||n.isComputedPropertyName(c.getNameNode()))return;const l=b(c),f=u(c.getInitializer());if(!Z.includes(l)||f===void 0||!n.isStringLiteral(f)&&!n.isNoSubstitutionTemplateLiteral(f))return;r[l]=f.getLiteralValue()}const{exportName:i,file:s,reason:o,rule:a}=r;return i?.trim()&&s?.trim()&&o?.trim()&&a?.trim()?{exportName:i,file:s,reason:o,rule:a}:void 0},te=(e,t)=>{const r=g(e,t,"accept");if("absent"in r)return{};const i="literal"in r?u(r.literal):void 0;if(i===void 0||!n.isArrayLiteralExpression(i))return{acceptUnreadable:!0};const s=[];for(const o of i.getElements()){const a=ee(o);if(a===void 0)return{acceptUnreadable:!0};s.push(a)}return{accept:s}},re=(e,t)=>{const r=g(e,t,"minSeverity"),i=te(e,t);return"absent"in r?{advisor:i}:"literal"in r&&n.isStringLiteral(r.literal)?{advisor:{...i,minSeverity:r.literal.getLiteralValue()}}:{advisor:{...i,unreadable:!0}}},ie=(e,t)=>{const r=g(e,t,"exclude");if("absent"in r)return{};if(!("literal"in r)||!n.isArrayLiteralExpression(r.literal))return{unreadable:!0};const i=[];for(const s of r.literal.getElements()){if(!n.isStringLiteral(s)&&!n.isNoSubstitutionTemplateLiteral(s)||s.getLiteralValue().startsWith("!"))return{unreadable:!0};i.push(s.getLiteralValue())}return{exclude:i}},ne=(e,t,r)=>{const i=g(e,t,"lazyFunctions");if("absent"in i)return{};if("unreadable"in i)return e!==void 0&&(n.isIdentifier(e)||e.getText().includes("lazyFunctions")||r&&!n.isObjectLiteralExpression(e))?{lazyFunctionsUnreadable:!0}:{};const s="literal"in i?u(i.literal):void 0;return s!==void 0&&(n.isTrueLiteral(s)||n.isFalseLiteral(s))?{lazyFunctions:s.getLiteralValue()}:{lazyFunctionsUnreadable:!0}},se=(e,t)=>{const r=u(e),i=r!==void 0&&n.isIdentifier(r),s=r!==void 0&&n.isIdentifier(r)?t.getVariableDeclaration(r.getText()):void 0,o=s?.getVariableStatement()?.getDeclarationKind()===R.Const,a=s?.getNameNode(),l=s!==void 0&&o&&a!==void 0&&n.isIdentifier(a)&&a.findReferencesAsNodes().length===1?u(s.getInitializer())??r:r;return{codegen:{...ie(l,t),...ne(l,t,i)}}},oe=(e,t)=>{const r=g(e,t,"merge");return"absent"in r?{durableObjects:{}}:"literal"in r&&(n.isTrueLiteral(r.literal)||n.isFalseLiteral(r.literal))?{durableObjects:{merge:r.literal.getLiteralValue()}}:{durableObjects:{unreadable:!0}}},ae=(e,t)=>{const r=g(e,t,"companion");return"absent"in r?{studio:{}}:"literal"in r&&(n.isTrueLiteral(r.literal)||n.isFalseLiteral(r.literal))?{studio:{companion:r.literal.getLiteralValue()}}:{studio:{unreadable:!0}}},le=(e,t)=>{const r=g(e,t,"headers");if("absent"in r)return{security:{}};const i="literal"in r?y(r.literal):d;return i===d?{security:{unreadable:!0}}:{security:{headers:i}}},V=(e,t)=>{const r=e.getProperty(t);if(r!==void 0)return(n.isPropertyAssignment(r)?r.getInitializer():void 0)??"unreadable"},x=(e,t)=>{const r=V(e,t);if(r!==void 0)return r!=="unreadable"&&(n.isStringLiteral(r)||n.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():!1},ce=e=>{const t=V(e,"rpc");if(t!==void 0)return t!=="unreadable"&&n.isFalseLiteral(t)?!1:"unreadable"},ue=e=>{const t=u(e);if(t===void 0||!n.isObjectLiteralExpression(t))return{services:{unreadable:!0}};const r={};for(const i of t.getProperties()){if(!n.isPropertyAssignment(i)||n.isComputedPropertyName(i.getNameNode()))return{services:{unreadable:!0}};const s=u(i.getInitializer());if(s===void 0||!n.isObjectLiteralExpression(s)||s.getProperties().some(l=>!n.isPropertyAssignment(l)))return{services:{unreadable:!0}};const o=x(s,"dir"),a=x(s,"entrypoint"),c=ce(s);if(typeof o!="string"||a===!1||c==="unreadable")return{services:{unreadable:!0}};r[b(i)]={dir:o,...a===void 0?{}:{entrypoint:a},...c===void 0?{}:{rpc:c}}}return{services:{declared:r}}},de=(e,t)=>n.isShorthandPropertyAssignment(e)?e.getNameNode():m(e,t),fe=(e,t)=>{const r=m(e,t);return r!==void 0&&n.isStringLiteral(r)?{target:r.getLiteralValue()}:{unreadable:!0}},me=(e,t)=>{const r=m(e,t);return r!==void 0&&(n.isTrueLiteral(r)||n.isFalseLiteral(r))?{remote:r.getLiteralValue()}:r!==void 0&&n.isObjectLiteralExpression(r)?{remote:!0}:{unreadable:!0}},h=new Map([["advisor",{read:(e,t)=>re(m(e,t),t),unreadable:{advisor:{unreadable:!0}}}],["codegen",{read:(e,t)=>se(de(e,t),t),unreadable:{codegen:{lazyFunctionsUnreadable:!0,unreadable:!0}}}],["durableObjects",{read:(e,t)=>oe(m(e,t),t),unreadable:{durableObjects:{unreadable:!0}}}],["remote",{read:me,unreadable:{unreadable:!0}}],["security",{read:(e,t)=>le(m(e,t),t),unreadable:{security:{unreadable:!0}}}],["services",{read:(e,t)=>ue(m(e,t)),unreadable:{services:{unreadable:!0}}}],["studio",{read:(e,t)=>ae(m(e,t),t),unreadable:{studio:{unreadable:!0}}}],["target",{read:fe,unreadable:{unreadable:!0}}]]),pe=(e,t)=>n.isGetAccessorDeclaration(e)||n.isMethodDeclaration(e)?h.get(b(e))?.unreadable??{}:!n.isPropertyAssignment(e)&&!n.isShorthandPropertyAssignment(e)?{}:h.get(b(e))?.read(e,t)??{},v=e=>{let t;try{t=$(e,"utf8")}catch{return{unreadable:!0}}const i=new _({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(D(e),t,{overwrite:!0}),s=X(i);if(s===void 0)return{unreadable:!0};if(s.getProperties().some(a=>n.isSpreadAssignment(a))){const a=l=>s.getProperties().some(f=>!n.isSpreadAssignment(f)&&b(f)===l);let c={unreadable:!0};for(const[l,f]of h)a(l)&&(c={...c,...f.unreadable});return c}let o={};for(const a of s.getProperties())o={...o,...pe(a,i)};return o},be=e=>{const t=I(e);return t===void 0?{}:v(t)},Pe=e=>{const{durableObjects:t}=be(e);return t?.unreadable&&console.warn("@lunora/codegen: `durableObjects.merge` in lunora.config is not a boolean literal — the Durable Object classes stay separate."),t?.merge===!0};let j;const Ne=e=>{const t=O(e),{codegen:r}=t===void 0?{}:v(t);if(r?.lazyFunctionsUnreadable){const i=t===void 0?void 0:z(t,{throwIfNoEntry:!1}),s=t===void 0||i===void 0?"":`${t}:${String(i.mtimeMs)}:${String(i.size)}`;s!==j&&(j=s,console.warn("@lunora/codegen: `codegen.lazyFunctions` in lunora.config is not a boolean literal, so the config does not turn the function registry lazy."))}return r?.lazyFunctions===!0},k=new Set,Ee=e=>{const t=O(e),{studio:r}=t===void 0?{}:v(t);return r?.unreadable&&t!==void 0&&!k.has(t)&&(k.add(t),console.warn("@lunora/codegen: `studio.companion` in lunora.config is not a boolean literal, so the companion Worker is not generated.")),r?.companion===!0},T=new Set,ge=(e,t,r)=>{let i;r!==void 0?{problems:i}=r:t.unreadable&&t.security===void 0?i=["is not an object literal codegen can read, so `security.headers` cannot be read either"]:i=["`security.headers` is not built from literals"];const s=`${e??""}:${i.join(";")}`;return T.has(s)||(T.add(s),console.warn(`@lunora/codegen: lunora.config ${i.join("; ")}, so the default security headers apply.`)),!0},xe=e=>{const t=O(e),r=t===void 0?{}:v(t),{security:i}=r,o=i?.unreadable===!0||r.unreadable===!0&&i===void 0?void 0:W(i?.headers);return o?.ok?o.value:ge(t,r,o)};export{d as N,Ee as a,Ae as b,Ne as c,xe as d,Pe as e,y as l,be as r};
@@ -1 +1 @@
1
- import{d as E}from"./declared-output-Iaar469J.mjs";import{v as u}from"./shared-DhqnD5R3.mjs";const p=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,l=/^(?:\.\.?\/)*_generated\//u,i=/\.[A-Za-z]\w*$/u,R=t=>t.replaceAll(p,(e,r)=>{const o=r.replace(l,"./");return`import("${i.test(o)?o:`${o}.js`}")`}),_=/import\("(?<spec>[^"]+)"\)/gu,a="node_modules/",m=/^@types\//u,A=t=>t.replaceAll(_,(e,r)=>{const o=r.lastIndexOf(a);if(o===-1||o>0&&r[o-1]!=="/")return e;const s=r.slice(o+a.length);return s===""||m.test(s)?e:`import("${s}")`}),I=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,f=/^(?:\.\.?\/)+/u,g=t=>{const e=[];for(const r of t.split("/"))if(!(r===""||r===".")){if(r===".."&&e.length>0&&e.at(-1)!==".."){e.pop();continue}e.push(r)}return e.join("/")},S=(t,e)=>t.replaceAll(I,(r,o)=>{if(l.test(o.replace(f,"")))return r;const s=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",c=`../${g(`${s}/${o}`)}`;return`import("${i.test(c)?c:`${c}.js`}")`}),v=(t,e)=>R(S(A(t),e)),d=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],L=new RegExp(String.raw`import\("@lunora/(?<pkg>${d.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),T={flags:new Set(["/web"]),platform:new Set},M=(t,e)=>e?t.replaceAll(L,(r,o,s)=>{const n=T[o];return s&&n&&!n.has(s)?r:`import("lunorash/${o}${s??""}")`}):t,O=t=>["Doc","Id"].filter(e=>new RegExp(String.raw`(?<![.$\w])${e}<`,"u").test(t)),U=t=>E(t)?u(t.output):t.returnType;export{O as a,M as b,U as c,v as r};
1
+ import{d as E}from"./declared-output-Iaar469J.mjs";import{v as u}from"./shared-Cn7dMQ_u.mjs";const p=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,l=/^(?:\.\.?\/)*_generated\//u,i=/\.[A-Za-z]\w*$/u,R=t=>t.replaceAll(p,(e,r)=>{const o=r.replace(l,"./");return`import("${i.test(o)?o:`${o}.js`}")`}),_=/import\("(?<spec>[^"]+)"\)/gu,a="node_modules/",m=/^@types\//u,A=t=>t.replaceAll(_,(e,r)=>{const o=r.lastIndexOf(a);if(o===-1||o>0&&r[o-1]!=="/")return e;const s=r.slice(o+a.length);return s===""||m.test(s)?e:`import("${s}")`}),I=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,f=/^(?:\.\.?\/)+/u,g=t=>{const e=[];for(const r of t.split("/"))if(!(r===""||r===".")){if(r===".."&&e.length>0&&e.at(-1)!==".."){e.pop();continue}e.push(r)}return e.join("/")},S=(t,e)=>t.replaceAll(I,(r,o)=>{if(l.test(o.replace(f,"")))return r;const s=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",c=`../${g(`${s}/${o}`)}`;return`import("${i.test(c)?c:`${c}.js`}")`}),v=(t,e)=>R(S(A(t),e)),d=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],L=new RegExp(String.raw`import\("@lunora/(?<pkg>${d.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),T={flags:new Set(["/web"]),platform:new Set},M=(t,e)=>e?t.replaceAll(L,(r,o,s)=>{const n=T[o];return s&&n&&!n.has(s)?r:`import("lunorash/${o}${s??""}")`}):t,O=t=>["Doc","Id"].filter(e=>new RegExp(String.raw`(?<![.$\w])${e}<`,"u").test(t)),U=t=>E(t)?u(t.output):t.returnType;export{O as a,M as b,U as c,v as r};
@@ -1,4 +1,4 @@
1
- import{CAPABILITIES as Qe}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{existsSync as D,readdirSync as de,readlinkSync as ce,lstatSync as qe,statSync as Le}from"node:fs";import{join as h,relative as y,dirname as d,sep as ue,isAbsolute as _e,resolve as Ve,basename as Ge}from"node:path";import{ts as c,Project as He}from"ts-morph";import{G as pe,a as C,u as Ke,d as Ue}from"./shared-DhqnD5R3.mjs";import{p as Je}from"./platform-8oj7iXQy.mjs";const me=/(?:\.d)?\.([cm]?)tsx?$/u,ze=t=>t.replace(me,".d.$1ts"),ye=(t,o)=>{const a=y(t,o).split(ue).join("/").replace(me,".$1js");return a.startsWith(".")?a:`./${a}`},he=t=>t.replaceAll("\\","/"),Y=(t,o,a)=>he(h(t,ze(y(o,a)))),Ye=t=>ye(".",h("services",t.name,y(d(t.wranglerPath),t.main))),Xe=t=>{const o=[],a=e=>{(c.isImportDeclaration(e)||c.isExportDeclaration(e))&&e.moduleSpecifier!==void 0&&c.isStringLiteral(e.moduleSpecifier)?o.push(e.moduleSpecifier):c.isImportTypeNode(e)&&c.isLiteralTypeNode(e.argument)&&c.isStringLiteral(e.argument.literal)&&o.push(e.argument.literal),c.forEachChild(e,a)};return a(t),o},T=t=>{const{ctimeMs:o,mtimeMs:a,size:e}=Le(t);return`${String(a)}:${String(o)}:${String(e)}`},Ze=new Set([".git",".wrangler","dist","node_modules","target"]),fe=t=>de(t,{withFileTypes:!0}).flatMap(o=>{const a=h(t,o.name);return o.isSymbolicLink()?[`${a}->${ce(a)}`]:o.isDirectory()&&o.name.startsWith("@")?[`${a}:${T(a)}`,...fe(a)]:[]}),be=t=>[`${t}:${T(t)}`,...fe(t)],ge=t=>{const o=h(t,"node_modules"),a=D(o)?be(o):[],e=d(t);return e===t?a:[...a,...ge(e)]},et=(t,o)=>{const a=[];try{const e=s=>{for(const n of de(s,{withFileTypes:!0})){const l=h(s,n.name);if(l!==o)if(n.isSymbolicLink())a.push(`${l}->${ce(l)}`);else if(n.isDirectory()){if(n.name==="node_modules")a.push(...be(l));else if(!Ze.has(n.name)){if(!qe(l).isDirectory())throw new Error(`${l} changed during the scan`);e(l)}}else a.push(`${l}:${T(l)}`)}};e(t),a.push(...ge(t))}catch{return}return[...new Set(a)].toSorted((e,s)=>e.localeCompare(s)).join(`
1
+ import{CAPABILITIES as Qe}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{existsSync as D,readdirSync as de,readlinkSync as ce,lstatSync as qe,statSync as Le}from"node:fs";import{join as h,relative as y,dirname as d,sep as ue,isAbsolute as _e,resolve as Ve,basename as Ge}from"node:path";import{ts as c,Project as He}from"ts-morph";import{G as pe,a as C,u as Ke,d as Ue}from"./shared-Cn7dMQ_u.mjs";import{p as Je}from"./platform-8oj7iXQy.mjs";const me=/(?:\.d)?\.([cm]?)tsx?$/u,ze=t=>t.replace(me,".d.$1ts"),ye=(t,o)=>{const a=y(t,o).split(ue).join("/").replace(me,".$1js");return a.startsWith(".")?a:`./${a}`},he=t=>t.replaceAll("\\","/"),Y=(t,o,a)=>he(h(t,ze(y(o,a)))),Ye=t=>ye(".",h("services",t.name,y(d(t.wranglerPath),t.main))),Xe=t=>{const o=[],a=e=>{(c.isImportDeclaration(e)||c.isExportDeclaration(e))&&e.moduleSpecifier!==void 0&&c.isStringLiteral(e.moduleSpecifier)?o.push(e.moduleSpecifier):c.isImportTypeNode(e)&&c.isLiteralTypeNode(e.argument)&&c.isStringLiteral(e.argument.literal)&&o.push(e.argument.literal),c.forEachChild(e,a)};return a(t),o},T=t=>{const{ctimeMs:o,mtimeMs:a,size:e}=Le(t);return`${String(a)}:${String(o)}:${String(e)}`},Ze=new Set([".git",".wrangler","dist","node_modules","target"]),fe=t=>de(t,{withFileTypes:!0}).flatMap(o=>{const a=h(t,o.name);return o.isSymbolicLink()?[`${a}->${ce(a)}`]:o.isDirectory()&&o.name.startsWith("@")?[`${a}:${T(a)}`,...fe(a)]:[]}),be=t=>[`${t}:${T(t)}`,...fe(t)],ge=t=>{const o=h(t,"node_modules"),a=D(o)?be(o):[],e=d(t);return e===t?a:[...a,...ge(e)]},et=(t,o)=>{const a=[];try{const e=s=>{for(const n of de(s,{withFileTypes:!0})){const l=h(s,n.name);if(l!==o)if(n.isSymbolicLink())a.push(`${l}->${ce(l)}`);else if(n.isDirectory()){if(n.name==="node_modules")a.push(...be(l));else if(!Ze.has(n.name)){if(!qe(l).isDirectory())throw new Error(`${l} changed during the scan`);e(l)}}else a.push(`${l}:${T(l)}`)}};e(t),a.push(...ge(t))}catch{return}return[...new Set(a)].toSorted((e,s)=>e.localeCompare(s)).join(`
2
2
  `)},tt=t=>Ge(d(t)).startsWith("@")?d(d(t)):d(t),se=(t,o)=>!y(o,t).startsWith("..")&&!t.split(ue).includes("node_modules"),ie=(t,o)=>{const a=[];let e=t;for(;e!==d(e)&&!D(h(e,"package.json"));)a.push(e),e=d(e);if(D(h(e,"package.json"))){for(const s of[...a,e,h(e,"package.json")])o.add(s);return e}},at=(t,o,a)=>{let e=t;for(;y(e,o).startsWith("..")&&e!==d(e);)a.add(e),e=d(e);a.add(e)},rt=(t,o)=>{const a=new Set;t.some(e=>se(e,o))&&ie(o,a);for(const e of t){if(se(e,o)){for(let n=d(e);n!==o&&n!==d(n);n=d(n))a.add(n);continue}const s=ie(d(e),a);s===void 0?at(d(e),o,a):a.add(tt(s))}return[...a].map(e=>[e,T(e)])},xe=new Map,le=([t,o])=>{try{return T(t)===o}catch{return!1}},ot=(t,o,a)=>{const e=xe.get(t);return e?.optionsKey===o&&e.stamps.every(n=>le(n))&&e.directories.every(n=>le(n))&&a!==void 0&&e.tree===a?e.files:void 0},nt=(t,o,a)=>{const e=[...o.stamps,...o.directories].every(([,s])=>Math.floor(Number.parseFloat(s))<=a);o.tree!==void 0&&e&&xe.set(t,{...o,tree:o.tree})},st=(t,o)=>({directories:rt(o,t),stamps:o.map(a=>[a,T(a)])}),ht=(t,o)=>{const a=d(t.wranglerPath),e=y(a,t.main);if(e.startsWith("..")||_e(e))throw new Error(`@lunora/codegen: service "${t.name}": its entry module (${t.main}) must be inside ${a} to be typed as RPC`);const s=h(o,"services",t.name),n=c.findConfigFile(a,i=>c.sys.fileExists(i)),l=new He({compilerOptions:{composite:!1,declaration:!0,declarationMap:!1,emitDeclarationOnly:!0,incremental:!1,noEmit:!1,noEmitOnError:!1,outDir:s,rootDir:a},skipAddingFilesFromTsConfig:!0,...n===void 0?{}:{tsConfigFilePath:n}}),m=JSON.stringify([t.name,t.main,t.wranglerPath,o]),v=JSON.stringify(l.getCompilerOptions()),w=et(a,Ve(o)),g=ot(m,v,w);if(g!==void 0)return g;const A=Date.now();l.addSourceFileAtPath(t.main),l.resolveSourceFileDependencies();const $=l.getProgram().compilerObject.getSourceFiles().map(i=>i.fileName).filter(i=>D(i)),{directories:F,stamps:S}=st(a,$),u={...l.getCompilerOptions(),preserveSymlinks:!0},O=new Map(l.getSourceFiles().map(i=>i.getFilePath()).filter(i=>!i.endsWith(".d.ts")&&!y(a,i).startsWith("..")).map(i=>[Y(s,a,i),i])),f={};for(const i of l.emitToMemory({emitOnlyDtsFiles:!0}).getFiles()){const B=O.get(he(i.filePath));if(B===void 0)continue;const R=c.createSourceFile(i.filePath,i.text,c.ScriptTarget.Latest,!1);let{text:b}=i;for(const k of Xe(R).toReversed()){const x=c.resolveModuleName(k.text,B,u,c.sys).resolvedModule?.resolvedFileName;if(x===void 0)continue;const I=Y(s,a,x),W=O.has(I)?I:x;b=`${b.slice(0,k.getStart(R))}${JSON.stringify(ye(d(i.filePath),W))}${b.slice(k.getEnd())}`}f[y(o,i.filePath)]=`${pe}${b}`}if(f[y(o,Y(s,a,t.main))]===void 0)throw new Error(`@lunora/codegen: service "${t.name}": TypeScript emitted no declaration for its entry module ${t.main}`);return nt(m,{files:f,optionsKey:v,directories:F,stamps:S,tree:w},A),f},it=(t,o=[])=>{const a=new Set;for(const e of t.tables)for(const s of Object.values(e.shape)){const n=Ke(s);n.kind==="storage"&&typeof n.bucket=="string"&&n.bucket!==""&&a.add(n.bucket)}for(const e of o)e!==""&&e!=="default"&&a.add(e);return["default",...[...a].toSorted((e,s)=>e.localeCompare(s))]},ft=({agents:t=[],capabilities:o=new Set,containers:a=[],env:e,hasVectors:s=!0,hasFlags:n=!1,hasNotify:l=!1,identity:m,queues:v=[],schema:w,services:g=[],storageRuleBuckets:A=[],topics:$=[],useUmbrella:F=!1,workflows:S=[]}={})=>{const u=Ue(F),O=it(w??{tables:[]},A).map(r=>JSON.stringify(r)).join(" | "),f=r=>r.sandbox===!0?"SandboxContainerAccessor":"ContainerAccessor",i=[...new Set(a.map(r=>f(r)))].toSorted((r,p)=>r.localeCompare(p)),B=a.length>0?`import type { ${i.join(", ")} } from "@lunora/container";
3
3
  `:"",R=a.length>0?`
4
4
  readonly containers: {${a.map(r=>`