@lunora/codegen 1.0.0-alpha.364 → 1.0.0-alpha.365

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.
@@ -0,0 +1 @@
1
+ import"./json-data-Chfs2Cz5.mjs";import{p as i,j as r,t as n,h as o,u as g,k as F,d as u,x as p,n as l,g as f,f as d,m as k,i as w,v as W,l as v,w as A}from"./shard-runtime-Dad_kcaX.mjs";import"./shared-Br_OnErI.mjs";import"./platform-8oj7iXQy.mjs";export{i as buildDoTypeImports,r as emitAgentFragments,n as emitAgents,o as emitContainerFragments,g as emitContainers,F as emitPaymentFragments,u as emitQueueFragments,p as emitQueues,l as emitQueuesMetadataFragments,f as emitServiceFragments,d as emitTopicFragments,k as emitWorkflowEventFragments,w as emitWorkflowFragments,W as emitWorkflows,v as emitWorkflowsMetadataFragments,A as queueAliasFindings};
@@ -1,11 +1,11 @@
1
- import{APP_METHOD_CAPABILITIES as T}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{i as N}from"./schema-BgM8A3XV.mjs";import{a as I,I as q,G as f}from"./shared-Br_OnErI.mjs";const L={configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},y=e=>[...T.filter(({key:t})=>e.capabilities.has(t)).map(({appMethod:t})=>t),...e.hasVectors?[L]:[]],w=e=>y(e).length>0,k=e=>(e.emailAgents?.length??0)>0,c=e=>e.tables.some(t=>N(t)),p=e=>e.liveStreams===!0&&(e.liveStreamDeclarations?.length??0)>0,j=e=>e.hasScheduler?`
1
+ import{APP_METHOD_CAPABILITIES as T}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{i as q}from"./schema-BgM8A3XV.mjs";import{a as N,I,G as y}from"./shared-Br_OnErI.mjs";const L={configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},f=e=>[...T.filter(({key:t})=>e.capabilities.has(t)).map(({appMethod:t})=>t),...e.hasVectors?[L]:[]],w=e=>f(e).length>0,k=e=>(e.emailAgents?.length??0)>0,c=e=>e.tables.some(t=>q(t)),p=e=>e.liveStreams===!0&&(e.liveStreamDeclarations?.length??0)>0,j=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
- `:"",P=e=>e?`
8
+ `:"",G=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 T}from"./CAPABILITY_PROBES-brcmKenl.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
- `:"",$=e=>e?`
117
+ `:"",P=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
  *
@@ -249,11 +249,12 @@ const buildGlobalIntrospector = (database: D1DatabaseLike): GlobalIntrospector =
249
249
  * shard-local ones it filtered out before calling here — a single
250
250
  * \`startLine\` plus positional counting would mis-attribute every row after
251
251
  * the first gap. \`importGlobalRows\` prefers \`row.line\` when present and
252
- * falls back to the position-derived count otherwise. A dry run is passed through and writes nothing.
252
+ * falls back to the position-derived count otherwise. A dry run is passed through and writes nothing;
253
+ * \`onConflict: "replace"\` overwrites a row whose \`_id\` already exists instead of reporting a conflict.
253
254
  */
254
255
  const buildGlobalImporter =
255
256
  (database: D1DatabaseLike, cdc: boolean) =>
256
- (request: { dryRun?: boolean; rows: ReadonlyArray<{ doc: Record<string, unknown>; line: number; table: string }>; startLine?: number }) => {
257
+ (request: { dryRun?: boolean; onConflict?: "replace" | "skip"; rows: ReadonlyArray<{ doc: Record<string, unknown>; line: number; table: string }>; startLine?: number }) => {
257
258
  const exec = buildExec(database);
258
259
  // Same reason the PITR applier carries it: a bulk import that skips the
259
260
  // changelog restores rows no downstream consumer is ever told about.
@@ -262,6 +263,7 @@ const buildGlobalImporter =
262
263
  return importGlobalRows(writer, schema as unknown as D1CtxDbOptions["schema"], {
263
264
  dryRun: request.dryRun === true,
264
265
  exec,
266
+ onConflict: request.onConflict ?? "skip",
265
267
  rows: request.rows.map((row) => ({ doc: row.doc, line: row.line, table: row.table })),
266
268
  ...(request.startLine === undefined ? {} : { startLine: request.startLine }),
267
269
  });
@@ -337,12 +339,12 @@ const buildGlobalCdcApplier =
337
339
 
338
340
  return request.changes.length;
339
341
  };
340
- `:"",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(postgres(env.HYPERDRIVE.connectionString)))`. Cache the driver on the DO instance; rebuild lazily after hibernation. */\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}']:[]],B=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," 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> = {};"]:[],...c(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>;"]:[]],G=e=>y(e).map(({configKey:t,doc:r,method:a})=>` /** ${r} */
342
+ `:"",$=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(postgres(env.HYPERDRIVE.connectionString)))`. 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>;"]:[]," 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> = {};"]:[],...c(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>;"]:[]],B=e=>f(e).map(({configKey:t,doc:r,method:a})=>` /** ${r} */
341
343
  public ${a}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${t}"]>>): this {
342
344
  this.shardExtras.${t} = factory as NonNullable<ShardConfig["${t}"]>;
343
345
 
344
346
  return this;
345
- }`),W=e=>[...e.hasAccess?[" /** Wire Cloudflare Access (Zero Trust) — feeds the verified Access identity into `ctx.auth` / RLS via `resolveIdentity`. Call it with no argument when the Access policy is attached to the Worker (the identity arrives on the execution context; nothing to configure); pass `teamDomain` + `aud` for a hostname-scoped Access application, whose `Cf-Access-Jwt-Assertion` JWT is verified against your team JWKS. When `.auth(...)` is also configured, Access is composed ahead of it (Access wins when it authenticated the caller; everyone else falls through to the app session). */\n public access(selector?: Selector<Env, CreateAccessResolverOptions>): this {\n this.accessSelector = selector ?? (() => undefined);\n\n return this;\n }"]:[],` /** Bearer token gating the \`/_lunora/admin/*\` endpoints the studio calls. */
347
+ }`),_=e=>[...e.hasAccess?[" /** Wire Cloudflare Access (Zero Trust) — feeds the verified Access identity into `ctx.auth` / RLS via `resolveIdentity`. Call it with no argument when the Access policy is attached to the Worker (the identity arrives on the execution context; nothing to configure); pass `teamDomain` + `aud` for a hostname-scoped Access application, whose `Cf-Access-Jwt-Assertion` JWT is verified against your team JWKS. When `.auth(...)` is also configured, Access is composed ahead of it (Access wins when it authenticated the caller; everyone else falls through to the app session). */\n public access(selector?: Selector<Env, CreateAccessResolverOptions>): this {\n this.accessSelector = selector ?? (() => undefined);\n\n return this;\n }"]:[],` /** Bearer token gating the \`/_lunora/admin/*\` endpoints the studio calls. */
346
348
  public admin(selector: Selector<Env, string>): this {
347
349
  this.adminToken = selector;
348
350
 
@@ -406,7 +408,7 @@ const buildGlobalCdcApplier =
406
408
  this.storageDeclaration = declaration;
407
409
 
408
410
  return this;
409
- }`]:[],...G(e)],_=e=>{const t=a=>e.hasScheduler?`
411
+ }`]:[],...B(e)],W=e=>{const t=a=>e.hasScheduler?`
410
412
  ...(this.schedulerDeclaration ? { scheduler: this.resolveScheduler(env) as unknown as ${a}["scheduler"] } : {}),`:"",r=[" cdc: this.cdcEnabled,"," reactiveCache: this.reactiveCacheConfig,"," ...(this.maxRelationKeysLimit === undefined ? {} : { maxRelationKeys: this.maxRelationKeysLimit }),"," ...(this.observabilitySink === undefined ? {} : { observability: this.observabilitySink }),",...e.hasDeliveryAuthorization===!1?[]:[" ...(this.deliveryAuthorizationSelector === undefined ? {} : { deliveryAuthorization: this.deliveryAuthorizationSelector }),"]," ...(this.relationExistsPushDownMode === undefined ? {} : { relationExistsPushDown: this.relationExistsPushDownMode }),",...e.hasGlobal?[` ...(this.globalDeclaration
411
413
  ? {
412
414
  d1: (rawEnv: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string | null }) => {
@@ -489,7 +491,7 @@ const buildGlobalCdcApplier =
489
491
  : {}),`]:[],...c(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 r.length>0?`
490
492
  ${r.join(`
491
493
  `)}
492
- `:""},H=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],U=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],F=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],Q=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],z=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],J=e=>e?['import notifyConfig from "../notify.js";']:[],K=e=>k(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],V=e=>k(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],Y=e=>{const{hasFramework:t,hasGlobal:r,hasHyperdriveGlobal:a,hasQueue:n,useUmbrella:o}=e,i=o?"lunorash/runtime":"@lunora/runtime",d=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike",...c(e)?["ShardRegistryRpc"]:[],"WorkerOptions",...n?["TriggerTrace"]:[],...r?["GlobalIntrospector"]:[],...e.tables.length>0?["ShardingInfo"]:[],...t?["FrameworkHostHandler"]:[]],l=[...r||a?["createCrossShardRelationCapabilities"]:[],...c(e)?["createDynamicShardRegistry","createQueryCoordinator"]:[],"createWorker",...e.jurisdiction?["declareAppJurisdiction"]:[],"resolveLogArchiveFromEnv",...e.hasAuth?["memoizeIdentity"]:[],...t?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...d].toSorted((s,u)=>s.localeCompare(u)).join(", ")} } from "${i}";`,`import { ${l} } from "${i}";`]},X=e=>{const{hasAccess:t,hasAuth:r,hasGlobal:a,hasHyperdriveGlobal:n,hasKvIntrospector:o,hasQueue:i,hasScheduler:d,hasStorage:l,hasWorkflow:s}=e;return[...r?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import type * as LunoraAuthModule from "./authModule.js";']:[],...U(t,r),...z(a),...n?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...F(o),...Q(e.hasVectors),...d?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...l?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...s?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...K(e),...Y(e),"",...H(e.identity),...V(e),...a||n?['import schema from "../schema.js";']:[],...J(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...i?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','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";']:[]]},Z=e=>e.jurisdiction&&e.jurisdictionPinsAuth===!0?`
494
+ `:""},H=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],U=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],F=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";']:[],z=e=>e?['import notifyConfig from "../notify.js";']:[],K=e=>k(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],V=e=>k(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],Y=e=>{const{hasFramework:t,hasGlobal:r,hasHyperdriveGlobal:a,hasQueue:n,useUmbrella:o}=e,i=o?"lunorash/runtime":"@lunora/runtime",d=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike",...c(e)?["ShardRegistryRpc"]:[],"WorkerOptions",...n?["TriggerTrace"]:[],...r?["GlobalIntrospector"]:[],...e.tables.length>0?["ShardingInfo"]:[],...t?["FrameworkHostHandler"]:[]],l=[...r||a?["createCrossShardRelationCapabilities"]:[],...c(e)?["createDynamicShardRegistry","createQueryCoordinator"]:[],"createWorker",...e.jurisdiction?["declareAppJurisdiction"]:[],"resolveLogArchiveFromEnv",...e.hasAuth?["memoizeIdentity"]:[],...t?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...d].toSorted((s,u)=>s.localeCompare(u)).join(", ")} } from "${i}";`,`import { ${l} } from "${i}";`]},X=e=>{const{hasAccess:t,hasAuth:r,hasGlobal:a,hasHyperdriveGlobal:n,hasKvIntrospector:o,hasQueue:i,hasScheduler:d,hasStorage:l,hasWorkflow:s}=e;return[...r?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import type * as LunoraAuthModule from "./authModule.js";']:[],...U(t,r),...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";']:[],...F(o),...Q(e.hasVectors),...d?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...l?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...s?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...K(e),...Y(e),"",...H(e.identity),...V(e),...a||n?['import schema from "../schema.js";']:[],...z(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...i?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','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";']:[]]},Z=e=>e.jurisdiction&&e.jurisdictionPinsAuth===!0?`
493
495
  // The schema's jurisdiction pins the auth object like every other DO.
494
496
  jurisdiction: ${JSON.stringify(e.jurisdiction)},`:"",ee=e=>typeof e=="string"?`{ mode: { kind: ${JSON.stringify(e)} } }`:`{ mode: { field: ${JSON.stringify(e.field)}, kind: "shardBy" } }`,te=e=>[...e.tables.length>0?[` const tableSharding = new Map<string, ShardingInfo>([
495
497
  ${e.tables.map(t=>` [${JSON.stringify(t.name)}, ${ee(t.shardMode)}],`).join(`
@@ -501,7 +503,7 @@ ${e.tables.map(t=>` [${JSON.stringify(t.name)}, ${ee(t.shardMode)}],`
501
503
 
502
504
  if (shardRegistry) {
503
505
  options.queryCoordinator = createQueryCoordinator({ registry: createDynamicShardRegistry({ ${e.jurisdiction?`jurisdiction: ${JSON.stringify(e.jurisdiction)}, `:""}env, namespace: shardRegistry }) });
504
- }`]:[]],S=e=>(e.liveStreamDeclarations??[]).map(t=>{if(I(t.exportName,"live stream export name"),!q.test(t.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(t.filePath)}`);return` { id: ${JSON.stringify(t.id)}, load: () => import("../${t.filePath}.js").then((m) => m.${t.exportName}) },`}),re=e=>p(e)?[" httpRouter: liveStreamRouter([",...S(e)," ], this.httpRouterApp),"]:[" ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"],ae=e=>p(e)?[" liveStreamRoutes: [",...(e.liveStreamDeclarations??[]).flatMap(t=>[` ${JSON.stringify(`GET /live/${t.id}/connect`)},`,` ${JSON.stringify(`POST /live/${t.id}/control`)},`])," ],"]:[],ne=e=>p(e)?`liveStreamRouter([
506
+ }`]:[]],S=e=>(e.liveStreamDeclarations??[]).map(t=>{if(N(t.exportName,"live stream export name"),!I.test(t.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(t.filePath)}`);return` { id: ${JSON.stringify(t.id)}, load: () => import("../${t.filePath}.js").then((m) => m.${t.exportName}) },`}),re=e=>p(e)?[" httpRouter: liveStreamRouter([",...S(e)," ], this.httpRouterApp),"]:[" ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"],ae=e=>p(e)?[" liveStreamRoutes: [",...(e.liveStreamDeclarations??[]).flatMap(t=>[` ${JSON.stringify(`GET /live/${t.id}/connect`)},`,` ${JSON.stringify(`POST /live/${t.id}/control`)},`])," ],"]:[],ne=e=>p(e)?`liveStreamRouter([
505
507
  ${S(e).join(`
506
508
  `)}
507
509
  ], host)`:"host",se=e=>[...te(e),...e.hasScheduler?[` if (this.schedulerDeclaration) {
@@ -523,8 +525,10 @@ ${S(e).join(`
523
525
  // plane: the rows \`resolveTableSharding\` classifies as \`.global()\`
524
526
  // land here, and without it they are reported, not written.
525
527
  options.importGlobals = buildGlobalImporter(database, this.cdcEnabled);
526
- // The importer above skips the write for a dry run.
528
+ // The importer above skips the write for a dry run, and
529
+ // overwrites an existing \`_id\` under \`onConflict: "replace"\`.
527
530
  options.importGlobalsSupportsDryRun = true;
531
+ options.importGlobalsSupportsReplace = true;
528
532
  // The read/replay half of the same admin plane. Each one is the
529
533
  // only reason its endpoint can see the global storage plane at
530
534
  // all, and every one of them fails SILENTLY when unset — export
@@ -537,6 +541,47 @@ ${S(e).join(`
537
541
  options.syncGlobals = buildGlobalCdcSync(database);
538
542
  options.applyGlobals = buildGlobalCdcApplier(database, this.cdcEnabled);
539
543
  }
544
+ }`]:[],...e.hasHyperdriveGlobal?[` const hyperdriveDeclaration = this.hyperdriveGlobalDeclaration;
545
+
546
+ if (hyperdriveDeclaration) {
547
+ const engine = hyperdriveDeclaration.engine;
548
+ const hyperdriveSchema = schema as unknown as SqlCtxDbOptions["schema"];
549
+ const exec = (): SqlExec => hyperdriveDeclaration.exec(env);
550
+ const cdc = this.cdcEnabled;
551
+
552
+ options.globalIntrospector = {
553
+ facetColumn: (request) => createHyperdriveGlobalIntrospector(engine, exec(), hyperdriveSchema).facetColumn(request),
554
+ listTables: () => createHyperdriveGlobalIntrospector(engine, exec(), hyperdriveSchema).listTables(),
555
+ readTablePage: (request) => createHyperdriveGlobalIntrospector(engine, exec(), hyperdriveSchema).readTablePage(request),
556
+ };
557
+ options.importGlobals = (request) =>
558
+ importHyperdriveGlobalRows({
559
+ cdc,
560
+ dryRun: request.dryRun === true,
561
+ engine,
562
+ exec: exec(),
563
+ onConflict: request.onConflict ?? "skip",
564
+ rows: request.rows,
565
+ schema: hyperdriveSchema,
566
+ ...(request.startLine === undefined ? {} : { startLine: request.startLine }),
567
+ });
568
+ options.importGlobalsSupportsDryRun = true;
569
+ options.importGlobalsSupportsReplace = true;
570
+ options.exportGlobals = (request) => exportHyperdriveGlobalRows({ engine, exec: exec(), schema: hyperdriveSchema, tables: request.tables });
571
+ options.syncGlobals = async (request) => {
572
+ const page = await readHyperdriveGlobalCdc(engine, exec(), request);
573
+
574
+ // \`as unknown as\`: \`CdcChange\` is an interface, which carries no implicit index signature.
575
+ return { changes: page.changes as unknown as ReadonlyArray<Record<string, unknown>>, cursor: page.cursor };
576
+ };
577
+ options.applyGlobals = (request) =>
578
+ applyHyperdriveGlobalCdc({
579
+ cdc,
580
+ changes: request.changes as unknown as Parameters<typeof applyHyperdriveGlobalCdc>[0]["changes"],
581
+ engine,
582
+ exec: exec(),
583
+ schema: hyperdriveSchema,
584
+ });
540
585
  }`]:[],...e.hasStorage?[` if (this.storageDeclaration) {
541
586
  Object.assign(options, this.buildStorageAdmin(env));
542
587
  options.storage = (rawEnv: unknown, origin?: string) => this.resolveStorage(rawEnv as Env, origin);
@@ -776,8 +821,8 @@ ${r.map(([a,,n])=>` ${a}: ${n},`).join(`
776
821
  };
777
822
  })());
778
823
  `},ce=e=>E(e)?{asyncIfDeferred:"async ",deferredArgument:", deferred",deferredParameter:", deferred: DeferredModules",loadDeferredLine:`
779
- const deferred = await loadDeferredModules();`}:{asyncIfDeferred:"",deferredArgument:"",deferredParameter:"",loadDeferredLine:""},be=e=>e?`${f}export { authDiscoveryPathsFor, createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, handleAuthDiscoveryRequest, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth/worker";
780
- `:"",de=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,r)=>t.localeCompare(r)).join(", "),me=e=>{const t=(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0,r={...e,hasVectors:t},{hasAuth:a}=r,n=M(r),o=se(r),i=a?` let auth: LunoraAuth | null = null;
824
+ const deferred = await loadDeferredModules();`}:{asyncIfDeferred:"",deferredArgument:"",deferredParameter:"",loadDeferredLine:""},be=e=>e?`${y}export { authDiscoveryPathsFor, createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, handleAuthDiscoveryRequest, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth/worker";
825
+ `:"",de=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,r)=>t.localeCompare(r)).join(", "),me=e=>{const t=(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0,r={...e,hasVectors:t},{hasAuth:a}=r,n=$(r),o=se(r),i=a?` let auth: LunoraAuth | null = null;
781
826
  let authInit: Promise<void> | null = null;
782
827
  // One memo per env for THIS assembled worker: a framework-hosted worker rebuilds its options per
783
828
  // request and must reuse it, but a second \`assemble()\` has its own auth closure and must not share.
@@ -845,7 +890,7 @@ ${g.map(v=>` { agent: lunoraAgentDefinitions.${v.exportName}, classNa
845
890
  `:"",O=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
846
891
  public build(): ComposedApp {
847
892
  return this.assemble();
848
- }${r.hasFramework?"\n\n /** Compose Lunora's realtime plane INTO a meta-framework's Cloudflare handler (SvelteKit/Astro/Nuxt). The framework `host` serves everything except the reserved `/_lunora/*` endpoints; pass the adapter-emitted worker (e.g. SvelteKit's `_worker.js`, Astro's `handle`). */\n public buildFrameworkWorker(host: FrameworkHostHandler): ComposedApp {\n return this.assemble(host);\n }":""}`;return`${f}${X(r).join(`
893
+ }${r.hasFramework?"\n\n /** Compose Lunora's realtime plane INTO a meta-framework's Cloudflare handler (SvelteKit/Astro/Nuxt). The framework `host` serves everything except the reserved `/_lunora/*` endpoints; pass the adapter-emitted worker (e.g. SvelteKit's `_worker.js`, Astro's `handle`). */\n public buildFrameworkWorker(host: FrameworkHostHandler): ComposedApp {\n return this.assemble(host);\n }":""}`;return`${y}${X(r).join(`
849
894
  `)}
850
895
 
851
896
  /** Read a value off the per-request \`env\`. Returns \`undefined\` to leave the capability unconfigured (its \`ctx.*\`/admin surface stays a clear-error stub). */
@@ -878,12 +923,12 @@ interface ComposedApp extends LunoraWorker {
878
923
  * first request so per-isolate singletons are built once.
879
924
  */
880
925
  class AppBuilder<Env extends object> {
881
- ${B(r).join(`
926
+ ${M(r).join(`
882
927
  `)}
883
928
 
884
929
  private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
885
930
 
886
- ${W(r).join(`
931
+ ${_(r).join(`
887
932
 
888
933
  `)}
889
934
 
@@ -891,7 +936,7 @@ ${O}
891
936
 
892
937
  /** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
893
938
  private assemble(${x}): ComposedApp {
894
- const ShardDO = createShardDO({${_(r)}});
939
+ const ShardDO = createShardDO({${W(r)}});
895
940
 
896
941
  // Per-isolate singletons: the worker (and auth instance) are expensive to
897
942
  // build, so the first request constructs them and every later request on
@@ -945,7 +990,7 @@ ${r.hasFramework?`
945
990
  `:""}
946
991
  return composed;
947
992
  }
948
- ${j(r)}${P(r.hasStorage)}
993
+ ${j(r)}${G(r.hasStorage)}
949
994
  /** Fan the recorded declarations into the worker-side \`createWorker\` options. */
950
995
  private buildWorkerOptions(env: Env, ${R}): WorkerOptions {
951
996
  const options: WorkerOptions = {
@@ -970,7 +1015,7 @@ ${o.join(`
970
1015
  return options;
971
1016
  }
972
1017
  }
973
- ${$(r.hasGlobal)}
1018
+ ${P(r.hasGlobal)}
974
1019
  /**
975
1020
  * Shape of the project's root \`lunora.config.*\`.
976
1021
  *
@@ -1 +1 @@
1
- import"./SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-DyIoujoy.mjs";import"./shard-runtime-DXlpfT3P.mjs";import"./shared-Br_OnErI.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
1
+ import"./SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-DOqocTdL.mjs";import"./shard-runtime-Dad_kcaX.mjs";import"./shared-Br_OnErI.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};