@rebasepro/server 0.11.0 → 0.11.1-canary.g16c8254

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.es.js CHANGED
@@ -2,8 +2,8 @@ import { createRequire as __createRequire } from "module";
2
2
  import process from "process";
3
3
  __createRequire(import.meta.url);
4
4
  import { i as __toESM, n as __exportAll } from "./chunk-DSJWtz9O.js";
5
- import { C as RebaseClientError, S as RebaseApiError, _ as toCanonicalOp, a as DEFAULT_DATA_SOURCE_KEY, b as GeoPoint, f as isPostgresCollectionConfig, i as DEFAULT_STORAGE_SOURCE_KEY, n as serializeCollections, r as SCHEMA_VERSION_HEADER, s as isSQLAdmin, t as computeSchemaVersion, u as getCollectionDataPath, v as EntityReference, x as Vector, y as EntityRelation } from "./src-BYbxB4PR.js";
6
- import { a as deserializeFilter, c as serializeLogicalCondition, d as resolveDataSource, f as findRelation, h as toSnakeCase, i as buildSdkData, l as CollectionRegistry, m as buildCompositeId, n as serializeOrderBy, o as deserializeLogicalCondition, p as resolveCollectionRelations, r as buildRoutedRebaseData, s as serializeFilter, t as deserializeOrderBy, u as createDataSourceRegistry } from "./src-q6_elgGZ.js";
5
+ import { C as EntityReference, D as RebaseApiError, E as Vector, O as RebaseClientError, S as toCanonicalOp, T as GeoPoint, _ as ADMIN_COLLECTION_KEYS, a as findStorageSuffixCollision, c as isSQLAdmin, d as getCollectionDataPath, h as DEFAULT_DATA_SOURCE_KEY, i as DEFAULT_STORAGE_SOURCE_KEY, n as serializeCollections, o as normalizeStorageSources, p as isPostgresCollectionConfig, r as SCHEMA_VERSION_HEADER, s as storageEnvSuffix, t as computeSchemaVersion, v as ADMIN_PROPERTY_KEYS, w as EntityRelation } from "./src-Ivjud8jD.js";
6
+ import { _ as toSnakeCase, a as deserializeFilter, c as serializeLogicalCondition, d as CollectionRegistry, f as createDataSourceRegistry, g as buildCompositeId, h as resolveCollectionRelations, i as buildSdkData, l as collectAllPages, m as findRelation, n as serializeOrderBy, o as deserializeLogicalCondition, p as resolveDataSource, r as buildRoutedRebaseData, s as serializeFilter, t as deserializeOrderBy, u as paginateFind } from "./src-CoOAMnBh.js";
7
7
  import { t as logger } from "./logger-BYU66ENZ.js";
8
8
  import { a as generateRefreshToken, c as getRefreshTokenTtlMs, d as verifyAccessToken, f as verifyDownloadToken, i as generateDownloadToken, l as hashRefreshToken, n as configureJwt, o as getAccessTokenExpiry, p as require_jsonwebtoken, r as generateAccessToken, s as getRefreshTokenExpiry, t as MAX_COOKIE_AGE_MS } from "./jwt-D-eI6TTu.js";
9
9
  import { t as nativeDynamicImport } from "./dynamic-import-Dvh-K5fl.js";
@@ -93,6 +93,359 @@ var BackendCollectionRegistry = class extends CollectionRegistry {
93
93
  }
94
94
  };
95
95
  //#endregion
