@lunora/codegen 1.0.0-alpha.42 → 1.0.0-alpha.420

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 (130) hide show
  1. package/LICENSE.md +201 -104
  2. package/README.md +4 -4
  3. package/dist/index.d.mts +4583 -2045
  4. package/dist/index.d.ts +4583 -2045
  5. package/dist/index.mjs +1 -35
  6. package/dist/packem_shared/AGENTS_FILENAME-C4tHmiZZ.mjs +1 -0
  7. package/dist/packem_shared/ALL_NOTIFY_CHANNELS-BgkkvuUe.mjs +1 -0
  8. package/dist/packem_shared/CAPABILITY_PROBES-DCzOjTN7.mjs +25 -0
  9. package/dist/packem_shared/COMPANION_BINDING-Da_v9XpC.mjs +1 -0
  10. package/dist/packem_shared/CONTAINERS_FILENAME-d3XTFcqV.mjs +1 -0
  11. package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
  12. package/dist/packem_shared/DEFAULT_TARGET-CVYzxQ0y.mjs +1 -0
  13. package/dist/packem_shared/ENV_FILENAME-DJ11PXN5.mjs +1 -0
  14. package/dist/packem_shared/FLAGS_FILENAME-DeSjFBWq.mjs +1 -0
  15. package/dist/packem_shared/GENERATED_HEADER-DgrhC3Iv.mjs +1 -0
  16. package/dist/packem_shared/LUNORA_ERROR_CODES-D7AVT7qF.mjs +1 -0
  17. package/dist/packem_shared/MUTATORS_FILENAME-C0ZV0hh6.mjs +1 -0
  18. package/dist/packem_shared/OPENRPC_VERSION-BOBo0zdQ.mjs +3 -0
  19. package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs +1 -0
  20. package/dist/packem_shared/QUEUES_FILENAME-DbuJZnrY.mjs +1 -0
  21. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-BljJJD8u.mjs +56 -0
  22. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs +2 -0
  23. package/dist/packem_shared/SHAPES_FILENAME-C-hrGfJ2.mjs +1 -0
  24. package/dist/packem_shared/SchemaSnapshotParseError-CV7mmuPi.mjs +17 -0
  25. package/dist/packem_shared/WORKFLOWS_FILENAME-7FysJsMZ.mjs +1 -0
  26. package/dist/packem_shared/attribution-Cwt30DDJ.mjs +1 -0
  27. package/dist/packem_shared/buildOpenApiDocument-DmV_PBFv.mjs +3 -0
  28. package/dist/packem_shared/capabilitiesUsedBy-BNvoiCu1.mjs +1 -0
  29. package/dist/packem_shared/classify-procedure-call-BmEirzc_.mjs +1 -0
  30. package/dist/packem_shared/companionServiceBinding-BZjm486n.mjs +1 -0
  31. package/dist/packem_shared/context-property-calls-BT1J7BqY.mjs +1 -0
  32. package/dist/packem_shared/context-root-BpDEhvNE.mjs +1 -0
  33. package/dist/packem_shared/createCodegenProject-dC6oJh5H.mjs +1 -0
  34. package/dist/packem_shared/database-calls-d-Sssc-3.mjs +1 -0
  35. package/dist/packem_shared/declared-output-Iaar469J.mjs +1 -0
  36. package/dist/packem_shared/describeErrorLevelFindings-DlkgCw8a.mjs +1 -0
  37. package/dist/packem_shared/discoverAuthApiCalls-CuqaLRa0.mjs +1 -0
  38. package/dist/packem_shared/discoverCrons-bT8F5GyL.mjs +1 -0
  39. package/dist/packem_shared/discoverFunctions-C9HUlfiV.mjs +1 -0
  40. package/dist/packem_shared/discoverHttpRoutes-CesuhqW1.mjs +1 -0
  41. package/dist/packem_shared/discoverHyperdriveCalls-BmAoOGGq.mjs +1 -0
  42. package/dist/packem_shared/discoverInserts-DIarYU2P.mjs +1 -0
  43. package/dist/packem_shared/discoverMaskProcedures-jkRrWS86.mjs +1 -0
  44. package/dist/packem_shared/discoverMigrations-C9AlZYFi.mjs +1 -0
  45. package/dist/packem_shared/discoverNondeterministicCalls-ZeZDQJAI.mjs +1 -0
  46. package/dist/packem_shared/discoverQueries-DLZHcDzB.mjs +1 -0
  47. package/dist/packem_shared/discoverR2sqlCalls-D_HWbbky.mjs +1 -0
  48. package/dist/packem_shared/discoverRlsMetadata-C0UkQkWd.mjs +1 -0
  49. package/dist/packem_shared/discoverRlsProcedures-BbSdCvmA.mjs +1 -0
  50. package/dist/packem_shared/discoverSandboxUsage-Dgvv6F_7.mjs +1 -0
  51. package/dist/packem_shared/discoverSchema-BLTROO8Z.mjs +1 -0
  52. package/dist/packem_shared/discoverStorageRulesMetadata-DeBgC7po.mjs +1 -0
  53. package/dist/packem_shared/dispatch-namespace-DwTjD7BU.mjs +1 -0
  54. package/dist/packem_shared/emitAgents-vWoT8-Yb.mjs +1 -0
  55. package/dist/packem_shared/emitApi-lwadq5G7.mjs +147 -0
  56. package/dist/packem_shared/emitApp-LFKtDRYu.mjs +1162 -0
  57. package/dist/packem_shared/emitCrons-CCRKs482.mjs +138 -0
  58. package/dist/packem_shared/emitDataModel-BvCZS4Yq.mjs +114 -0
  59. package/dist/packem_shared/emitDrizzleSchema-BzOChEYW.mjs +15 -0
  60. package/dist/packem_shared/emitFunctions-ppMX7E3X.mjs +528 -0
  61. package/dist/packem_shared/emitServer-CGRV_uIq.mjs +1 -0
  62. package/dist/packem_shared/emitShard-CDWgekIG.mjs +1 -0
  63. package/dist/packem_shared/exported-procedure-chains-CfH5jrzD.mjs +1 -0
  64. package/dist/packem_shared/fingerprintSchemaSources-TN-rU6Of.mjs +1 -0
  65. package/dist/packem_shared/formatAdvisories-Bue5tbp6.mjs +2 -0
  66. package/dist/packem_shared/handler-reference-BkOkxxg8.mjs +1 -0
  67. package/dist/packem_shared/index-CfSmiylg.mjs +1 -0
  68. package/dist/packem_shared/index-DtJBMdZ4.mjs +1 -0
  69. package/dist/packem_shared/ip-reads-D2qhKEb6.mjs +1 -0
  70. package/dist/packem_shared/isD1GlobalTable-udvHAAzD.mjs +1 -0
  71. package/dist/packem_shared/isTestPath-Uwb5a6Kq.mjs +1 -0
  72. package/dist/packem_shared/isTypedSchema-CDv3pJB6.mjs +4 -0
  73. package/dist/packem_shared/json-data-Chfs2Cz5.mjs +1 -0
  74. package/dist/packem_shared/loadProjectConfig-BXwH3_gn.mjs +1 -0
  75. package/dist/packem_shared/module-specifiers-BctA0m_p.mjs +1 -0
  76. package/dist/packem_shared/modules-DdOd-7Wp.mjs +1 -0
  77. package/dist/packem_shared/parse-validator-BisfC8bR.mjs +1 -0
  78. package/dist/packem_shared/platform-8oj7iXQy.mjs +1 -0
  79. package/dist/packem_shared/policies-Dn_tuTZd.mjs +1 -0
  80. package/dist/packem_shared/project-config-file-DR7xrrNB.mjs +1 -0
  81. package/dist/packem_shared/property-name-7cBlgK_O.mjs +1 -0
  82. package/dist/packem_shared/qualifiers-qqH8fRTo.mjs +1 -0
  83. package/dist/packem_shared/readPackageDependencies-RHhGiz0k.mjs +1 -0
  84. package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
  85. package/dist/packem_shared/reserved-words-CW1QFbTd.mjs +1 -0
  86. package/dist/packem_shared/schema-BgM8A3XV.mjs +1 -0
  87. package/dist/packem_shared/schemaFromIr-CByOxuZb.mjs +1 -0
  88. package/dist/packem_shared/server-Dfxmm5Zw.mjs +377 -0
  89. package/dist/packem_shared/shard-CWAD5mYy.mjs +1897 -0
  90. package/dist/packem_shared/shard-runtime-G5mZQjY0.mjs +351 -0
  91. package/dist/packem_shared/shared-Cn7dMQ_u.mjs +13 -0
  92. package/dist/packem_shared/unwrap-handler-return-DvbyiLjc.mjs +1 -0
  93. package/dist/sdk/index.d.mts +288 -0
  94. package/dist/sdk/index.d.ts +288 -0
  95. package/dist/sdk/index.mjs +394 -0
  96. package/package.json +22 -9
  97. package/dist/packem_shared/CONTAINERS_FILENAME-DjpXMqhp.mjs +0 -224
  98. package/dist/packem_shared/CodegenDiagnosticError-DyQ5FwkM.mjs +0 -24
  99. package/dist/packem_shared/FLAGS_FILENAME-fEZtzWXi.mjs +0 -139
  100. package/dist/packem_shared/GENERATED_HEADER-D6RK1WF1.mjs +0 -3
  101. package/dist/packem_shared/LUNORA_ERROR_CODES-DvTLozCu.mjs +0 -68
  102. package/dist/packem_shared/MUTATORS_FILENAME-BZOfUhlY.mjs +0 -81
  103. package/dist/packem_shared/OPENRPC_VERSION-CzhfvCIQ.mjs +0 -60
  104. package/dist/packem_shared/QUEUES_FILENAME-Xv6Vy-Ku.mjs +0 -145
  105. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-Cl1EBMdR.mjs +0 -3438
  106. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-D0ARY6rL.mjs +0 -249
  107. package/dist/packem_shared/SHAPES_FILENAME-DOhPGi-6.mjs +0 -94
  108. package/dist/packem_shared/WORKFLOWS_FILENAME-B2By8S4s.mjs +0 -152
  109. package/dist/packem_shared/buildOpenApiDocument-bg-NnLka.mjs +0 -183
  110. package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
  111. package/dist/packem_shared/discoverAuthApiCalls-WMx8L2FG.mjs +0 -62
  112. package/dist/packem_shared/discoverCrons-D-jrpm97.mjs +0 -256
  113. package/dist/packem_shared/discoverFunctions-CZ91aenA.mjs +0 -518
  114. package/dist/packem_shared/discoverHttpRoutes-DNZLDCmm.mjs +0 -131
  115. package/dist/packem_shared/discoverInserts-DFRJhmCv.mjs +0 -61
  116. package/dist/packem_shared/discoverMaskProcedures-B5iFnZ-X.mjs +0 -273
  117. package/dist/packem_shared/discoverMigrations-CdKtMlBc.mjs +0 -97
  118. package/dist/packem_shared/discoverNondeterministicCalls-C_PrQPkA.mjs +0 -122
  119. package/dist/packem_shared/discoverQueries-B8W9UPrt.mjs +0 -62
  120. package/dist/packem_shared/discoverR2sqlCalls-Bm7Rfnf4.mjs +0 -80
  121. package/dist/packem_shared/discoverRlsMetadata-B4GL4ZKm.mjs +0 -280
  122. package/dist/packem_shared/discoverSchema-DFWVgU5o.mjs +0 -874
  123. package/dist/packem_shared/discoverStorageRulesMetadata-nosjYcvN.mjs +0 -97
  124. package/dist/packem_shared/emit-31Yg1Ee5.mjs +0 -3474
  125. package/dist/packem_shared/emitApp-DCP7Pr6M.mjs +0 -668
  126. package/dist/packem_shared/formatAdvisories-DRhEiJUz.mjs +0 -114
  127. package/dist/packem_shared/parse-validator-BSJo1HGP.mjs +0 -144
  128. package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
  129. package/dist/packem_shared/redact-oTmsol5A.mjs +0 -33
  130. package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
