@lunora/codegen 1.0.0-alpha.427 → 1.0.0-alpha.428
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-BO_bGItv.mjs +57 -0
- package/dist/packem_shared/{emitApp-LFKtDRYu.mjs → emitApp-BJxszWDO.mjs} +88 -47
- package/dist/packem_shared/{emitDataModel-BvCZS4Yq.mjs → emitDataModel-BCyOctft.mjs} +24 -24
- package/dist/packem_shared/{emitDrizzleSchema-BzOChEYW.mjs → emitDrizzleSchema-D_b193PY.mjs} +1 -1
- package/dist/packem_shared/{emitShard-CDWgekIG.mjs → emitShard-CPaRxNYn.mjs} +1 -1
- package/dist/packem_shared/{shard-CWAD5mYy.mjs → shard-BbYT2omp.mjs} +3 -1
- package/package.json +12 -2
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-jjnAlXZN.mjs +0 -57
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import{APP_METHOD_CAPABILITIES as
|
|
1
|
+
import{APP_METHOD_CAPABILITIES as L}from"./CAPABILITY_PROBES-DCzOjTN7.mjs";import{i as $}from"./schema-BgM8A3XV.mjs";import{a as j,I as G,G as w}from"./shared-Cn7dMQ_u.mjs";const P={configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},k=e=>[...L.filter(({key:t})=>e.capabilities.has(t)).map(({appMethod:t})=>t),...e.hasVectors?[P]:[]],S=e=>k(e).length>0,E=e=>(e.emailAgents?.length??0)>0,c=e=>e.tables.some(t=>$(t)),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
|
-
`:"",
|
|
8
|
+
`:"",M=e=>e?`
|
|
9
9
|
/**
|
|
10
10
|
* One bucket's \`Storage\`, signing under the name it is registered as.
|
|
11
11
|
*
|
|
@@ -107,14 +107,15 @@ import{APP_METHOD_CAPABILITIES as T}from"./CAPABILITY_PROBES-DCzOjTN7.mjs";impor
|
|
|
107
107
|
storageDelete: (key: string, opts?: { bucket?: string }) => pick(opts?.bucket).delete(key),
|
|
108
108
|
storageDownload: (key: string, opts?: { bucket?: string }) => pick(opts?.bucket).download(key),
|
|
109
109
|
storageList: (prefix?: string, opts?: { bucket?: string; cursor?: string; limit?: number }) => pick(opts?.bucket).list(prefix, opts),
|
|
110
|
+
storageMultipartUpload: (key: string, opts?: { bucket?: string; contentType?: string; customMetadata?: Record<string, string> }) => pick(opts?.bucket).createMultipartUpload(key, opts),
|
|
110
111
|
...(hasSigning ? {
|
|
111
112
|
storageSignedUrl: (key: string, opts?: { bucket?: string; contentType?: string; expiresInSeconds?: number; method?: "GET" | "PUT"; origin?: string }) =>
|
|
112
113
|
pick(opts?.bucket, opts?.origin).getSignedUrl(key, opts),
|
|
113
114
|
} : {}),
|
|
114
|
-
storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string; sha256?: string }) => pick(opts?.bucket).upload(key, body, opts),
|
|
115
|
+
storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string; customMetadata?: Record<string, string>; sha256?: string }) => pick(opts?.bucket).upload(key, body, opts),
|
|
115
116
|
};
|
|
116
117
|
}
|
|
117
|
-
`:"",
|
|
118
|
+
`:"",B=e=>e?`
|
|
118
119
|
/**
|
|
119
120
|
* 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
121
|
*
|
|
@@ -312,6 +313,32 @@ const buildGlobalImporter =
|
|
|
312
313
|
});
|
|
313
314
|
};
|
|
314
315
|
|
|
316
|
+
/**
|
|
317
|
+
* \`importGlobalsStaging\` for a staged replace import: the \`.global()\` rows wait
|
|
318
|
+
* in D1's staging table until the commit writes them through the same writer
|
|
319
|
+
* \`importGlobals\` uses (changelog included), then prunes. See \`@lunora/d1\`'s
|
|
320
|
+
* \`import-staging\` for what the commit guarantees without a transaction.
|
|
321
|
+
*/
|
|
322
|
+
const buildGlobalImportStaging = (database: D1DatabaseLike, cdc: boolean) => {
|
|
323
|
+
const globalSchema = schema as unknown as D1CtxDbOptions["schema"];
|
|
324
|
+
|
|
325
|
+
return {
|
|
326
|
+
abort: (request: { generation: string; session: string }) => abortStagedGlobalRows(buildExec(database), request.session, request.generation),
|
|
327
|
+
commit: (request: { generation: string; session: string; staged: boolean; tables: ReadonlyArray<string> }) => {
|
|
328
|
+
const exec = buildExec(database);
|
|
329
|
+
|
|
330
|
+
return commitStagedGlobalRows(createD1CtxDb({ cdc, exec, schema: globalSchema }), exec, globalSchema, request);
|
|
331
|
+
},
|
|
332
|
+
stage: (request: {
|
|
333
|
+
generation: string;
|
|
334
|
+
rows: ReadonlyArray<{ doc: Record<string, unknown>; line: number; table: string }>;
|
|
335
|
+
session: string;
|
|
336
|
+
tables: ReadonlyArray<string>;
|
|
337
|
+
}) =>
|
|
338
|
+
stageGlobalRows(buildExec(database), globalSchema, request),
|
|
339
|
+
};
|
|
340
|
+
};
|
|
341
|
+
|
|
315
342
|
/**
|
|
316
343
|
* \`exportGlobals\` for the admin export endpoint (and the scheduled R2 backup,
|
|
317
344
|
* which drains the same stream): the read twin of {@link buildGlobalImporter},
|
|
@@ -382,12 +409,12 @@ const buildGlobalCdcApplier =
|
|
|
382
409
|
|
|
383
410
|
return request.changes.length;
|
|
384
411
|
};
|
|
385
|
-
`:"",
|
|
412
|
+
`:"",W=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}']:[]],H=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>;"]:[],...S(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>;"]:[]],U=e=>k(e).map(({configKey:t,doc:r,method:a})=>` /** ${r} */
|
|
386
413
|
public ${a}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${t}"]>>): this {
|
|
387
414
|
this.shardExtras.${t} = factory as NonNullable<ShardConfig["${t}"]>;
|
|
388
415
|
|
|
389
416
|
return this;
|
|
390
|
-
}`),
|
|
417
|
+
}`),F=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. */
|
|
391
418
|
public admin(selector: Selector<Env, string>): this {
|
|
392
419
|
this.adminToken = selector;
|
|
393
420
|
|
|
@@ -456,7 +483,7 @@ const buildGlobalCdcApplier =
|
|
|
456
483
|
this.storageDeclaration = declaration;
|
|
457
484
|
|
|
458
485
|
return this;
|
|
459
|
-
}`]:[],...
|
|
486
|
+
}`]:[],...U(e)],Q=e=>{const t=a=>e.hasScheduler?`
|
|
460
487
|
...(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
|
|
461
488
|
? {
|
|
462
489
|
d1: (rawEnv: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; onBookmark?: (bookmark: string | undefined) => void; userId?: string | null | undefined }) => {
|
|
@@ -564,14 +591,14 @@ const buildGlobalCdcApplier =
|
|
|
564
591
|
? {
|
|
565
592
|
scheduler: (rawEnv: Record<string, unknown>) => this.resolveScheduler(rawEnv as Env),
|
|
566
593
|
}
|
|
567
|
-
: {}),`]:[],...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) } : {}),"]:[],...
|
|
594
|
+
: {}),`]:[],...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) } : {}),"]:[],...S(e)?[" ...this.shardExtras,"]:[]];return r.length>0?`
|
|
568
595
|
${r.join(`
|
|
569
596
|
`)}
|
|
570
|
-
`:""},
|
|
571
|
-
claims: ${t},`},
|
|
597
|
+
`:""},z=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],J=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],K=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],V=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],Y=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { abortStagedGlobalRows, applyCdcChanges, applySqlMigrationFiles, commitStagedGlobalRows, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec, stageGlobalRows } from "@lunora/d1";']:[],X=e=>e?['import notifyConfig from "../notify.js";']:[],Z=e=>E(e)?e.lazyFunctions===!0?['import type { dispatchAgentEmail } from "@lunora/agent/inbound";']:['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],ee=e=>E(e)&&e.lazyFunctions!==!0?['import * as lunoraAgentDefinitions from "../agents.js";']:[],te=e=>{const{hasFramework:t,hasGlobal:r,hasHyperdriveGlobal:a,hasQueue:s,useUmbrella:n}=e,o=n?"lunorash/runtime":"@lunora/runtime",d=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","SecurityOptions","ShardNamespaceLike",...c(e)?["ShardRegistryRpc"]:[],"WorkerOptions",...s?["TriggerTrace"]:[],...r?["GlobalIntrospector"]:[],...e.tables.length>0?["ShardingInfo"]:[],...t?["FrameworkHostHandler"]:[]],l=[...r||a?["createCrossShardRelationCapabilities"]:[],...c(e)?["createDynamicShardRegistry","createQueryCoordinator"]:[],"createWorker",...e.jurisdiction?["declareAppJurisdiction"]:[],"resolveLogArchiveFromEnv",...e.studioAssetsBinding!==void 0&&(e.wantsArchitecture||e.wantsOpenApi||e.wantsOpenRpc)?["loadStudioDocument"]:[],...e.hasAuth?["memoizeIdentity"]:[],...t?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...d].toSorted((i,u)=>i.localeCompare(u)).join(", ")} } from "${o}";`,`import { ${l} } from "${o}";`]},re=e=>{const{hasAccess:t,hasAuth:r,hasGlobal:a,hasHyperdriveGlobal:s,hasKvIntrospector:n,hasQueue:o,hasScheduler:d,hasStorage:l,hasWorkflow:i}=e;return[...r?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import type * as LunoraAuthModule from "./authModule.js";']:[],...J(t,r),...Y(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";']:[],...K(n),...V(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";']:[],...i?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...Z(e),...te(e),"",...z(e.identity),...ee(e),...a||s?['import schema from "../schema.js";']:[],...X(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...o?['import { createQueueCaptureSink, dispatchForwardedQueueBatch, 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";']:[]]},R=e=>e.authClaims===void 0||e.authClaims.length===0?void 0:JSON.stringify(e.authClaims),ae=e=>{const t=R(e);return t===void 0?"":`, ${t}`},se=e=>{const t=R(e);return t===void 0?"":`
|
|
598
|
+
claims: ${t},`},ne=e=>e.jurisdiction&&e.jurisdictionPinsAuth===!0?`
|
|
572
599
|
// The schema's jurisdiction pins the auth object like every other DO.
|
|
573
|
-
jurisdiction: ${JSON.stringify(e.jurisdiction)},`:"",
|
|
574
|
-
${e.tables.map(t=>` [${JSON.stringify(t.name)}, ${
|
|
600
|
+
jurisdiction: ${JSON.stringify(e.jurisdiction)},`:"",oe=e=>typeof e=="string"?`{ mode: { kind: ${JSON.stringify(e)} } }`:`{ mode: { field: ${JSON.stringify(e.field)}, kind: "shardBy" } }`,ie=e=>[...e.tables.length>0?[` const tableSharding = new Map<string, ShardingInfo>([
|
|
601
|
+
${e.tables.map(t=>` [${JSON.stringify(t.name)}, ${oe(t.shardMode)}],`).join(`
|
|
575
602
|
`)}
|
|
576
603
|
]);
|
|
577
604
|
|
|
@@ -580,14 +607,14 @@ ${e.tables.map(t=>` [${JSON.stringify(t.name)}, ${se(t.shardMode)}],`
|
|
|
580
607
|
|
|
581
608
|
if (shardRegistry) {
|
|
582
609
|
options.queryCoordinator = createQueryCoordinator({ registry: createDynamicShardRegistry({ ${e.jurisdiction?`jurisdiction: ${JSON.stringify(e.jurisdiction)}, `:""}env, namespace: shardRegistry }) });
|
|
583
|
-
}`]:[]],
|
|
610
|
+
}`]:[]],le=[` const adminRevocations = this.adminRevocationsSelector?.(env);
|
|
584
611
|
|
|
585
612
|
if (adminRevocations) {
|
|
586
613
|
options.adminRevocations = adminRevocations;
|
|
587
|
-
}`],
|
|
588
|
-
${
|
|
614
|
+
}`],D=e=>(e.liveStreamDeclarations??[]).map(t=>{if(j(t.exportName,"live stream export name"),!G.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}) },`}),ce=e=>p(e)?[" httpRouter: liveStreamRouter([",...D(e)," ], this.httpRouterApp),"]:[" ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"],de=e=>p(e)?[" liveStreamRoutes: [",...(e.liveStreamDeclarations??[]).flatMap(t=>[` ${JSON.stringify(`GET /live/${t.id}/connect`)},`,` ${JSON.stringify(`POST /live/${t.id}/control`)},`])," ],"]:[],he=e=>p(e)?`liveStreamRouter([
|
|
615
|
+
${D(e).join(`
|
|
589
616
|
`)}
|
|
590
|
-
], host)`:"host",
|
|
617
|
+
], host)`:"host",ue=e=>e.agentWorkflows===void 0?[]:[` options.agentWorkflows = ${JSON.stringify(e.agentWorkflows)};`],pe=e=>[...ie(e),...e.hasAdminRevocations===!1?[]:le,...e.hasScheduler?[` if (this.schedulerDeclaration) {
|
|
591
618
|
options.schedulerDO = this.schedulerDeclaration.namespace(env);
|
|
592
619
|
}`]:[],...e.hasWorkflow?[` options.workflowsClient = (workflowEnv) => {
|
|
593
620
|
const source = workflowEnv as Record<string, unknown>;
|
|
@@ -606,6 +633,7 @@ ${E(e).join(`
|
|
|
606
633
|
// plane: the rows \`resolveTableSharding\` classifies as \`.global()\`
|
|
607
634
|
// land here, and without it they are reported, not written.
|
|
608
635
|
options.importGlobals = buildGlobalImporter(database, this.cdcEnabled);
|
|
636
|
+
options.importGlobalsStaging = buildGlobalImportStaging(database, this.cdcEnabled);
|
|
609
637
|
// The importer above skips the write for a dry run, overwrites an
|
|
610
638
|
// existing \`_id\` under \`onConflict: "replace"\`, and removes the row
|
|
611
639
|
// an \`op: "delete"\` row names.
|
|
@@ -698,7 +726,7 @@ ${E(e).join(`
|
|
|
698
726
|
}`,...e.hasAuth?[` // Captured before the branch so the narrowing survives — reading
|
|
699
727
|
// \`this.authDeclaration.namespace\` again below would be optional all over again.
|
|
700
728
|
const authDeclaration = this.authDeclaration;
|
|
701
|
-
const { authDiscoveryPathsFor, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, handleAuthDiscoveryRequest, handleAuthRequest, resolveSessionIdentity } = deferred.auth;
|
|
729
|
+
const { authCredentialColumns, authCredentialTableNames, authDiscoveryPathsFor, authTableNames, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, createSqlAuthDataPort, d1Executor, handleAuthDiscoveryRequest, handleAuthRequest, resolveSessionIdentity } = deferred.auth;
|
|
702
730
|
const authNamespace = authDeclaration?.namespace;
|
|
703
731
|
const authD1 = authDeclaration?.d1;
|
|
704
732
|
|
|
@@ -719,7 +747,7 @@ ${E(e).join(`
|
|
|
719
747
|
// Memoised on the declaration: each worker built for a new \`env\` runs
|
|
720
748
|
// these options again, and \`options(env)\` rebuilds every plugin.
|
|
721
749
|
discoveryPaths,
|
|
722
|
-
internalSecret,${
|
|
750
|
+
internalSecret,${ne(e)}${se(e)}
|
|
723
751
|
namespace,
|
|
724
752
|
...(objectName === undefined ? {} : { objectName }),
|
|
725
753
|
});
|
|
@@ -733,6 +761,9 @@ ${E(e).join(`
|
|
|
733
761
|
// Set only once auth is pinned to a jurisdiction: copies the users left in the
|
|
734
762
|
// un-pinned object across (\`__lunora_admin__:copyAuthToJurisdiction\`).
|
|
735
763
|
options.authJurisdictionMove = authWiring.jurisdictionMove;
|
|
764
|
+
// Every table of the object, for the admin export / import (\`$auth\`), so a
|
|
765
|
+
// backup, restore or eject carries users and sessions with the app's data.
|
|
766
|
+
options.authData = authWiring.dataPort;
|
|
736
767
|
// \`authAdmin\` stays D1-only: its ~30 methods read the auth tables directly
|
|
737
768
|
// from the worker, which DO storage does not allow. The studio's auth pages
|
|
738
769
|
// therefore report "not configured" in this mode rather than silently
|
|
@@ -761,7 +792,7 @@ ${E(e).join(`
|
|
|
761
792
|
// the same claims (role, expiry, profile, and the active organization and
|
|
762
793
|
// team checked against membership) on the identity, and it is unit-tested
|
|
763
794
|
// where this template cannot be.
|
|
764
|
-
return resolveSessionIdentity(auth, (request as Request).headers${
|
|
795
|
+
return resolveSessionIdentity(auth, (request as Request).headers${ae(e)});
|
|
765
796
|
};
|
|
766
797
|
const authInstance = getAuth();
|
|
767
798
|
|
|
@@ -769,6 +800,16 @@ ${E(e).join(`
|
|
|
769
800
|
options.authAdmin = createAuthAdmin(authInstance);
|
|
770
801
|
}
|
|
771
802
|
options.authAuditReader = createAuthAuditReader(d1Executor(authD1(env) as never));
|
|
803
|
+
// better-auth's tables for the admin export / import (\`$auth\`). A table the
|
|
804
|
+
// schema declares (\`authTables(...)\`) already travels as a \`.global()\` row.
|
|
805
|
+
options.authData = authInstance
|
|
806
|
+
? createSqlAuthDataPort(
|
|
807
|
+
d1Executor(authD1(env) as never),
|
|
808
|
+
authTableNames(authInstance.options).filter((table) => options.resolveTableSharding?.(table) === undefined),
|
|
809
|
+
authCredentialTableNames(authInstance.options).filter((table) => options.resolveTableSharding?.(table) === undefined),
|
|
810
|
+
authCredentialColumns(authInstance.options),
|
|
811
|
+
)
|
|
812
|
+
: undefined;
|
|
772
813
|
}
|
|
773
814
|
|
|
774
815
|
// Both modes pay a session lookup per request (the auth object hop, or a D1
|
|
@@ -865,13 +906,13 @@ ${E(e).join(`
|
|
|
865
906
|
options.resolveIdentity = fallback ? composeResolvers(accessResolver, fallback) : accessResolver;
|
|
866
907
|
}`:` if (this.accessSelector) {
|
|
867
908
|
options.resolveIdentity = createAccessResolver(this.accessSelector(env));
|
|
868
|
-
}`]:[],...
|
|
909
|
+
}`]:[],...ue(e),...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
|
|
869
910
|
${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(t.bindingName)}] as ShardNamespaceLike,`).join(`
|
|
870
911
|
`)}
|
|
871
|
-
};`]:[]],
|
|
912
|
+
};`]:[]],y=e=>e.lazyFunctions===!0?'(await import("./queues.js")).LUNORA_QUEUE_REGISTRY':"LUNORA_QUEUE_REGISTRY",f=e=>[" 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>,"],me=e=>{if(!e.hasQueue)return[];const t=e.lazyFunctions===!0?"async ":"";return[` queue: ${t}(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], ${y(e)}, {`,...f(e)," holdSeconds: trigger.holdSeconds,"," traceparent: trigger.traceparent,"," fetchImpl: queueFetch,",...e.liveStreams?[" live: queueLive,"]:[]," }),",` queueHandler: ${t}(forwarded: Parameters<typeof dispatchForwardedQueueBatch>[0], queueEnv: unknown, _context: ExecutionContextLike, hold?: { holdSeconds: number }): ReturnType<typeof dispatchForwardedQueueBatch> =>`,` dispatchForwardedQueueBatch(forwarded, ${y(e)}, {`,...f(e)," holdSeconds: hold?.holdSeconds,"," }),"," queueHandlerHolds: true,"]},be=e=>{const t=[[e.wantsArchitecture,"architecture","architecture","architecture"],[e.wantsOpenApi,"openApiSpec","openapi","openApiSpec"],[e.wantsOpenRpc,"openRpcSpec","openrpc","openRpcSpec"]],{studioAssetsBinding:r}=e;return t.flatMap(([a,s,n,o])=>a?r===void 0?[` ${s}: () => import("./${n}.js").then((module) => module.${o}),`]:[` ${s}: () => loadStudioDocument((env as Record<string, unknown>)[${JSON.stringify(r)}], ${JSON.stringify(n)}),`]:[])},ge=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)},`]:[],...be(e),...me(e),...ce(e),...de(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(t=>`(env as Record<string, unknown>)[${JSON.stringify(t)}]`).join(" ?? ")}) as WorkerOptions["spaAssets"],`]],ve=e=>e?`
|
|
872
913
|
/** The identity memo per \`env\` object, owned by one assembled worker. */
|
|
873
914
|
type IdentityMemoStore = WeakMap<object, ReturnType<typeof memoizeIdentity>>;
|
|
874
|
-
`:"",
|
|
915
|
+
`:"",A=e=>e.hasAuth,ye=e=>A(e)?`
|
|
875
916
|
/** What the worker reads only once a request arrives: loaded then, not at isolate startup (Cloudflare caps startup at 1 s of CPU). */
|
|
876
917
|
interface DeferredModules {
|
|
877
918
|
auth: typeof LunoraAuthModule;
|
|
@@ -886,13 +927,13 @@ const loadDeferredModules = (): Promise<DeferredModules> =>
|
|
|
886
927
|
auth: await import("./authModule.js"),
|
|
887
928
|
};
|
|
888
929
|
})());
|
|
889
|
-
`:"",
|
|
930
|
+
`:"",fe=(e,t)=>{const r=`buildWorker(rawEnv as Env${t})`,a=e?`
|
|
890
931
|
await ensureAuth(env);`:"",s=e?`
|
|
891
932
|
await ensureAuth(rawEnv as Env);`:"";return e?{ensureAuthCall:a,ensureRawAuthCall:s,eventWorker:"target",eventWorkerLine:`
|
|
892
933
|
const target = (await authReady(rawEnv as Env)) ? (worker ??= ${r}) : ${r};`}:{ensureAuthCall:a,ensureRawAuthCall:s,eventWorker:"worker",eventWorkerLine:`
|
|
893
|
-
worker ??= ${r};`}},
|
|
894
|
-
const deferred = await loadDeferredModules();`}:{asyncIfDeferred:"",deferredArgument:"",deferredParameter:"",loadDeferredLine:""},
|
|
895
|
-
`:"",
|
|
934
|
+
worker ??= ${r};`}},we=e=>A(e)?{asyncIfDeferred:"async ",deferredArgument:", deferred",deferredParameter:", deferred: DeferredModules",loadDeferredLine:`
|
|
935
|
+
const deferred = await loadDeferredModules();`}:{asyncIfDeferred:"",deferredArgument:"",deferredParameter:"",loadDeferredLine:""},xe=e=>e?`${w}export { authCredentialColumns, authCredentialTableNames, authDiscoveryPathsFor, authTableNames, createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, createSqlAuthDataPort, d1Executor, handleAuthDiscoveryRequest, handleAuthRequest, lunoraD1Adapter, resolveSessionIdentity } from "@lunora/auth/worker";
|
|
936
|
+
`:"",ke=e=>{const t=e.emailAgents??[];if(t.length===0)return"";const r=a=>t.map(s=>`${a}{ agent: lunoraAgentDefinitions.${s.exportName}, className: ${JSON.stringify(s.className)} },`).join(`
|
|
896
937
|
`);return e.lazyFunctions!==!0?` composed.email = dispatchAgentEmail([
|
|
897
938
|
${r(" ")}
|
|
898
939
|
]);
|
|
@@ -911,14 +952,14 @@ ${r(" ")}
|
|
|
911
952
|
return agentEmail(message, rawEnv, context);
|
|
912
953
|
};
|
|
913
954
|
|
|
914
|
-
`},
|
|
955
|
+
`},Se=e=>e.securityHeaders===void 0?"":`
|
|
915
956
|
/**
|
|
916
957
|
* \`security.headers\` from \`lunora.config\`: the baseline security headers the Worker sends, and the same values
|
|
917
958
|
* the build writes into the static assets' \`_headers\`. An app that calls \`createWorker\` itself passes it as
|
|
918
959
|
* \`security: { headers: LUNORA_SECURITY_HEADERS }\`.
|
|
919
960
|
*/
|
|
920
961
|
const LUNORA_SECURITY_HEADERS: SecurityOptions["headers"] = ${JSON.stringify(e.securityHeaders)};
|
|
921
|
-
`,
|
|
962
|
+
`,Ee=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,r)=>t.localeCompare(r)).join(", "),Ce=e=>{const t=(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0,r={...e,hasVectors:t},{hasAuth:a}=r,s=W(r),n=pe(r),o=a?` let auth: LunoraAuth | null = null;
|
|
922
963
|
let authInit: Promise<void> | null = null;
|
|
923
964
|
// One memo per env for THIS assembled worker: every worker it builds reuses it, but a second
|
|
924
965
|
// \`assemble()\` has its own auth closure and must not share.
|
|
@@ -989,11 +1030,11 @@ const LUNORA_SECURITY_HEADERS: SecurityOptions["headers"] = ${JSON.stringify(e.s
|
|
|
989
1030
|
return false;
|
|
990
1031
|
},
|
|
991
1032
|
);
|
|
992
|
-
`:"",{asyncIfDeferred:l,deferredArgument:i,deferredParameter:u,loadDeferredLine:h}=
|
|
993
|
-
host ? withFrameworkWorker(${
|
|
1033
|
+
`:"",{asyncIfDeferred:l,deferredArgument:i,deferredParameter:u,loadDeferredLine:h}=we(r),{ensureAuthCall:x,ensureRawAuthCall:C,eventWorker:m,eventWorkerLine:b}=fe(a,i),g=`${a?"() => auth, identityMemos":"() => null"}${i}`,O=`${a?"getAuth: () => LunoraAuth | null, identityMemos: IdentityMemoStore":"_getAuth: () => null"}${u}`,v=`env: Env${u}`,q=r.hasFramework?` const buildWorker = (${v}): LunoraWorker =>
|
|
1034
|
+
host ? withFrameworkWorker(${he(r)}, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${g})) : createWorker(this.buildWorkerOptions(env, ${g}));`:` const buildWorker = (${v}): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${g}));`,T=r.hasFramework?"host?: FrameworkHostHandler":"",N=ke(r),I=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
|
|
994
1035
|
public build(): ComposedApp {
|
|
995
1036
|
return this.assemble();
|
|
996
|
-
}${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`${
|
|
1037
|
+
}${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`${w}${re(r).join(`
|
|
997
1038
|
`)}
|
|
998
1039
|
|
|
999
1040
|
/** Read a value off the per-request \`env\`. Returns \`undefined\` to leave the capability unconfigured (its \`ctx.*\`/admin surface stays a clear-error stub). */
|
|
@@ -1001,7 +1042,7 @@ type Selector<Env, T> = (env: Env) => T | undefined;
|
|
|
1001
1042
|
|
|
1002
1043
|
/** The generated \`createShardDO\` config — \`.observability()\`, \`.maxRelationKeys()\` and the long-tail \`.ai()\` / \`.kv()\` / … methods pass straight through to it. */
|
|
1003
1044
|
type ShardConfig = NonNullable<Parameters<typeof createShardDO>[0]>;
|
|
1004
|
-
${
|
|
1045
|
+
${Se(r)}${ve(a)}${ye(r)}${r.jurisdiction?`
|
|
1005
1046
|
// Module scope, so every isolate loading this script (the worker and each Durable
|
|
1006
1047
|
// Object class it exports) knows the schema's jurisdiction before a request runs.
|
|
1007
1048
|
// \`@lunora/mail\` reads it to pin its shard RPC like every other DO path.
|
|
@@ -1026,32 +1067,32 @@ interface ComposedApp extends LunoraWorker {
|
|
|
1026
1067
|
* first request so per-isolate singletons are built once.
|
|
1027
1068
|
*/
|
|
1028
1069
|
class AppBuilder<Env extends object> {
|
|
1029
|
-
${
|
|
1070
|
+
${H(r).join(`
|
|
1030
1071
|
`)}
|
|
1031
1072
|
|
|
1032
1073
|
private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
|
|
1033
1074
|
|
|
1034
|
-
${
|
|
1075
|
+
${F(r).join(`
|
|
1035
1076
|
|
|
1036
1077
|
`)}
|
|
1037
1078
|
|
|
1038
|
-
${
|
|
1079
|
+
${I}
|
|
1039
1080
|
|
|
1040
1081
|
/** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
|
|
1041
|
-
private assemble(${
|
|
1042
|
-
const ShardDO = createShardDO({${
|
|
1082
|
+
private assemble(${T}): ComposedApp {
|
|
1083
|
+
const ShardDO = createShardDO({${Q(r)}});
|
|
1043
1084
|
|
|
1044
1085
|
// Per-isolate singletons: the worker (and auth instance) are expensive to
|
|
1045
1086
|
// build, so the first request constructs them and every later request on
|
|
1046
1087
|
// the same isolate reuses them.
|
|
1047
1088
|
let worker: LunoraWorker | null = null;
|
|
1048
1089
|
${o}${d}
|
|
1049
|
-
${
|
|
1090
|
+
${q}
|
|
1050
1091
|
|
|
1051
1092
|
const composed: ComposedApp = {
|
|
1052
1093
|
ShardDO,
|
|
1053
1094
|
fetch: async (request: Request, rawEnv: unknown, context: ExecutionContextLike): Promise<Response> => {
|
|
1054
|
-
const env = rawEnv as Env;${h}${
|
|
1095
|
+
const env = rawEnv as Env;${h}${x}
|
|
1055
1096
|
worker ??= buildWorker(env${i});
|
|
1056
1097
|
|
|
1057
1098
|
return worker.fetch(request, rawEnv, context);
|
|
@@ -1060,7 +1101,7 @@ ${C}
|
|
|
1060
1101
|
|
|
1061
1102
|
return ${m}.scheduled(controller, rawEnv, context);
|
|
1062
1103
|
},
|
|
1063
|
-
serverQuery: ${l}(request, rawEnv, reference, args, options) => {${h}${
|
|
1104
|
+
serverQuery: ${l}(request, rawEnv, reference, args, options) => {${h}${C}
|
|
1064
1105
|
worker ??= buildWorker(rawEnv as Env${i});
|
|
1065
1106
|
|
|
1066
1107
|
return worker.serverQuery(request, rawEnv, reference, args, options);
|
|
@@ -1071,7 +1112,7 @@ ${C}
|
|
|
1071
1112
|
},`:""}
|
|
1072
1113
|
};
|
|
1073
1114
|
|
|
1074
|
-
${
|
|
1115
|
+
${N} if (this.emailHandler) {
|
|
1075
1116
|
const handler = this.emailHandler;
|
|
1076
1117
|
|
|
1077
1118
|
composed.email = (message, rawEnv, context) => handler(rawEnv as Env)(message, rawEnv, context);
|
|
@@ -1090,11 +1131,11 @@ ${r.hasFramework?`
|
|
|
1090
1131
|
`:""}
|
|
1091
1132
|
return composed;
|
|
1092
1133
|
}
|
|
1093
|
-
${
|
|
1134
|
+
${_(r)}${M(r.hasStorage)}
|
|
1094
1135
|
/** Fan the recorded declarations into the worker-side \`createWorker\` options. */
|
|
1095
|
-
private buildWorkerOptions(env: Env, ${
|
|
1136
|
+
private buildWorkerOptions(env: Env, ${O}): WorkerOptions {
|
|
1096
1137
|
const options: WorkerOptions = {
|
|
1097
|
-
${
|
|
1138
|
+
${ge(r).join(`
|
|
1098
1139
|
`)}
|
|
1099
1140
|
};
|
|
1100
1141
|
|
|
@@ -1115,7 +1156,7 @@ ${r.securityHeaders===void 0?"":"\n // `security.headers` from lunora.con
|
|
|
1115
1156
|
return options;
|
|
1116
1157
|
}
|
|
1117
1158
|
}
|
|
1118
|
-
${
|
|
1159
|
+
${B(r.hasGlobal)}
|
|
1119
1160
|
/**
|
|
1120
1161
|
* Shape of the project's root \`lunora.config.*\`.
|
|
1121
1162
|
*
|
|
@@ -1158,5 +1199,5 @@ interface LunoraConfig<Env extends object = object> {
|
|
|
1158
1199
|
const defineApp = <Env extends object>(): AppBuilder<Env> => new AppBuilder<Env>();
|
|
1159
1200
|
|
|
1160
1201
|
export { AppBuilder, defineApp${r.securityHeaders===void 0?"":", LUNORA_SECURITY_HEADERS"} };
|
|
1161
|
-
export type { ${
|
|
1162
|
-
`};export{
|
|
1202
|
+
export type { ${Ee(r)} };
|
|
1203
|
+
`};export{Ce as emitApp,xe as emitAuthModule};
|
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
import{r as
|
|
1
|
+
import{r as M}from"./qualifiers-qqH8fRTo.mjs";import{a as d,e as o,v as l,f as v,G as _}from"./shared-Cn7dMQ_u.mjs";const D="schema",R=a=>{for(const e of a.tables)d(e.name,"table name");const m=a.tables.map(e=>`"${e.name}"`).join(" | ")||"never",p=a.tables.filter(e=>e.extensionKey===void 0).map(e=>`"${e.name}"`).join(" | ")||"never",c=a.tables.map(e=>{const t=Object.entries(e.shape).map(([h,r])=>{const s=o(h);if(r.kind==="optional"){const i=r.inner?l(r.inner):"unknown",k=e.shardMode==="global"?`${i} | null`:i;return` ${s}?: ${k};`}return` ${s}: ${l(r)};`}).join(`
|
|
2
2
|
`),n=t?`
|
|
3
3
|
${t}
|
|
4
|
-
`:"",
|
|
4
|
+
`:"",g=e.commitOrdered===!0?`
|
|
5
5
|
_commitSeq: number;`:"";return`export interface Doc_${e.name} {
|
|
6
6
|
_id: Id<"${e.name}">;
|
|
7
|
-
_creationTime: number;${
|
|
7
|
+
_creationTime: number;${g}${n}}`}).join(`
|
|
8
8
|
|
|
9
|
-
`),
|
|
10
|
-
`),
|
|
11
|
-
`),
|
|
12
|
-
`),
|
|
13
|
-
`),
|
|
14
|
-
`)
|
|
9
|
+
`),y=a.tables.map(e=>` ${e.name}: Doc_${e.name};`).join(`
|
|
10
|
+
`),x=a.tables.map(e=>{const t=e.indexes.map(n=>JSON.stringify(n.name)).join(" | ");return` ${e.name}: ${t||"never"};`}).join(`
|
|
11
|
+
`),b=a.tables.map(e=>{const t=e.searchIndexes.map(n=>JSON.stringify(n.name)).join(" | ");return` ${e.name}: ${t||"never"};`}).join(`
|
|
12
|
+
`),f=a.tables.map(e=>{const t=e.rankIndexes.map(n=>JSON.stringify(n.name)).join(" | ");return` ${e.name}: ${t||"never"};`}).join(`
|
|
13
|
+
`),T=a.tables.map(e=>{const t=e.shardMode==="global"?"":(e.geoIndexes??[]).map(n=>JSON.stringify(n.name)).join(" | ");return` ${e.name}: ${t||"never"};`}).join(`
|
|
14
|
+
`),$=a.vectorIndexes.map(e=>JSON.stringify(e.name)).join(" | ")||"never",u=a.tables.map(e=>v(e)).join(`
|
|
15
15
|
|
|
16
|
-
`),
|
|
17
|
-
`),
|
|
16
|
+
`),I=a.tables.map(e=>` ${e.name}: Insert_${e.name};`).join(`
|
|
17
|
+
`),N=a.tables.map(e=>{const t=e.relations.map(n=>(d(n.table,"relation target table"),n.kind==="one"?` ${o(n.name)}: OneRelation<"${n.table}", ${JSON.stringify(n.field)}>;`:` ${o(n.name)}: ManyRelation<"${n.table}">;`)).join(`
|
|
18
18
|
`);return t?` ${e.name}: {
|
|
19
19
|
${t}
|
|
20
20
|
};`:` ${e.name}: {};`}).join(`
|
|
21
|
-
`);return
|
|
21
|
+
`);return M(`${_}export type TableName = ${m};
|
|
22
22
|
|
|
23
23
|
/**
|
|
24
24
|
* The tables **this app declared** — every {@link TableName} except those an add-on
|
|
@@ -35,14 +35,14 @@ ${t}
|
|
|
35
35
|
* const EXPORTED: readonly AppTableName[] = ["nodes", "tagColors"];
|
|
36
36
|
* \`\`\`
|
|
37
37
|
*/
|
|
38
|
-
export type AppTableName = ${
|
|
38
|
+
export type AppTableName = ${p};
|
|
39
39
|
|
|
40
40
|
export type Id<TName extends string> = string & { readonly __table: TName };
|
|
41
41
|
|
|
42
|
-
${
|
|
42
|
+
${c}
|
|
43
43
|
|
|
44
44
|
export interface DataModel {
|
|
45
|
-
${
|
|
45
|
+
${y}
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
export type Doc<T extends keyof DataModel> = DataModel[T];
|
|
@@ -52,40 +52,40 @@ export type Doc<T extends keyof DataModel> = DataModel[T];
|
|
|
52
52
|
* Used by \`TableReader.withIndex()\` to constrain callers to declared names.
|
|
53
53
|
*/
|
|
54
54
|
export interface IndexNamesByTable {
|
|
55
|
-
${
|
|
55
|
+
${x}
|
|
56
56
|
}
|
|
57
57
|
|
|
58
58
|
export type IndexName<T extends keyof DataModel> = IndexNamesByTable[T];
|
|
59
59
|
|
|
60
60
|
/** Per-table search-index name union. \`never\` for tables without searchIndex. */
|
|
61
61
|
export interface SearchIndexNamesByTable {
|
|
62
|
-
${
|
|
62
|
+
${b}
|
|
63
63
|
}
|
|
64
64
|
|
|
65
65
|
export type SearchIndexName<T extends keyof DataModel> = SearchIndexNamesByTable[T];
|
|
66
66
|
|
|
67
67
|
/** Per-table rank-index name union. \`never\` for tables without a rankIndex. */
|
|
68
68
|
export interface RankIndexNamesByTable {
|
|
69
|
-
${
|
|
69
|
+
${f}
|
|
70
70
|
}
|
|
71
71
|
|
|
72
72
|
export type RankIndexName<T extends keyof DataModel> = RankIndexNamesByTable[T];
|
|
73
73
|
|
|
74
74
|
/** Per-table geo-index name union. \`never\` for tables without a geoIndex. */
|
|
75
75
|
export interface GeoIndexNamesByTable {
|
|
76
|
-
${
|
|
76
|
+
${T}
|
|
77
77
|
}
|
|
78
78
|
|
|
79
79
|
export type GeoIndexName<T extends keyof DataModel> = GeoIndexNamesByTable[T];
|
|
80
80
|
|
|
81
81
|
/** Union of declared vector index names. \`never\` when none are declared. */
|
|
82
|
-
export type VectorIndexName = ${
|
|
82
|
+
export type VectorIndexName = ${$};
|
|
83
83
|
|
|
84
|
-
${
|
|
84
|
+
${u}
|
|
85
85
|
|
|
86
86
|
/** Per-table insert shape, accepted by \`ctx.db.<table>.insert(...)\`. */
|
|
87
87
|
export interface InsertModel {
|
|
88
|
-
${
|
|
88
|
+
${I}
|
|
89
89
|
}
|
|
90
90
|
|
|
91
91
|
export type Insert<T extends keyof DataModel> = InsertModel[T];
|
|
@@ -108,7 +108,7 @@ export interface ManyRelation<Target extends keyof DataModel> {
|
|
|
108
108
|
|
|
109
109
|
/** Per-table relation map keyed by accessor name. \`{}\` for tables with none. */
|
|
110
110
|
export interface Relations {
|
|
111
|
-
${
|
|
111
|
+
${N}
|
|
112
112
|
}
|
|
113
113
|
|
|
114
|
-
`,
|
|
114
|
+
`,D)};export{D as SCHEMA_MODULE_PATH,R as emitDataModel};
|
package/dist/packem_shared/{emitDrizzleSchema-BzOChEYW.mjs → emitDrizzleSchema-D_b193PY.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{SCHEMA_MODULE_PATH as c}from"./emitDataModel-
|
|
1
|
+
import{SCHEMA_MODULE_PATH as c}from"./emitDataModel-BCyOctft.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 +1 @@
|
|
|
1
|
-
import"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-
|
|
1
|
+
import"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-BbYT2omp.mjs";import"./shard-runtime-G5mZQjY0.mjs";import"./shared-Cn7dMQ_u.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
|
|
@@ -165,7 +165,9 @@ ${y()}
|
|
|
165
165
|
|
|
166
166
|
// \`importShardRows\` inserts with \`allowExplicitId\`, so a source
|
|
167
167
|
// database's \`_id\`s carry across verbatim and every foreign key
|
|
168
|
-
// referencing them stays valid without a second remapping pass.
|
|
168
|
+
// referencing them stays valid without a second remapping pass. A
|
|
169
|
+
// staged replace's commit (\`replaceTables\` / \`keepIds\`) arrives inside
|
|
170
|
+
// the base class's transaction.
|
|
169
171
|
return importShardRows(writer, schema as unknown as SchemaLike, args);
|
|
170
172
|
}
|
|
171
173
|
|