96
+ //#region src/collections/validate-config.ts
97
+ /**
98
+ * Read the unknown-key policy from the environment.
99
+ *
100
+ * `REBASE_STRICT_COLLECTION_CONFIG` accepts `error`/`strict`/`1`/`true` to
101
+ * escalate, `off`/`0`/`false` to silence, and anything else warns.
102
+ */
103
+ function unknownKeyPolicyFromEnv(env = process.env) {
104
+ const raw = env.REBASE_STRICT_COLLECTION_CONFIG?.trim().toLowerCase();
105
+ if (!raw) return "warn";
106
+ if ([
107
+ "error",
108
+ "strict",
109
+ "1",
110
+ "true",
111
+ "yes"
112
+ ].includes(raw)) return "error";
113
+ if ([
114
+ "off",
115
+ "0",
116
+ "false",
117
+ "no",
118
+ "none"
119
+ ].includes(raw)) return "off";
120
+ return "warn";
121
+ }
122
+ /** `BaseCollectionConfig`, plus every engine-specific field, plus the `admin` block. */
123
+ var COLLECTION_KEYS = new Set([
124
+ "slug",
125
+ "name",
126
+ "singularName",
127
+ "description",
128
+ "childCollections",
129
+ "dataSource",
130
+ "engine",
131
+ "databaseId",
132
+ "properties",
133
+ "auth",
134
+ "disableDefaultPolicies",
135
+ "callbacks",
136
+ "ownerId",
137
+ "metadata",
138
+ "history",
139
+ "strictWrites",
140
+ "table",
141
+ "relations",
142
+ "securityRules",
143
+ "schema",
144
+ "path",
145
+ "subcollections",
146
+ "admin"
147
+ ]);
148
+ /** `BaseProperty` — legal on a property of any type. */
149
+ var BASE_PROPERTY_KEYS = [
150
+ "type",
151
+ "name",
152
+ "description",
153
+ "propertyConfig",
154
+ "columnName",
155
+ "defaultValue",
156
+ "validation",
157
+ "excludeFromApi",
158
+ "dynamicProps",
159
+ "conditions",
160
+ "callbacks",
161
+ "metadata",
162
+ "admin"
163
+ ];
164
+ /** The keys each property `type` adds on top of {@link BASE_PROPERTY_KEYS}. */
165
+ var PROPERTY_KEYS_BY_TYPE = {
166
+ string: [
167
+ "columnType",
168
+ "isId",
169
+ "enum",
170
+ "storage",
171
+ "userSelect",
172
+ "email",
173
+ "url"
174
+ ],
175
+ number: [
176
+ "columnType",
177
+ "isId",
178
+ "enum"
179
+ ],
180
+ boolean: [],
181
+ date: [
182
+ "columnType",
183
+ "mode",
184
+ "timezone",
185
+ "autoValue"
186
+ ],
187
+ geopoint: [],
188
+ binary: [],
189
+ vector: ["dimensions"],
190
+ reference: [
191
+ "isId",
192
+ "path",
193
+ "fixedFilter",
194
+ "includeId",
195
+ "includeEntityLink"
196
+ ],
197
+ relation: [
198
+ "isId",
199
+ "relation",
200
+ "resolvedRelation",
201
+ "fixedFilter",
202
+ "includeId",
203
+ "includeEntityLink",
204
+ "widget"
205
+ ],
206
+ array: [
207
+ "columnType",
208
+ "of",
209
+ "oneOf",
210
+ "sortable",
211
+ "canAddElements"
212
+ ],
213
+ map: [
214
+ "columnType",
215
+ "properties",
216
+ "propertiesOrder",
217
+ "previewProperties",
218
+ "keyValue"
219
+ ]
220
+ };
221
+ var PROPERTY_TYPES = Object.keys(PROPERTY_KEYS_BY_TYPE);
222
+ /** `RelationBase` plus the fields of every `kind` in the tagged union. */
223
+ var RELATION_KEYS = new Set([
224
+ "kind",
225
+ "relationName",
226
+ "target",
227
+ "onUpdate",
228
+ "onDelete",
229
+ "overrides",
230
+ "validation",
231
+ "localKey",
232
+ "foreignKeyOnTarget",
233
+ "through",
234
+ "joinPath",
235
+ "cardinality"
236
+ ]);
237
+ var RELATION_KINDS = [
238
+ "belongsTo",
239
+ "hasOne",
240
+ "hasMany",
241
+ "manyToMany",
242
+ "via"
243
+ ];
244
+ /** Which link field each `kind` admits. Anything else is a leftover shape. */
245
+ var RELATION_FIELDS_BY_KIND = {
246
+ belongsTo: ["localKey"],
247
+ hasOne: ["foreignKeyOnTarget"],
248
+ hasMany: ["foreignKeyOnTarget"],
249
+ manyToMany: ["through"],
250
+ via: ["joinPath", "cardinality"]
251
+ };
252
+ var RELATION_LINK_FIELDS = [
253
+ "localKey",
254
+ "foreignKeyOnTarget",
255
+ "through",
256
+ "joinPath",
257
+ "cardinality"
258
+ ];
259
+ /** Collection-level keys that no longer exist at the top level. */
260
+ var COLLECTION_MIGRATIONS = { editable: { fix: "`editable` was removed in 0.10 — collections are editable by default. Delete it, or use `admin.disableDefaultActions` to take actions away" } };
261
+ for (const key of ADMIN_COLLECTION_KEYS) COLLECTION_MIGRATIONS[key] = {
262
+ fix: `\`${key}\` moved into the collection's \`admin\` block in 0.11 — write \`admin: { ${key}: … }\``,
263
+ codemod: "node scripts/codemod/collections-admin-block.mjs"
264
+ };
265
+ /** Property-level keys that no longer exist at the top level of a property. */
266
+ var PROPERTY_MIGRATIONS = {
267
+ ui: { fix: "`ui` was renamed to `admin` in 0.11, to match the collection's block — rename the key" },
268
+ editable: { fix: "`editable` was removed in 0.10 — properties are editable by default. Use `admin.readOnly` or `admin.disabled` instead" }
269
+ };
270
+ for (const key of ADMIN_PROPERTY_KEYS) PROPERTY_MIGRATIONS[key] = { fix: `\`${key}\` belongs in the property's \`admin\` block — write \`admin: { ${key}: … }\`` };
271
+ /**
272
+ * The flat relation fields that `RelationProperty` used to carry.
273
+ *
274
+ * All of them moved into the nested `relation` object. Two of them do not
275
+ * survive the move at all: `direction` and `inverseRelationName` were how the
276
+ * old shape said which side owned the link, and the `kind` discriminant says it
277
+ * now.
278
+ */
279
+ var RELATION_PROPERTY_MIGRATIONS = {
280
+ target: { fix: "move `target` inside `relation` — `relation: { kind: …, target: … }`" },
281
+ cardinality: { fix: "`cardinality` is implied by the relation's `kind` (`belongsTo`/`hasOne` are one, `hasMany`/`manyToMany` are many); it survives only on `relation: { kind: \"via\" }`" },
282
+ direction: { fix: "`direction` was removed — the `kind` says which side owns the link. `owning` + one is `belongsTo`, `inverse` + one is `hasOne`, `inverse` + many is `hasMany`, `owning` + many is `manyToMany`" },
283
+ inverseRelationName: { fix: "`inverseRelationName` was removed — name the far side with `relation: { kind: \"hasMany\", foreignKeyOnTarget: … }` instead of pointing at it" },
284
+ localKey: { fix: "move `localKey` inside `relation` — `relation: { kind: \"belongsTo\", localKey: … }`" },
285
+ foreignKeyOnTarget: { fix: "move `foreignKeyOnTarget` inside `relation` — `relation: { kind: \"hasOne\" | \"hasMany\", foreignKeyOnTarget: … }`" },
286
+ through: { fix: "move `through` inside `relation` — `relation: { kind: \"manyToMany\", through: … }`" },
287
+ joinPath: { fix: "move `joinPath` inside `relation` — `relation: { kind: \"via\", joinPath: … }`" },
288
+ onUpdate: { fix: "move `onUpdate` inside `relation`" },
289
+ onDelete: { fix: "move `onDelete` inside `relation`" },
290
+ overrides: { fix: "move `overrides` inside `relation`" },
291
+ relationName: { fix: "move `relationName` inside `relation` — `relation: { kind: …, relationName: … }`" }
292
+ };
293
+ var RELATION_UNION_CODEMOD = "node scripts/codemod/relations-tagged-union.mjs";
294
+ /** Fields the old flat `Relation` carried that the tagged union does not. */
295
+ var RELATION_MIGRATIONS = {
296
+ direction: {
297
+ fix: RELATION_PROPERTY_MIGRATIONS.direction.fix,
298
+ codemod: RELATION_UNION_CODEMOD
299
+ },
300
+ inverseRelationName: {
301
+ fix: RELATION_PROPERTY_MIGRATIONS.inverseRelationName.fix,
302
+ codemod: RELATION_UNION_CODEMOD
303
+ }
304
+ };
305
+ function isPlainObject$2(value) {
306
+ return typeof value === "object" && value !== null && !Array.isArray(value);
307
+ }
308
+ var ProblemCollector = class {
309
+ unknownKeys;
310
+ problems = [];
311
+ constructor(unknownKeys) {
312
+ this.unknownKeys = unknownKeys;
313
+ }
314
+ error(path, message) {
315
+ this.problems.push({
316
+ severity: "error",
317
+ path,
318
+ message
319
+ });
320
+ }
321
+ /** A key we know moved or died. Always fatal — we know exactly what to do. */
322
+ migrated(path, key, migration) {
323
+ this.error(path, `\`${key}\` is no longer read here. ${migration.fix}.` + (migration.codemod ? ` Run \`${migration.codemod}\` to migrate the whole project.` : ""));
324
+ }
325
+ /** A key nobody recognises. Might be metadata, might be newer than us. */
326
+ unknown(path, key, context) {
327
+ if (this.unknownKeys === "off") return;
328
+ this.problems.push({
329
+ severity: this.unknownKeys === "error" ? "error" : "warning",
330
+ path,
331
+ message: `\`${key}\` is not a known ${context} key and is being ignored. If it is deliberate metadata this is safe; if it is a typo or a key from an older version, the feature it configures is silently absent.`
332
+ });
333
+ }
334
+ };
335
+ function checkRelation(relation, path, collect) {
336
+ if (!isPlainObject$2(relation)) return;
337
+ const kind = relation.kind;
338
+ if (typeof kind !== "string") collect.error(path, `a relation has no \`kind\`. Relations became a tagged union in 0.11 — pick one of ${RELATION_KINDS.join(", ")}. Run \`${RELATION_UNION_CODEMOD}\` to migrate the whole project.`);
339
+ else if (!RELATION_KINDS.includes(kind)) collect.error(path, `\`kind: "${kind}"\` is not a relation kind. Expected one of ${RELATION_KINDS.join(", ")}.`);
340
+ for (const key of Object.keys(relation)) {
341
+ const migration = RELATION_MIGRATIONS[key];
342
+ if (migration) {
343
+ collect.migrated(`${path}.${key}`, key, migration);
344
+ continue;
345
+ }
346
+ if (!RELATION_KEYS.has(key)) collect.unknown(`${path}.${key}`, key, "relation");
347
+ }
348
+ if (typeof kind === "string" && RELATION_FIELDS_BY_KIND[kind]) {
349
+ const allowed = RELATION_FIELDS_BY_KIND[kind];
350
+ for (const field of RELATION_LINK_FIELDS) if (relation[field] !== void 0 && !allowed.includes(field)) collect.error(`${path}.${field}`, `\`${field}\` is not valid on a "${kind}" relation. A "${kind}" takes ${allowed.length ? allowed.map((a) => `\`${a}\``).join(" and ") : "no link field"}.`);
351
+ }
352
+ }
353
+ function checkProperty(property, path, collect) {
354
+ if (typeof property === "function") return;
355
+ if (!isPlainObject$2(property)) {
356
+ collect.error(path, "a property must be an object.");
357
+ return;
358
+ }
359
+ const type = property.type;
360
+ if (typeof type !== "string") collect.error(path, "a property has no `type`.");
361
+ else if (!PROPERTY_TYPES.includes(type)) collect.error(path, `\`type: "${type}"\` is not a property type. Expected one of ${PROPERTY_TYPES.join(", ")}.`);
362
+ const allowed = new Set([...BASE_PROPERTY_KEYS, ...typeof type === "string" ? PROPERTY_KEYS_BY_TYPE[type] ?? [] : []]);
363
+ for (const key of Object.keys(property)) {
364
+ if (allowed.has(key)) continue;
365
+ if (type === "relation" && RELATION_PROPERTY_MIGRATIONS[key]) {
366
+ collect.migrated(`${path}.${key}`, key, {
367
+ ...RELATION_PROPERTY_MIGRATIONS[key],
368
+ codemod: RELATION_UNION_CODEMOD
369
+ });
370
+ continue;
371
+ }
372
+ const migration = PROPERTY_MIGRATIONS[key];
373
+ if (migration) {
374
+ collect.migrated(`${path}.${key}`, key, migration);
375
+ continue;
376
+ }
377
+ collect.unknown(`${path}.${key}`, key, `property (\`${String(type)}\`)`);
378
+ }
379
+ if (type === "relation" && property.relation !== void 0) checkRelation(property.relation, `${path}.relation`, collect);
380
+ if (type === "array") {
381
+ const of = property.of;
382
+ if (Array.isArray(of)) of.forEach((entry, index) => checkProperty(entry, `${path}.of[${index}]`, collect));
383
+ else if (of !== void 0) checkProperty(of, `${path}.of`, collect);
384
+ const oneOf = property.oneOf;
385
+ if (isPlainObject$2(oneOf) && isPlainObject$2(oneOf.properties)) checkProperties(oneOf.properties, `${path}.oneOf.properties`, collect);
386
+ }
387
+ if (type === "map" && isPlainObject$2(property.properties)) checkProperties(property.properties, `${path}.properties`, collect);
388
+ }
389
+ function checkProperties(properties, path, collect) {
390
+ for (const [key, property] of Object.entries(properties)) checkProperty(property, `${path}.${key}`, collect);
391
+ }
392
+ function checkCollection(collection, index, collect) {
393
+ if (!isPlainObject$2(collection)) {
394
+ collect.error(`collection[${index}]`, "a collection must be an object.");
395
+ return;
396
+ }
397
+ const slug = typeof collection.slug === "string" && collection.slug ? collection.slug : void 0;
398
+ const at = slug ?? `collection[${index}]`;
399
+ if (!slug) collect.error(at, "a collection has no `slug`. It is the collection's identity — the URL, the API path and the key every relation targets.");
400
+ for (const key of Object.keys(collection)) {
401
+ if (COLLECTION_KEYS.has(key)) continue;
402
+ const migration = COLLECTION_MIGRATIONS[key];
403
+ if (migration) {
404
+ collect.migrated(`${at}.${key}`, key, migration);
405
+ continue;
406
+ }
407
+ collect.unknown(`${at}.${key}`, key, "collection");
408
+ }
409
+ if (isPlainObject$2(collection.properties)) checkProperties(collection.properties, `${at}.properties`, collect);
410
+ else if (collection.properties !== void 0) collect.error(`${at}.properties`, "`properties` must be an object keyed by property name.");
411
+ if (Array.isArray(collection.relations)) collection.relations.forEach((relation, i) => {
412
+ checkRelation(relation, `${at}.relations[${isPlainObject$2(relation) && typeof relation.relationName === "string" ? relation.relationName : String(i)}]`, collect);
413
+ });
414
+ }
415
+ /**
416
+ * Every problem across every collection, in one pass.
417
+ *
418
+ * Pure: it logs nothing and throws nothing, so callers that want to render the
419
+ * list themselves (the doctor, a test) can.
420
+ */
421
+ function findCollectionConfigProblems(collections, options = {}) {
422
+ const collect = new ProblemCollector(options.unknownKeys ?? unknownKeyPolicyFromEnv());
423
+ collections.forEach((collection, index) => checkCollection(collection, index, collect));
424
+ return collect.problems;
425
+ }
426
+ function render(problems) {
427
+ return problems.map((p) => ` • ${p.path}\n ${p.message}`).join("\n\n");
428
+ }
429
+ /**
430
+ * Warn about everything questionable, then refuse to boot if anything is wrong.
431
+ *
432
+ * Warnings are logged even when there are errors: someone migrating wants the
433
+ * whole picture in one run, and the second-most annoying thing after a broken
434
+ * boot is a boot that breaks again on something it could have told you the
435
+ * first time.
436
+ */
437
+ function assertCollectionConfigs(collections, options = {}) {
438
+ const problems = findCollectionConfigProblems(collections, options);
439
+ if (problems.length === 0) return;
440
+ const warnings = problems.filter((p) => p.severity === "warning");
441
+ const errors = problems.filter((p) => p.severity === "error");
442
+ if (warnings.length > 0) logger.warn(`[collections] ${warnings.length} unrecognised key(s) in the collection config, ignored:\n\n` + render(warnings) + "\n\nSet REBASE_STRICT_COLLECTION_CONFIG=error to make these fail the boot.\n");
443
+ if (errors.length === 0) return;
444
+ throw new Error(`${errors.length} problem(s) in the collection config.\n\nThese keys are not read by this version. Nothing would have failed at runtime — whatever they configure would simply be absent — so they are fatal at boot instead.
445
+
446
+ ` + render(errors) + "\n");
447
+ }
448
+ //#endregion
96
449
  //#region src/collections/loader.ts