@@ -0,0 +1,1162 @@
1
+ import{APP_METHOD_CAPABILITIES as T}from"./CAPABILITY_PROBES-DCzOjTN7.mjs";import{i as I}from"./schema-BgM8A3XV.mjs";import{a as L,I as $,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=>[...T.filter(({key:t})=>e.capabilities.has(t)).map(({appMethod:t})=>t),...e.hasVectors?[j]:[]],w=e=>f(e).length>0,k=e=>(e.emailAgents?.length??0)>0,c=e=>e.tables.some(t=>I(t)),p=e=>e.liveStreams===!0&&(e.liveStreamDeclarations?.length??0)>0,P=e=>e.hasScheduler?`
2
+ /** Resolve the \`SchedulerDO\`-backed scheduler for this env; \`undefined\` until the namespace is wired. */
3
+ private resolveScheduler(env: Env): ReturnType<typeof createScheduler> | undefined {
4
+ const namespace = this.schedulerDeclaration?.namespace(env);
5
+
6
+ return namespace ? createScheduler({${e.jurisdiction?` jurisdiction: ${JSON.stringify(e.jurisdiction)},`:""} namespace }) : undefined;
7
+ }
8
+ `:"",G=e=>e?`
9
+ /**
10
+ * One bucket's \`Storage\`, signing under the name it is registered as.
11
+ *
12
+ * \`bucketName\` is bound into every signed URL's HMAC canonical, so a bucket
13
+ * that signs as the default's name lets a URL minted for one bucket verify
14
+ * against another sharing the secret — and multi-bucket verification fails
15
+ * outright. Hence \`"default"\` for the bare \`ctx.storage\` bucket and the
16
+ * \`buckets\` key for every other.
17
+ *
18
+ * \`origin\` is the request's own origin, the base when no \`publicBaseUrl\` is
19
+ * declared.
20
+ */
21
+ private makeStorage(env: Env, declaration: StorageDeclaration<Env>, bucket: R2BucketLike, bucketName: string, origin?: string): Storage {
22
+ const publicBaseUrl = declaration.publicBaseUrl?.(env) ?? origin;
23
+ const s3 = declaration.s3?.(env);
24
+ const signingSecret = declaration.signingSecret?.(env);
25
+
26
+ return createStorage({
27
+ bucket,
28
+ bucketName,
29
+ ...(publicBaseUrl === undefined ? {} : { publicBaseUrl }),
30
+ ...(s3 === undefined ? {} : { s3 }),
31
+ ...(signingSecret === undefined ? {} : { signingSecret }),
32
+ });
33
+ }
34
+
35
+ /** Resolve the storage capability (single or multi-bucket) for the DO side. */
36
+ private resolveStorage(env: Env, origin?: string): Storage | undefined {
37
+ const declaration = this.storageDeclaration;
38
+
39
+ if (!declaration) {
40
+ return undefined;
41
+ }
42
+
43
+ const defaultBucket = declaration.bucket(env);
44
+
45
+ if (!defaultBucket) {
46
+ return undefined;
47
+ }
48
+
49
+ const extraEntries = Object.entries(declaration.buckets ?? {})
50
+ .map(([name, selector]) => [name, selector(env)] as const)
51
+ .filter((entry): entry is [string, R2BucketLike] => Boolean(entry[1]));
52
+
53
+ if (extraEntries.length === 0) {
54
+ return this.makeStorage(env, declaration, defaultBucket, "default", origin);
55
+ }
56
+
57
+ const map: Record<string, Storage> = { default: this.makeStorage(env, declaration, defaultBucket, "default", origin) };
58
+
59
+ for (const [name, bucket] of extraEntries) {
60
+ map[name] = this.makeStorage(env, declaration, bucket, name, origin);
61
+ }
62
+
63
+ return createBucketStorage(map, { default: "default" });
64
+ }
65
+
66
+ /** Derive the studio file-browser admin functions from the same buckets \`.storage()\` declared. */
67
+ private buildStorageAdmin(env: Env): Partial<WorkerOptions> {
68
+ const declaration = this.storageDeclaration;
69
+
70
+ if (!declaration) {
71
+ return {};
72
+ }
73
+
74
+ const defaultBucket = declaration.bucket(env);
75
+
76
+ if (!defaultBucket) {
77
+ return {};
78
+ }
79
+
80
+ const bindings: Record<string, R2BucketLike> = { default: defaultBucket };
81
+
82
+ for (const [name, selector] of Object.entries(declaration.buckets ?? {})) {
83
+ const bucket = selector(env);
84
+
85
+ if (bucket) {
86
+ bindings[name] = bucket;
87
+ }
88
+ }
89
+
90
+ // \`Object.hasOwn\`, not a bare lookup: \`bindings\` is a plain object, so a
91
+ // prototype key (\`?bucket=constructor\`, \`__proto__\`, \`toString\`) resolves
92
+ // to an inherited Object.prototype member instead of the default bucket.
93
+ //
94
+ // \`origin\` is the base when no \`publicBaseUrl\` is declared: the origin the
95
+ // admin request reached the worker on, which the signed-URL route hands
96
+ // over and then verifies. Only the secret gates signing.
97
+ const pick = (name?: string, origin?: string): Storage => {
98
+ const wanted = name !== undefined && name !== "" ? name : "default";
99
+ const bucketName = Object.hasOwn(bindings, wanted) ? wanted : "default";
100
+
101
+ return this.makeStorage(env, declaration, bindings[bucketName] ?? defaultBucket, bucketName, origin);
102
+ };
103
+ const hasSigning = Boolean(declaration.signingSecret?.(env));
104
+
105
+ return {
106
+ storageBuckets: Object.keys(bindings),
107
+ storageDelete: (key: string, opts?: { bucket?: string }) => pick(opts?.bucket).delete(key),
108
+ storageDownload: (key: string, opts?: { bucket?: string }) => pick(opts?.bucket).download(key),
109
+ storageList: (prefix?: string, opts?: { bucket?: string; cursor?: string; limit?: number }) => pick(opts?.bucket).list(prefix, opts),
110
+ ...(hasSigning ? {
111
+ storageSignedUrl: (key: string, opts?: { bucket?: string; contentType?: string; expiresInSeconds?: number; method?: "GET" | "PUT"; origin?: string }) =>
112
+ pick(opts?.bucket, opts?.origin).getSignedUrl(key, opts),
113
+ } : {}),
114
+ storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string; sha256?: string }) => pick(opts?.bucket).upload(key, body, opts),
115
+ };
116
+ }
117
+ `:"",_=e=>e?`
118
+ /**
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
+ *
121
+ * Opens a D1 Sessions API session pinned to \`bookmark\` (the caller's own
122
+ * last-known write, when supplied) so reads observe it — read-your-writes
123
+ * across replicas. \`onBookmark\`, when supplied, is invoked with the bookmark
124
+ * produced by each write so the caller (the generated DO) can record it on the
125
+ * dispatch's bookmark sink and echo \`x-d1-bookmark\` on the response.
126
+ *
127
+ * Wrapped in \`retryingExec\` so D1's documented baseline of transient failures
128
+ * (storage-object resets, isolate memory evictions, dropped connections) does
129
+ * not surface on every \`.global()\` read. Only statements that are provably
130
+ * read-only retry; writes — including the \`UPDATE … RETURNING\` the store's
131
+ * optimistic-concurrency check issues through \`all\` — pass straight through,
132
+ * because a transient error never says whether the write applied.
133
+ *
134
+ * Every read and write also records D1's own \`meta\` accounting (\`rows_read\` /
135
+ * \`rows_written\` / \`duration\`) against a low-cardinality \`verb:table\` tag.
136
+ * Rows READ is rows SCANNED, not returned, so this is the number that explains
137
+ * a D1 bill and the one a missing index inflates without anything being
138
+ * deployed; the dashboard's own metric is per-database and can't name the query.
139
+ * The emit is best-effort — instrumentation must never fail a served query.
140
+ */
141
+ const buildSessionExec = (database: D1DatabaseLike, constraint: string, onBookmark?: (bookmark: string | undefined) => void): D1Exec => {
142
+ // Real D1 always exposes \`withSession\`; guarded the same way as \`batch\`
143
+ // below so a hand-rolled test double that omits it keeps working via
144
+ // \`prepare()\` straight on the raw binding — today's behaviour. \`constraint\`
145
+ // is the Sessions API constraint the session opens with (see \`buildExec\`).
146
+ const session = typeof database.withSession === "function" ? database.withSession(constraint) : undefined;
147
+ const target = session ?? database;
148
+ const batchFn = target.batch;
149
+
150
+ return retryingExec({
151
+ all: async (sql, parameters) => {
152
+ const result = await target
153
+ .prepare(sql)
154
+ .bind(...parameters)
155
+ .all<Record<string, unknown>>();
156
+
157
+ // \`all\` carries writes, not just reads: D1 runs
158
+ // \`UPDATE/DELETE … RETURNING\` through it exactly like \`.run()\`, and
159
+ // that is precisely what \`@lunora/sql-store\` issues for its
160
+ // optimistic-concurrency compare-and-swap — so \`patch\`, \`replace\`
161
+ // and \`delete\` all land here and nowhere else. Without this the
162
+ // bookmark those writes produced was never reported, and the next
163
+ // read could pin a replica that has not seen them: read-your-writes
164
+ // lost on the exact path the bookmark exists for. Reporting it after
165
+ // a plain \`SELECT\` too is harmless and correct — the session's
166
+ // bookmark only ever moves forward, and the sink takes the last
167
+ // value.
168
+ onBookmark?.(session?.getBookmark() ?? undefined);
169
+ meter(sql, result.meta);
170
+
171
+ return result.results;
172
+ },
173
+ // D1's own \`batch\` runs the whole array as one atomic SQLite
174
+ // transaction. Guarded because \`batch\` is optional in the structural
175
+ // type (test doubles may omit it) — real D1 always has it; a double
176
+ // without it still works through the store's sequential fallback.
177
+ // Invoked via \`.call(target, ...)\` rather than \`target.batch(...)\`
178
+ // directly so TS can narrow the captured \`batchFn\` across the closure
179
+ // boundary (a property-access narrowing like
180
+ // \`hasBatch = typeof target.batch === "function"\` does not survive
181
+ // into a nested arrow function); \`.call\` still binds \`this\` to
182
+ // \`target\`, so the real workerd \`D1Database\`/session doesn't throw
183
+ // \`TypeError: Illegal invocation\` the way a detached
184
+ // \`const fn = target.batch; fn(...)\` capture would.
185
+ ...(batchFn ? {
186
+ batch: async (statements) => {
187
+ const results = await batchFn.call(
188
+ target,
189
+ statements.map(({ params, sql }) => target.prepare(sql).bind(...params)),
190
+ );
191
+
192
+ // Meter each leg. D1 returns one result per statement, in
193
+ // order, each with its own \`meta\` — and a batch is where the
194
+ // expensive writes live (\`@lunora/sql-store\` runs its
195
+ // backfills through here), so discarding it left exactly the
196
+ // statements worth costing unaccounted. Guarded on the array
197
+ // because \`batch\` is optional in the structural type and a
198
+ // test double may resolve to anything.
199
+ if (Array.isArray(results)) {
200
+ for (const [index, statement] of statements.entries()) {
201
+ meter(statement.sql, (results[index] as { meta?: Record<string, unknown> } | undefined)?.meta);
202
+ }
203
+ }
204
+
205
+ onBookmark?.(session?.getBookmark() ?? undefined);
206
+ },
207
+ } : {}),
208
+ run: async (sql, parameters) => {
209
+ const result = await target
210
+ .prepare(sql)
211
+ .bind(...parameters)
212
+ .run();
213
+
214
+ meter(sql, result.meta);
215
+ onBookmark?.(session?.getBookmark() ?? undefined);
216
+ },
217
+ });
218
+ };
219
+
220
+ const meter = (sql: string, meta: Record<string, unknown> | undefined): void => {
221
+ try {
222
+ emitD1QueryCost(sql, meta);
223
+ } catch {
224
+ // Best-effort: never let cost accounting fail the query it measures.
225
+ }
226
+ };
227
+
228
+ /**
229
+ * The primary exec, for a read that must see every committed write (a policy check on a write
230
+ * path). Every statement opens its own \`"first-primary"\` session, and so does every retry:
231
+ * that constraint covers only a session's first read, so one session shared by two reads, or by
232
+ * a retry, can serve the later read from a replica that has not caught up. It reports no
233
+ * bookmark: the sink keeps the last value it is given, and a later replica read reports an older
234
+ * one, which would move the client's bookmark backwards.
235
+ */
236
+ const buildPrimaryExec = (database: D1DatabaseLike): D1Exec => {
237
+ const statement = (sql: string, parameters: ReadonlyArray<unknown>) =>
238
+ (typeof database.withSession === "function" ? database.withSession("first-primary") : database).prepare(sql).bind(...parameters);
239
+
240
+ return retryingExec({
241
+ all: async (sql, parameters) => {
242
+ const result = await statement(sql, parameters).all<Record<string, unknown>>();
243
+
244
+ meter(sql, result.meta);
245
+
246
+ return result.results;
247
+ },
248
+ run: async (sql, parameters) => {
249
+ const result = await statement(sql, parameters).run();
250
+
251
+ meter(sql, result.meta);
252
+ },
253
+ });
254
+ };
255
+
256
+ /**
257
+ * The replica exec reads at the caller's bookmark, or \`"first-unconstrained"\` (lowest latency,
258
+ * any replica) without one. \`primary\` is the per-statement primary exec (see \`buildPrimaryExec\`).
259
+ */
260
+ const buildExec = (database: D1DatabaseLike, bookmark?: string, onBookmark?: (bookmark: string | undefined) => void): D1Exec => {
261
+ const replica = buildSessionExec(database, bookmark ?? "first-unconstrained", onBookmark);
262
+
263
+ if (typeof database.withSession !== "function") {
264
+ return replica;
265
+ }
266
+
267
+ return { ...replica, primary: buildPrimaryExec(database) };
268
+ };
269
+
270
+ /** Introspect \`.global()\` (D1-backed) tables for the studio's global data browser. */
271
+ const buildGlobalIntrospector = (database: D1DatabaseLike): GlobalIntrospector => {
272
+ const exec = buildExec(database);
273
+
274
+ return {
275
+ facetColumn: (options) => facetGlobalColumn(exec, schema as never, options),
276
+ listTables: () => listGlobalTables(exec, schema as never),
277
+ readTablePage: (options) => readGlobalTablePage(exec, schema as never, options),
278
+ };
279
+ };
280
+
281
+ /**
282
+ * \`importGlobals\` for the admin bulk-import endpoint: routes \`.global()\` rows
283
+ * through the same D1 writer \`.global()\` reads/writes already use, via
284
+ * \`@lunora/d1\`'s \`importGlobalRows\`. Mirrors \`runShardImport\`'s shard-local
285
+ * twin (\`createShardCtxDb\` + \`importShardRows\`) — same \`{ rows, startLine }\`
286
+ * shape, same trusted-import \`allowExplicitId\` semantics, forwarded as-is.
287
+ *
288
+ * Passes each row's own \`line\` through rather than dropping it: the caller
289
+ * (\`@lunora/runtime\`'s NDJSON import stream) already carries the row's true
290
+ * physical source line, and global rows are typically interspersed with
291
+ * shard-local ones it filtered out before calling here — a single
292
+ * \`startLine\` plus positional counting would mis-attribute every row after
293
+ * the first gap. \`importGlobalRows\` prefers \`row.line\` when present and
294
+ * falls back to the position-derived count otherwise. A dry run is passed through and writes nothing;
295
+ * \`onConflict: "replace"\` overwrites a row whose \`_id\` already exists instead of reporting a conflict, and a row's
296
+ * \`op: "delete"\` removes the stored row it names.
297
+ */
298
+ const buildGlobalImporter =
299
+ (database: D1DatabaseLike, cdc: boolean) =>
300
+ (request: { dryRun?: boolean; onConflict?: "replace" | "skip"; rows: ReadonlyArray<{ doc: Record<string, unknown>; line: number; op?: "delete"; table: string }>; startLine?: number }) => {
301
+ const exec = buildExec(database);
302
+ // Same reason the PITR applier carries it: a bulk import that skips the
303
+ // changelog restores rows no downstream consumer is ever told about.
304
+ const writer = createD1CtxDb({ cdc, exec, schema: schema as unknown as D1CtxDbOptions["schema"] });
305
+
306
+ return importGlobalRows(writer, schema as unknown as D1CtxDbOptions["schema"], {
307
+ dryRun: request.dryRun === true,
308
+ exec,
309
+ onConflict: request.onConflict ?? "skip",
310
+ rows: request.rows.map((row) => ({ doc: row.doc, line: row.line, ...(row.op === undefined ? {} : { op: row.op }), table: row.table })),
311
+ ...(request.startLine === undefined ? {} : { startLine: request.startLine }),
312
+ });
313
+ };
314
+
315
+ /**
316
+ * \`exportGlobals\` for the admin export endpoint (and the scheduled R2 backup,
317
+ * which drains the same stream): the read twin of {@link buildGlobalImporter},
318
+ * over the same D1 handle. \`@lunora/d1\`'s \`exportGlobalRows\` keyset-paginates
319
+ * each table and provisions the schema's global tables first, so a table that
320
+ * was never written exports as empty instead of throwing \`no such table\`.
321
+ *
322
+ * \`tables\` is forwarded as-is: the runtime passes an empty array for "every
323
+ * table" (its \`tables === undefined\` case), which is exactly what
324
+ * \`selectGlobalTables\` reads an empty allowlist as.
325
+ */
326
+ const buildGlobalExporter =
327
+ (database: D1DatabaseLike) =>
328
+ (request: { tables: ReadonlyArray<string> }) =>
329
+ exportGlobalRows(buildExec(database), schema as unknown as D1CtxDbOptions["schema"], { tables: request.tables });
330
+
331
+ /**
332
+ * \`syncGlobals\` for the admin CDC sync + warehouse-connector endpoints: pages
333
+ * the global \`__cdc_log\` past \`sinceSeq\`, the global-plane twin of the shard's
334
+ * \`runShardCdcSync\`.
335
+ *
336
+ * Probes \`sqlite_master\` first, exactly as the shard twin does. The changelog
337
+ * table is only created when the global writer runs with CDC enabled, so on
338
+ * every other app a straight read would throw \`no such table: __cdc_log\` and
339
+ * turn "nothing has changed yet" into a 500. Absent log ⇒ an empty page that
340
+ * leaves the caller's cursor where it was.
341
+ */
342
+ const buildGlobalCdcSync =
343
+ (database: D1DatabaseLike) =>
344
+ async (request: { limit?: number; sinceSeq: number }): Promise<{ changes: ReadonlyArray<Record<string, unknown>>; cursor: number }> => {
345
+ const exec = buildExec(database);
346
+ const present = await exec.all(\`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?\`, ["__cdc_log"]);
347
+
348
+ if (present.length === 0) {
349
+ return { changes: [], cursor: request.sinceSeq };
350
+ }
351
+
352
+ const page = await readD1CdcChanges(exec, request);
353
+
354
+ // \`as unknown as\`, because \`CdcChange\` is an interface and interfaces carry
355
+ // no implicit index signature — the shapes are otherwise identical.
356
+ return { changes: page.changes as unknown as ReadonlyArray<Record<string, unknown>>, cursor: page.cursor };
357
+ };
358
+
359
+ /**
360
+ * \`applyGlobals\` for the admin point-in-time-recovery apply endpoint: replays a
361
+ * batch of global CDC changes through the same D1 writer \`.global()\` writes go
362
+ * through, and reports how many were replayed.
363
+ *
364
+ * \`applyCdcChanges\` is order-sensitive and idempotent per row (insert, falling
365
+ * back to replace on conflict), so the batch is handed over untouched — the
366
+ * caller already emits it in commit order. The changes arrive as plain parsed
367
+ * JSON off the wire, hence the cast to the replayer's own change shape.
368
+ *
369
+ * The writer carries the app's own \`cdc\` setting, so a replay APPENDS to the
370
+ * global changelog like any other write. Built without it the restored rows
371
+ * reach the tables and nothing else: a warehouse connector's cursor walks past a
372
+ * range that has no entries and its mirror silently diverges from the database,
373
+ * with nothing on either side able to notice — and every live \`.global()\` shape
374
+ * misses the restore until the next unconditional resync.
375
+ */
376
+ const buildGlobalCdcApplier =
377
+ (database: D1DatabaseLike, cdc: boolean) =>
378
+ async (request: { changes: ReadonlyArray<Record<string, unknown>> }): Promise<number> => {
379
+ const writer = createD1CtxDb({ cdc, exec: buildExec(database), schema: schema as unknown as D1CtxDbOptions["schema"] });
380
+
381
+ await applyCdcChanges(writer, request.changes as unknown as Parameters<typeof applyCdcChanges>[1]);
382
+
383
+ return request.changes.length;
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}']:[]],B=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> = {};"]:[],...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>;"]:[]],W=e=>f(e).map(({configKey:t,doc:r,method:a})=>` /** ${r} */
386
+ public ${a}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${t}"]>>): this {
387
+ this.shardExtras.${t} = factory as NonNullable<ShardConfig["${t}"]>;
388
+
389
+ return this;
390
+ }`),H=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
+ public admin(selector: Selector<Env, string>): this {
392
+ this.adminToken = selector;
393
+
394
+ return this;
395
+ }`," /**\n * Opt into change-data-capture: every write records a post-image to `__cdc_log` — on this shard AND, when the app has `.global()` tables, on the global backend. Backs streaming export, replay-PITR, and the `.global()` half of `defineShape` replication (whose poll tick asks the global changelog which tables moved). Off by default: it costs a changelog row per write, which an app using none of the above should not pay.\n *\n * REQUIRED for a shard-local `defineShape`: those replicate out of `__cdc_log`, and a `shape_subscribe` is refused with `SHAPE_REQUIRES_CDC` without it.\n *\n * It also changes how fresh a `.global()` shape is against writes made OUTSIDE `ctx.db` — an admin import, a PITR replay, an external ETL job, or a predicate over wall clock. With CDC off the poll re-reads every shape every 2s. With it on the poll asks the global changelog which tables moved and skips the rest, so a change the changelog never saw waits for the 30s unconditional resync instead. Writes through `ctx.db` are unaffected: they append, so the poll sees them on the next tick either way.\n */\n public cdc(enabled = true): this {\n this.cdcEnabled = enabled;\n\n return this;\n }",` /**
396
+ * Enable the per-shard reactive query cache: query results are memoized by \`(functionPath, args, identity)\` and invalidated by the ctx-db write hooks BEFORE the subscription broadcast, so a subscriber re-running its query always observes the post-write state.
397
+ *
398
+ * Off by default (every dispatch re-runs its handler). Pass an options object to tune the caps: \`maxEntries\` (default 1000) and \`maxBytes\` (default 4 MiB); either accepts \`Number.POSITIVE_INFINITY\` to disable that cap.
399
+ */
400
+ public reactiveCache(config: boolean | { maxBytes?: number; maxEntries?: number } = true): this {
401
+ this.reactiveCacheConfig = config;
402
+
403
+ return this;
404
+ }`,` /** Ceiling on the join keys ONE relation-crossing \`where\` predicate may pre-resolve via semijoin before failing closed. Omit for the engine default. */
405
+ public maxRelationKeys(limit: NonNullable<ShardConfig["maxRelationKeys"]>): this {
406
+ this.maxRelationKeysLimit = limit;
407
+
408
+ return this;
409
+ }`," /**\n * Route the shard's `ctx.log` lines, `ctx.trace` spans and `ctx.metrics` measurements to a telemetry sink.\n *\n * The DO half of observability: without it every in-handler signal stays in the shard's local ring buffer (the studio Logs panel) and reaches no collector. The worker half — one `onRpc` event per dispatched RPC — is a `createWorker` option; pass the SAME sink to both via `.extend((env) => ({ observability: sink(env) }))` to correlate them.\n */\n public observability(selector: NonNullable<ShardConfig[\"observability\"]>): this {\n this.observabilitySink = selector;\n\n return this;\n }",' /** Resolution policy for a relation-crossing `where` whose child is co-located in this shard: `"auto"` (cost-based, the engine default), `"always"` (inline correlated EXISTS) or `"never"` (universal semijoin). All three return identical rows. */\n public relationExistsPushDown(mode: NonNullable<ShardConfig["relationExistsPushDown"]>): this {\n this.relationExistsPushDownMode = mode;\n\n return this;\n }',...e.hasDeliveryAuthorization===!1?[]:[` /** Authorize each RPC/subscription read and fence its eventual delivery against durable authority epochs. */
410
+ public deliveryAuthorization(selector: (env: Env) => ReturnType<NonNullable<ShardConfig["deliveryAuthorization"]>>): this {
411
+ this.deliveryAuthorizationSelector = selector as NonNullable<ShardConfig["deliveryAuthorization"]>;
412
+
413
+ return this;
414
+ }`],...e.hasAuth?[' /** Wire better-auth — the builder lazily builds the instance, runs `ensureMigrated`, and dispatches `/api/auth/*` inside the worker (instrumented for the auth-failure SLO). Pass `d1` for the D1-backed default, or `namespace` + `internalSecret` to host the auth tables in a Durable Object (what `@better-auth/scim` needs). */\n public auth(declaration: AuthDeclaration<Env>): this {\n // Reject the ambiguous and the empty shapes here rather than at the first\n // request: with neither storage set, auth would silently never answer, and\n // with both it is unclear which one owns the tables.\n if (declaration.d1 && declaration.namespace) {\n throw new Error(".auth(): pass either `d1` or `namespace`, not both — they are two different homes for the same tables.");\n }\n\n if (!declaration.d1 && !declaration.namespace) {\n throw new Error(".auth(): needs `d1` (D1-backed) or `namespace` (Durable-Object-backed) to know where the auth tables live.");\n }\n\n if (declaration.namespace && !declaration.internalSecret) {\n throw new Error(\n ".auth(): `namespace` requires `internalSecret` — the auth DO binding is reachable from any worker bound to it, so identity resolution is gated on a shared secret and would otherwise fail closed on every request.",\n );\n }\n\n this.authDeclaration = declaration;\n\n return this;\n }']:[]," /** Escape hatch — merge raw `WorkerOptions` (anything not yet sugared) over the derived options at build time. The second `derived` argument is a snapshot of the options assembled so far (after `.auth(...)` etc.), so you can compose rather than clobber — e.g. wrap `derived.resolveIdentity` instead of replacing it. */\n public extend(fn: (env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>): this {\n this.extendFns.push(fn);\n\n return this;\n }",...e.hasGlobal?[` /** Back \`.global()\` (cross-tenant) tables with D1 — wires \`ctx.db\` routing, the studio global browser, and reverse cross-shard relations. */
415
+ public global(declaration: GlobalDeclaration<Env>): this {
416
+ this.globalDeclaration = declaration;
417
+
418
+ return this;
419
+ }`]:[],...e.hasHyperdriveGlobal?[` /** Back \`.global({ backend: "hyperdrive" })\` tables with a Postgres/MySQL database via Hyperdrive — wires reactive \`ctx.db\` routing through the shared store core. */
420
+ public hyperdriveGlobal(declaration: HyperdriveGlobalDeclaration<Env>): this {
421
+ this.hyperdriveGlobalDeclaration = declaration;
422
+
423
+ return this;
424
+ }`]:[],` /** Cloudflare Email Routing entry — exposes the top-level \`email\` handler. */
425
+ public onEmail(handler: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>): this {
426
+ this.emailHandler = handler;
427
+
428
+ return this;
429
+ }`," /** Mount a whole HTTP app (`httpRouter()` from `@lunora/server`, or anything with a `fetch`) ahead of Lunora's own routes. Use this for a multi-endpoint hono app with its own CORS + error handling; `.route()` is for one-off endpoints. */\n public httpRouter(app: HttpRouterLike): this {\n this.httpRouterApp = app;\n\n return this;\n }",` /** Mount a custom HTTP route (e.g. an asset-serving or test endpoint). Key is \`"METHOD path"\`, \`"path"\`, or a path prefix matched by the runtime. */
430
+ public route(key: string, handler: Route): this {
431
+ this.routeMap[key] = handler;
432
+
433
+ return this;
434
+ }`,...e.hasScheduler?[` /** Wire the \`SchedulerDO\` — backs \`ctx.scheduler\` and the studio's scheduled-jobs view. */
435
+ public scheduler(declaration: SchedulerDeclaration<Env>): this {
436
+ this.schedulerDeclaration = declaration;
437
+
438
+ return this;
439
+ }`]:[],` /** The shard Durable Object namespace (typically \`env.SHARD\`) — required: every app routes RPC + WebSocket traffic through it. */
440
+ public shard(selector: Selector<Env, ShardNamespaceLike>): this {
441
+ this.shardSelector = selector;
442
+
443
+ return this;
444
+ }`,...e.hasAdminRevocations===!1?[]:[` /** The \`AdminRevocationDO\` namespace (typically \`env.ADMIN_REVOCATIONS\`). Records revoked named admin tokens where a point-in-time restore of the default shard cannot rewind them. Without it no named admin token can be created and any that exist are refused. */
445
+ public adminRevocations(selector: Selector<Env, ShardNamespaceLike>): this {
446
+ this.adminRevocationsSelector = selector;
447
+
448
+ return this;
449
+ }`],...c(e)?[" /** The `ShardRegistryDO` namespace (typically `env.SHARD_REGISTRY`). Each shard registers itself for the `.shardBy()` tables it writes, and cross-shard export, CDC sync and migrations fan out to the shards it lists. Without it they refuse a `.shardBy()` table. */\n public shardRegistry(selector: Selector<Env, ShardNamespaceLike | ShardRegistryRpc>): this {\n this.shardRegistrySelector = selector;\n\n return this;\n }"]:[],...e.hasSourcedTables?[` /** Resolve the SQL client a \`.source(...)\` table's ingest poll reads from, given the wrangler Hyperdrive binding it named. Build it with \`@lunora/hyperdrive\`'s \`createHyperdrive\` plus your driver adapter. REQUIRED for a sourced table: without it every poll tick records "no sourceClient resolved for binding" and the table stays empty. */
450
+ public sourceClient(factory: (env: Env, binding: string) => ReturnType<NonNullable<ShardConfig["sourceClient"]>>): this {
451
+ this.sourceClientFactory = factory as NonNullable<ShardConfig["sourceClient"]>;
452
+
453
+ return this;
454
+ }`]:[],...e.hasStorage?[` /** Wire R2 storage — backs \`ctx.storage\` (incl. multi-bucket) and the studio file browser, from one declaration. */
455
+ public storage(declaration: StorageDeclaration<Env>): this {
456
+ this.storageDeclaration = declaration;
457
+
458
+ return this;
459
+ }`]:[],...W(e)],U=e=>{const t=a=>e.hasScheduler?`
460
+ ...(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
+ ? {
462
+ 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 }) => {
463
+ const env = rawEnv as Env;
464
+ const database = this.globalDeclaration?.d1(env);
465
+
466
+ if (!database) {
467
+ return undefined;
468
+ }
469
+
470
+ const origin = this.globalDeclaration?.origin?.(env);
471
+ const crossShard = origin
472
+ ? createCrossShardRelationCapabilities({
473
+ get identity() {
474
+ return request?.identity;
475
+ },
476
+ origin,
477
+ get userId() {
478
+ return request?.userId ?? undefined;
479
+ },
480
+ })
481
+ : undefined;
482
+
483
+ return createD1CtxDb({
484
+ ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${t("D1CtxDbOptions")}
485
+ ...(request?.cdcRetentionMs === undefined ? {} : { cdcRetentionMs: request.cdcRetentionMs }),
486
+ // Getters, like the cross-shard identity above: reading the
487
+ // request's caller marks the live query as caller-dependent, so
488
+ // it may happen only when a \`.serverDefault\` column is stamped.
489
+ auth: {
490
+ get identity() {
491
+ return request?.identity ?? null;
492
+ },
493
+ get userId() {
494
+ return request?.userId ?? null;
495
+ },
496
+ },
497
+ // Forwarded from the shard's own \`cdc\` config, so ONE
498
+ // switch governs both changelogs. Built without it, the
499
+ // global \`__cdc_log\` is never written and the shape
500
+ // poll's changed-tables fast path is unreachable.
501
+ cdc: request?.cdc ?? false,
502
+ exec: buildExec(database, request?.bookmark, request?.onBookmark),
503
+ // The binding outlives this per-request writer, so the
504
+ // provisioning sweep runs once per isolate rather than
505
+ // once per request. See \`SqlCtxDbOptions.provisionScope\`.
506
+ provisionScope: database,
507
+ schema: schema as unknown as D1CtxDbOptions["schema"],
508
+ });
509
+ },
510
+ }
511
+ : {}),`]:[],...e.hasHyperdriveGlobal?[` ...(this.hyperdriveGlobalDeclaration
512
+ ? {
513
+ hyperdriveGlobal: (rawEnv: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; userId?: string | null | undefined }) => {
514
+ const env = rawEnv as Env;
515
+ const declaration = this.hyperdriveGlobalDeclaration;
516
+ const exec = declaration?.exec(env) as SqlExec | undefined;
517
+
518
+ if (!declaration || !exec) {
519
+ return undefined;
520
+ }
521
+
522
+ const origin = declaration.origin?.(env);
523
+ const crossShard = origin
524
+ ? createCrossShardRelationCapabilities({
525
+ get identity() {
526
+ return request?.identity;
527
+ },
528
+ origin,
529
+ get userId() {
530
+ return request?.userId ?? undefined;
531
+ },
532
+ })
533
+ : undefined;
534
+
535
+ return createHyperdriveGlobalCtxDb({
536
+ ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${t("SqlCtxDbOptions")}
537
+ ...(request?.cdcRetentionMs === undefined ? {} : { cdcRetentionMs: request.cdcRetentionMs }),
538
+ // Getters, like the cross-shard identity above: reading the
539
+ // request's caller marks the live query as caller-dependent, so
540
+ // it may happen only when a \`.serverDefault\` column is stamped.
541
+ auth: {
542
+ get identity() {
543
+ return request?.identity ?? null;
544
+ },
545
+ get userId() {
546
+ return request?.userId ?? null;
547
+ },
548
+ },
549
+ // See the D1 twin: one \`cdc\` switch, both changelogs.
550
+ cdc: request?.cdc ?? false,
551
+ engine: declaration.engine as HyperdriveEngine,
552
+ exec,
553
+ // The DECLARATION, not \`exec\` — \`exec(env)\` is a user
554
+ // callback that builds a fresh client per call, so scoping
555
+ // to its result would key the memo on a new object every
556
+ // request and never share anything. The declaration is
557
+ // built once and names one database.
558
+ provisionScope: declaration,
559
+ schema: schema as unknown as SqlCtxDbOptions["schema"],
560
+ });
561
+ },
562
+ }
563
+ : {}),`]:[],...e.hasScheduler?[` ...(this.schedulerDeclaration
564
+ ? {
565
+ scheduler: (rawEnv: Record<string, unknown>) => this.resolveScheduler(rawEnv as Env),
566
+ }
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) } : {}),"]:[],...w(e)?[" ...this.shardExtras,"]:[]];return r.length>0?`
568
+ ${r.join(`
569
+ `)}
570
+ `:""},F=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],z=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],Q=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],J=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],K=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, applySqlMigrationFiles, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],V=e=>e?['import notifyConfig from "../notify.js";']:[],Y=e=>k(e)?e.lazyFunctions===!0?['import type { dispatchAgentEmail } from "@lunora/agent/inbound";']:['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],X=e=>k(e)&&e.lazyFunctions!==!0?['import * as lunoraAgentDefinitions from "../agents.js";']:[],Z=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}";`]},ee=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";']:[],...z(t,r),...K(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";']:[],...Q(n),...J(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";']:[],...Y(e),...Z(e),"",...F(e.identity),...X(e),...a||s?['import schema from "../schema.js";']:[],...V(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...o?['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";']:[]]},S=e=>e.authClaims===void 0||e.authClaims.length===0?void 0:JSON.stringify(e.authClaims),te=e=>{const t=S(e);return t===void 0?"":`, ${t}`},re=e=>{const t=S(e);return t===void 0?"":`
571
+ claims: ${t},`},ae=e=>e.jurisdiction&&e.jurisdictionPinsAuth===!0?`
572
+ // The schema's jurisdiction pins the auth object like every other DO.
573
+ jurisdiction: ${JSON.stringify(e.jurisdiction)},`:"",se=e=>typeof e=="string"?`{ mode: { kind: ${JSON.stringify(e)} } }`:`{ mode: { field: ${JSON.stringify(e.field)}, kind: "shardBy" } }`,ne=e=>[...e.tables.length>0?[` const tableSharding = new Map<string, ShardingInfo>([
574
+ ${e.tables.map(t=>` [${JSON.stringify(t.name)}, ${se(t.shardMode)}],`).join(`
575
+ `)}
576
+ ]);
577
+
578
+ options.listSchemaTables = () => [...tableSharding.keys()];
579
+ options.resolveTableSharding = (table) => tableSharding.get(table);`]:[],...c(e)?[` const shardRegistry = this.shardRegistrySelector?.(env);
580
+
581
+ if (shardRegistry) {
582
+ options.queryCoordinator = createQueryCoordinator({ registry: createDynamicShardRegistry({ ${e.jurisdiction?`jurisdiction: ${JSON.stringify(e.jurisdiction)}, `:""}env, namespace: shardRegistry }) });
583
+ }`]:[]],oe=[` const adminRevocations = this.adminRevocationsSelector?.(env);
584
+
585
+ if (adminRevocations) {
586
+ options.adminRevocations = adminRevocations;
587
+ }`],E=e=>(e.liveStreamDeclarations??[]).map(t=>{if(L(t.exportName,"live stream export name"),!$.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}) },`}),ie=e=>p(e)?[" httpRouter: liveStreamRouter([",...E(e)," ], this.httpRouterApp),"]:[" ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"],le=e=>p(e)?[" liveStreamRoutes: [",...(e.liveStreamDeclarations??[]).flatMap(t=>[` ${JSON.stringify(`GET /live/${t.id}/connect`)},`,` ${JSON.stringify(`POST /live/${t.id}/control`)},`])," ],"]:[],ce=e=>p(e)?`liveStreamRouter([
588
+ ${E(e).join(`
589
+ `)}
590
+ ], host)`:"host",de=e=>e.agentWorkflows===void 0?[]:[` options.agentWorkflows = ${JSON.stringify(e.agentWorkflows)};`],he=e=>[...ne(e),...e.hasAdminRevocations===!1?[]:oe,...e.hasScheduler?[` if (this.schedulerDeclaration) {
591
+ options.schedulerDO = this.schedulerDeclaration.namespace(env);
592
+ }`]:[],...e.hasWorkflow?[` options.workflowsClient = (workflowEnv) => {
593
+ const source = workflowEnv as Record<string, unknown>;
594
+ const accountId = source["CLOUDFLARE_ACCOUNT_ID"];
595
+ const apiToken = source["CLOUDFLARE_API_TOKEN"];
596
+
597
+ return typeof accountId === "string" && accountId !== "" && typeof apiToken === "string" && apiToken !== ""
598
+ ? createWorkflowsRestClient({ accountId, apiToken })
599
+ : undefined;
600
+ };`]:[],...e.hasGlobal?[` if (this.globalDeclaration) {
601
+ const database = this.globalDeclaration.d1(env);
602
+
603
+ if (database) {
604
+ options.globalIntrospector = buildGlobalIntrospector(database);
605
+ // \`importGlobals\` wires the admin bulk-import endpoint's global
606
+ // plane: the rows \`resolveTableSharding\` classifies as \`.global()\`
607
+ // land here, and without it they are reported, not written.
608
+ options.importGlobals = buildGlobalImporter(database, this.cdcEnabled);
609
+ // The importer above skips the write for a dry run, overwrites an
610
+ // existing \`_id\` under \`onConflict: "replace"\`, and removes the row
611
+ // an \`op: "delete"\` row names.
612
+ options.importGlobalsSupportsDryRun = true;
613
+ options.importGlobalsSupportsReplace = true;
614
+ options.importGlobalsSupportsDelete = true;
615
+ // The read/replay half of the same admin plane. Each one is the
616
+ // only reason its endpoint can see the global storage plane at
617
+ // all, and every one of them fails SILENTLY when unset — export
618
+ // and \`lunora backup create\` answer 200 having written only
619
+ // shard-local rows (an export→import round trip then restores
620
+ // cleanly minus every global row), CDC sync answers with only
621
+ // shard changes, and point-in-time apply reports
622
+ // \`globalApplied: 0\`. Nothing here is project-specific either.
623
+ options.exportGlobals = buildGlobalExporter(database);
624
+ options.syncGlobals = buildGlobalCdcSync(database);
625
+ options.applyGlobals = buildGlobalCdcApplier(database, this.cdcEnabled);
626
+ // \`lunora migrate apply\` runs the generated SQL files against this binding, recording each in
627
+ // \`__lunora_sql_migrations\`. A file runs once per stage, and nothing else runs it. The schema lets a
628
+ // column a file adds be filled the way the runtime fills it, so its rows never read NULL.
629
+ options.applySqlMigrations = (request) =>
630
+ applySqlMigrationFiles(database, request.files, { ...request, schema: schema as unknown as D1CtxDbOptions["schema"] });
631
+ }
632
+ }`]:[],...e.hasHyperdriveGlobal?[` const hyperdriveDeclaration = this.hyperdriveGlobalDeclaration;
633
+
634
+ if (hyperdriveDeclaration) {
635
+ const engine = hyperdriveDeclaration.engine;
636
+ const hyperdriveSchema = schema as unknown as SqlCtxDbOptions["schema"];
637
+ const exec = (): SqlExec => hyperdriveDeclaration.exec(env);
638
+ const cdc = this.cdcEnabled;
639
+
640
+ options.globalIntrospector = {
641
+ facetColumn: (request) => createHyperdriveGlobalIntrospector(engine, exec(), hyperdriveSchema).facetColumn(request),
642
+ listTables: () => createHyperdriveGlobalIntrospector(engine, exec(), hyperdriveSchema).listTables(),
643
+ readTablePage: (request) => createHyperdriveGlobalIntrospector(engine, exec(), hyperdriveSchema).readTablePage(request),
644
+ };
645
+ options.importGlobals = (request) =>
646
+ importHyperdriveGlobalRows({
647
+ cdc,
648
+ dryRun: request.dryRun === true,
649
+ engine,
650
+ exec: exec(),
651
+ onConflict: request.onConflict ?? "skip",
652
+ rows: request.rows,
653
+ schema: hyperdriveSchema,
654
+ ...(request.startLine === undefined ? {} : { startLine: request.startLine }),
655
+ });
656
+ options.importGlobalsSupportsDryRun = true;
657
+ options.importGlobalsSupportsReplace = true;
658
+ options.importGlobalsSupportsDelete = true;
659
+ options.exportGlobals = (request) => exportHyperdriveGlobalRows({ engine, exec: exec(), schema: hyperdriveSchema, tables: request.tables });
660
+ options.syncGlobals = async (request) => {
661
+ const page = await readHyperdriveGlobalCdc(engine, exec(), request);
662
+
663
+ // \`as unknown as\`: \`CdcChange\` is an interface, which carries no implicit index signature.
664
+ return { changes: page.changes as unknown as ReadonlyArray<Record<string, unknown>>, cursor: page.cursor };
665
+ };
666
+ options.applyGlobals = (request) =>
667
+ applyHyperdriveGlobalCdc({
668
+ cdc,
669
+ changes: request.changes as unknown as Parameters<typeof applyHyperdriveGlobalCdc>[0]["changes"],
670
+ engine,
671
+ exec: exec(),
672
+ schema: hyperdriveSchema,
673
+ });
674
+ }`]:[],...e.hasStorage?[` if (this.storageDeclaration) {
675
+ Object.assign(options, this.buildStorageAdmin(env));
676
+ options.storage = (rawEnv: unknown, origin?: string) => this.resolveStorage(rawEnv as Env, origin);
677
+ }`]:[],...e.hasKvIntrospector?[" options.kvIntrospector = createKvIntrospectorFromEnv(env);"]:[],...e.hasVectors?[` if (this.shardExtras.vectors) {
678
+ options.vectorIntrospector = createVectorAdminIntrospector({
679
+ indexes: this.shardExtras.vectors(env as unknown as Record<string, unknown>),
680
+ registry: LUNORA_VECTOR_INDEXES,
681
+ });
682
+ } else {
683
+ // Emitted only when the schema declares an index, so reaching here
684
+ // means the app declared one and never bound it. The studio's
685
+ // Vectors tab is on (its flag is the same index count) and every
686
+ // request to it would answer VECTORS_NOT_CONFIGURED, while
687
+ // \`ctx.vectors\` is the throwing stub — so this is already broken,
688
+ // just later and less legibly. Same shape as \`.auth()\`'s guards.
689
+ throw new Error(
690
+ ".vectors(): the schema declares vector index(es) but no binding map was chained. Pass \`.vectors((env) => ({ <indexName>: env.<BINDING> }))\` so \`ctx.vectors\` resolves and the studio's Vectors tab can list them.",
691
+ );
692
+ }`]:[],...e.hasNotify?[` if (notifyConfig.store) {
693
+ options.notifySubscriptionStore = notifyConfig.store(env as Record<string, unknown>);
694
+ }`]:[],` const logArchive = resolveLogArchiveFromEnv(env);
695
+
696
+ if (logArchive !== undefined) {
697
+ options.logArchive = logArchive;
698
+ }`,...e.hasAuth?[` // Captured before the branch so the narrowing survives — reading
699
+ // \`this.authDeclaration.namespace\` again below would be optional all over again.
700
+ const authDeclaration = this.authDeclaration;
701
+ const { authDiscoveryPathsFor, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, handleAuthDiscoveryRequest, handleAuthRequest, resolveSessionIdentity } = deferred.auth;
702
+ const authNamespace = authDeclaration?.namespace;
703
+ const authD1 = authDeclaration?.d1;
704
+
705
+ if (authDeclaration && authNamespace) {
706
+ // DO-backed mode. The auth tables live inside the object and DO storage is
707
+ // unreachable from here, so better-auth runs in there and this worker talks
708
+ // to it. \`createDoAuthWiring\` is a tested function in \`@lunora/auth\` rather
709
+ // than more emitted code: request-path logic in generated output can only be
710
+ // typechecked, never unit-tested.
711
+ const discoveryPaths = authDiscoveryPathsFor(authDeclaration, env);
712
+ const internalSecret = authDeclaration.internalSecret?.(env);
713
+ const namespace = authNamespace(env);
714
+ const objectName = authDeclaration.objectName?.(env);
715
+ const authWiring = createDoAuthWiring({
716
+ // The OAuth discovery documents (an \`mcp()\` resource's metadata, the
717
+ // issuer's) are derived here from the declared options, so the worker
718
+ // forwards only those exact paths and no other probe reaches the object.
719
+ // Memoised on the declaration: each worker built for a new \`env\` runs
720
+ // these options again, and \`options(env)\` rebuilds every plugin.
721
+ discoveryPaths,
722
+ internalSecret,${ae(e)}${re(e)}
723
+ namespace,
724
+ ...(objectName === undefined ? {} : { objectName }),
725
+ });
726
+
727
+ options.authHandler = authWiring.authHandler;
728
+ options.authDiscoveryHandler = authWiring.discoveryHandler;
729
+ options.resolveIdentity = authWiring.resolveIdentity;
730
+ // The audit log lives in the object like every other auth table, so the feed
731
+ // reads through it rather than querying D1.
732
+ options.authAuditReader = authWiring.auditReader;
733
+ // Set only once auth is pinned to a jurisdiction: copies the users left in the
734
+ // un-pinned object across (\`__lunora_admin__:copyAuthToJurisdiction\`).
735
+ options.authJurisdictionMove = authWiring.jurisdictionMove;
736
+ // \`authAdmin\` stays D1-only: its ~30 methods read the auth tables directly
737
+ // from the worker, which DO storage does not allow. The studio's auth pages
738
+ // therefore report "not configured" in this mode rather than silently
739
+ // returning empty data.
740
+ } else if (authDeclaration && authD1) {
741
+ options.authHandler = (request) => {
742
+ const auth = getAuth();
743
+
744
+ return auth ? handleAuthRequest(auth, request) : Promise.resolve(undefined);
745
+ };
746
+ // The OAuth discovery documents outside \`/api/auth\` (served only with an
747
+ // \`mcp()\` or \`oauthProvider()\` plugin, and only after the app's own routes).
748
+ options.authDiscoveryHandler = (request) => {
749
+ const auth = getAuth();
750
+
751
+ return auth ? handleAuthDiscoveryRequest(auth, request) : Promise.resolve(undefined);
752
+ };
753
+ options.resolveIdentity = async (request) => {
754
+ const auth = getAuth();
755
+
756
+ if (!auth) {
757
+ return null;
758
+ }
759
+
760
+ // \`resolveSessionIdentity\` is shared with the DO wiring, so both modes put
761
+ // the same claims (role, expiry, profile, and the active organization and
762
+ // team checked against membership) on the identity, and it is unit-tested
763
+ // where this template cannot be.
764
+ return resolveSessionIdentity(auth, (request as Request).headers${te(e)});
765
+ };
766
+ const authInstance = getAuth();
767
+
768
+ if (authInstance) {
769
+ options.authAdmin = createAuthAdmin(authInstance);
770
+ }
771
+ options.authAuditReader = createAuthAuditReader(d1Executor(authD1(env) as never));
772
+ }
773
+
774
+ // Both modes pay a session lookup per request (the auth object hop, or a D1
775
+ // read), and the runtime resolves identity once per RPC and per fan-out leg.
776
+ // Memoise per credential. The default window is the shorter of 60s and
777
+ // better-auth's cookie-cache \`maxAge\`; \`LUNORA_IDENTITY_CACHE_MS\` overrides it, \`0\`
778
+ // disables the cross-request cache. The memoised \`getSession\` result may itself
779
+ // come from better-auth's cookie cache, so the worst case is the two stacked: a
780
+ // revoked session or a changed role can resolve for up to the memo window PLUS the
781
+ // cookie-cache \`maxAge\` (about 120s with the presets).
782
+ //
783
+ // An app that switched the cookie cache OFF (the \`strict\` session preset) asked
784
+ // for fast revocation, so its default is per-request memoisation only; the env var
785
+ // still opts back in. Read from the declared options at runtime, the one place
786
+ // the chosen policy is visible.
787
+ //
788
+ // Built once per \`env\` object and kept for this assembled worker: a framework-hosted
789
+ // worker rebuilds these options on every request, and a fresh memo per build
790
+ // would never hit. A different \`env\` object gets its own memo.
791
+ if (options.resolveIdentity) {
792
+ let memo = identityMemos.get(env);
793
+
794
+ if (!memo) {
795
+ // A wrangler var may be a JSON number (\`0\`) or a string. A blank string is
796
+ // unset, not \`0\` (\`Number("")\` is 0); anything else non-numeric is unset too.
797
+ const identityCacheRaw = (env as { LUNORA_IDENTITY_CACHE_MS?: unknown }).LUNORA_IDENTITY_CACHE_MS;
798
+ let identityCacheMs = Number.NaN;
799
+
800
+ if (typeof identityCacheRaw === "number") {
801
+ identityCacheMs = identityCacheRaw;
802
+ } else if (typeof identityCacheRaw === "string" && identityCacheRaw.trim() !== "") {
803
+ identityCacheMs = Number(identityCacheRaw);
804
+ }
805
+
806
+ // \`options(env)\` is application code. A scheduled, queue or serverQuery event must
807
+ // not fail to construct — and so never run — because that callback throws, so a
808
+ // throw is caught rather than escaping.
809
+ let defaultMs: number;
810
+
811
+ try {
812
+ const cookieCache = authDeclaration?.options(env).session?.cookieCache;
813
+ // better-auth's \`maxAge\` is in SECONDS; createAuth fills 60 when it is unset.
814
+ const cookieCacheSeconds = typeof cookieCache?.maxAge === "number" && cookieCache.maxAge >= 0 ? cookieCache.maxAge : 60;
815
+
816
+ // createAuth fills \`{ enabled: true, maxAge: 60 }\` only when \`cookieCache\` is absent; a partial
817
+ // object without \`enabled: true\` has NO cookie cache, so the memo stays per-request there.
818
+ defaultMs = cookieCache === undefined || cookieCache.enabled === true ? Math.min(60_000, cookieCacheSeconds * 1000) : 0;
819
+ } catch {
820
+ // The policy is unreadable. Fall back to PER-REQUEST memoisation, not the 60s
821
+ // window: a 60s cross-request cache would let a revoked session keep
822
+ // resolving for a minute, which is exactly what the \`strict\` preset turned
823
+ // off. Construction still does not fail, so the event still runs.
824
+ defaultMs = 0;
825
+ }
826
+
827
+ memo = memoizeIdentity(options.resolveIdentity, {
828
+ // better-auth resolves the session from ALL request headers, so the key
829
+ // must cover every header a supported plugin authenticates on: the
830
+ // session cookie and \`Authorization\` (bearer / jwt). \`x-api-key\` requests are never keyed (see below).
831
+ cacheKey: (request: Request) => {
832
+ // A revoked API key must stop resolving on its next call. Revocation is a row
833
+ // delete with nothing in the cookie to change, so a key request is never
834
+ // memoised across requests; the lookup is one row read per call.
835
+ if (request.headers.get("x-api-key") !== null) {
836
+ return undefined;
837
+ }
838
+
839
+ const parts = ["authorization", "cookie"].map((name) => request.headers.get(name) ?? "");
840
+
841
+ if (parts.every((part) => part === "")) {
842
+ return undefined;
843
+ }
844
+
845
+ const key = parts.join("\\u0000");
846
+
847
+ // The map is bounded in ENTRIES, not in key size, so a client with one
848
+ // valid session could add a junk cookie per request and grow it without
849
+ // bound. Skip the cache for an oversized credential set rather than
850
+ // truncating the key, which could collide with a different credential and
851
+ // hand back the wrong identity.
852
+ return key.length > 4_096 ? undefined : key;
853
+ },
854
+ maxEntries: 2_000,
855
+ ttlMs: Number.isFinite(identityCacheMs) && identityCacheMs >= 0 ? identityCacheMs : defaultMs,
856
+ });
857
+ identityMemos.set(env, memo);
858
+ }
859
+
860
+ options.resolveIdentity = memo;
861
+ }`]:[],...e.hasAccess?[e.hasAuth?` if (this.accessSelector) {
862
+ const accessResolver = createAccessResolver(this.accessSelector(env));
863
+ const fallback = options.resolveIdentity;
864
+
865
+ options.resolveIdentity = fallback ? composeResolvers(accessResolver, fallback) : accessResolver;
866
+ }`:` if (this.accessSelector) {
867
+ options.resolveIdentity = createAccessResolver(this.accessSelector(env));
868
+ }`]:[],...de(e),...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
869
+ ${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(t.bindingName)}] as ShardNamespaceLike,`).join(`
870
+ `)}
871
+ };`]:[]],ue=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,"]:[]," }),"]:[],pe=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)}),`]:[])},me=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)},`]:[],...pe(e),...ue(e),...ie(e),...le(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"],`]],be=e=>e?`
872
+ /** The identity memo per \`env\` object, owned by one assembled worker. */
873
+ type IdentityMemoStore = WeakMap<object, ReturnType<typeof memoizeIdentity>>;
874
+ `:"",R=e=>e.hasAuth,ge=e=>R(e)?`
875
+ /** What the worker reads only once a request arrives: loaded then, not at isolate startup (Cloudflare caps startup at 1 s of CPU). */
876
+ interface DeferredModules {
877
+ auth: typeof LunoraAuthModule;
878
+ }
879
+
880
+ let deferredModules: Promise<DeferredModules> | undefined;
881
+
882
+ /** Loads {@link DeferredModules} once per isolate; every entry that builds the worker awaits it first. */
883
+ const loadDeferredModules = (): Promise<DeferredModules> =>
884
+ (deferredModules ??= (async (): Promise<DeferredModules> => {
885
+ return {
886
+ auth: await import("./authModule.js"),
887
+ };
888
+ })());
889
+ `:"",ve=(e,t)=>{const r=`buildWorker(rawEnv as Env${t})`,a=e?`
890
+ await ensureAuth(env);`:"",s=e?`
891
+ await ensureAuth(rawEnv as Env);`:"";return e?{ensureAuthCall:a,ensureRawAuthCall:s,eventWorker:"target",eventWorkerLine:`
892
+ const target = (await authReady(rawEnv as Env)) ? (worker ??= ${r}) : ${r};`}:{ensureAuthCall:a,ensureRawAuthCall:s,eventWorker:"worker",eventWorkerLine:`
893
+ worker ??= ${r};`}},ye=e=>R(e)?{asyncIfDeferred:"async ",deferredArgument:", deferred",deferredParameter:", deferred: DeferredModules",loadDeferredLine:`
894
+ const deferred = await loadDeferredModules();`}:{asyncIfDeferred:"",deferredArgument:"",deferredParameter:"",loadDeferredLine:""},De=e=>e?`${y}export { authDiscoveryPathsFor, createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, handleAuthDiscoveryRequest, handleAuthRequest, lunoraD1Adapter, resolveSessionIdentity } from "@lunora/auth/worker";
895
+ `:"",fe=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
+ `);return e.lazyFunctions!==!0?` composed.email = dispatchAgentEmail([
897
+ ${r(" ")}
898
+ ]);
899
+
900
+ `:` let agentEmail: ReturnType<typeof dispatchAgentEmail> | undefined;
901
+
902
+ composed.email = async (message, rawEnv, context) => {
903
+ if (agentEmail === undefined) {
904
+ const [{ dispatchAgentEmail: dispatch }, lunoraAgentDefinitions] = await Promise.all([import("@lunora/agent/inbound"), import("../agents.js")]);
905
+
906
+ agentEmail ??= dispatch([
907
+ ${r(" ")}
908
+ ]);
909
+ }
910
+
911
+ return agentEmail(message, rawEnv, context);
912
+ };
913
+
914
+ `},we=e=>e.securityHeaders===void 0?"":`
915
+ /**
916
+ * \`security.headers\` from \`lunora.config\`: the baseline security headers the Worker sends, and the same values
917
+ * the build writes into the static assets' \`_headers\`. An app that calls \`createWorker\` itself passes it as
918
+ * \`security: { headers: LUNORA_SECURITY_HEADERS }\`.
919
+ */
920
+ const LUNORA_SECURITY_HEADERS: SecurityOptions["headers"] = ${JSON.stringify(e.securityHeaders)};
921
+ `,ke=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,r)=>t.localeCompare(r)).join(", "),Ae=e=>{const t=(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0,r={...e,hasVectors:t},{hasAuth:a}=r,s=M(r),n=he(r),o=a?` let auth: LunoraAuth | null = null;
922
+ let authInit: Promise<void> | null = null;
923
+ // One memo per env for THIS assembled worker: every worker it builds reuses it, but a second
924
+ // \`assemble()\` has its own auth closure and must not share.
925
+ const identityMemos: IdentityMemoStore = new WeakMap();
926
+ `:"",d=a?`
927
+ const initAuth = async (env: Env): Promise<void> => {
928
+ if (!this.authDeclaration) {
929
+ return;
930
+ }
931
+
932
+ const d1 = this.authDeclaration.d1;
933
+
934
+ // DO-backed mode builds no instance here: better-auth runs inside the
935
+ // object, which materialises its own schema (the Kysely migrator below is
936
+ // dialect-bound and cannot target DO storage).
937
+ if (!d1) {
938
+ return;
939
+ }
940
+
941
+ // Apply the better-auth schema lazily on first request (raw-D1 Kysely
942
+ // migrator). For production run the migrate command ahead of deploy.
943
+ // The migration instance takes the RAW binding: better-auth migrates
944
+ // only through Kysely and rejects the adapter the request instance uses.
945
+ //
946
+ // CONSTRUCTED BEFORE THE MIGRATION, ASSIGNED AFTER IT. Both halves matter:
947
+ // building it first gives \`ensureMigrated\`'s schema-check invalidation a
948
+ // registered check to invalidate, and assigning it only afterwards keeps a
949
+ // concurrent request from serving \`/api/auth/*\` against tables the
950
+ // migrator has not created yet. See \`emit-app.ts\` in @lunora/codegen for
951
+ // the full reasoning.
952
+ //
953
+ // On a first boot against an unmigrated database this means better-auth's
954
+ // eager schema check runs BEFORE the migration, so one
955
+ // "the auth tables do not match…" line on a cold start is expected.
956
+ const { createAuth, lunoraD1Adapter } = (await loadDeferredModules()).auth;
957
+ const requestAuth = createAuth({ ...this.authDeclaration.options(env), database: lunoraD1Adapter(d1(env) as never) });
958
+
959
+ // Loaded on first request, not at module evaluation: the migrator pulls in kysely and
960
+ // the better-auth migrator, which would otherwise sit in the worker startup closure.
961
+ const { createMigrationAuth, ensureMigrated } = await import("@lunora/auth/migrate");
962
+ await ensureMigrated(createMigrationAuth({ ...this.authDeclaration.options(env), database: d1(env) as never }));
963
+
964
+ auth = requestAuth;
965
+ };
966
+
967
+ // Single-flighted on the PROMISE, not on \`auth\`. Every \`fetch\` awaits this
968
+ // and the body above is async, so a per-isolate cold start runs it once
969
+ // rather than once per concurrent request — better-auth's migrator emits a
970
+ // bare \`CREATE TABLE\` (no IF NOT EXISTS), so a second concurrent run on a
971
+ // fresh database fails with \`table user already exists\` and, because this is
972
+ // awaited ahead of the router, 500s every route. Evicted on failure so a
973
+ // transient error retries instead of being replayed forever.
974
+ const ensureAuth = (env: Env): Promise<void> =>
975
+ (authInit ??= initAuth(env).catch((error: unknown) => {
976
+ authInit = null;
977
+ throw error;
978
+ }));
979
+
980
+ // For host-owned events (cron, queue, mail), which must not go down with auth. The failure is
981
+ // logged each time: auth retries on the next event, and an isolate that only ever sees these
982
+ // would otherwise repeat it with nothing saying why the admin and auth surfaces are missing.
983
+ const authReady = (env: Env): Promise<boolean> =>
984
+ ensureAuth(env).then(
985
+ () => true,
986
+ (error: unknown) => {
987
+ console.error("[lunora] auth failed to initialise; this event runs without auth:", error);
988
+
989
+ return false;
990
+ },
991
+ );
992
+ `:"",{asyncIfDeferred:l,deferredArgument:i,deferredParameter:u,loadDeferredLine:h}=ye(r),{ensureAuthCall:D,ensureRawAuthCall:A,eventWorker:m,eventWorkerLine:b}=ve(a,i),g=`${a?"() => auth, identityMemos":"() => null"}${i}`,x=`${a?"getAuth: () => LunoraAuth | null, identityMemos: IdentityMemoStore":"_getAuth: () => null"}${u}`,v=`env: Env${u}`,C=r.hasFramework?` const buildWorker = (${v}): LunoraWorker =>
993
+ host ? withFrameworkWorker(${ce(r)}, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${g})) : createWorker(this.buildWorkerOptions(env, ${g}));`:` const buildWorker = (${v}): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${g}));`,O=r.hasFramework?"host?: FrameworkHostHandler":"",q=fe(r),N=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
994
+ public build(): ComposedApp {
995
+ 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`${y}${ee(r).join(`
997
+ `)}
998
+
999
+ /** Read a value off the per-request \`env\`. Returns \`undefined\` to leave the capability unconfigured (its \`ctx.*\`/admin surface stays a clear-error stub). */
1000
+ type Selector<Env, T> = (env: Env) => T | undefined;
1001
+
1002
+ /** The generated \`createShardDO\` config — \`.observability()\`, \`.maxRelationKeys()\` and the long-tail \`.ai()\` / \`.kv()\` / … methods pass straight through to it. */
1003
+ type ShardConfig = NonNullable<Parameters<typeof createShardDO>[0]>;
1004
+ ${we(r)}${be(a)}${ge(r)}${r.jurisdiction?`
1005
+ // Module scope, so every isolate loading this script (the worker and each Durable
1006
+ // Object class it exports) knows the schema's jurisdiction before a request runs.
1007
+ // \`@lunora/mail\` reads it to pin its shard RPC like every other DO path.
1008
+ declareAppJurisdiction(${JSON.stringify(r.jurisdiction)});
1009
+ `:""}
1010
+ ${s.join(`
1011
+
1012
+ `)}${s.length>0?`
1013
+
1014
+ `:""}/** The composed app: a Cloudflare module worker (\`fetch\` / \`scheduled\` / optional \`email\`) plus the \`ShardDO\` class binding. */
1015
+ interface ComposedApp extends LunoraWorker {
1016
+ /** Cloudflare Email Routing entry — present only when \`.onEmail(...)\` was configured. */
1017
+ email?: (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
1018
+ /** The generated shard Durable Object class — re-export it as a named export so wrangler can bind it. */
1019
+ ShardDO: ReturnType<typeof createShardDO>;
1020
+ }
1021
+
1022
+ /**
1023
+ * Fluent worker-composition builder. Records each capability declaration, then
1024
+ * \`.build()\` fans them into the DO-side \`createShardDO\` factory and the
1025
+ * worker-side \`createWorker\` options — constructing the worker lazily on the
1026
+ * first request so per-isolate singletons are built once.
1027
+ */
1028
+ class AppBuilder<Env extends object> {
1029
+ ${B(r).join(`
1030
+ `)}
1031
+
1032
+ private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
1033
+
1034
+ ${H(r).join(`
1035
+
1036
+ `)}
1037
+
1038
+ ${N}
1039
+
1040
+ /** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
1041
+ private assemble(${O}): ComposedApp {
1042
+ const ShardDO = createShardDO({${U(r)}});
1043
+
1044
+ // Per-isolate singletons: the worker (and auth instance) are expensive to
1045
+ // build, so the first request constructs them and every later request on
1046
+ // the same isolate reuses them.
1047
+ let worker: LunoraWorker | null = null;
1048
+ ${o}${d}
1049
+ ${C}
1050
+
1051
+ const composed: ComposedApp = {
1052
+ ShardDO,
1053
+ fetch: async (request: Request, rawEnv: unknown, context: ExecutionContextLike): Promise<Response> => {
1054
+ const env = rawEnv as Env;${h}${D}
1055
+ worker ??= buildWorker(env${i});
1056
+
1057
+ return worker.fetch(request, rawEnv, context);
1058
+ },
1059
+ scheduled: async (controller: ScheduledControllerLike, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {${h}${b}
1060
+
1061
+ return ${m}.scheduled(controller, rawEnv, context);
1062
+ },
1063
+ serverQuery: ${l}(request, rawEnv, reference, args, options) => {${h}${A}
1064
+ worker ??= buildWorker(rawEnv as Env${i});
1065
+
1066
+ return worker.serverQuery(request, rawEnv, reference, args, options);
1067
+ },${r.hasQueue||r.hasFramework?`
1068
+ queue: async (batch: unknown, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {${h}${b}
1069
+
1070
+ return ${m}.queue?.(batch, rawEnv, context);
1071
+ },`:""}
1072
+ };
1073
+
1074
+ ${q} if (this.emailHandler) {
1075
+ const handler = this.emailHandler;
1076
+
1077
+ composed.email = (message, rawEnv, context) => handler(rawEnv as Env)(message, rawEnv, context);
1078
+ }
1079
+ ${r.hasFramework?`
1080
+ // A framework host may export its own \`email\` (Nitro's \`cloudflare-module\`
1081
+ // does). Nothing in Lunora serves one, so when the app registered no handler
1082
+ // of its own the host's is the only one there is — forward to it rather than
1083
+ // dropping the entry.
1084
+ if (!composed.email && host && typeof host === "object" && typeof host.email === "function") {
1085
+ composed.email = ${l}(message, rawEnv, context) => {${h}${b}
1086
+
1087
+ return ${m}.email?.(message, rawEnv, context) ?? Promise.resolve();
1088
+ };
1089
+ }
1090
+ `:""}
1091
+ return composed;
1092
+ }
1093
+ ${P(r)}${G(r.hasStorage)}
1094
+ /** Fan the recorded declarations into the worker-side \`createWorker\` options. */
1095
+ private buildWorkerOptions(env: Env, ${x}): WorkerOptions {
1096
+ const options: WorkerOptions = {
1097
+ ${me(r).join(`
1098
+ `)}
1099
+ };
1100
+
1101
+ const adminToken = this.adminToken?.(env);
1102
+
1103
+ if (adminToken !== undefined) {
1104
+ options.adminToken = adminToken;
1105
+ }
1106
+
1107
+ ${n.join(`
1108
+
1109
+ `)}${n.length>0?`
1110
+
1111
+ `:""} for (const fn of this.extendFns) {
1112
+ Object.assign(options, fn(env, { ...options }));
1113
+ }
1114
+ ${r.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"}
1115
+ return options;
1116
+ }
1117
+ }
1118
+ ${_(r.hasGlobal)}
1119
+ /**
1120
+ * Shape of the project's root \`lunora.config.*\`.
1121
+ *
1122
+ * Declared HERE, not in a package, so the \`app\` hook is typed against THIS
1123
+ * project's builder with no annotation to keep in step — and so the config file
1124
+ * needs only a type-only import, which is erased. That matters: the hook is
1125
+ * bundled into the worker, and a runtime import in that file ships with it.
1126
+ */
1127
+ interface LunoraConfig<Env extends object = object> {
1128
+ /** Codegen's static advisor. \`minSeverity\` is the lowest level it reports and writes into \`_generated/shard.ts\`; an \`"error"\` is never dropped, so the gate that fails codegen stays on. \`accept\` demotes a reviewed ERROR to INFO when its rule, file and export all match. A literal, for the same reason as \`target\`. */
1129
+ advisor?: { accept?: ReadonlyArray<{ exportName: string; file: string; reason: string; rule: string }>; minSeverity?: "error" | "info" | "warn" };
1130
+ /** Receives this project's \`defineApp()\` builder and returns it — where a Vite-first app makes the builder calls its generated entry cannot derive. */
1131
+ app?: (app: AppBuilder<Env>) => AppBuilder<Env>;
1132
+ /** Codegen settings. \`exclude\` adds globs (relative to \`lunora/\`, e.g. \`"seed/**"\`) to skip on top of the built-in test-file patterns. \`lazyFunctions: true\` emits the per-module lazy function registry for every command and bundler plugin that generates or checks \`_generated/\`. Literals, for the same reason as \`target\`. */
1133
+ codegen?: { exclude?: string[]; lazyFunctions?: boolean };
1134
+ /** Host the shard, scheduler and shard registry in ONE Durable Object class (\`merge: true\`, plan 462) — before the first deploy only. A literal, for the same reason as \`target\`. */
1135
+ durableObjects?: { merge?: boolean };
1136
+ /** Opt into remote-binding dev without \`--remote\` or \`LUNORA_REMOTE\` on every run. A literal, for the same reason as \`target\`. */
1137
+ remote?: boolean;
1138
+ /** 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\`. */
1139
+ services?: Record<string, { dir: string; entrypoint?: string; rpc?: false }>;
1140
+ /** 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\`. */
1141
+ security?: { headers?: SecurityOptions["headers"] };
1142
+ /** 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\`. */
1143
+ studio?: { companion?: boolean };
1144
+ /** 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. */
1145
+ target?: string;
1146
+ }
1147
+
1148
+ /**
1149
+ * Start composing the app. Chain the capability methods, then \`.build()\`.
1150
+ *
1151
+ * \`Env\` is constrained to \`object\`, not \`Record<string, unknown>\`: an \`interface Env\`
1152
+ * — which is what wrangler's generated \`worker-configuration.d.ts\` gives you, and
1153
+ * what any app with its own bindings declares — is NOT assignable to an index
1154
+ * signature, so the stricter bound forced every real app to write
1155
+ * \`type AppEnv = Env & Record<string, unknown>\`. The builder only ever reads \`env\`
1156
+ * through the selectors you pass it, so the looser bound costs nothing.
1157
+ */
1158
+ const defineApp = <Env extends object>(): AppBuilder<Env> => new AppBuilder<Env>();
1159
+
1160
+ export { AppBuilder, defineApp${r.securityHeaders===void 0?"":", LUNORA_SECURITY_HEADERS"} };
1161
+ export type { ${ke(r)} };
1162
+ `};export{Ae as emitApp,De as emitAuthModule};