97
450
  function isCollectionFile(file) {
98
451
  return (file.endsWith(".ts") || file.endsWith(".js")) && !file.startsWith(".") && !file.includes(".test.") && !file.endsWith(".d.ts") && file !== "index.ts" && file !== "index.js";
@@ -132,16 +485,27 @@ function applyCollectionDefaults(collections, defaults) {
132
485
  * configuration error, and continuing produces the worst outcome available: an
133
486
  * API missing a route, or a policy file missing a table, with a successful exit
134
487
  * code. Both read as "no data" rather than as a failure.
135
- */
136
- async function loadCollectionsFromDirectory(source) {
488
+ *
489
+ * Every collection is strict-parsed on the way out — see `validate-config` for
490
+ * why a key that moved is fatal and a key nobody recognises only warns. It
491
+ * happens here, at the one definition of "the collections", so the runtime, the
492
+ * schema generator, the policy generator and the doctor all see the same
493
+ * verdict rather than three of them silently accepting a config the fourth
494
+ * rejects.
495
+ */
496
+ async function loadCollectionsFromDirectory(source, options = {}) {
137
497
  const resolved = path$1.resolve(source);
498
+ const validate = (collections) => {
499
+ if (options.validate !== false) assertCollectionConfigs(collections, options.validate ?? {});
500
+ return collections;
501
+ };
138
502
  if (!fs$2.existsSync(resolved)) {
139
503
  logger.warn(`[collections] Not found: ${resolved}`);
140
504
  return [];
141
505
  }
142
506
  if (!fs$2.statSync(resolved).isDirectory()) {
143
507
  const mod = await importModule(resolved);
144
- return applyCollectionDefaults([...mod.backendCollections || mod.collections || []], { defaultSecurityRules: mod.defaultSecurityRules });
508
+ return validate(applyCollectionDefaults([...mod.backendCollections || mod.collections || []], { defaultSecurityRules: mod.defaultSecurityRules }));
145
509
  }
146
510
  const collections = [];
147
511
  const failures = [];
@@ -153,7 +517,7 @@ async function loadCollectionsFromDirectory(source) {
153
517
  failures.push(`${file}: ${err instanceof Error ? err.message : String(err)}`);
154
518
  }
155
519
  if (failures.length > 0) throw new Error(`Could not load ${failures.length} collection file(s) from ${resolved}:\n` + failures.map((f) => ` • ${f}`).join("\n") + "\n\nEvery collection file must import cleanly and default-export a collection.");
156
- return applyCollectionDefaults(collections, await readDefaults(resolved));
520
+ return validate(applyCollectionDefaults(collections, await readDefaults(resolved)));
157
521
  }
158
522
  //#endregion
159
523
  //#region src/services/driver-registry.ts
@@ -528,6 +892,33 @@ function parseLogicalGroup(type, raw) {
528
892
  return "type" in parsed ? parsed : void 0;
529
893
  }
530
894
  /**
895
+ * Parse the `?where=` JSON filter object.
896
+ *
897
+ * This is the dialect the OpenAPI document publishes on every
898
+ * `GET /api/data/{slug}` — `{"status":["==","active"]}`: field → canonical
899
+ * `[WhereFilterOp, value]` tuple. It is normalized through the same
900
+ * `deserializeFilter` as the `?field=op.value` params below, so a value that
901
+ * arrives as a PostgREST dot-string (`{"status":"eq.active"}`) or as a bare
902
+ * scalar (`{"status":"active"}`) compiles to the same condition. Unlike the
903
+ * querystring dialect, JSON carries types — a number stays a number.
904
+ *
905
+ * A malformed value is a 400 rather than a silent drop: dropping the filter
906
+ * would run the read unfiltered and return everything RLS happens to allow.
907
+ */
908
+ function parseWhereParam(raw) {
909
+ const str = String(raw).trim();
910
+ if (!str) return void 0;
911
+ let parsed;
912
+ try {
913
+ parsed = JSON.parse(str);
914
+ } catch {
915
+ throw ApiError.badRequest("Invalid `where` parameter: expected a JSON object, e.g. {\"status\":[\"==\",\"active\"]}", "INVALID_WHERE");
916
+ }
917
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw ApiError.badRequest("Invalid `where` parameter: expected a JSON object mapping fields to conditions, e.g. {\"status\":[\"==\",\"active\"]}", "INVALID_WHERE");
918
+ const filter = deserializeFilter(parsed);
919
+ return Object.keys(filter).length > 0 ? filter : void 0;
920
+ }
921
+ /**
531
922
  * Parse query parameters into QueryOptions
532
923
  */
533
924
  function parseQueryOptions(query, limits = {}) {
@@ -566,14 +957,19 @@ function parseQueryOptions(query, limits = {}) {
566
957
  "vector_distance",
567
958
  "vector_threshold",
568
959
  "or",
569
- "and"
960
+ "and",
961
+ "where"
570
962
  ];
571
963
  const filterDict = {};
572
964
  for (const [key, rawValue] of Object.entries(query)) {
573
965
  if (reservedQueryKeys.includes(key)) continue;
574
966
  filterDict[key] = rawValue;
575
967
  }
576
- const where = deserializeFilter(filterDict);
968
+ const whereVal = getLastValue(query.where);
969
+ const where = {
970
+ ...whereVal !== void 0 && whereVal !== null ? parseWhereParam(whereVal) : void 0,
971
+ ...deserializeFilter(filterDict)
972
+ };
577
973
  if (Object.keys(where).length > 0) options.where = where;
578
974
  const orderByVal = getLastValue(query.orderBy);
579
975
  if (orderByVal) try {
@@ -599,16 +995,17 @@ function parseQueryOptions(query, limits = {}) {
599
995
  const vectorVal = getLastValue(query.vector);
600
996
  if (vectorSearchVal && vectorVal) {
601
997
  const vectorStr = String(vectorVal);
602
- let queryVector;
998
+ let decoded;
603
999
  try {
604
- queryVector = JSON.parse(vectorStr);
605
- if (!Array.isArray(queryVector) || !queryVector.every((v) => typeof v === "number")) throw new Error("Expected array of numbers");
1000
+ decoded = JSON.parse(vectorStr);
606
1001
  } catch {
607
- throw new Error("Invalid vector format. Expected JSON array of numbers, e.g. [0.1,0.2,0.3]");
1002
+ decoded = void 0;
608
1003
  }
1004
+ if (!Array.isArray(decoded) || !decoded.every((v) => typeof v === "number")) throw ApiError.badRequest("Invalid `vector` format. Expected a JSON array of numbers, e.g. [0.1,0.2,0.3]", "INVALID_VECTOR");
1005
+ const queryVector = decoded;
609
1006
  const distanceParamVal = getLastValue(query.vector_distance);
610
1007
  const distanceParam = distanceParamVal ? String(distanceParamVal) : "cosine";
611
- if (distanceParam !== "cosine" && distanceParam !== "l2" && distanceParam !== "inner_product") throw new Error(`Invalid vector_distance: ${distanceParam}. Expected: cosine, l2, or inner_product`);
1008
+ if (distanceParam !== "cosine" && distanceParam !== "l2" && distanceParam !== "inner_product") throw ApiError.badRequest(`Invalid \`vector_distance\`: ${distanceParam}. Expected: cosine, l2, or inner_product`, "INVALID_VECTOR_DISTANCE");
612
1009
  const vectorSearch = {
613
1010
  property: String(vectorSearchVal),
614
1011
  vector: queryVector,
@@ -617,7 +1014,7 @@ function parseQueryOptions(query, limits = {}) {
617
1014
  const thresholdVal = getLastValue(query.vector_threshold);
618
1015
  if (thresholdVal) {
619
1016
  const threshold = parseFloat(String(thresholdVal));
620
- if (isNaN(threshold)) throw new Error("Invalid vector_threshold. Expected a number.");
1017
+ if (isNaN(threshold)) throw ApiError.badRequest("Invalid `vector_threshold`. Expected a number.", "INVALID_VECTOR_THRESHOLD");
621
1018
  vectorSearch.threshold = threshold;
622
1019
  }
623
1020
  options.vectorSearch = vectorSearch;
@@ -765,7 +1162,14 @@ var TABLE$2 = "\"rebase\".\"idempotency_keys\"";
765
1162
  * by a scheduled job — there is no cron guaranteed to be running.
766
1163
  */
767
1164
  var TTL_HOURS = 24;
768
- /** The principal a key belongs to; anonymous and service writes share a sentinel. */
1165
+ /**
1166
+ * The principal a key belongs to; anonymous and service writes share a sentinel.
1167
+ *
1168
+ * The NUL is written as an escape, not as a raw byte in the source. The
1169
+ * sentinel itself is deliberate — a uid can never contain one — but written
1170
+ * literally it makes this file test as binary, and every repo-wide grep then
1171
+ * skips all 124 lines of it silently. Identical at runtime.
1172
+ */
769
1173
  function principal(uid) {
770
1174
  return uid && uid.length > 0 ? uid : "\0anon";
771
1175
  }
@@ -11970,7 +12374,7 @@ function assertStorageAccessControlConfigured(state, isProduction) {
11970
12374
  //#region src/init/docs.ts
11971
12375
  async function mountOpenApiDocs(app, basePath, enableSwagger, activeCollections, requireAuth) {
11972
12376
  if (enableSwagger === false || activeCollections.length === 0) return;
11973
- const { generateOpenApiSpec } = await import("./openapi-generator-CeOnlAJ3.js");
12377
+ const { generateOpenApiSpec } = await import("./openapi-generator-Bjzmb5cn.js");
11974
12378
  app.get(`${basePath}/docs`, (c) => {
11975
12379
  const spec = generateOpenApiSpec(activeCollections, {
11976
12380
  basePath,
@@ -12206,6 +12610,25 @@ function rebaseReviver(_key, value) {
12206
12610
  }
12207
12611
  return value;
12208
12612
  }
12613
+ /**
12614
+ * True when there is no browser to have signed a user in — a Node script, a
12615
+ * cron job, an edge worker.
12616
+ *
12617
+ * Anonymous is an ordinary, correct state in a browser: before sign-in, on a
12618
+ * marketing page, for public reads. Warning there would be noise that teaches
12619
+ * people to ignore warnings, so the guard is off entirely. This uses the same
12620
+ * `typeof window` test as {@link resolveBaseUrl}, and additionally treats a
12621
+ * defined `document` as a browser so an SSR shim or test harness that installs
12622
+ * only one of the two is still excluded.
12623
+ */
12624
+ function isServerLikeEnvironment() {
12625
+ return typeof window === "undefined" && typeof document === "undefined";
12626
+ }
12627
+ /**
12628
+ * Emitted once per client. Kept as a constant so the wording is testable and
12629
+ * greppable — this is the string a user will paste into a search.
12630
+ */
12631
+ var ANONYMOUS_SERVER_CLIENT_WARNING = "[rebase] This client was created outside a browser with no credential — no `token`, no auth token getter, and no cookie auth flow — so every request runs as an anonymous caller. Row-level security will return only publicly readable rows, which is usually nothing and occasionally the wrong thing. Inside a cron or function handler, use the `client` you were handed instead of building a new one: its data plane is already admin-scoped. In a standalone script or job, pass the service key as `token`. If you really do want anonymous access, pass `anonymous: true` to silence this.";
12209
12632
  function buildQueryString(params) {
12210
12633
  if (!params) return "";
12211
12634
  const parts = [];
@@ -12252,12 +12675,31 @@ function resolveBaseUrl(configured) {
12252
12675
  if (typeof window !== "undefined" && window.location?.origin) return window.location.origin;
12253
12676
  return "";
12254
12677
  }
12255
- function createTransport(config) {
12678
+ function createTransport(config, environment) {
12256
12679
  const fetchFn = config.fetch || globalThis.fetch;
12257
12680
  const apiPath = config.apiPath || "/api";
12258
12681
  let token = config.token;
12259
12682
  let tokenGetter;
12260
12683
  let onUnauthorizedHandler = config.onUnauthorized;
12684
+ /** Once per client, never per request — log spam is its own bug. */
12685
+ let anonymousWarningIssued = false;
12686
+ /**
12687
+ * Warn a server-side caller that it built a client that can only ever be
12688
+ * anonymous. Deliberately checked at the *first request* rather than at
12689
+ * construction: `setToken()` / `setAuthTokenGetter()` and a server-side
12690
+ * `auth.signIn…()` (which calls `transport.setToken`) all land after the
12691
+ * constructor, and warning at construction would fire on every one of them.
12692
+ */
12693
+ function warnIfAnonymousServerClient(activeToken) {
12694
+ if (anonymousWarningIssued) return;
12695
+ if (activeToken) return;
12696
+ if (tokenGetter) return;
12697
+ if (config.anonymous) return;
12698
+ if (environment?.credentialOutOfBand) return;
12699
+ if (!isServerLikeEnvironment()) return;
12700
+ anonymousWarningIssued = true;
12701
+ console.warn(ANONYMOUS_SERVER_CLIENT_WARNING);
12702
+ }
12261
12703
  function getHeaders(activeToken, init) {
12262
12704
  return {
12263
12705
  "Content-Type": "application/json",
@@ -12272,6 +12714,7 @@ function createTransport(config) {
12272
12714
  const fetched = await tokenGetter();
12273
12715
  if (fetched !== null && fetched !== void 0) activeToken = fetched;
12274
12716
  } catch (e) {}
12717
+ warnIfAnonymousServerClient(activeToken);
12275
12718
  const headers = getHeaders(activeToken, init);
12276
12719
  if (init?.body instanceof FormData) delete headers["Content-Type"];
12277
12720
  const res = await fetchFn(url, {
@@ -13309,6 +13752,12 @@ function createCollectionClient(transport, slug, ws) {
13309
13752
  meta: raw.meta
13310
13753
  };
13311
13754
  },
13755
+ iterate(params) {
13756
+ return paginateFind((p) => client.find(p), params, slug);
13757
+ },
13758
+ findAll(params) {
13759
+ return collectAllPages((p) => client.find(p), params, slug);
13760
+ },
13312
13761
  async findById(id) {
13313
13762
  try {
13314
13763
  const raw = await transport.request(`${basePath}/${encodeURIComponent(String(id))}`, { method: "GET" });
@@ -16109,6 +16558,8 @@ var OfflineManager = class {
16109
16558
  meta: answer.meta
16110
16559
  };
16111
16560
  },
16561
+ iterate: (params) => paginateFind((p) => wrapped.find(p), params, slug),
16562
+ findAll: (params) => collectAllPages((p) => wrapped.find(p), params, slug),
16112
16563
  findById: async (id) => {
16113
16564
  await this.ensureCollection(slug);
16114
16565
  if (this.connectivity.shouldAttempt()) try {
@@ -17176,7 +17627,7 @@ function deriveWebSocketUrl(baseUrl) {
17176
17627
  return baseUrl.replace(/^https?:\/\//i, (match) => match.toLowerCase() === "https://" ? "wss://" : "ws://").replace(/\/$/, "");
17177
17628
  }
17178
17629
  function createRebaseClient(options) {
17179
- const transport = createTransport(options);
17630
+ const transport = createTransport(options, { credentialOutOfBand: options.auth?.authFlowMode === "cookie" });
17180
17631
  const auth = createAuth(transport, options.auth);
17181
17632
  const admin = createAdmin(transport, options.admin);
17182
17633
  const cron = createCron(transport, options.cron);
@@ -17553,13 +18004,37 @@ function createEmailService(config) {
17553
18004
  }
17554
18005
  //#endregion
17555
18006
  //#region src/singleton.ts
17556
- var _instance = null;
18007
+ /**
18008
+ * The backing instance lives on a process-global slot, NOT in a module-local
18009
+ * variable — because more than one copy of this module can be loaded into one
18010
+ * process, and a module-local would leave every copy but the booting one dead.
18011
+ *
18012
+ * That is the normal layout under the managed runtime, not an edge case: the
18013
+ * image ships the framework at `/app/node_modules`, while a project's bundle
18014
+ * installs its own dependencies into `/bundle/node_modules` — and every custom
18015
+ * function imports `defineFunction` from `@rebasepro/server`, which resolves to
18016
+ * the bundle's transitively-installed copy. `initializeRebaseBackend()` then ran
18017
+ * against `/app`'s copy while every function held `/bundle`'s, so `rebase.data`,
18018
+ * `rebase.storage` and `rebase.dataAsAdmin` threw "server not initialized yet"
18019
+ * on EVERY request, forever, in an otherwise healthy process.
18020
+ *
18021
+ * `Symbol.for` is the fix because its registry is per-process rather than
18022
+ * per-module: whichever copy boots publishes here, and every other copy — same
18023
+ * version or not — reads the same live client.
18024
+ */
18025
+ var INSTANCE_SLOT = Symbol.for("@rebasepro/server:singleton-instance");
18026
+ function getInstance() {
18027
+ return globalThis[INSTANCE_SLOT] ?? null;
18028
+ }
18029
+ function setInstance(client) {
18030
+ globalThis[INSTANCE_SLOT] = client;
18031
+ }
17557
18032
  /**
17558
18033
  * @internal Called once during server initialization to set the backing instance.
17559
18034
  * This is invoked by `initializeRebaseBackend()` — never call it manually.
17560
18035
  */
17561
18036
  function _initRebase(client) {
17562
- _instance = client;
18037
+ setInstance(client);
17563
18038
  }
17564
18039
  /**
17565
18040
  * @internal Allows overriding the underlying instance for unit testing.
@@ -17567,17 +18042,17 @@ function _initRebase(client) {
17567
18042
  */
17568
18043
  function _setRebaseMock(mockInstance) {
17569
18044
  if (process.env.NODE_ENV !== "test") throw new Error("_setRebaseMock can only be called in a test environment (NODE_ENV=test).");
17570
- _instance = {
17571
- ..._instance || {},
18045
+ setInstance({
18046
+ ...getInstance() || {},
17572
18047
  ...mockInstance
17573
- };
18048
+ });
17574
18049
  }
17575
18050
  /**
17576
18051
  * @internal Resets the singleton instance, useful for afterEach() in test suites.
17577
18052
  */
17578
18053
  function _resetRebaseMock() {
17579
18054
  if (process.env.NODE_ENV !== "test") throw new Error("_resetRebaseMock can only be called in a test environment.");
17580
- _instance = null;
18055
+ setInstance(null);
17581
18056
  }
17582
18057
  /**
17583
18058
  * The server-side Rebase singleton.
@@ -17616,8 +18091,9 @@ function _resetRebaseMock() {
17616
18091
  */
17617
18092
  var rebase = new Proxy({}, {
17618
18093
  get(_, prop) {
17619
- if (!_instance) throw new Error(`rebase.${String(prop)}: server not initialized yet. The singleton is available after Rebase starts — don't call it at import time.`);
17620
- return _instance[prop];
18094
+ const instance = getInstance();
18095
+ if (!instance) throw new Error(`rebase.${String(prop)}: server not initialized yet. The singleton is available after Rebase starts — don't call it at import time.`);
18096
+ return instance[prop];
17621
18097
  },
17622
18098
  set(_, prop) {
17623
18099
  throw new Error(`Cannot set rebase.${String(prop)} directly. The singleton is read-only. Use _initRebase() during server startup.`);
@@ -17664,21 +18140,17 @@ async function _initializeRebaseBackend(config) {
17664
18140
  const dataSourceRegistry = createDataSourceRegistry(config.dataSources);
17665
18141
  collectionRegistry.setDataSources(dataSourceRegistry);
17666
18142
  if (config.callbacks) collectionRegistry.setGlobalCallbacks(config.callbacks);
17667
- const mode = config.mode ?? "cms";
17668
- logger.info(mode === "baas" ? "Starting in baas mode — collections derived from the database schema" : "Starting in cms mode — collections from config");
17669
18143
  let activeCollections = config.collections || [];
17670
- if (mode === "baas") {
17671
- if (activeCollections.length > 0 || config.collectionsDir) {
17672
- logger.warn("Ignoring configured collections: baas mode derives them from the database schema. Remove `collections`/`collectionsDir`, or use mode: \"cms\" to serve them.");
17673
- activeCollections = [];
17674
- }
17675
- } else if (config.collectionsDir && activeCollections.length === 0) {
18144
+ if (activeCollections.length > 0) assertCollectionConfigs(activeCollections);
18145
+ if (config.collectionsDir && activeCollections.length === 0) {
17676
18146
  activeCollections = await loadCollectionsFromDirectory(config.collectionsDir);
17677
18147
  logger.info("Auto-discovered collections", {
17678
18148
  count: activeCollections.length,
17679
18149
  dir: config.collectionsDir
17680
18150
  });
17681
18151
  }
18152
+ const introspectCollections = activeCollections.length === 0;
18153
+ logger.info(introspectCollections ? "No collections declared — deriving them from the database schema" : "Serving declared collections");
17682
18154
  const realtimeServices = {};
17683
18155
  const delegates = {};
17684
18156
  let bootstrappers = config.bootstrappers || [];
@@ -17706,16 +18178,16 @@ async function _initializeRebaseBackend(config) {
17706
18178
  const driverResult = await bootstrapper.initializeDriver({
17707
18179
  collections: activeCollections,
17708
18180
  collectionRegistry,
17709
- mode,
18181
+ introspectCollections,
17710
18182
  baas: config.baas
17711
18183
  });
17712
18184
  delegates[b.id || bootstrapper.type] = driverResult.driver;
17713
- if (mode === "baas") {
18185
+ if (introspectCollections) {
17714
18186
  const driverName = b.id || bootstrapper.type;
17715
- if (!driverResult.collections) throw new Error(`Driver "${driverName}" does not support baas mode: it cannot derive collections from the database schema. Use mode: "cms" and declare collections explicitly, or use a driver that implements introspection (e.g. @rebasepro/server-postgres).`);
18187
+ if (!driverResult.collections) throw new Error(`Driver "${driverName}" cannot derive collections from the database schema, and this project declared none. Declare collections, or use a driver that implements introspection (e.g. @rebasepro/server-postgres).`);
17716
18188
  if (driverResult.collections.length === 0) logger.warn(`Driver "${driverName}" found no tables to serve. The data API will not be mounted. Create tables (migrations, SQL, any tool) and restart.`);
17717
18189
  }
17718
- if (driverResult.collections?.length) activeCollections = [...activeCollections, ...driverResult.collections];
18190
+ if (introspectCollections && driverResult.collections?.length) activeCollections = [...activeCollections, ...driverResult.collections];
17719
18191
  if ((b.id || bootstrapper.type) === defaultDriverId || !defaultDriverResult) defaultDriverResult = driverResult;
17720
18192
  if (bootstrapper.initializeRealtime) {
17721
18193
  const realtime = await bootstrapper.initializeRealtime({}, driverResult);
@@ -17958,12 +18430,12 @@ async function _initializeRebaseBackend(config) {
17958
18430
  if (apiKeyPreAuth) router.use("/*", apiKeyPreAuth);
17959
18431
  router.use("/*", createRequireAuth({ serviceKey: internalServiceKey }), requireAdmin);
17960
18432
  };
17961
- const schemaEditorEnabled = config.schemaEditor ?? (!!config.collectionsDir && process.env.NODE_ENV !== "production" && mode === "cms");
18433
+ const schemaEditorEnabled = config.schemaEditor ?? (!!config.collectionsDir && !introspectCollections && process.env.NODE_ENV !== "production");
17962
18434
  if (schemaEditorEnabled && !config.collectionsDir) logger.warn("schemaEditor is enabled but no collectionsDir is set — the schema editor has nowhere to write. Skipping.");
17963
18435
  if (schemaEditorEnabled && config.collectionsDir) {
17964
18436
  let editorModule;
17965
18437
  try {
17966
- editorModule = await import("./schema-editor-routes-BFpXKkPD.js");
18438
+ editorModule = await import("./schema-editor-routes-DDxfOIid.js");
17967
18439
  } catch (err) {
17968
18440
  if (err?.code === "ERR_MODULE_NOT_FOUND") logger.warn("Schema Editor disabled: its dependency ts-morph is not installed. Run `npm install ts-morph@28.0.0` to enable it.");
17969
18441
  else throw err;
@@ -18215,7 +18687,6 @@ async function _initializeRebaseBackend(config) {
18215
18687
  contractRouter.route("/", createContractRoutes({
18216
18688
  collectionRegistry,
18217
18689
  schemaVersion: config.schemaVersion,
18218
- mode,
18219
18690
  runtimeVersion: config.runtimeVersion
18220
18691
  }));
18221
18692
  config.app.route(`${basePath}/meta`, contractRouter);
@@ -18488,6 +18959,97 @@ function defineCron(definition) {
18488
18959
  return definition;
18489
18960
  }
18490
18961
  //#endregion
18962
+ //#region src/cron/scale-to-zero.ts
18963
+ /**
18964
+ * Scale-to-zero detection for the cron scheduler.
18965
+ *
18966
+ * The scheduler drives jobs with in-process `setTimeout`. That works on any
18967
+ * always-running instance, but on a platform that freezes or evicts the
18968
+ * container between requests (Cloud Run with `--min-instances=0`, AWS Lambda,
18969
+ * Vercel functions) the timers simply never fire — the process boots, logs the
18970
+ * jobs as registered, and silently runs nothing.
18971
+ *
18972
+ * None of these platforms expose their scaling floor to the container, so this
18973
+ * detection is a heuristic: it identifies the *platform*, not the setting. It
18974
+ * is a warning only — it must never influence boot.
18975
+ *
18976
+ * Environment variables used here were verified against vendor documentation:
18977
+ * - `K_SERVICE` / `K_REVISION` / `K_CONFIGURATION` — Cloud Run services
18978
+ * (Cloud Run container contract; no variable exposes min-instances).
18979
+ * - `CLOUD_RUN_JOB` — Cloud Run jobs (same contract).
18980
+ * - `AWS_LAMBDA_FUNCTION_NAME` — reserved AWS Lambda runtime variable.
18981
+ * - `VERCEL=1` — Vercel system environment variable, available at runtime.
18982
+ * - `KUBERNETES_SERVICE_HOST` — injected into every pod by the kubelet. Used
18983
+ * as an *exclusion*: a Deployment pod runs continuously, and Knative on
18984
+ * Kubernetes also sets `K_SERVICE`, so a pod is never warned about.
18985
+ */
18986
+ /** Environment variable that permanently silences the scale-to-zero warning. */
18987
+ var CRON_ALWAYS_ON_ENV = "REBASE_CRON_ALWAYS_ON";
18988
+ /** Accepts the usual truthy spellings; anything else (including "") is false. */
18989
+ function isTruthy(value) {
18990
+ if (!value) return false;
18991
+ const normalised = value.trim().toLowerCase();
18992
+ return normalised === "1" || normalised === "true" || normalised === "yes" || normalised === "on";
18993
+ }
18994
+ /**
18995
+ * Identify a runtime whose instances can be frozen or torn down between
18996
+ * requests. Returns `undefined` when the platform is unknown or known to run
18997
+ * continuously.
18998
+ */
18999
+ function detectFreezableRuntime(env = process.env) {
19000
+ if (env.KUBERNETES_SERVICE_HOST) return void 0;
19001
+ if (env.K_SERVICE) {
19002
+ const signals = ["K_SERVICE"];
19003
+ if (env.K_REVISION) signals.push("K_REVISION");
19004
+ if (env.K_CONFIGURATION) signals.push("K_CONFIGURATION");
19005
+ return {
19006
+ platform: "Cloud Run",
19007
+ signals
19008
+ };
19009
+ }
19010
+ if (env.CLOUD_RUN_JOB) return {
19011
+ platform: "Cloud Run Jobs",
19012
+ signals: ["CLOUD_RUN_JOB"]
19013
+ };
19014
+ if (env.AWS_LAMBDA_FUNCTION_NAME) return {
19015
+ platform: "AWS Lambda",
19016
+ signals: ["AWS_LAMBDA_FUNCTION_NAME"]
19017
+ };
19018
+ if (env.VERCEL === "1") return {
19019
+ platform: "Vercel",
19020
+ signals: ["VERCEL"]
19021
+ };
19022
+ }
19023
+ /** How many job ids to name before collapsing the rest into "+N more". */
19024
+ var MAX_NAMED_JOBS = 10;
19025
+ /**
19026
+ * Build the boot-time warning, or `undefined` when it does not apply.
19027
+ *
19028
+ * Fires only when all of the following hold:
19029
+ * 1. `NODE_ENV=production` — a laptop or CI run is not at risk.
19030
+ * 2. At least one *enabled* job is registered — nothing to lose otherwise.
19031
+ * 3. The environment looks like a freezable platform (see above).
19032
+ * 4. `REBASE_CRON_ALWAYS_ON` is not set to a truthy value.
19033
+ */
19034
+ function buildScaleToZeroWarning(jobs, env = process.env) {
19035
+ if (env.NODE_ENV !== "production") return void 0;
19036
+ if (isTruthy(env["REBASE_CRON_ALWAYS_ON"])) return void 0;
19037
+ const enabled = jobs.filter((job) => job.enabled).map((job) => job.id);
19038
+ if (enabled.length === 0) return void 0;
19039
+ const runtime = detectFreezableRuntime(env);
19040
+ if (!runtime) return void 0;
19041
+ const named = enabled.slice(0, MAX_NAMED_JOBS);
19042
+ const list = enabled.length > named.length ? `${named.join(", ")} (+${enabled.length - named.length} more)` : named.join(", ");
19043
+ return {
19044
+ message: `[cron] ${runtime.platform} detected — in-process timers do not fire while an instance is frozen or scaled to zero, so ${enabled.length} enabled job(s) may never run: ${list}; drive them from an external scheduler instead (POST /api/cron/:id/trigger, e.g. Cloud Scheduler). ${runtime.platform} does not expose its scaling floor to the container, so an always-warm deployment cannot be confirmed from inside the process — set ${CRON_ALWAYS_ON_ENV}=1 to silence this if at least one instance is pinned warm.`,
19045
+ data: {
19046
+ platform: runtime.platform,
19047
+ signals: runtime.signals,
19048
+ jobs: enabled
19049
+ }
19050
+ };
19051
+ }
19052
+ //#endregion
18491
19053
  //#region src/cron/cron-scheduler.ts
18492
19054
  var cron_scheduler_exports = /* @__PURE__ */ __exportAll({
18493
19055
  CronScheduler: () => CronScheduler,
@@ -18696,6 +19258,7 @@ var CronScheduler = class {
18696
19258
  });
18697
19259
  for (const [id, job] of this.jobs) if (job.enabled) this.scheduleNext(id);
18698
19260
  if (!this.store) logger.warn("[cron] No cron store attached — runs are uncoordinated; with multiple app instances every instance will execute every job");
19261
+ this.warnIfScaleToZero();
18699
19262
  logger.info(`⏰ Cron scheduler started with ${this.jobs.size} job(s)`);
18700
19263
  }
18701
19264
  /**
@@ -18789,6 +19352,23 @@ var CronScheduler = class {
18789
19352
  return this.executeJob(job, true);
18790
19353
  }
18791
19354
  /**
19355
+ * Warn once at start when the process looks like it is running on a
19356
+ * platform that freezes or evicts instances between requests, where the
19357
+ * in-process timers this scheduler relies on never fire.
19358
+ *
19359
+ * Advisory only: any failure here is swallowed so a detection bug can
19360
+ * never take a production boot down.
19361
+ */
19362
+ warnIfScaleToZero() {
19363
+ try {
19364
+ const warning = buildScaleToZeroWarning([...this.jobs.values()].map((job) => ({
19365
+ id: job.id,
19366
+ enabled: job.enabled
19367
+ })));
19368
+ if (warning) logger.warn(warning.message, warning.data);
19369
+ } catch {}
19370
+ }
19371
+ /**
18792
19372
  * Schedule the next execution for a job.
18793
19373
  *
18794
19374
  * Safety guarantees:
@@ -19465,6 +20045,102 @@ function loadEnv(options) {
19465
20045
  return env;
19466
20046
  }
19467
20047
  //#endregion
20048
+ //#region src/services/webhook-service.ts
20049
+ var WebhookDispatcher = class {
20050
+ webhooks = [];
20051
+ maxRetries = 3;
20052
+ retryDelays = [
20053
+ 1e3,
20054
+ 5e3,
20055
+ 15e3
20056
+ ];
20057
+ /** Register webhooks to watch */
20058
+ setWebhooks(webhooks) {
20059
+ this.webhooks = webhooks.filter((w) => w.enabled);
20060
+ }
20061
+ /** Called when a entity changes — checks if any webhook matches */
20062
+ async onEntityChange(table, event, id, entity, previousEntity) {
20063
+ const matchingWebhooks = this.webhooks.filter((w) => w.table === table && w.events.includes(event));
20064
+ if (matchingWebhooks.length === 0) return [];
20065
+ const results = [];
20066
+ for (const webhook of matchingWebhooks) {
20067
+ const payload = {
20068
+ type: event,
20069
+ table,
20070
+ record: entity,
20071
+ old_record: event === "UPDATE" ? previousEntity : void 0,
20072
+ schema: "public",
20073
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
20074
+ };
20075
+ const result = await this.deliverWithRetry(webhook, event, payload);
20076
+ results.push(result);
20077
+ }
20078
+ return results;
20079
+ }
20080
+ async deliverWithRetry(webhook, event, payload) {
20081
+ for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
20082
+ const result = await this.deliver(webhook, event, payload, attempt);
20083
+ if (result.success) return result;
20084
+ if (attempt < this.maxRetries) await new Promise((r) => setTimeout(r, this.retryDelays[attempt - 1]));
20085
+ else return result;
20086
+ }
20087
+ return {
20088
+ webhookId: webhook.id,
20089
+ event,
20090
+ payload,
20091
+ statusCode: 0,
20092
+ responseBody: "Max retries exceeded",
20093
+ success: false,
20094
+ attemptNumber: this.maxRetries
20095
+ };
20096
+ }
20097
+ async deliver(webhook, event, payload, attemptNumber) {
20098
+ const body = JSON.stringify(payload);
20099
+ const headers = {
20100
+ "Content-Type": "application/json",
20101
+ "X-Webhook-Id": webhook.id,
20102
+ "X-Webhook-Event": event,
20103
+ "X-Webhook-Delivery": randomUUID$1(),
20104
+ "X-Webhook-Attempt": String(attemptNumber),
20105
+ ...webhook.headers || {}
20106
+ };
20107
+ if (webhook.secret) headers["X-Webhook-Signature"] = `sha256=${createHmac("sha256", webhook.secret).update(body).digest("hex")}`;
20108
+ try {
20109
+ const controller = new AbortController();
20110
+ const timeout = setTimeout(() => controller.abort(), 1e4);
20111
+ const response = await fetch(webhook.url, {
20112
+ method: "POST",
20113
+ headers,
20114
+ body,
20115
+ signal: controller.signal
20116
+ });
20117
+ clearTimeout(timeout);
20118
+ const responseBody = await response.text().catch(() => "");
20119
+ const success = response.status >= 200 && response.status < 300;
20120
+ return {
20121
+ webhookId: webhook.id,
20122
+ event,
20123
+ payload,
20124
+ statusCode: response.status,
20125
+ responseBody: responseBody.slice(0, 1e3),
20126
+ success,
20127
+ attemptNumber
20128
+ };
20129
+ } catch (error) {
20130
+ const message = error instanceof Error ? error.message : String(error);
20131
+ return {
20132
+ webhookId: webhook.id,
20133
+ event,
20134
+ payload,
20135
+ statusCode: 0,
20136
+ responseBody: message.slice(0, 1e3),
20137
+ success: false,
20138
+ attemptNumber
20139
+ };
20140
+ }
20141
+ }
20142
+ };
20143
+ //#endregion
19468
20144
  //#region src/utils/dev-port.ts
19469
20145
  var MAX_PORT_ATTEMPTS = 20;
19470
20146
  /** Filename written next to the project `.env` so the CLI can read it. */
@@ -19606,6 +20282,21 @@ function writeStateFile(projectRoot, port, serviceKey) {
19606
20282
  //#endregion
19607
20283
  //#region src/serve-spa.ts
19608
20284
  /**
20285
+ * Is `requestPath` the excluded path `prefix`, or something beneath it?
20286
+ *
20287
+ * Segment-aware on purpose. A plain `startsWith` reads "/api" as excluding
20288
+ * "/apidocs", and "/admin" as excluding "/administrators" — both ordinary
20289
+ * client-side routes of the app rooted at "/", both then answered with a 404
20290
+ * because the SPA fallback declined them and nothing else claims the path.
20291
+ * `apiBasePath` is always in the exclusion list, so this reached single-app
20292
+ * setups too, not just the multi-app ones the list was added for.
20293
+ */
20294
+ function isUnderPath(requestPath, prefix) {
20295
+ const trimmed = prefix.replace(/\/+$/, "");
20296
+ if (trimmed === "") return true;
20297
+ return requestPath === trimmed || requestPath.startsWith(`${trimmed}/`);
20298
+ }
20299
+ /**
19609
20300
  * Serve a Single Page Application from an Hono app.
19610
20301
  *
19611
20302
  * @internal Not part of the stable public API. Exported only because the
@@ -19615,21 +20306,30 @@ function writeStateFile(projectRoot, port, serviceKey) {
19615
20306
  * may change without a major version bump.
19616
20307
  */
19617
20308
  function serveSPA(app, config) {
19618
- const { frontendPath, apiBasePath = "/api", excludePaths = [], indexFile = "index.html" } = config;
20309
+ const { frontendPath, apiBasePath = "/api", excludePaths = [], indexFile = "index.html", spa = true } = config;
20310
+ const rawBase = config.basePath ?? "/";
20311
+ const basePath = rawBase !== "/" ? rawBase.replace(/\/+$/, "") : "/";
20312
+ const isRoot = basePath === "/";
19619
20313
  if (!fs$2.existsSync(frontendPath)) {
19620
20314
  logger.warn(`⚠️ Frontend build path does not exist: ${frontendPath}`);
19621
20315
  logger.warn(" SPA serving is disabled. Build your frontend first.");
19622
20316
  return;
19623
20317
  }
19624
- app.use("/*", responseCompression());
19625
- app.use("/*", serveStatic({
20318
+ const scope = isRoot ? "/*" : `${basePath}/*`;
20319
+ app.use(scope, responseCompression());
20320
+ app.use(scope, serveStatic({
19626
20321
  root: path$1.relative(process.cwd(), frontendPath),
19627
- precompressed: true
20322
+ precompressed: true,
20323
+ ...isRoot ? {} : { rewriteRequestPath: (p) => p.slice(basePath.length) || "/" }
19628
20324
  }));
20325
+ if (!spa) {
20326
+ logger.info(`✅ Static serving enabled at ${basePath} from: ${frontendPath}`);
20327
+ return;
20328
+ }
19629
20329
  const allExcludePaths = [apiBasePath, ...excludePaths];
19630
20330
  let cachedHtml = null;
19631
- app.get("*", async (c, next) => {
19632
- if (allExcludePaths.some((p) => c.req.path.startsWith(p))) return next();
20331
+ app.get(scope, async (c, next) => {
20332
+ if (allExcludePaths.some((p) => isUnderPath(c.req.path, p))) return next();
19633
20333
  const indexPath = path$1.join(frontendPath, indexFile);
19634
20334
  if (!cachedHtml) try {
19635
20335
  cachedHtml = await fsp.readFile(indexPath, "utf-8");
@@ -19639,7 +20339,7 @@ function serveSPA(app, config) {
19639
20339
  }
19640
20340
  return c.html(cachedHtml);
19641
20341
  });
19642
- logger.info(`✅ SPA serving enabled from: ${frontendPath}`);
20342
+ logger.info(`✅ SPA serving enabled at ${basePath} from: ${frontendPath}`);
19643
20343
  }
19644
20344
  //#endregion
19645
20345
  //#region src/boot/bundle.ts
@@ -19654,6 +20354,36 @@ var BundleError = class extends Error {
19654
20354
  };
19655
20355
  var MANIFEST_FILENAME = "manifest.json";
19656
20356
  /**
20357
+ * Bring a format-1 manifest up to the shape the rest of this runtime expects.
20358
+ *
20359
+ * Old bundles booting on a new runtime is the case the format version exists to
20360
+ * protect, so this is not a courtesy — it is the contract. A project built
20361
+ * before the rename ships `mode` and a single `entry.static` directory string,
20362
+ * and without this it would boot with no `kind` (so every gate keyed on
20363
+ * `kind === "backend"` would skip) and an `entry.static` the loader would try to
20364
+ * iterate as a list.
20365
+ *
20366
+ * In place, and only ever filling in what is absent, so a format-2 manifest
20367
+ * passes through untouched.
20368
+ */
20369
+ function upgradeLegacyManifest(manifest) {
20370
+ const legacy = manifest;
20371
+ if (!legacy.kind) legacy.kind = legacy.mode === "static" ? "static" : "backend";
20372
+ const entry = legacy.entry;
20373
+ if (!entry) return;
20374
+ if (typeof entry.static === "string") entry.static = [{
20375
+ path: "/",
20376
+ dir: entry.static,
20377
+ spa: true
20378
+ }];
20379
+ else if (!entry.static && typeof entry.admin === "string") entry.static = [{
20380
+ path: "/",
20381
+ dir: entry.admin,
20382
+ spa: true
20383
+ }];
20384
+ delete entry.admin;
20385
+ }
20386
+ /**
19657
20387
  * Read and validate a bundle's manifest.
19658
20388
  *
19659
20389
  * The checks here are the runtime half of the compatibility contract, and they
@@ -19671,7 +20401,8 @@ function readBundleManifest(bundleDir) {
19671
20401
  throw new BundleError(`${manifestPath} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`);
19672
20402
  }
19673
20403
  if (typeof manifest.bundleFormat !== "number") throw new BundleError(`${manifestPath} is missing "bundleFormat".`);
19674
- if (manifest.bundleFormat > 1) throw new BundleError(`This bundle uses format ${manifest.bundleFormat}, but this runtime understands up to 1.`, "Upgrade the runtime image, or rebuild the bundle with a matching CLI.");
20404
+ if (manifest.bundleFormat > 2) throw new BundleError(`This bundle uses format ${manifest.bundleFormat}, but this runtime understands up to 2.`, "Upgrade the runtime image, or rebuild the bundle with a matching CLI.");
20405
+ upgradeLegacyManifest(manifest);
19675
20406
  const contract = manifest.runtime?.contract;
19676
20407
  if (typeof contract === "number" && contract !== 1) throw new BundleError(`This bundle targets runtime contract v${contract}, but this runtime implements v1.`, contract > 1 ? "Upgrade the runtime image to a version that implements the newer contract." : "Rebuild the bundle against the current runtime (`rebase build`), or run a runtime image from the previous major.");
19677
20408
  return manifest;
@@ -19720,8 +20451,14 @@ function loadBundle(bundleDir) {
19720
20451
  collectionsDir: entry.collections ? resolveEntry(entry.collections, "collections") : entry.config ? resolveEntry(path.join(entry.config, "collections"), "collections") : void 0,
19721
20452
  functionsDir: resolveEntry(entry.functions, "functions"),
19722
20453
  cronsDir: resolveEntry(entry.crons, "crons"),
19723
- adminDir: resolveEntry(entry.admin, "admin"),
19724
- staticDir: resolveEntry(entry.static, "static")
20454
+ staticApps: (entry.static ?? []).map((item) => {
20455
+ const resolved = resolveEntry(item.dir, `static app "${item.path}"`);
20456
+ return resolved ? {
20457
+ path: item.path,
20458
+ dir: resolved,
20459
+ spa: item.spa !== false
20460
+ } : void 0;
20461
+ }).filter((item) => item !== void 0).sort((a, b) => b.path.length - a.path.length)
19725
20462
  };
19726
20463
  }
19727
20464
  /**
@@ -19770,7 +20507,7 @@ function createSourceBundle(options) {
19770
20507
  return {
19771
20508
  dir,
19772
20509
  manifest: {
19773
- bundleFormat: 1,
20510
+ bundleFormat: 2,
19774
20511
  runtime: {
19775
20512
  range: `^1`,
19776
20513
  builtAgainst: "source",
@@ -19778,7 +20515,7 @@ function createSourceBundle(options) {
19778
20515
  },
19779
20516
  schemaVersion: "",
19780
20517
  app: options.app ?? "backend",
19781
- mode: options.mode ?? "cms",
20518
+ kind: "backend",
19782
20519
  entry: {
19783
20520
  config: options.config ?? configDir,
19784
20521
  collections: collectionsDir,
@@ -19797,8 +20534,7 @@ function createSourceBundle(options) {
19797
20534
  collectionsDir: resolve(collectionsDir),
19798
20535
  functionsDir: resolve(options.functions),
19799
20536
  cronsDir: resolve(options.crons),
19800
- adminDir: void 0,
19801
- staticDir: void 0
20537
+ staticApps: []
19802
20538
  };
19803
20539
  }
19804
20540
  /**
@@ -20081,12 +20817,17 @@ function resolveCorsOrigin(env) {
20081
20817
  *
20082
20818
  * The default key maps to no suffix at all, which is what keeps every existing
20083
20819
  * single-database deployment working untouched.
20820
+ *
20821
+ * The rule itself lives in `@rebasepro/types` so the CLI and any control plane
20822
+ * derive identical names from identical keys; this wrapper exists only to raise
20823
+ * it as a `BundleError`, which is what the rest of boot reports failures as.
20084
20824
  */
20085
20825
  function envSuffixForKey(key, defaultKey) {
20086
- if (!key || key === defaultKey) return "";
20087
- const normalized = key.replace(/[^A-Za-z0-9]+/g, "_").replace(/^_+|_+$/g, "").toUpperCase();
20088
- if (!normalized) throw new BundleError(`Source key "${key}" cannot be turned into an environment variable name.`, "Use a key containing at least one letter or digit.");
20089
- return `__${normalized}`;
20826
+ try {
20827
+ return storageEnvSuffix(key, defaultKey);
20828
+ } catch (err) {
20829
+ throw new BundleError(`Source key "${key}" cannot be turned into an environment variable name.`, "Use a key containing at least one letter or digit.");
20830
+ }
20090
20831
  }
20091
20832
  /** Read `<base>` for the default source, `<base>__<KEY>` for a named one. */
20092
20833
  function readVar(env, base, suffix) {
@@ -20105,13 +20846,8 @@ function readBool(env, base, suffix) {
20105
20846
  * without this check one of them would silently read the other's configuration.
20106
20847
  */
20107
20848
  function assertDistinctSuffixes(definitions, defaultKey, what) {
20108
- const seen = /* @__PURE__ */ new Map();
20109
- for (const def of definitions) {
20110
- const suffix = envSuffixForKey(def.key, defaultKey);
20111
- const existing = seen.get(suffix);
20112
- if (existing !== void 0 && existing !== def.key) throw new BundleError(`${what} keys "${existing}" and "${def.key}" both map to the same environment variable suffix "${suffix || "(none)"}".`, "Rename one of them so each source has its own configuration.");
20113
- seen.set(suffix, def.key);
20114
- }
20849
+ const collision = findStorageSuffixCollision(definitions.map((d) => d.key), defaultKey);
20850
+ if (collision) throw new BundleError(`${what} keys "${collision.a}" and "${collision.b}" both map to the same environment variable suffix "${collision.suffix || "(none)"}".`, "Rename one of them so each source has its own configuration.");
20115
20851
  }
20116
20852
  /** Which driver package backs a given engine, before env overrides. */
20117
20853
  var ENGINE_DRIVERS = {
@@ -20188,23 +20924,37 @@ function resolvePoolConfig(env, suffix) {
20188
20924
  */
20189
20925
  function resolveStorageBackend(env, key, engineHint, defaultBasePath) {
20190
20926
  const suffix = envSuffixForKey(key, DEFAULT_STORAGE_SOURCE_KEY);
20191
- const type = (readVar(env, "STORAGE_TYPE", suffix) || engineHint || "").toLowerCase();
20927
+ const declaredType = readVar(env, "STORAGE_TYPE", suffix);
20928
+ const type = (declaredType || engineHint || "").toLowerCase();
20929
+ const explicit = Boolean(declaredType);
20192
20930
  if (type === "s3") {
20193
20931
  const bucket = readVar(env, "S3_BUCKET", suffix);
20194
- if (!bucket) throw new BundleError(`Storage source "${key}" is set to s3 but has no bucket — set ${`S3_BUCKET${suffix}`}.`);
20932
+ if (!bucket) {
20933
+ if (!explicit) return void 0;
20934
+ throw new BundleError(`Storage source "${key}" is set to s3 but has no bucket — set ${`S3_BUCKET${suffix}`}.`);
20935
+ }
20936
+ const accessKeyId = readVar(env, "S3_ACCESS_KEY_ID", suffix);
20937
+ const secretAccessKey = readVar(env, "S3_SECRET_ACCESS_KEY", suffix);
20938
+ if (!accessKeyId || !secretAccessKey) {
20939
+ if (!explicit) return void 0;
20940
+ throw new BundleError(`Storage source "${key}" is set to s3 with a bucket but no credentials — set ${[!accessKeyId && `S3_ACCESS_KEY_ID${suffix}`, !secretAccessKey && `S3_SECRET_ACCESS_KEY${suffix}`].filter(Boolean).join(" and ")}.`, "A bucket without credentials cannot be reached: every upload fails when the request is signed.");
20941
+ }
20195
20942
  return {
20196
20943
  type: "s3",
20197
20944
  bucket,
20198
20945
  region: readVar(env, "S3_REGION", suffix) || "auto",
20199
- accessKeyId: readVar(env, "S3_ACCESS_KEY_ID", suffix) || "",
20200
- secretAccessKey: readVar(env, "S3_SECRET_ACCESS_KEY", suffix) || "",
20946
+ accessKeyId,
20947
+ secretAccessKey,
20201
20948
  endpoint: readVar(env, "S3_ENDPOINT", suffix),
20202
20949
  forcePathStyle: readBool(env, "S3_FORCE_PATH_STYLE", suffix)
20203
20950
  };
20204
20951
  }
20205
20952
  if (type === "gcs") {
20206
20953
  const bucket = readVar(env, "GCS_BUCKET", suffix);
20207
- if (!bucket) throw new BundleError(`Storage source "${key}" is set to gcs but has no bucket — set ${`GCS_BUCKET${suffix}`}.`);
20954
+ if (!bucket) {
20955
+ if (!explicit) return void 0;
20956
+ throw new BundleError(`Storage source "${key}" is set to gcs but has no bucket — set ${`GCS_BUCKET${suffix}`}.`);
20957
+ }
20208
20958
  return {
20209
20959
  type: "gcs",
20210
20960
  bucket,
@@ -20240,6 +20990,45 @@ function resolveStorageSources(env, definitions, defaultBasePath) {
20240
20990
  }
20241
20991
  return Object.keys(result).length > 0 ? result : void 0;
20242
20992
  }
20993
+ /**
20994
+ * Read a project's declared storage sources from its `rebase.json`.
20995
+ *
20996
+ * A managed bundle carries its topology in `manifest.json`, resolved at build
20997
+ * time. A **custom** runtime has no manifest — it builds its own image and its
20998
+ * own entrypoint — so without this it would have to re-declare in code what
20999
+ * `rebase.json` already says, and the two would drift. Since a custom image
21000
+ * contains the repository anyway, reading the file it already ships is what
21001
+ * keeps one declaration authoritative for both runtimes.
21002
+ *
21003
+ * Walks up from `startDir` because an entrypoint lives at `backend/src` in the
21004
+ * scaffolded layout and somewhere else in a hand-rolled one. A missing,
21005
+ * unreadable or malformed file means "declared nothing" — one default source —
21006
+ * which is the correct reading of every project that predates this and must
21007
+ * never be an error: a storage declaration is optional, and failing to boot a
21008
+ * whole backend over an absent optional file would be the worse bug.
21009
+ */
21010
+ function loadDeclaredStorageSources(startDir, levels = 5) {
21011
+ let dir = startDir;
21012
+ for (let i = 0; i <= levels; i++) {
21013
+ const candidate = path.join(dir, "rebase.json");
21014
+ if (fs.existsSync(candidate)) {
21015
+ let declared;
21016
+ try {
21017
+ declared = JSON.parse(fs.readFileSync(candidate, "utf8"))?.storage;
21018
+ } catch (err) {
21019
+ logger.warn(`Could not read storage sources from ${candidate}: ${err instanceof Error ? err.message : String(err)}. Continuing with a single default storage source.`);
21020
+ return [];
21021
+ }
21022
+ const sources = normalizeStorageSources(declared, void 0);
21023
+ assertDistinctSuffixes(sources, DEFAULT_STORAGE_SOURCE_KEY, "Storage source");
21024
+ return sources;
21025
+ }
21026
+ const parent = path.dirname(dir);
21027
+ if (parent === dir) break;
21028
+ dir = parent;
21029
+ }
21030
+ return [];
21031
+ }
20243
21032
  //#endregion
20244
21033
  //#region src/boot/driver.ts
20245
21034
  /**
@@ -20741,16 +21530,17 @@ async function bootFromBundle(options = {}) {
20741
21530
  const devRoot = process.env.REBASE_DEV_PROJECT_ROOT || process.cwd();
20742
21531
  logger.info("Loaded bundle", {
20743
21532
  app: bundle.manifest.app,
20744
- mode: bundle.manifest.mode,
21533
+ kind: bundle.manifest.kind,
20745
21534
  schemaVersion: bundle.manifest.schemaVersion,
20746
21535
  builtAgainst: bundle.manifest.runtime?.builtAgainst
20747
21536
  });
20748
- if (bundle.manifest.mode === "static") return bootStaticApp(bundle, devRoot, options);
21537
+ if (bundle.manifest.kind === "static") return bootStaticApp(bundle, devRoot, options);
20749
21538
  const env = loadBootEnv();
20750
21539
  const isProduction = env.NODE_ENV === "production";
20751
21540
  const configExports = await loadBundleConfigExports(bundle);
20752
21541
  const dataSourceDefs = configExports.dataSources;
20753
- const storageSourceDefs = configExports.storageSources;
21542
+ const declaredStorage = normalizeStorageSources(bundle.manifest.storage?.sources, configExports.storageSources);
21543
+ const storageSourceDefs = declaredStorage.length > 0 ? declaredStorage : void 0;
20754
21544
  const dataSources = await initializeDataSources(resolveDataSources(process.env, dataSourceDefs), await loadBundleSchema(bundle), [
20755
21545
  bundle.dir,
20756
21546
  path.join(bundle.dir, "backend"),
@@ -20775,7 +21565,6 @@ async function bootFromBundle(options = {}) {
20775
21565
  server,
20776
21566
  app,
20777
21567
  basePath: env.REBASE_BASE_PATH,
20778
- mode: bundle.manifest.mode ?? "cms",
20779
21568
  collectionsDir: bundle.collectionsDir,
20780
21569
  functionsDir: bundle.functionsDir,
20781
21570
  cronsDir: bundle.cronsDir,
@@ -20821,20 +21610,24 @@ async function bootFromBundle(options = {}) {
20821
21610
  if (!env.REBASE_METRICS_TOKEN) logger.warn("Metrics are enabled without REBASE_METRICS_TOKEN — /metrics is readable by anyone who can reach this port. Set a token, or keep the port on a private network.");
20822
21611
  app.route("/metrics", createMetricsRoutes(metrics.registry, env.REBASE_METRICS_TOKEN));
20823
21612
  }
20824
- if (env.REBASE_SERVE_STATIC) {
20825
- const staticRoot = bundle.staticDir ?? bundle.adminDir;
20826
- if (staticRoot) {
20827
- logger.info("Serving static assets", { path: staticRoot });
20828
- serveSPA(app, {
20829
- frontendPath: staticRoot,
20830
- apiBasePath: env.REBASE_BASE_PATH,
20831
- excludePaths: [
20832
- "/health",
20833
- "/livez",
20834
- "/metrics"
20835
- ]
20836
- });
20837
- }
21613
+ if (env.REBASE_SERVE_STATIC) for (const staticApp of bundle.staticApps) {
21614
+ const siblings = bundle.staticApps.filter((other) => other !== staticApp).map((other) => other.path).filter((other) => other !== "/");
21615
+ logger.info("Serving static assets", {
21616
+ path: staticApp.dir,
21617
+ at: staticApp.path
21618
+ });
21619
+ serveSPA(app, {
21620
+ frontendPath: staticApp.dir,
21621
+ basePath: staticApp.path,
21622
+ apiBasePath: env.REBASE_BASE_PATH,
21623
+ excludePaths: [
21624
+ "/health",
21625
+ "/livez",
21626
+ "/metrics",
21627
+ ...siblings
21628
+ ],
21629
+ spa: staticApp.spa
21630
+ });
20838
21631
  }
20839
21632
  let port = env.PORT;
20840
21633
  if (options.listen !== false) if (isProduction) {
@@ -20886,8 +21679,7 @@ async function bootFromBundle(options = {}) {
20886
21679
  * backend — the only difference is what the bundle contains.
20887
21680
  */
20888
21681
  async function bootStaticApp(bundle, devRoot, options) {
20889
- const staticRoot = bundle.staticDir ?? bundle.adminDir;
20890
- if (!staticRoot) throw new BundleError("A static bundle declares no assets to serve.", "Its manifest has `mode: \"static\"` but no `entry.static` — rebuild the app with `rebase build`.");
21682
+ if (bundle.staticApps.length === 0) throw new BundleError("A static bundle declares no assets to serve.", "Its manifest has `kind: \"static\"` but no `entry.static` — rebuild the app with `rebase build`.");
20891
21683
  const isProduction = process.env.NODE_ENV === "production";
20892
21684
  const requestedPort = Number(process.env.PORT ?? "3001") || 3001;
20893
21685
  const basePath = process.env.REBASE_BASE_PATH || "/api";
@@ -20907,19 +21699,26 @@ async function bootStaticApp(bundle, devRoot, options) {
20907
21699
  latencyMs: 0
20908
21700
  }));
20909
21701
  if (metrics) app.route("/metrics", createMetricsRoutes(metrics.registry, metricsToken));
20910
- logger.info("Serving static app", {
20911
- app: bundle.manifest.app,
20912
- path: staticRoot
20913
- });
20914
- serveSPA(app, {
20915
- frontendPath: staticRoot,
20916
- apiBasePath: basePath,
20917
- excludePaths: [
20918
- "/health",
20919
- "/livez",
20920
- "/metrics"
20921
- ]
20922
- });
21702
+ for (const staticApp of bundle.staticApps) {
21703
+ const siblings = bundle.staticApps.filter((other) => other !== staticApp).map((other) => other.path).filter((other) => other !== "/");
21704
+ logger.info("Serving static app", {
21705
+ app: bundle.manifest.app,
21706
+ path: staticApp.dir,
21707
+ at: staticApp.path
21708
+ });
21709
+ serveSPA(app, {
21710
+ frontendPath: staticApp.dir,
21711
+ basePath: staticApp.path,
21712
+ apiBasePath: basePath,
21713
+ excludePaths: [
21714
+ "/health",
21715
+ "/livez",
21716
+ "/metrics",
21717
+ ...siblings
21718
+ ],
21719
+ spa: staticApp.spa
21720
+ });
21721
+ }
20923
21722
  let port = requestedPort;
20924
21723
  if (options.listen !== false) if (isProduction) {
20925
21724
  await new Promise((resolve, reject) => {
@@ -20997,7 +21796,8 @@ async function ensureCollectionSchema(bundle, dataSources, env) {
20997
21796
  logger.info("REBASE_MIGRATE_ON_BOOT=none — leaving the database schema untouched.");
20998
21797
  return;
20999
21798
  }
21000
- if ((bundle.manifest.mode ?? "cms") !== "cms") return;
21799
+ if (bundle.manifest.kind !== "backend") return;
21800
+ if (!bundle.manifest.entry?.config) return;
21001
21801
  if (!bundle.collectionsDir) return;
21002
21802
  const primary = dataSources[0];
21003
21803
  if (!primary?.bootstrapper.ensureCollectionSchema) return;
@@ -21043,7 +21843,6 @@ function createContractRoutes(config) {
21043
21843
  version: config.runtimeVersion ?? "unknown",
21044
21844
  contract: 1
21045
21845
  },
21046
- mode: config.mode,
21047
21846
  collections: serialized,
21048
21847
  collectionSlugs: collections.map((collection) => collection.slug).filter((slug) => Boolean(slug)).sort(),
21049
21848
  generatedAt: (/* @__PURE__ */ new Date()).toISOString()
@@ -21062,15 +21861,12 @@ function createContractRoutes(config) {
21062
21861
  router.get("/schema-version", (c) => {
21063
21862
  const schemaVersion = schemaVersionOf(config.collectionRegistry.getRawCollections());
21064
21863
  c.header(SCHEMA_VERSION_HEADER, schemaVersion);
21065
- return c.json({
21066
- schemaVersion,
21067
- mode: config.mode
21068
- });
21864
+ return c.json({ schemaVersion });
21069
21865
  });
21070
21866
  logger.debug("Contract routes mounted");
21071
21867
  return router;
21072
21868
  }
21073
21869
  //#endregion
21074
- export { ApiError, BundleError, CronScheduler, DEFAULT_DRIVER_ID, DEFAULT_MAX_FILE_SIZE, DEFAULT_STORAGE_ID, DOCUMENT_MIME_TYPES, DefaultDriverRegistry, DefaultStorageRegistry, GCSStorageController, IMAGE_MIME_TYPES, LocalStorageController, MetricsRegistry, S3StorageController, SMTPEmailService, TransformCache, TusHandler, _resetRebaseMock, _setRebaseMock, applyCollectionDefaults, authJwt, authRoles, authUid, bootFromBundle, classifySurface, cleanupDevPortFile, createAppleProvider, createBackupRoutes, createBitbucketProvider, createBuiltinAuthAdapter, createContractRoutes, createCronRoutes, createCronStore, createCustomAuthAdapter, createDiscordProvider, createEmailService, createFacebookProvider, createFunctionRoutes, createGitHubProvider, createGitLabProvider, createGoogleProvider, createHistoryRoutes, createLinkedinProvider, createMetricsMiddleware, createMetricsRoutes, createMicrosoftProvider, createSlackProvider, createSourceBundle, createSpotifyProvider, createStorageController, createStorageRoutes, createTwitterProvider, defineCron, defineFunction, envSuffixForKey, errorHandler, extractUserFromToken, fileTokenAuth, generateSecurePassword, getEmailVerificationTemplate, getMagicLinkTemplate, getPasswordResetTemplate, getUserInvitationTemplate, getWelcomeEmailTemplate, hashPassword, httpMethodToOperation, initializeDataSource, initializeDataSources, initializeRebaseBackend, installShutdownHandlers, isApiKeyToken, isAuthAdapter, isDatabaseAdapter, isLocalhostOrigin, isOperationAllowed, isRebaseApiError, isTransformableImage, listBackupObjects, listenWithPortRetry, loadBootEnv, loadBundle, loadBundleConfigExports, loadBundleSchema, loadCollectionsFromDirectory, loadCronJobsFromDirectory, loadEnv, loadFunctionsFromDirectory, loadUsersCollection, logger, optionalAuth, parseBackupDestination, parseBackupTimestamp, parseTransformOptions, queryTokenAuth, readBackupBytes, readBundleManifest, rebase, requireAdmin, requireAuth, resolveAuthHooks, resolveAuthOptions, resolveCorsOrigin, resolveDataSources, resolveEmailOptions, resolveStorageBackend, resolveStorageSources, runFromBundle, safeCompare, serveSPA, transformImage, validateApiKey, validateCronExpression, validatePasswordStrength, verifyPassword };
21870
+ export { ApiError, BundleError, CronScheduler, DEFAULT_DRIVER_ID, DEFAULT_MAX_FILE_SIZE, DEFAULT_STORAGE_ID, DOCUMENT_MIME_TYPES, DefaultDriverRegistry, DefaultStorageRegistry, GCSStorageController, IMAGE_MIME_TYPES, LocalStorageController, MetricsRegistry, S3StorageController, SMTPEmailService, TransformCache, TusHandler, WebhookDispatcher, _resetRebaseMock, _setRebaseMock, applyCollectionDefaults, assertCollectionConfigs, assertDistinctSuffixes, authJwt, authRoles, authUid, bootFromBundle, classifySurface, cleanupDevPortFile, createAppleProvider, createBackupRoutes, createBitbucketProvider, createBuiltinAuthAdapter, createContractRoutes, createCronRoutes, createCronStore, createCustomAuthAdapter, createDiscordProvider, createEmailService, createFacebookProvider, createFunctionRoutes, createGitHubProvider, createGitLabProvider, createGoogleProvider, createHistoryRoutes, createLinkedinProvider, createMetricsMiddleware, createMetricsRoutes, createMicrosoftProvider, createSlackProvider, createSourceBundle, createSpotifyProvider, createStorageController, createStorageRoutes, createTwitterProvider, defineCron, defineFunction, envSuffixForKey, errorHandler, extractUserFromToken, fileTokenAuth, findCollectionConfigProblems, generateSecurePassword, getEmailVerificationTemplate, getMagicLinkTemplate, getPasswordResetTemplate, getUserInvitationTemplate, getWelcomeEmailTemplate, hashPassword, httpMethodToOperation, initializeDataSource, initializeDataSources, initializeRebaseBackend, installShutdownHandlers, isApiKeyToken, isAuthAdapter, isDatabaseAdapter, isLocalhostOrigin, isOperationAllowed, isRebaseApiError, isTransformableImage, listBackupObjects, listenWithPortRetry, loadBootEnv, loadBundle, loadBundleConfigExports, loadBundleSchema, loadCollectionsFromDirectory, loadCronJobsFromDirectory, loadDeclaredStorageSources, loadEnv, loadFunctionsFromDirectory, loadUsersCollection, logger, optionalAuth, parseBackupDestination, parseBackupTimestamp, parseTransformOptions, queryTokenAuth, readBackupBytes, readBundleManifest, rebase, requireAdmin, requireAuth, resolveAuthHooks, resolveAuthOptions, resolveCorsOrigin, resolveDataSources, resolveEmailOptions, resolveStorageBackend, resolveStorageSources, runFromBundle, safeCompare, serveSPA, transformImage, unknownKeyPolicyFromEnv, validateApiKey, validateCronExpression, validatePasswordStrength, verifyPassword };
21075
21871
 
21076
21872
  //# sourceMappingURL=index.es.js.map