@rebasepro/types 0.34.2 → 0.35.1
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/controllers/client.d.ts +23 -1
- package/dist/index.es.js +458 -2316
- package/dist/index.es.js.map +1 -1
- package/dist/schema/column_options.d.ts +6 -0
- package/dist/schema/columns.d.ts +12 -1
- package/dist/schema/index.d.ts +1 -0
- package/dist/schema/rpc.d.ts +148 -0
- package/dist/types/backend.d.ts +86 -0
- package/dist/types/database_adapter.d.ts +7 -1
- package/dist/types/project_manifest.d.ts +198 -0
- package/dist/types/storage_authorize.d.ts +54 -0
- package/dist/users/import.d.ts +123 -0
- package/dist/users/index.d.ts +1 -0
- package/package.json +1 -1
package/dist/index.es.js
CHANGED
|
@@ -1,38 +1,9 @@
|
|
|
1
1
|
//#region src/errors.ts
|
|
2
|
-
/**
|
|
3
|
-
* The single error type thrown across the entire Rebase client surface —
|
|
4
|
-
* HTTP data/control-plane calls, realtime/WebSocket operations, and
|
|
5
|
-
* client-side logic errors (e.g. an unknown collection accessor). A `catch`
|
|
6
|
-
* block only ever needs to check for this one class:
|
|
7
|
-
*
|
|
8
|
-
* ```ts
|
|
9
|
-
* import { RebaseApiError } from "@rebasepro/client"; // re-exported
|
|
10
|
-
*
|
|
11
|
-
* try {
|
|
12
|
-
* await client.data.products.update(id, { price: 9 });
|
|
13
|
-
* } catch (e) {
|
|
14
|
-
* if (e instanceof RebaseApiError) {
|
|
15
|
-
* if (e.status === 404) { ... } // HTTP failures carry a status
|
|
16
|
-
* console.error(e.code, e.details);
|
|
17
|
-
* }
|
|
18
|
-
* }
|
|
19
|
-
* ```
|
|
20
|
-
*
|
|
21
|
-
* `status` is present for HTTP failures and `undefined` otherwise, so its
|
|
22
|
-
* presence distinguishes transport-level errors from realtime/logic errors.
|
|
23
|
-
*
|
|
24
|
-
* @group Errors
|
|
25
|
-
*/
|
|
26
2
|
var RebaseApiError = class extends Error {
|
|
27
|
-
/** HTTP status code, or `undefined` for non-HTTP errors. */
|
|
28
3
|
status;
|
|
29
|
-
/** Stable machine-readable error code, when the server supplied one. See {@link RebaseErrorCode}. */
|
|
30
4
|
code;
|
|
31
|
-
/** Structured error payload from the server, when present. */
|
|
32
5
|
details;
|
|
33
|
-
/** See {@link RebaseErrorInit.requestId}. Quote it in a bug report. */
|
|
34
6
|
requestId;
|
|
35
|
-
/** See {@link RebaseErrorInit.retryAfterSeconds}. */
|
|
36
7
|
retryAfterSeconds;
|
|
37
8
|
constructor(message, init = {}) {
|
|
38
9
|
super(message);
|
|
@@ -45,41 +16,12 @@ var RebaseApiError = class extends Error {
|
|
|
45
16
|
if (init.cause !== void 0) this.cause = init.cause;
|
|
46
17
|
}
|
|
47
18
|
};
|
|
48
|
-
/**
|
|
49
|
-
* Client-side logic error — raised before any request is made (e.g. accessing
|
|
50
|
-
* an unknown collection accessor when a typed dictionary is configured).
|
|
51
|
-
*
|
|
52
|
-
* A subclass of {@link RebaseApiError} (with no `status`), so a single
|
|
53
|
-
* `catch (e) { if (e instanceof RebaseApiError) ... }` handles it too.
|
|
54
|
-
*
|
|
55
|
-
* @group Errors
|
|
56
|
-
*/
|
|
57
19
|
var RebaseClientError = class extends RebaseApiError {
|
|
58
|
-
/**
|
|
59
|
-
* `init` is the same one {@link RebaseApiError} takes, and it is what makes
|
|
60
|
-
* `code` reachable at all.
|
|
61
|
-
*
|
|
62
|
-
* The constructor used to accept a message and nothing else, so every
|
|
63
|
-
* client-side failure — an undefined filter value, an unknown accessor,
|
|
64
|
-
* `listen()` on a client built with `realtime: false`, a function name with
|
|
65
|
-
* a `/` in it, `refreshSession()` while signed out — arrived with `code ===
|
|
66
|
-
* undefined`. The documented `switch (e.code)` in this file's own example
|
|
67
|
-
* fell to `default: throw e` for all of them, and the only client-side error
|
|
68
|
-
* that *did* carry a code was `OFFLINE`, because that one path minted a
|
|
69
|
-
* `RebaseApiError` instead.
|
|
70
|
-
*/
|
|
71
20
|
constructor(message, init = {}) {
|
|
72
21
|
super(message, init);
|
|
73
22
|
this.name = "RebaseClientError";
|
|
74
23
|
}
|
|
75
24
|
};
|
|
76
|
-
/**
|
|
77
|
-
* Brand for a contract method a particular client cannot serve.
|
|
78
|
-
*
|
|
79
|
-
* `Symbol.for` rather than a fresh symbol: two copies of `@rebasepro/types` in
|
|
80
|
-
* one tree — which happens, see `docs/dependency-duplication-traps.md` — must
|
|
81
|
-
* agree about it, and a module-local symbol would not.
|
|
82
|
-
*/
|
|
83
25
|
var UNSUPPORTED_METHOD = Symbol.for("rebase.unsupportedMethod");
|
|
84
26
|
function unsupportedMethod(message) {
|
|
85
27
|
const stub = () => {
|
|
@@ -88,61 +30,16 @@ function unsupportedMethod(message) {
|
|
|
88
30
|
stub[UNSUPPORTED_METHOD] = true;
|
|
89
31
|
return stub;
|
|
90
32
|
}
|
|
91
|
-
/**
|
|
92
|
-
* Can this method actually do anything?
|
|
93
|
-
*
|
|
94
|
-
* `true` for a stub from {@link unsupportedMethod} **and** for a method that is
|
|
95
|
-
* simply not there — a partial client, a hand-built test double, an
|
|
96
|
-
* implementation written against an older shape of the interface. Both mean the
|
|
97
|
-
* same thing to a caller, so both answer the same way, and an adapter that
|
|
98
|
-
* checks this cannot be caught out by either.
|
|
99
|
-
*
|
|
100
|
-
* Ordinary code does not need it: calling the method and letting it throw is
|
|
101
|
-
* the normal path. Adapters do — the admin panel chooses between subscribing
|
|
102
|
-
* and a one-shot `find()` by asking whether the client can listen, and a UI
|
|
103
|
-
* that subscribes into a throw is worse than one that polls. This is the
|
|
104
|
-
* question `if (accessor.listen)` used to be asking, made explicit now that the
|
|
105
|
-
* method is always there to call.
|
|
106
|
-
*
|
|
107
|
-
* @group Errors
|
|
108
|
-
*/
|
|
109
33
|
function isUnsupported(method) {
|
|
110
34
|
if (typeof method !== "function") return true;
|
|
111
35
|
return method[UNSUPPORTED_METHOD] === true;
|
|
112
36
|
}
|
|
113
37
|
//#endregion
|
|
114
38
|
//#region src/types/filter-operators.ts
|
|
115
|
-
/** The wire spelling of a {@link RelationAggregateSort}: `min(applications.created_at)`. */
|
|
116
39
|
var RELATION_AGGREGATE_SORT_PATTERN = /^(min|max|count|sum|avg)\(([^().]+)(?:\.([^()]+))?\)$/;
|
|
117
|
-
/**
|
|
118
|
-
* A {@link RelationAggregateSort} as a single string — `min(applications.created_at)`,
|
|
119
|
-
* `count(applications)`.
|
|
120
|
-
*
|
|
121
|
-
* The wire form is a string because every layer below the call site already is
|
|
122
|
-
* one: `OrderByTuple` is `[string, direction]`, the REST parameter is
|
|
123
|
-
* `?orderBy=key:direction`, the driver contract takes `orderBy?: string |
|
|
124
|
-
* OrderByTuple[]`, and a cursor names its keys by string. `_score` established
|
|
125
|
-
* the same pattern — a sort key that is not a column, spelled as one — and this
|
|
126
|
-
* reuses it rather than widening five signatures to carry an object that would
|
|
127
|
-
* be flattened at the end anyway.
|
|
128
|
-
*
|
|
129
|
-
* SQL's own spelling, so the key reads as what it compiles to. Neither `:` nor
|
|
130
|
-
* `,` appears in it, which is what keeps it safe in the colon-delimited wire
|
|
131
|
-
* shorthand.
|
|
132
|
-
*
|
|
133
|
-
* @group Models
|
|
134
|
-
*/
|
|
135
40
|
function encodeRelationAggregateSort(sort) {
|
|
136
41
|
return `${sort.agg}(${sort.relation}${sort.field ? `.${sort.field}` : ""})`;
|
|
137
42
|
}
|
|
138
|
-
/**
|
|
139
|
-
* Read the string spelling back, or `undefined` if it is not one.
|
|
140
|
-
*
|
|
141
|
-
* `undefined` rather than a throw: this is asked of *every* sort key to find
|
|
142
|
-
* out which kind it is, and an ordinary column name is not an error.
|
|
143
|
-
*
|
|
144
|
-
* @group Models
|
|
145
|
-
*/
|
|
146
43
|
function parseRelationAggregateSort(key) {
|
|
147
44
|
const match = RELATION_AGGREGATE_SORT_PATTERN.exec(key);
|
|
148
45
|
if (!match) return void 0;
|
|
@@ -154,20 +51,12 @@ function parseRelationAggregateSort(key) {
|
|
|
154
51
|
...field && { field }
|
|
155
52
|
};
|
|
156
53
|
}
|
|
157
|
-
/** Is this sort key the object form rather than a field name? */
|
|
158
54
|
function isRelationAggregateSort(key) {
|
|
159
55
|
return typeof key === "object" && key !== null && typeof key.relation === "string" && typeof key.agg === "string";
|
|
160
56
|
}
|
|
161
|
-
/** A sort key in the single-string form every layer below the call site speaks. */
|
|
162
57
|
function sortKeyToString(key) {
|
|
163
58
|
return isRelationAggregateSort(key) ? encodeRelationAggregateSort(key) : key;
|
|
164
59
|
}
|
|
165
|
-
/**
|
|
166
|
-
* Read a {@link CaseFoldedFieldPath}: the function and the field it folds, or
|
|
167
|
-
* `undefined` for any other key.
|
|
168
|
-
*
|
|
169
|
-
* @group Models
|
|
170
|
-
*/
|
|
171
60
|
function parseCaseFoldedFieldPath(key) {
|
|
172
61
|
const match = /^(lower|upper)\(\s*([^()\s]+)\s*\)$/.exec(key);
|
|
173
62
|
return match ? {
|
|
@@ -175,7 +64,6 @@ function parseCaseFoldedFieldPath(key) {
|
|
|
175
64
|
field: match[2]
|
|
176
65
|
} : void 0;
|
|
177
66
|
}
|
|
178
|
-
/** Maps canonical operators to their REST short-code equivalents. */
|
|
179
67
|
var CANONICAL_TO_REST = {
|
|
180
68
|
"==": "eq",
|
|
181
69
|
"!=": "neq",
|
|
@@ -196,7 +84,6 @@ var CANONICAL_TO_REST = {
|
|
|
196
84
|
"is-null": "isnull",
|
|
197
85
|
"is-not-null": "notnull"
|
|
198
86
|
};
|
|
199
|
-
/** Maps REST short-code operators to their canonical equivalents. */
|
|
200
87
|
var REST_TO_CANONICAL = {
|
|
201
88
|
"eq": "==",
|
|
202
89
|
"neq": "!=",
|
|
@@ -217,21 +104,7 @@ var REST_TO_CANONICAL = {
|
|
|
217
104
|
"isnull": "is-null",
|
|
218
105
|
"notnull": "is-not-null"
|
|
219
106
|
};
|
|
220
|
-
/**
|
|
221
|
-
* Operators that test for null/not-null and therefore ignore their value.
|
|
222
|
-
* Codecs normalize the value of these conditions to `null`.
|
|
223
|
-
*/
|
|
224
107
|
var NULL_OPS = /* @__PURE__ */ new Set(["is-null", "is-not-null"]);
|
|
225
|
-
/**
|
|
226
|
-
* Operators whose operand is a **list** of values rather than one value.
|
|
227
|
-
*
|
|
228
|
-
* On the wire that list is always parenthesised — `in.(draft,review)` — which
|
|
229
|
-
* is what lets the REST codec tell `?status=in.(a,b)` (the operator) from
|
|
230
|
-
* `?status=in.progress` (a value that happens to start with an operator's
|
|
231
|
-
* name). See `deserializeSingle` in `@rebasepro/common`.
|
|
232
|
-
*
|
|
233
|
-
* @group Models
|
|
234
|
-
*/
|
|
235
108
|
var LIST_OPS = /* @__PURE__ */ new Set([
|
|
236
109
|
"in",
|
|
237
110
|
"not-in",
|
|
@@ -239,12 +112,6 @@ var LIST_OPS = /* @__PURE__ */ new Set([
|
|
|
239
112
|
"array-contains-all",
|
|
240
113
|
"array-contained-by"
|
|
241
114
|
]);
|
|
242
|
-
/**
|
|
243
|
-
* Every canonical operator, in a stable order. Useful for engine capability
|
|
244
|
-
* declarations ({@link DataSourceCapabilities.filterOperators}) and for
|
|
245
|
-
* building operator subsets.
|
|
246
|
-
* @group Models
|
|
247
|
-
*/
|
|
248
115
|
var ALL_WHERE_FILTER_OPS = [
|
|
249
116
|
"<",
|
|
250
117
|
"<=",
|
|
@@ -265,105 +132,27 @@ var ALL_WHERE_FILTER_OPS = [
|
|
|
265
132
|
"is-null",
|
|
266
133
|
"is-not-null"
|
|
267
134
|
];
|
|
268
|
-
/** All canonical operator strings for runtime validation. */
|
|
269
135
|
var CANONICAL_OPS = new Set(ALL_WHERE_FILTER_OPS);
|
|
270
|
-
/**
|
|
271
|
-
* The REST table as a `Map`, because the key `toCanonicalOp` is handed comes
|
|
272
|
-
* off the wire.
|
|
273
|
-
*
|
|
274
|
-
* Indexed as a plain object, every `Object.prototype` member answered:
|
|
275
|
-
* `toCanonicalOp("valueOf")` returned the inherited *function* as though it
|
|
276
|
-
* were a `WhereFilterOp`, and every caller here treats a defined result as
|
|
277
|
-
* "known operator". Same defect the REST codec's own lookup tables were
|
|
278
|
-
* converted away from in `filter-dialect.ts`; this is the copy that survived
|
|
279
|
-
* one package over, and it now sits under the operator validation the REST
|
|
280
|
-
* parser does, which would otherwise have admitted `["constructor", x]`.
|
|
281
|
-
*/
|
|
282
136
|
var REST_OP_LOOKUP = new Map(Object.entries(REST_TO_CANONICAL));
|
|
283
|
-
/**
|
|
284
|
-
* Resolve any operator string (canonical or REST short-code) to its
|
|
285
|
-
* canonical `WhereFilterOp` form. Returns `undefined` for unknown operators.
|
|
286
|
-
*
|
|
287
|
-
* @example
|
|
288
|
-
* toCanonicalOp("==") // "=="
|
|
289
|
-
* toCanonicalOp("eq") // "=="
|
|
290
|
-
* toCanonicalOp("cs") // "array-contains"
|
|
291
|
-
* toCanonicalOp("xyz") // undefined
|
|
292
|
-
*/
|
|
293
137
|
function toCanonicalOp(op) {
|
|
294
138
|
if (CANONICAL_OPS.has(op)) return op;
|
|
295
139
|
return REST_OP_LOOKUP.get(op);
|
|
296
140
|
}
|
|
297
141
|
//#endregion
|
|
298
142
|
//#region src/types/search.ts
|
|
299
|
-
/** The column name used when {@link SearchConfig.column} is not given. */
|
|
300
143
|
var DEFAULT_SEARCH_COLUMN = "search_vector";
|
|
301
|
-
/** The matching strategy used when {@link SearchConfig.mode} is not given. */
|
|
302
144
|
var DEFAULT_SEARCH_MODE = "fts";
|
|
303
|
-
/** The text search configuration used when {@link SearchConfig.language} is not given. */
|
|
304
145
|
var DEFAULT_SEARCH_LANGUAGE = "simple";
|
|
305
|
-
/** The weight a field carries when it does not name one. */
|
|
306
146
|
var DEFAULT_SEARCH_WEIGHT = "B";
|
|
307
|
-
/** The similarity floor used when {@link SearchConfig.fuzzyThreshold} is not given. */
|
|
308
147
|
var DEFAULT_FUZZY_THRESHOLD = .3;
|
|
309
|
-
/**
|
|
310
|
-
* The relevance sort key. Valid only on a collection that declares a
|
|
311
|
-
* {@link SearchConfig} *and* on a query that carries a search string; anywhere
|
|
312
|
-
* else it is an unknown field and the request is refused.
|
|
313
|
-
*/
|
|
314
148
|
var RELEVANCE_SORT_FIELD = "_score";
|
|
315
149
|
//#endregion
|
|
316
150
|
//#region src/types/relations.ts
|
|
317
|
-
/**
|
|
318
|
-
* The key a junction row's own columns are carried under, in both directions.
|
|
319
|
-
*
|
|
320
|
-
* A read that includes a `manyToMany` relation serves each related row with its
|
|
321
|
-
* link's columns nested here — `{ id: 5, name: "ts", _pivot: { role: "owner" } }`
|
|
322
|
-
* — and a membership write may name the same key on an element to state what
|
|
323
|
-
* the link should hold. One constant because the two have to be the same word:
|
|
324
|
-
* a wire name that differs between the read and the write it round-trips
|
|
325
|
-
* through is a shape no client can echo back.
|
|
326
|
-
*
|
|
327
|
-
* Leading underscore, like `_matches`: it reads as metadata about the row
|
|
328
|
-
* rather than as one of its columns. A payload property may not be named
|
|
329
|
-
* `_pivot` either — `checkJunctionPayload` refuses it — so the key means one
|
|
330
|
-
* thing wherever it appears.
|
|
331
|
-
*
|
|
332
|
-
* @group Models
|
|
333
|
-
*/
|
|
334
151
|
var JUNCTION_PIVOT_KEY = "_pivot";
|
|
335
|
-
/**
|
|
336
|
-
* The key a row carries the totals of its counted relations under.
|
|
337
|
-
*
|
|
338
|
-
* An include that asks for a count — `include: { tags: { limit: 4, count: true } }`
|
|
339
|
-
* — serves, beside the (capped) `tags`, how many related rows there are in all:
|
|
340
|
-
* `{ id: 1, tags: [ …4 rows ], _count: { tags: 37 } }`. One object per row,
|
|
341
|
-
* keyed by relation name, so counting a second relation adds a key rather than
|
|
342
|
-
* a second top-level name.
|
|
343
|
-
*
|
|
344
|
-
* Leading underscore, like {@link JUNCTION_PIVOT_KEY} and `_matches`: it
|
|
345
|
-
* describes the read, not the record, and no column or form writes it. A
|
|
346
|
-
* collection with a property of this name cannot ask for a count — the read
|
|
347
|
-
* answers 400 rather than writing over the column.
|
|
348
|
-
*
|
|
349
|
-
* @group Models
|
|
350
|
-
*/
|
|
351
152
|
var INCLUDE_COUNT_KEY = "_count";
|
|
352
|
-
/**
|
|
353
|
-
* The conditions of a join step, as a list: one entry for a plain step, one
|
|
354
|
-
* per alternative for a step that joins on any of several.
|
|
355
|
-
* @group Models
|
|
356
|
-
*/
|
|
357
153
|
function joinConditions(step) {
|
|
358
154
|
return Array.isArray(step.on) ? step.on : [step.on];
|
|
359
155
|
}
|
|
360
|
-
/**
|
|
361
|
-
* The one condition of a step that has no alternatives — for the write paths,
|
|
362
|
-
* which only run on a writable chain and a chain with alternatives never is.
|
|
363
|
-
* Throws rather than pick one of several: writing a link into the wrong column
|
|
364
|
-
* is the mistake read-only exists to prevent.
|
|
365
|
-
* @group Models
|
|
366
|
-
*/
|
|
367
156
|
function soleJoinCondition(step) {
|
|
368
157
|
if (Array.isArray(step.on)) {
|
|
369
158
|
if (step.on.length === 1) return step.on[0];
|
|
@@ -374,62 +163,11 @@ function soleJoinCondition(step) {
|
|
|
374
163
|
}
|
|
375
164
|
//#endregion
|
|
376
165
|
//#region src/types/policy.ts
|
|
377
|
-
/**
|
|
378
|
-
* The id a request without a logged-in user reports as `rebase.uid()`.
|
|
379
|
-
*
|
|
380
|
-
* A user-context request always sets `app.uid`: blank would read back as
|
|
381
|
-
* `NULL`, and `NULL` is how the trusted server context is recognised, so an
|
|
382
|
-
* anonymous visitor would be promoted to server privileges. The driver
|
|
383
|
-
* therefore substitutes this sentinel at the single chokepoint where the GUC
|
|
384
|
-
* is set.
|
|
385
|
-
*
|
|
386
|
-
* The consequence for policy authors is that **`rebase.uid() IS NOT NULL` is a
|
|
387
|
-
* tautology on the user path** — it is true for anonymous visitors too. Use
|
|
388
|
-
* {@link policy.authenticated} to mean "signed in", and
|
|
389
|
-
* {@link policy.serverContext} to mean "the trusted server context". Do not
|
|
390
|
-
* hand-write the comparison: see {@link ANONYMOUS_USER_IDS} for why one
|
|
391
|
-
* literal is not enough.
|
|
392
|
-
*
|
|
393
|
-
* @group Models
|
|
394
|
-
*/
|
|
395
166
|
var ANONYMOUS_USER_ID = "anonymous";
|
|
396
|
-
/**
|
|
397
|
-
* Every uid that has ever meant "nobody is signed in" — newest first.
|
|
398
|
-
*
|
|
399
|
-
* There are two because there were two. The types, the policy compiler, the
|
|
400
|
-
* JavaScript evaluator and the linter were all built on
|
|
401
|
-
* {@link ANONYMOUS_USER_ID}, while the request path scoped unauthenticated
|
|
402
|
-
* callers as `'anon'` — so `policy.authenticated()`, which compiled to
|
|
403
|
-
* `rebase.uid() <> 'anonymous'`, was *true* for an anonymous visitor. The
|
|
404
|
-
* sanctioned way to write "signed in" granted to everyone, and the linter
|
|
405
|
-
* flagged the spelling that actually worked as a foreign convention.
|
|
406
|
-
*
|
|
407
|
-
* The request path now reports {@link ANONYMOUS_USER_ID}. `'anon'` stays here
|
|
408
|
-
* because policies outlive the server that generated them: a database still
|
|
409
|
-
* holding policies from before the fix, or a project whose server has not been
|
|
410
|
-
* upgraded yet, must not become a grant in either direction. Compile against
|
|
411
|
-
* this list, not against a single literal.
|
|
412
|
-
*
|
|
413
|
-
* No real user id is ever one of these, so a match is always "not signed in".
|
|
414
|
-
*
|
|
415
|
-
* @group Models
|
|
416
|
-
*/
|
|
417
167
|
var ANONYMOUS_USER_IDS = [ANONYMOUS_USER_ID, "anon"];
|
|
418
|
-
/**
|
|
419
|
-
* Whether a uid stands for "no one is signed in", in any spelling rebase has
|
|
420
|
-
* used. `null`/`undefined` is the trusted server context, not an anonymous
|
|
421
|
-
* caller, and is therefore **not** anonymous — see {@link ANONYMOUS_USER_ID}.
|
|
422
|
-
*
|
|
423
|
-
* @group Models
|
|
424
|
-
*/
|
|
425
168
|
function isAnonymousUid(uid) {
|
|
426
169
|
return typeof uid === "string" && ANONYMOUS_USER_IDS.includes(uid);
|
|
427
170
|
}
|
|
428
|
-
/**
|
|
429
|
-
* Every `kind` a {@link PolicyExpression} node can have — the discriminator
|
|
430
|
-
* {@link isPolicyShorthand} and {@link isPolicyExpressionKind} read.
|
|
431
|
-
* @group Models
|
|
432
|
-
*/
|
|
433
171
|
var POLICY_EXPRESSION_KINDS = [
|
|
434
172
|
"true",
|
|
435
173
|
"false",
|
|
@@ -445,28 +183,10 @@ var POLICY_EXPRESSION_KINDS = [
|
|
|
445
183
|
"existsIn",
|
|
446
184
|
"raw"
|
|
447
185
|
];
|
|
448
|
-
/**
|
|
449
|
-
* Whether `kind` names a {@link PolicyExpression} node.
|
|
450
|
-
* @group Models
|
|
451
|
-
*/
|
|
452
186
|
function isPolicyExpressionKind(kind) {
|
|
453
187
|
return typeof kind === "string" && POLICY_EXPRESSION_KINDS.includes(kind);
|
|
454
188
|
}
|
|
455
189
|
var isShorthandValue = (value) => value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
|
|
456
|
-
/**
|
|
457
|
-
* Whether a rule's `condition` / `check` is a {@link PolicyShorthand} rather
|
|
458
|
-
* than a {@link PolicyExpression}.
|
|
459
|
-
*
|
|
460
|
-
* True only for a plain object with at least one key, none of them `kind`,
|
|
461
|
-
* whose every value is a string, a finite number, a boolean or `null`. Every
|
|
462
|
-
* expression node carries `kind`, so no expression is ever taken for a
|
|
463
|
-
* shorthand — and an object that has a `kind` key is never taken for a
|
|
464
|
-
* shorthand either, whatever its value: such an object is ambiguous (a column
|
|
465
|
-
* called `kind`, or a misspelt node) and the compiler refuses it rather than
|
|
466
|
-
* guessing.
|
|
467
|
-
*
|
|
468
|
-
* @group Models
|
|
469
|
-
*/
|
|
470
190
|
function isPolicyShorthand(value) {
|
|
471
191
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
472
192
|
const proto = Object.getPrototypeOf(value);
|
|
@@ -475,7 +195,6 @@ function isPolicyShorthand(value) {
|
|
|
475
195
|
const entries = Object.entries(value);
|
|
476
196
|
return entries.length > 0 && entries.every(([, v]) => isShorthandValue(v));
|
|
477
197
|
}
|
|
478
|
-
/** @group Models */
|
|
479
198
|
var policy = {
|
|
480
199
|
true: () => ({ kind: "true" }),
|
|
481
200
|
false: () => ({ kind: "false" }),
|
|
@@ -538,291 +257,70 @@ var policy = {
|
|
|
538
257
|
};
|
|
539
258
|
//#endregion
|
|
540
259
|
//#region src/types/rls-functions.ts
|
|
541
|
-
/**
|
|
542
|
-
* The SQL helper functions RLS policies call, and the schema they live in.
|
|
543
|
-
*
|
|
544
|
-
* ## One schema, and it is ours
|
|
545
|
-
*
|
|
546
|
-
* Rebase creates exactly one schema in a project's database: `rebase`. These
|
|
547
|
-
* three functions live in it alongside the framework's own tables, and that is
|
|
548
|
-
* the whole contract — a reader can look at a database and know precisely which
|
|
549
|
-
* namespace belongs to the framework and that nothing else was touched.
|
|
550
|
-
*
|
|
551
|
-
* It used to be two. `uid()`, `jwt()` and `roles()` sat in a schema called
|
|
552
|
-
* `auth`, which is Supabase's name, chosen so that a developer who had written
|
|
553
|
-
* Supabase RLS would recognise `auth.uid()`. The familiarity was real but the
|
|
554
|
-
* name was not Rebase's to take, and taking it had a concrete cost: pointing
|
|
555
|
-
* Rebase at a database that already had a Supabase `auth` schema meant
|
|
556
|
-
* `CREATE OR REPLACE FUNCTION auth.uid() RETURNS text` against Supabase's
|
|
557
|
-
* `RETURNS uuid`, which Postgres rejects outright —
|
|
558
|
-
*
|
|
559
|
-
* ERROR: cannot change return type of existing function
|
|
560
|
-
* HINT: Use DROP FUNCTION auth.uid() first.
|
|
561
|
-
*
|
|
562
|
-
* — and the failure landed inside a catch-all that logged a warning and carried
|
|
563
|
-
* on, leaving a database with auth tables, no helper functions, and policies
|
|
564
|
-
* calling functions that did not exist. Under `rebase db migrate` the same
|
|
565
|
-
* statements aborted the migration instead.
|
|
566
|
-
*
|
|
567
|
-
* `rebase.uid()` collides with nobody. A Supabase database keeps its `auth`
|
|
568
|
-
* schema untouched and gains a `rebase` one, which is what a gradual migration
|
|
569
|
-
* needs.
|
|
570
|
-
*
|
|
571
|
-
* ## Why functions at all, rather than inlining `current_setting`
|
|
572
|
-
*
|
|
573
|
-
* Because the indirection has already been spent once. `uid()` resolves
|
|
574
|
-
* `app.uid` and falls back to the pre-rename `app.user_id`, so that during a
|
|
575
|
-
* rolling deploy — old and new pods serving one database — both eras resolve
|
|
576
|
-
* the principal. That was a single `CREATE OR REPLACE`. Inlined into policy
|
|
577
|
-
* bodies it would have been a rewrite of every policy on every table.
|
|
578
|
-
*
|
|
579
|
-
* ## Why the name is not configurable
|
|
580
|
-
*
|
|
581
|
-
* A policy body is stored SQL: Postgres parses `USING (…)` once and keeps it, so
|
|
582
|
-
* these strings are written into every policy in every database Rebase has
|
|
583
|
-
* provisioned. Everything that reads policies back — the SQL-to-policy parser
|
|
584
|
-
* behind the admin UI, the drift checker, `rls-check` — would have to know the
|
|
585
|
-
* configured value to recognise its own output. One frozen name is the feature.
|
|
586
|
-
*/
|
|
587
|
-
/** The schema Rebase owns. The only schema Rebase creates. */
|
|
588
260
|
var REBASE_SCHEMA = "rebase";
|
|
589
|
-
/**
|
|
590
|
-
* The principal of the current request, as text, or NULL in the server context.
|
|
591
|
-
*
|
|
592
|
-
* Never NULL for a user request — an anonymous one carries
|
|
593
|
-
* {@link ANONYMOUS_USER_ID} — which is what makes `IS NULL` a reliable test for
|
|
594
|
-
* the trusted server plane and `IS NOT NULL` a tautology.
|
|
595
|
-
*/
|
|
596
261
|
var RLS_UID_SQL = `${REBASE_SCHEMA}.uid()`;
|
|
597
|
-
/**
|
|
598
|
-
* Is the caller one of this database's request roles? What a permissive
|
|
599
|
-
* policy is ANDed with under `rls.policyTarget: "requestRole"`, so another
|
|
600
|
-
* application's role holding a grant on the table gets nothing from it.
|
|
601
|
-
* `current_user` is passed in — inside the function, which reads the recorded
|
|
602
|
-
* roles with its owner's rights, `current_user` would be the owner — and the
|
|
603
|
-
* sub-select makes it one evaluation per statement, not one per row.
|
|
604
|
-
*/
|
|
605
262
|
var RLS_IS_REQUEST_ROLE_SQL = `(SELECT ${REBASE_SCHEMA}.is_request_role(current_user::text))`;
|
|
606
|
-
/** The request's roles as a comma-separated string, for `string_to_array`. */
|
|
607
263
|
var RLS_ROLES_SQL = `${REBASE_SCHEMA}.roles()`;
|
|
608
|
-
/**
|
|
609
|
-
* The Postgres role that policies granting only the server context or admins
|
|
610
|
-
* are written `TO`: the injected `<table>_default_admin_*` baseline, and any
|
|
611
|
-
* permissive rule whose every clause requires one of the two (`roles: ["admin"]`).
|
|
612
|
-
*
|
|
613
|
-
* Postgres ORs the permissive policies that apply to the current role. Written
|
|
614
|
-
* `TO public`, the baseline applied to every signed-in user too, as
|
|
615
|
-
* `(InitPlan) OR owner_id = (InitPlan)` — and an OR with a per-statement
|
|
616
|
-
* constant arm cannot use the owner index, so a user's owner-scoped list or
|
|
617
|
-
* count scanned the whole table (78 ms against 2.8 ms at 1M rows). Written `TO`
|
|
618
|
-
* this role, the policy is not in a user's plan at all.
|
|
619
|
-
*
|
|
620
|
-
* It holds no privilege and cannot log in: being in it only decides which
|
|
621
|
-
* policies apply, and those still test `rebase.uid() IS NULL` or the `admin`
|
|
622
|
-
* role. Admin requests switch to a request role that inherits it
|
|
623
|
-
* ({@link adminRequestRoleFor}); a connection that is itself subject to RLS
|
|
624
|
-
* inherits it for the server context. One fixed name, so the policy text is the
|
|
625
|
-
* same in every deployment and every generated migration. FROZEN.
|
|
626
|
-
*/
|
|
627
264
|
var REBASE_ADMIN_ROLE = "rebase_admin";
|
|
628
|
-
/**
|
|
629
|
-
* The role the admin request roles ({@link adminRequestRoleFor}) inherit and
|
|
630
|
-
* nothing else does, so an admin-only grant can apply to admin REQUESTS alone.
|
|
631
|
-
*
|
|
632
|
-
* {@link REBASE_ADMIN_ROLE} cannot do that job: the connection inherits it for
|
|
633
|
-
* the server context, and so would any process on it that does not switch
|
|
634
|
-
* roles. Its policies therefore keep their test (`rebase.uid() IS NULL` or the
|
|
635
|
-
* `admin` role) — and any policy expression that is not a constant is a
|
|
636
|
-
* security barrier, behind which Postgres will not evaluate a non-leakproof
|
|
637
|
-
* operator as an index condition. An admin's `tags && $1`, `name ~ $1` or
|
|
638
|
-
* jsonb filter scanned the whole table where the owner's used the index.
|
|
639
|
-
*
|
|
640
|
-
* Each admin-only grant gets a companion `TO` this role `USING (true)`.
|
|
641
|
-
* Postgres folds the OR of the permissive policies to `true` for a member, the
|
|
642
|
-
* barrier goes, and an admin request plans as the owner's does; restrictive
|
|
643
|
-
* policies still apply. Membership is the boundary: only the admin request
|
|
644
|
-
* roles hold it, granted `WITH INHERIT TRUE, SET FALSE`, and only from
|
|
645
|
-
* PostgreSQL 16, whose per-grant INHERIT keeps the connection (which holds
|
|
646
|
-
* those roles `WITH INHERIT FALSE`) out. A boot that finds the connection with
|
|
647
|
-
* its privileges revokes every membership, and the companions admit nobody.
|
|
648
|
-
* One fixed name, as {@link REBASE_ADMIN_ROLE}. FROZEN.
|
|
649
|
-
*/
|
|
650
265
|
var REBASE_ADMIN_REQUEST_ROLE = "rebase_admin_request";
|
|
651
|
-
/**
|
|
652
|
-
* The role an admin request runs as, for a signed-in request role: it inherits
|
|
653
|
-
* that role (its grants and every policy written for it) and
|
|
654
|
-
* {@link REBASE_ADMIN_ROLE}. One per request role rather than the shared
|
|
655
|
-
* `rebase_admin` itself, because roles belong to the cluster: a project with a
|
|
656
|
-
* request role of its own (`rls.requestRole`) would otherwise share its admin
|
|
657
|
-
* access with every other project on the cluster. FROZEN derivation.
|
|
658
|
-
*/
|
|
659
266
|
function adminRequestRoleFor(requestRole) {
|
|
660
267
|
return `${requestRole}_admin`;
|
|
661
268
|
}
|
|
662
|
-
/**
|
|
663
|
-
* Whether a request with these roles passes `rolesOverlap(["admin"])` — the
|
|
664
|
-
* test `string_to_array(rebase.roles(), ',') && ARRAY['admin']` makes of the
|
|
665
|
-
* comma-joined `app.user_roles`, so a role name with a comma in it is split
|
|
666
|
-
* exactly as Postgres splits it.
|
|
667
|
-
*/
|
|
668
269
|
function holdsAdminRole(roles) {
|
|
669
270
|
return roles.join(",").split(",").includes("admin");
|
|
670
271
|
}
|
|
671
|
-
/**
|
|
672
|
-
* Whether the caller is a GUEST — signed in through anonymous sign-in rather
|
|
673
|
-
* than with an account.
|
|
674
|
-
*
|
|
675
|
-
* A different question from {@link ANONYMOUS_USER_ID}, and the two are easy to
|
|
676
|
-
* confuse: that sentinel means "no session at all", while this means "a session
|
|
677
|
-
* with nobody behind it". Anonymous sign-in mints a real user row with a real
|
|
678
|
-
* uid, so before this reached the database the two kinds of caller were one
|
|
679
|
-
* principal inside every policy.
|
|
680
|
-
*/
|
|
681
272
|
var RLS_IS_ANONYMOUS_SQL = `${REBASE_SCHEMA}.is_anonymous()`;
|
|
682
|
-
/** The request's JWT claims as `jsonb`, or `{}`. */
|
|
683
273
|
var RLS_JWT_SQL = `${REBASE_SCHEMA}.jwt()`;
|
|
684
|
-
/**
|
|
685
|
-
* The pre-1.0 spellings, for recognising policies and hand-written SQL that
|
|
686
|
-
* predate the move.
|
|
687
|
-
*
|
|
688
|
-
* Kept because policies outlive the server that wrote them: a database migrated
|
|
689
|
-
* by an older release still holds `auth.uid()` in its policy bodies until the
|
|
690
|
-
* next push or boot recompiles them, and anything that reads policies back has
|
|
691
|
-
* to recognise both eras or report the framework's own output as foreign drift.
|
|
692
|
-
* Also used to give a project whose `securityRules` contain raw `auth.uid()` a
|
|
693
|
-
* message naming the replacement, instead of a parse failure.
|
|
694
|
-
*/
|
|
695
274
|
var LEGACY_RLS_SCHEMA = "auth";
|
|
696
275
|
var LEGACY_RLS_UID_SQL = `${LEGACY_RLS_SCHEMA}.uid()`;
|
|
697
276
|
var LEGACY_RLS_ROLES_SQL = `${LEGACY_RLS_SCHEMA}.roles()`;
|
|
698
277
|
var LEGACY_RLS_JWT_SQL = `${LEGACY_RLS_SCHEMA}.jwt()`;
|
|
699
|
-
/**
|
|
700
|
-
* Rewrites the pre-1.0 function calls in a fragment of policy SQL.
|
|
701
|
-
*
|
|
702
|
-
* Deliberately anchored on a word boundary and the schema qualifier, so a column
|
|
703
|
-
* called `auth_uid` or a table named `auth` is left alone.
|
|
704
|
-
*/
|
|
705
278
|
function rewriteLegacyRlsFunctions(sql) {
|
|
706
279
|
return sql.replace(/\bauth\.(uid|jwt|roles)\s*\(\s*\)/gi, (_match, fn) => `${REBASE_SCHEMA}.${fn.toLowerCase()}()`);
|
|
707
280
|
}
|
|
708
|
-
/** Whether a fragment of SQL still calls the pre-1.0 functions. */
|
|
709
281
|
function usesLegacyRlsFunctions(sql) {
|
|
710
282
|
return /\bauth\.(uid|jwt|roles)\s*\(\s*\)/i.test(sql);
|
|
711
283
|
}
|
|
712
284
|
//#endregion
|
|
713
285
|
//#region src/types/security_rules.ts
|
|
714
|
-
/**
|
|
715
|
-
* Whether a rule is the {@link RedactedSecurityRule} marker the server sends
|
|
716
|
-
* in place of a rule whose SQL it withheld.
|
|
717
|
-
*
|
|
718
|
-
* @group Models
|
|
719
|
-
*/
|
|
720
286
|
function isRedactedSecurityRule(rule) {
|
|
721
287
|
return "redacted" in rule && rule.redacted === true;
|
|
722
288
|
}
|
|
723
289
|
//#endregion
|
|
724
290
|
//#region src/types/tenancy.ts
|
|
725
|
-
/** Narrow a {@link TenantSource} to its claim form. @group Models */
|
|
726
291
|
function isTenantClaimSource(source) {
|
|
727
292
|
return typeof source.claim === "string";
|
|
728
293
|
}
|
|
729
|
-
/** Narrow a {@link TenantSource} to its membership form. @group Models */
|
|
730
294
|
function isTenantMembershipSource(source) {
|
|
731
295
|
return typeof source.membership === "object" && source.membership !== null;
|
|
732
296
|
}
|
|
733
|
-
/**
|
|
734
|
-
* The roles tenancy does not apply to, when the collection names none.
|
|
735
|
-
*
|
|
736
|
-
* `admin`, mirroring the security baseline every collection already carries
|
|
737
|
-
* (`<table>_default_admin_read` / `_write`): the Studio, `dataAsAdmin` and a
|
|
738
|
-
* support operator all run with it, and a tenancy rule that locked them out
|
|
739
|
-
* would make the admin panel show an empty table on a collection full of rows.
|
|
740
|
-
*
|
|
741
|
-
* @group Models
|
|
742
|
-
*/
|
|
743
297
|
var DEFAULT_TENANT_BYPASS_ROLES = ["admin"];
|
|
744
298
|
//#endregion
|
|
745
299
|
//#region src/types/backend.ts
|
|
746
|
-
/**
|
|
747
|
-
* Type guard: can this admin plan a live schema change?
|
|
748
|
-
*
|
|
749
|
-
* Planning is engine-specific — it renders DDL, a Drizzle schema and the
|
|
750
|
-
* declarative SQL artifacts — so the implementation lives in the driver
|
|
751
|
-
* package. The server detects the capability structurally, exactly as it does
|
|
752
|
-
* for SQL, rather than importing an engine it is supposed to know nothing
|
|
753
|
-
* about.
|
|
754
|
-
*
|
|
755
|
-
* @group Admin
|
|
756
|
-
*/
|
|
757
300
|
function isSchemaEditingAdmin(admin) {
|
|
758
301
|
return !!admin && typeof admin.planSchemaChange === "function";
|
|
759
302
|
}
|
|
760
|
-
/**
|
|
761
|
-
* Type guard: does this admin support SQL operations?
|
|
762
|
-
* @group Admin
|
|
763
|
-
*/
|
|
764
303
|
function isSQLAdmin(admin) {
|
|
765
304
|
return !!admin && typeof admin.executeSql === "function";
|
|
766
305
|
}
|
|
767
|
-
/**
|
|
768
|
-
* Type guard: does this admin support schema management?
|
|
769
|
-
* @group Admin
|
|
770
|
-
*/
|
|
771
306
|
function isSchemaAdmin(admin) {
|
|
772
307
|
return !!admin && (typeof admin.fetchUnmappedTables === "function" || typeof admin.fetchTableMetadata === "function");
|
|
773
308
|
}
|
|
774
|
-
/**
|
|
775
|
-
* Type guard: does this admin support database branching?
|
|
776
|
-
* @group Admin
|
|
777
|
-
*/
|
|
778
309
|
function isBranchAdmin(admin) {
|
|
779
310
|
return !!admin && typeof admin.createBranch === "function";
|
|
780
311
|
}
|
|
781
312
|
//#endregion
|
|
782
313
|
//#region src/types/schema_editing.ts
|
|
783
|
-
/**
|
|
784
|
-
* The SQL `db push` and `db generate` render — `schema.sql`, `policies.sql` and
|
|
785
|
-
* the rest — is not here, and must not come back. Both commands regenerate it
|
|
786
|
-
* from the collections before reading it, so nothing ever read a committed
|
|
787
|
-
* copy; it lives in the gitignored `.rebase/sql/`. When the commit carried it,
|
|
788
|
-
* it carried a second copy besides: these paths are from the project root,
|
|
789
|
-
* while the CLI writes beside the backend, so a live edit left `drizzle/` and
|
|
790
|
-
* `backend/drizzle/` disagreeing about the schema.
|
|
791
|
-
*/
|
|
792
314
|
var DEFAULT_COMMIT_PATHS = { schemaFile: "backend/src/schema.generated.ts" };
|
|
793
315
|
//#endregion
|
|
794
316
|
//#region src/types/channel_bus.ts
|
|
795
|
-
/**
|
|
796
|
-
* Whether `setting` is an already-constructed transport rather than a request
|
|
797
|
-
* for a built-in one.
|
|
798
|
-
*
|
|
799
|
-
* Structural rather than nominal so that an instance from a *different copy* of
|
|
800
|
-
* `@rebasepro/types` — an entirely normal outcome of a separately versioned
|
|
801
|
-
* transport package — is still recognised.
|
|
802
|
-
*/
|
|
803
317
|
function isChannelBusInstance(setting) {
|
|
804
318
|
return typeof setting?.publish === "function";
|
|
805
319
|
}
|
|
806
320
|
//#endregion
|
|
807
321
|
//#region src/types/data_source.ts
|
|
808
|
-
/**
|
|
809
|
-
* The default data-source key, used when a collection does not name a
|
|
810
|
-
* `dataSource`. Shared by the frontend router and the backend driver
|
|
811
|
-
* registry so both agree on "the default database".
|
|
812
|
-
* @group Models
|
|
813
|
-
*/
|
|
814
322
|
var DEFAULT_DATA_SOURCE_KEY = "(default)";
|
|
815
|
-
/**
|
|
816
|
-
* Relation kinds assumed filterable when a driver does not say.
|
|
817
|
-
*
|
|
818
|
-
* `belongsTo` alone: its filter is a comparison on a column of the row being
|
|
819
|
-
* filtered, the one shape that needs no query construction a driver might not
|
|
820
|
-
* have. Everything else is a correlated subquery over another table.
|
|
821
|
-
*
|
|
822
|
-
* @group Models
|
|
823
|
-
*/
|
|
824
323
|
var DEFAULT_FILTERABLE_RELATION_KINDS = ["belongsTo"];
|
|
825
|
-
/** @group Models */
|
|
826
324
|
var POSTGRES_CAPABILITIES = {
|
|
827
325
|
key: "postgres",
|
|
828
326
|
label: "PostgreSQL",
|
|
@@ -845,7 +343,6 @@ var POSTGRES_CAPABILITIES = {
|
|
|
845
343
|
supportsSQLAdmin: true,
|
|
846
344
|
supportsSchemaAdmin: true
|
|
847
345
|
};
|
|
848
|
-
/** @group Models */
|
|
849
346
|
var FIREBASE_CAPABILITIES = {
|
|
850
347
|
key: "firestore",
|
|
851
348
|
label: "Firebase / Firestore",
|
|
@@ -863,11 +360,6 @@ var FIREBASE_CAPABILITIES = {
|
|
|
863
360
|
supportsSQLAdmin: false,
|
|
864
361
|
supportsSchemaAdmin: false
|
|
865
362
|
};
|
|
866
|
-
/**
|
|
867
|
-
* Fallback capabilities when the driver is unknown.
|
|
868
|
-
* Enables everything so nothing is hidden unexpectedly.
|
|
869
|
-
* @group Models
|
|
870
|
-
*/
|
|
871
363
|
var DEFAULT_CAPABILITIES = {
|
|
872
364
|
key: "(default)",
|
|
873
365
|
label: "Default",
|
|
@@ -890,13 +382,6 @@ var BUILT_IN_CAPABILITIES = /* @__PURE__ */ new Map([
|
|
|
890
382
|
["firestore", FIREBASE_CAPABILITIES],
|
|
891
383
|
["(default)", DEFAULT_CAPABILITIES]
|
|
892
384
|
]);
|
|
893
|
-
/**
|
|
894
|
-
* Capabilities registered at runtime, on `globalThis` rather than in a module
|
|
895
|
-
* local: a third-party driver inlines its own copy of this package and
|
|
896
|
-
* registers through it, while the app and the server read through theirs. A
|
|
897
|
-
* module local made the registration land in a copy nobody else reads.
|
|
898
|
-
* See `module-state-across-copies.test.ts`.
|
|
899
|
-
*/
|
|
900
385
|
var REGISTERED_CAPABILITIES_KEY = Symbol.for("@rebasepro/types.dataSourceCapabilities.v1");
|
|
901
386
|
function registeredCapabilities() {
|
|
902
387
|
const g = globalThis;
|
|
@@ -907,45 +392,23 @@ function registeredCapabilities() {
|
|
|
907
392
|
}
|
|
908
393
|
return registered;
|
|
909
394
|
}
|
|
910
|
-
/**
|
|
911
|
-
* Look up capabilities for a given engine key.
|
|
912
|
-
* If `engine` is undefined or not found, returns `DEFAULT_CAPABILITIES`.
|
|
913
|
-
* @group Models
|
|
914
|
-
*/
|
|
915
395
|
function getDataSourceCapabilities(engine) {
|
|
916
396
|
if (!engine) return POSTGRES_CAPABILITIES;
|
|
917
397
|
return registeredCapabilities().get(engine) ?? BUILT_IN_CAPABILITIES.get(engine) ?? DEFAULT_CAPABILITIES;
|
|
918
398
|
}
|
|
919
|
-
/**
|
|
920
|
-
* Register custom capabilities for a third-party driver.
|
|
921
|
-
* @group Models
|
|
922
|
-
*/
|
|
923
399
|
function registerDataSourceCapabilities(capabilities) {
|
|
924
400
|
registeredCapabilities().set(capabilities.key, capabilities);
|
|
925
401
|
}
|
|
926
402
|
//#endregion
|
|
927
403
|
//#region src/types/resources.ts
|
|
928
|
-
/** The key a resource takes when a project declares only one of its kind. */
|
|
929
404
|
var DEFAULT_RESOURCE_KEY = "(default)";
|
|
930
405
|
var BRAND = Symbol.for("@rebasepro/types.resource");
|
|
931
|
-
/** Whether a value is a resource handle rather than a plain string key. */
|
|
932
406
|
function isResourceHandle(value) {
|
|
933
407
|
return typeof value === "object" && value !== null && BRAND in value;
|
|
934
408
|
}
|
|
935
|
-
/** The key a resource reference names, whether it is a handle or already a key. */
|
|
936
409
|
function resourceKeyOf(ref) {
|
|
937
410
|
return isResourceHandle(ref) ? ref.key : ref;
|
|
938
411
|
}
|
|
939
|
-
/**
|
|
940
|
-
* Replace every resource handle inside a value with its key, deeply.
|
|
941
|
-
*
|
|
942
|
-
* Applied where authored config becomes data: `defineCollection`, the
|
|
943
|
-
* collection loaders, the derive step. Past that point a collection is plain
|
|
944
|
-
* data that serialises, compares with `===` and reaches the admin UI over the
|
|
945
|
-
* wire, so a handle must not survive into it. Plain objects and arrays are
|
|
946
|
-
* walked; anything else — a function, a Date, a class instance — is a leaf and
|
|
947
|
-
* is returned as it is, which is what keeps callbacks and validators intact.
|
|
948
|
-
*/
|
|
949
412
|
function resolveResourceRefs(value) {
|
|
950
413
|
if (isResourceHandle(value)) return value.key;
|
|
951
414
|
if (Array.isArray(value)) {
|
|
@@ -973,31 +436,6 @@ function resolveResourceRefs(value) {
|
|
|
973
436
|
return value;
|
|
974
437
|
}
|
|
975
438
|
var GLOBAL_KEY = Symbol.for("@rebasepro/types.resourceRegistry");
|
|
976
|
-
/**
|
|
977
|
-
* Where kinds live, versioned — and why the version is in the symbol.
|
|
978
|
-
*
|
|
979
|
-
* Sharing one kinds map across copies means the copy that registers SECOND is
|
|
980
|
-
* the one that runs the comparison. That copy is whatever the bundle happens to
|
|
981
|
-
* carry, which for a driver is a build of this package frozen at its release —
|
|
982
|
-
* so the rule enforced is the rule that shipped THEN, not the one written here.
|
|
983
|
-
*
|
|
984
|
-
* `revision` (390bb03cd, applied to `database` in 346df48e2) was supposed to
|
|
985
|
-
* settle a disagreement between two copies, and it settles it only when the
|
|
986
|
-
* copy doing the arithmetic knows what `revision` is. 0.17.0–0.17.3 do not:
|
|
987
|
-
* they deep-equal the spec and throw. The runtime registers at import and a
|
|
988
|
-
* driver is imported after it, so the old copy is always second, always the
|
|
989
|
-
* judge, and always throws — verified by the bundle corpus on 2026-09-07,
|
|
990
|
-
* which reported v0.17.3's message verbatim ("Two packages cannot define the
|
|
991
|
-
* same kind.", no revision clause) while the runtime it ran on was 0.18.
|
|
992
|
-
*
|
|
993
|
-
* So copies that understand `revision` keep their kinds here, under a symbol
|
|
994
|
-
* no released copy looks at, and the legacy map is left to whoever still wants
|
|
995
|
-
* it. An old copy then registers into a map nobody contests, finds no existing
|
|
996
|
-
* entry, and cannot throw — in any load order, which is what the previous fix
|
|
997
|
-
* only claimed. Bumping this suffix again is how a future change to the
|
|
998
|
-
* REGISTRATION PROTOCOL is made; a change to a kind's own definition is still
|
|
999
|
-
* `revision`, among peers that share this map.
|
|
1000
|
-
*/
|
|
1001
439
|
var KINDS_KEY = Symbol.for("@rebasepro/types.resourceKinds.v2");
|
|
1002
440
|
function registry() {
|
|
1003
441
|
const g = globalThis;
|
|
@@ -1020,16 +458,6 @@ function registry() {
|
|
|
1020
458
|
declarations: shared.declarations
|
|
1021
459
|
};
|
|
1022
460
|
}
|
|
1023
|
-
/**
|
|
1024
|
-
* Every kind visible to this copy: the versioned map, plus anything only a
|
|
1025
|
-
* legacy copy registered.
|
|
1026
|
-
*
|
|
1027
|
-
* The fallback is not for Rebase's own kinds — this copy defines all of those —
|
|
1028
|
-
* but for a third-party driver built against an older `@rebasepro/types` that
|
|
1029
|
-
* registers a kind of its own. Dropping it would make that kind invisible and
|
|
1030
|
-
* turn `declareResource` into "unknown resource kind" for something genuinely
|
|
1031
|
-
* registered.
|
|
1032
|
-
*/
|
|
1033
461
|
function visibleKinds() {
|
|
1034
462
|
const { kinds, legacyKinds } = registry();
|
|
1035
463
|
if (legacyKinds.size === 0) return kinds;
|
|
@@ -1038,19 +466,12 @@ function visibleKinds() {
|
|
|
1038
466
|
return merged;
|
|
1039
467
|
}
|
|
1040
468
|
var amendments = /* @__PURE__ */ new Map();
|
|
1041
|
-
/**
|
|
1042
|
-
* Correct a registered kind without touching its registered literal.
|
|
1043
|
-
*
|
|
1044
|
-
* Use this, never an edit to the literal, for a kind that has shipped in a
|
|
1045
|
-
* published package. The amendment applies to reads through this copy only.
|
|
1046
|
-
*/
|
|
1047
469
|
function amendResourceKind(kind, amendment) {
|
|
1048
470
|
amendments.set(kind, {
|
|
1049
471
|
...amendments.get(kind),
|
|
1050
472
|
...amendment
|
|
1051
473
|
});
|
|
1052
474
|
}
|
|
1053
|
-
/** A registered kind as this copy sees it: the shared literal plus this copy's amendments. */
|
|
1054
475
|
function effectiveKind(spec) {
|
|
1055
476
|
const amendment = amendments.get(spec.kind);
|
|
1056
477
|
return amendment ? {
|
|
@@ -1058,25 +479,9 @@ function effectiveKind(spec) {
|
|
|
1058
479
|
...amendment
|
|
1059
480
|
} : spec;
|
|
1060
481
|
}
|
|
1061
|
-
/** `kind:key`, the graph's primary key. */
|
|
1062
482
|
function declarationId(kind, key) {
|
|
1063
483
|
return `${kind}:${key}`;
|
|
1064
484
|
}
|
|
1065
|
-
/**
|
|
1066
|
-
* Register a resource kind.
|
|
1067
|
-
*
|
|
1068
|
-
* Idempotent for an identical spec. When a spec for the same kind is already
|
|
1069
|
-
* registered and differs, the `revision` decides: the higher one is kept and
|
|
1070
|
-
* the other copy is warned about, in either load order. Two different specs at
|
|
1071
|
-
* the SAME revision are a genuine conflict — two packages defining one kind, or
|
|
1072
|
-
* a change that forgot to bump — and still throw.
|
|
1073
|
-
*
|
|
1074
|
-
* Both copies in that comparison are peers on `KINDS_KEY`, which is what makes
|
|
1075
|
-
* the rule enforceable: a copy old enough not to know `revision` writes to the
|
|
1076
|
-
* legacy map instead and never reaches this function's arithmetic. Registering
|
|
1077
|
-
* a kind an older copy already put in the legacy map is therefore not a
|
|
1078
|
-
* conflict — it is the ordinary case, and `visibleKinds` prefers this one.
|
|
1079
|
-
*/
|
|
1080
485
|
function registerResourceKind(spec) {
|
|
1081
486
|
const kinds = registry().kinds;
|
|
1082
487
|
const existing = kinds.get(spec.kind);
|
|
@@ -1090,13 +495,11 @@ function registerResourceKind(spec) {
|
|
|
1090
495
|
if (have === incoming) throw new Error(`Resource kind "${spec.kind}" is already registered with a different definition at revision ${have}. Two packages cannot define the same kind; a newer definition of the same kind must carry a higher \`revision\`.`);
|
|
1091
496
|
const [kept, dropped] = incoming > have ? [spec, existing] : [existing, spec];
|
|
1092
497
|
if (kept === spec) kinds.set(spec.kind, spec);
|
|
1093
|
-
console.warn(`[resources] Resource kind "${spec.kind}" is registered twice, at revisions ${dropped.revision ?? 0} and ${kept.revision ?? 0}; keeping revision ${kept.revision ?? 0}. The older copy is usually @rebasepro/types inlined in a driver built before the kind changed
|
|
498
|
+
console.warn(`[resources] Resource kind "${spec.kind}" is registered twice, at revisions ${dropped.revision ?? 0} and ${kept.revision ?? 0}; keeping revision ${kept.revision ?? 0}. The older copy is usually @rebasepro/types inlined in a driver built before the kind changed \u2014 rebuild the project with a current driver to remove it.`);
|
|
1094
499
|
}
|
|
1095
|
-
/** Every registered kind, for validators and for `rebase doctor`. */
|
|
1096
500
|
function resourceKinds() {
|
|
1097
501
|
return [...visibleKinds().values()].map(effectiveKind);
|
|
1098
502
|
}
|
|
1099
|
-
/** One registered kind, or undefined. */
|
|
1100
503
|
function resourceKind(kind) {
|
|
1101
504
|
const spec = visibleKinds().get(kind);
|
|
1102
505
|
return spec && effectiveKind(spec);
|
|
@@ -1106,19 +509,9 @@ var COMMON_OPTION_KEYS = [
|
|
|
1106
509
|
"transport",
|
|
1107
510
|
"label"
|
|
1108
511
|
];
|
|
1109
|
-
/** Whether an engine is one the kind knows, or an explicit `custom:` opt-out. */
|
|
1110
512
|
function isValidEngine(spec, engine) {
|
|
1111
513
|
return engine.startsWith("custom:") || spec.engines.includes(engine);
|
|
1112
514
|
}
|
|
1113
|
-
/**
|
|
1114
|
-
* Declare a resource. The primitive every kind's constructor is built from.
|
|
1115
|
-
*
|
|
1116
|
-
* Redeclaring the same `kind:key` with a *different* shape throws rather than
|
|
1117
|
-
* merging. Merging is what the old storage path did, and it silently discarded
|
|
1118
|
-
* one of the two engines — a declaration accepted and then ignored, which is
|
|
1119
|
-
* the failure this whole model exists to remove. Redeclaring it identically is
|
|
1120
|
-
* fine: a config module evaluated twice must not be an error.
|
|
1121
|
-
*/
|
|
1122
515
|
function declareResource(kind, key = DEFAULT_RESOURCE_KEY, options = {}) {
|
|
1123
516
|
const spec = resourceKind(kind);
|
|
1124
517
|
if (!spec) {
|
|
@@ -1144,7 +537,7 @@ function declareResource(kind, key = DEFAULT_RESOURCE_KEY, options = {}) {
|
|
|
1144
537
|
const id = declarationId(kind, key);
|
|
1145
538
|
const previous = registry().declarations.get(id);
|
|
1146
539
|
if (previous) {
|
|
1147
|
-
if (JSON.stringify(previous) !== JSON.stringify(declaration)) throw new Error(`${kind} "${key}" is declared twice with different configuration. Declare it once and export it
|
|
540
|
+
if (JSON.stringify(previous) !== JSON.stringify(declaration)) throw new Error(`${kind} "${key}" is declared twice with different configuration. Declare it once and export it \u2014 two declarations of one resource is the ambiguity this model exists to remove, so it is refused rather than merged.`);
|
|
1148
541
|
} else registry().declarations.set(id, declaration);
|
|
1149
542
|
return {
|
|
1150
543
|
...declaration,
|
|
@@ -1154,40 +547,17 @@ function declareResource(kind, key = DEFAULT_RESOURCE_KEY, options = {}) {
|
|
|
1154
547
|
[BRAND]: true
|
|
1155
548
|
};
|
|
1156
549
|
}
|
|
1157
|
-
/** Every declared resource, in declaration order, optionally filtered by kind. */
|
|
1158
550
|
function declaredResources(kind) {
|
|
1159
551
|
const all = [...registry().declarations.values()];
|
|
1160
552
|
return kind ? all.filter((r) => r.kind === kind) : all;
|
|
1161
553
|
}
|
|
1162
|
-
/**
|
|
1163
|
-
* Forget every declaration, keeping registered kinds.
|
|
1164
|
-
*
|
|
1165
|
-
* For tests and for a CLI that evaluates more than one project in a process.
|
|
1166
|
-
* Kinds survive because they are registered by module import, which will not
|
|
1167
|
-
* happen a second time.
|
|
1168
|
-
*/
|
|
1169
554
|
function resetDeclaredResources() {
|
|
1170
555
|
registry().declarations.clear();
|
|
1171
556
|
}
|
|
1172
|
-
/**
|
|
1173
|
-
* The env-var suffix a resource's bindings use: `__ANALYTICS` for `analytics`,
|
|
1174
|
-
* and nothing at all for the default-keyed one.
|
|
1175
|
-
*
|
|
1176
|
-
* The default takes no suffix so that a project with one database configured
|
|
1177
|
-
* through plain `DATABASE_URL` keeps working having declared nothing — the
|
|
1178
|
-
* overwhelmingly common project must not have to say so.
|
|
1179
|
-
*/
|
|
1180
557
|
function resourceEnvSuffix(key) {
|
|
1181
558
|
if (key === "(default)") return "";
|
|
1182
559
|
return `__${key.toUpperCase().replace(/[^A-Z0-9]+/g, "_").replace(/^_+|_+$/g, "")}`;
|
|
1183
560
|
}
|
|
1184
|
-
/**
|
|
1185
|
-
* Two resources of a kind whose keys differ but whose env suffixes do not.
|
|
1186
|
-
*
|
|
1187
|
-
* `media-files` and `media_files` both become `__MEDIA_FILES`, so one would
|
|
1188
|
-
* silently read the other's configuration. Returned rather than thrown so the
|
|
1189
|
-
* caller can report it with the rest of a validation pass.
|
|
1190
|
-
*/
|
|
1191
561
|
function findEnvSuffixCollision(keys) {
|
|
1192
562
|
const seen = /* @__PURE__ */ new Map();
|
|
1193
563
|
for (const key of keys) {
|
|
@@ -1202,15 +572,7 @@ function findEnvSuffixCollision(keys) {
|
|
|
1202
572
|
}
|
|
1203
573
|
return null;
|
|
1204
574
|
}
|
|
1205
|
-
/** The current graph format version. */
|
|
1206
575
|
var RESOURCE_GRAPH_VERSION = 1;
|
|
1207
|
-
/**
|
|
1208
|
-
* Build a graph from the current declarations, sorted for a stable diff.
|
|
1209
|
-
*
|
|
1210
|
-
* `usedBy` maps a `kind:key` id to the things that reach it. The derive step
|
|
1211
|
-
* supplies it after evaluating collections; a runtime building the graph at
|
|
1212
|
-
* boot passes nothing and gets declarations alone, which is all it binds from.
|
|
1213
|
-
*/
|
|
1214
576
|
function buildResourceGraph(usedBy) {
|
|
1215
577
|
return {
|
|
1216
578
|
version: 1,
|
|
@@ -1223,17 +585,9 @@ function buildResourceGraph(usedBy) {
|
|
|
1223
585
|
})
|
|
1224
586
|
};
|
|
1225
587
|
}
|
|
1226
|
-
/** `kind:key`, the id `usedBy` maps are keyed by. Exported for the derive step. */
|
|
1227
588
|
function resourceId(kind, key) {
|
|
1228
589
|
return declarationId(kind, key);
|
|
1229
590
|
}
|
|
1230
|
-
/**
|
|
1231
|
-
* The environment variables worth writing for a resource, given its engine.
|
|
1232
|
-
*
|
|
1233
|
-
* Falls back to every base the kind reads when the engine is unknown — a
|
|
1234
|
-
* `custom:` engine gets the full list rather than an empty one, because
|
|
1235
|
-
* guessing narrow would silently omit the variable it actually needs.
|
|
1236
|
-
*/
|
|
1237
591
|
function envBasesForResource(declaration) {
|
|
1238
592
|
const spec = resourceKind(declaration.kind);
|
|
1239
593
|
if (!spec) return [];
|
|
@@ -1241,62 +595,13 @@ function envBasesForResource(declaration) {
|
|
|
1241
595
|
}
|
|
1242
596
|
//#endregion
|
|
1243
597
|
//#region src/types/storage_source.ts
|
|
1244
|
-
/**
|
|
1245
|
-
* Describes a named storage backend — a place files live.
|
|
1246
|
-
*
|
|
1247
|
-
* Declared once and shared front + back: the frontend uses it to decide
|
|
1248
|
-
* transport (HTTP proxy vs direct SDK), the backend uses the same `key`
|
|
1249
|
-
* to resolve a StorageController, and collection properties reference
|
|
1250
|
-
* a definition by its `key` via `StorageConfig.storageSource`.
|
|
1251
|
-
*
|
|
1252
|
-
* This mirrors the {@link DataSourceDefinition} pattern used for databases.
|
|
1253
|
-
*
|
|
1254
|
-
* @group Models
|
|
1255
|
-
*/
|
|
1256
|
-
/**
|
|
1257
|
-
* The default storage source key, used when a property does not specify
|
|
1258
|
-
* a `storageSource`. Shared by the frontend and backend registries so
|
|
1259
|
-
* both agree on "the default storage backend".
|
|
1260
|
-
* @group Models
|
|
1261
|
-
*/
|
|
1262
598
|
var DEFAULT_STORAGE_SOURCE_KEY = "(default)";
|
|
1263
|
-
/**
|
|
1264
|
-
* The environment-variable suffix for a storage or data source key.
|
|
1265
|
-
*
|
|
1266
|
-
* `""` for the default source — so a single-bucket project keeps configuring
|
|
1267
|
-
* plain `S3_BUCKET` — and `__<KEY>` for every named one, uppercased with
|
|
1268
|
-
* non-alphanumerics collapsed to underscores: `media-cdn` → `S3_BUCKET__MEDIA_CDN`.
|
|
1269
|
-
*
|
|
1270
|
-
* The rule derives the variable name from the declared key rather than
|
|
1271
|
-
* discovering keys by scanning the environment. Scanning would have to guess how
|
|
1272
|
-
* `S3_BUCKET__MEDIA_CDN` splits into a key; deriving cannot be ambiguous, and a
|
|
1273
|
-
* typo surfaces as a missing source at boot instead of a silently ignored
|
|
1274
|
-
* variable.
|
|
1275
|
-
*
|
|
1276
|
-
* It lives in this package, with no dependencies, because four things must agree
|
|
1277
|
-
* on it exactly: the CLI (validating a build), the runtime (reading its own
|
|
1278
|
-
* environment), the control plane (writing a tenant's Secret), and the docs. A
|
|
1279
|
-
* second implementation of a naming convention is a second chance to disagree.
|
|
1280
|
-
*
|
|
1281
|
-
* @group Models
|
|
1282
|
-
*/
|
|
1283
599
|
function storageEnvSuffix(key, defaultKey = DEFAULT_STORAGE_SOURCE_KEY) {
|
|
1284
600
|
if (!key || key === defaultKey) return "";
|
|
1285
601
|
const normalized = key.replace(/[^A-Za-z0-9]+/g, "_").replace(/^_+|_+$/g, "").toUpperCase();
|
|
1286
602
|
if (!normalized) throw new Error(`Source key "${key}" cannot be turned into an environment variable name. Use a key containing at least one letter or digit.`);
|
|
1287
603
|
return `__${normalized}`;
|
|
1288
604
|
}
|
|
1289
|
-
/**
|
|
1290
|
-
* Two distinct keys that collapse onto the same variable name, or `null`.
|
|
1291
|
-
*
|
|
1292
|
-
* `media-cdn` and `media_cdn` are different source keys but the same suffix, so
|
|
1293
|
-
* without this one of them silently reads the other's configuration. Returns the
|
|
1294
|
-
* offending pair rather than throwing, so each caller can raise it in its own
|
|
1295
|
-
* idiom — a `BundleError` at boot, a build failure in the CLI, a rejected deploy
|
|
1296
|
-
* in a control plane.
|
|
1297
|
-
*
|
|
1298
|
-
* @group Models
|
|
1299
|
-
*/
|
|
1300
605
|
function findStorageSuffixCollision(keys, defaultKey = DEFAULT_STORAGE_SOURCE_KEY) {
|
|
1301
606
|
const seen = /* @__PURE__ */ new Map();
|
|
1302
607
|
for (const key of keys) {
|
|
@@ -1313,19 +618,6 @@ function findStorageSuffixCollision(keys, defaultKey = DEFAULT_STORAGE_SOURCE_KE
|
|
|
1313
618
|
}
|
|
1314
619
|
//#endregion
|
|
1315
620
|
//#region src/types/resource_kinds.ts
|
|
1316
|
-
/**
|
|
1317
|
-
* The kinds Rebase ships, and the constructors a project declares them with.
|
|
1318
|
-
*
|
|
1319
|
-
* Each kind is registered rather than hardcoded, so a fourth one arrives
|
|
1320
|
-
* without editing a manifest schema, a validator and a switch statement. That
|
|
1321
|
-
* cost is precisely why databases and buckets ended up declared in different
|
|
1322
|
-
* files with different rules — the cheapest thing to do was always to bolt the
|
|
1323
|
-
* new kind onto whichever home was nearest.
|
|
1324
|
-
*
|
|
1325
|
-
* A kind owns its engine list. `custom:<id>` is always accepted, so a build
|
|
1326
|
-
* that ships an engine this package has never heard of says so at the call site
|
|
1327
|
-
* instead of looking like a typo of one that exists.
|
|
1328
|
-
*/
|
|
1329
621
|
registerResourceKind({
|
|
1330
622
|
revision: 1,
|
|
1331
623
|
kind: "database",
|
|
@@ -1370,18 +662,6 @@ amendResourceKind("database", {
|
|
|
1370
662
|
function database(keyOrOptions = DEFAULT_RESOURCE_KEY, options = {}) {
|
|
1371
663
|
return typeof keyOrOptions === "string" ? declareResource("database", keyOrOptions, options) : declareResource("database", DEFAULT_RESOURCE_KEY, keyOrOptions);
|
|
1372
664
|
}
|
|
1373
|
-
/**
|
|
1374
|
-
* The extensions the project's databases gave Rebase leave to install.
|
|
1375
|
-
*
|
|
1376
|
-
* A flat union rather than a per-database answer, because the surfaces that ask
|
|
1377
|
-
* — `rebase db push` and the boot schema-ensure — drive one connection and
|
|
1378
|
-
* generate one `schema.sql` for every collection regardless of `dataSource`.
|
|
1379
|
-
* Splitting the permission by data source would be a distinction the rest of
|
|
1380
|
-
* that pipeline does not make, and a false precision is worse than none.
|
|
1381
|
-
*
|
|
1382
|
-
* Empty for a project that declared nothing, which is every project that has
|
|
1383
|
-
* not opted in — so this reads as a refusal by default, on purpose.
|
|
1384
|
-
*/
|
|
1385
665
|
function declaredDatabaseExtensions() {
|
|
1386
666
|
const names = /* @__PURE__ */ new Set();
|
|
1387
667
|
for (const declaration of declaredResources("database")) {
|
|
@@ -1391,21 +671,10 @@ function declaredDatabaseExtensions() {
|
|
|
1391
671
|
}
|
|
1392
672
|
return [...names].sort();
|
|
1393
673
|
}
|
|
1394
|
-
/** The `rls` options a database declaration gave, `{}` when it gave none or was never declared. */
|
|
1395
674
|
function declaredDatabaseRls(key = DEFAULT_DATA_SOURCE_KEY) {
|
|
1396
675
|
const rls = declaredResources("database").find((d) => d.key === key)?.options.rls;
|
|
1397
676
|
return rls && typeof rls === "object" ? rls : {};
|
|
1398
677
|
}
|
|
1399
|
-
/**
|
|
1400
|
-
* The policy settings every compile path must agree on — the boot's policy
|
|
1401
|
-
* ensure, `rebase db generate`, the drift check — read from the one place all
|
|
1402
|
-
* of them can see: the database declaration, with `REBASE_RLS_POLICY_TARGET` /
|
|
1403
|
-
* `REBASE_RLS_ADMIN_POLICIES` / `REBASE_RLS_DEFAULT_POLICIES` over it. Defaults
|
|
1404
|
-
* are what Rebase compiled before these existed, except `adminPolicies`, whose
|
|
1405
|
-
* default (`"adminRole"`) changed what the server-or-admin policies are `TO`.
|
|
1406
|
-
*
|
|
1407
|
-
* Browser-safe: where there is no `process`, only the declaration counts.
|
|
1408
|
-
*/
|
|
1409
678
|
function declaredRlsPolicyShape(dataSource = DEFAULT_DATA_SOURCE_KEY) {
|
|
1410
679
|
const declared = declaredDatabaseRls(dataSource);
|
|
1411
680
|
const env = typeof process !== "undefined" ? process.env : void 0;
|
|
@@ -1514,26 +783,6 @@ registerResourceKind({
|
|
|
1514
783
|
implicitDefault: false
|
|
1515
784
|
});
|
|
1516
785
|
amendResourceKind("topic", { envBases: [] });
|
|
1517
|
-
/**
|
|
1518
|
-
* Declared handlers and installed runtimes, for topics and queues — on
|
|
1519
|
-
* `globalThis` under a shared symbol, never in module locals.
|
|
1520
|
-
*
|
|
1521
|
-
* A module local is one per COPY of this package, and two copies in one
|
|
1522
|
-
* process is the normal layout rather than an accident: `@rebasepro/server`
|
|
1523
|
-
* inlines this package into its own dist, while `config/resources.ts` imports
|
|
1524
|
-
* it from `node_modules`. With locals, a project's `.handler()` and
|
|
1525
|
-
* `.subscription()` went into the project's copy and the worker read the
|
|
1526
|
-
* server's empty one (`Job queue started {"tasks":0}`), and the runtime the
|
|
1527
|
-
* server installed was invisible to the project's `enqueue`/`publish` — so
|
|
1528
|
-
* every queue and topic threw "no runtime is installed" inside a running
|
|
1529
|
-
* backend. The CLI deriving the graph had the same split. Same mechanism and
|
|
1530
|
-
* reasoning as `registry()` in resources.ts; `module-state-across-copies.test.ts`
|
|
1531
|
-
* loads two copies to hold it, and scans for any other module-level state that
|
|
1532
|
-
* would split the same way.
|
|
1533
|
-
*
|
|
1534
|
-
* The version is in the symbol: a change to this object's SHAPE takes a new
|
|
1535
|
-
* suffix, so no copy ever reads a shape it does not know.
|
|
1536
|
-
*/
|
|
1537
786
|
var WORK_KEY = Symbol.for("@rebasepro/types.workRegistry.v1");
|
|
1538
787
|
function work() {
|
|
1539
788
|
const g = globalThis;
|
|
@@ -1549,48 +798,21 @@ function work() {
|
|
|
1549
798
|
}
|
|
1550
799
|
return shared;
|
|
1551
800
|
}
|
|
1552
|
-
/**
|
|
1553
|
-
* Where `@rebasepro/server` publishes its client once it has booted (its
|
|
1554
|
-
* `singleton.ts`). Read only to tell the two causes of a missing runtime apart.
|
|
1555
|
-
*/
|
|
1556
801
|
var SERVER_INSTANCE_SLOT = Symbol.for("@rebasepro/server:singleton-instance");
|
|
1557
|
-
/**
|
|
1558
|
-
* Why there is no runtime to send through, as far as this process can tell.
|
|
1559
|
-
*
|
|
1560
|
-
* Outside a backend — the CLI evaluating config, a script, a unit test — the
|
|
1561
|
-
* answer is that there is nothing to deliver to. Inside one it is not: the
|
|
1562
|
-
* backend installs a runtime at boot for what `config/resources.ts` declared,
|
|
1563
|
-
* so a missing one there means boot never saw the declaration, or the backend
|
|
1564
|
-
* carries a copy of this package too old to share the slot it installs into.
|
|
1565
|
-
* Saying "outside a backend" to somebody whose backend is running sends them
|
|
1566
|
-
* looking for the wrong thing.
|
|
1567
|
-
*/
|
|
1568
802
|
function missingRuntimeCause(kind) {
|
|
1569
803
|
if (!(globalThis[SERVER_INSTANCE_SLOT] != null)) return "This works inside a running Rebase backend; this looks like code running outside one (a build, a script, or a test without a harness).";
|
|
1570
|
-
return `A Rebase backend is running in this process but installed no ${kind} runtime. It installs one at boot when config/resources.ts declares a ${kind}, so either this ${kind} is declared somewhere boot does not read, or the backend's copy of @rebasepro/types predates the shared runtime slot this copy reads
|
|
804
|
+
return `A Rebase backend is running in this process but installed no ${kind} runtime. It installs one at boot when config/resources.ts declares a ${kind}, so either this ${kind} is declared somewhere boot does not read, or the backend's copy of @rebasepro/types predates the shared runtime slot this copy reads \u2014 keep @rebasepro/server and @rebasepro/types on the same version.`;
|
|
1571
805
|
}
|
|
1572
|
-
/** Install the transport topics publish through. Called by the server at boot. */
|
|
1573
806
|
function setTopicRuntime(runtime) {
|
|
1574
807
|
work().topicRuntime = runtime;
|
|
1575
808
|
}
|
|
1576
|
-
/** Every declared subscription, for the worker to wire and the graph to record. */
|
|
1577
809
|
function declaredSubscriptions(topic) {
|
|
1578
810
|
const { subscriptions } = work();
|
|
1579
811
|
return topic ? subscriptions.filter((s) => s.topic === topic) : subscriptions.slice();
|
|
1580
812
|
}
|
|
1581
|
-
/** Forget declared subscriptions. For tests, alongside `resetDeclaredResources`. */
|
|
1582
813
|
function resetDeclaredSubscriptions() {
|
|
1583
814
|
work().subscriptions.length = 0;
|
|
1584
815
|
}
|
|
1585
|
-
/**
|
|
1586
|
-
* Declare a topic.
|
|
1587
|
-
*
|
|
1588
|
-
* ```ts
|
|
1589
|
-
* export const signups = topic<{ userId: string }>("signups");
|
|
1590
|
-
* signups.subscription("send-welcome", async (event) => { … });
|
|
1591
|
-
* await signups.publish({ userId });
|
|
1592
|
-
* ```
|
|
1593
|
-
*/
|
|
1594
816
|
function topic(key, options = {}) {
|
|
1595
817
|
if (options.delivery === "at-most-once") throw new Error(`Topic "${key}" asks for at-most-once delivery, which no shipped transport implements. The durable queue behind topics retries, so it is at-least-once and a handler must tolerate seeing an event twice. Refused rather than quietly given the other guarantee.`);
|
|
1596
818
|
return {
|
|
@@ -1631,17 +853,8 @@ registerResourceKind({
|
|
|
1631
853
|
],
|
|
1632
854
|
implicitDefault: false
|
|
1633
855
|
});
|
|
1634
|
-
/**
|
|
1635
|
-
* Declare a cron, as the scheduler's `defineCron` does on its way through.
|
|
1636
|
-
*
|
|
1637
|
-
* Projects do not call this: `defineCron` in `@rebasepro/server` does, so a
|
|
1638
|
-
* cron file is both the handler and the declaration — one file, one name, and
|
|
1639
|
-
* the graph derived from it says what a host needs to know without evaluating
|
|
1640
|
-
* the handler. Exported so the derive step and the scheduler spell the
|
|
1641
|
-
* declaration identically.
|
|
1642
|
-
*/
|
|
1643
856
|
function declareCron(name, options) {
|
|
1644
|
-
if (typeof options.schedule !== "string" || options.schedule.trim() === "") throw new Error(`Cron "${name}" needs a schedule
|
|
857
|
+
if (typeof options.schedule !== "string" || options.schedule.trim() === "") throw new Error(`Cron "${name}" needs a schedule \u2014 a five-field cron expression such as "0 3 * * *".`);
|
|
1645
858
|
return declareResource("cron", name, options);
|
|
1646
859
|
}
|
|
1647
860
|
registerResourceKind({
|
|
@@ -1656,7 +869,6 @@ registerResourceKind({
|
|
|
1656
869
|
],
|
|
1657
870
|
implicitDefault: false
|
|
1658
871
|
});
|
|
1659
|
-
/** Declare a function. Called by the derive step, not by projects. */
|
|
1660
872
|
function declareFunction(name, options = {}) {
|
|
1661
873
|
return declareResource("function", name, options);
|
|
1662
874
|
}
|
|
@@ -1668,31 +880,15 @@ registerResourceKind({
|
|
|
1668
880
|
optionKeys: ["maxAttempts"],
|
|
1669
881
|
implicitDefault: false
|
|
1670
882
|
});
|
|
1671
|
-
/** Install the transport queues enqueue through. Called by the server at boot. */
|
|
1672
883
|
function setQueueRuntime(runtime) {
|
|
1673
884
|
work().queueRuntime = runtime;
|
|
1674
885
|
}
|
|
1675
|
-
/** Every declared queue handler, for the worker to wire. */
|
|
1676
886
|
function declaredQueueConsumers() {
|
|
1677
887
|
return [...work().queueConsumers.values()];
|
|
1678
888
|
}
|
|
1679
|
-
/** Forget declared queue handlers. For tests, alongside `resetDeclaredResources`. */
|
|
1680
889
|
function resetDeclaredQueueConsumers() {
|
|
1681
890
|
work().queueConsumers.clear();
|
|
1682
891
|
}
|
|
1683
|
-
/**
|
|
1684
|
-
* Declare a queue.
|
|
1685
|
-
*
|
|
1686
|
-
* ```ts
|
|
1687
|
-
* export const thumbnails = queue<{ key: string }>("thumbnails");
|
|
1688
|
-
* thumbnails.handler(async ({ key }) => { … });
|
|
1689
|
-
* await thumbnails.enqueue({ key }, { runAt: new Date(Date.now() + 60_000) });
|
|
1690
|
-
* ```
|
|
1691
|
-
*
|
|
1692
|
-
* The difference from a topic is the number of consumers: a queue has one, a
|
|
1693
|
-
* topic fans out to every subscription. Both ride on the durable job queue, so
|
|
1694
|
-
* declaring either turns it on.
|
|
1695
|
-
*/
|
|
1696
892
|
function queue(key, options = {}) {
|
|
1697
893
|
return {
|
|
1698
894
|
...declareResource("queue", key, options),
|
|
@@ -1714,21 +910,6 @@ function queue(key, options = {}) {
|
|
|
1714
910
|
}
|
|
1715
911
|
};
|
|
1716
912
|
}
|
|
1717
|
-
/**
|
|
1718
|
-
* One declaration, as the data layer's definition.
|
|
1719
|
-
*
|
|
1720
|
-
* There is exactly one of these per kind, and everything that needs a
|
|
1721
|
-
* definition goes through it — the frontend, the managed runtime's boot path,
|
|
1722
|
-
* and an ejected project's own entrypoint. That is not tidiness: the mapping
|
|
1723
|
-
* used to exist twice, once here and once in `@rebasepro/server`'s
|
|
1724
|
-
* `graphToStorageSources`, and the two disagreed. The server's copy carried a
|
|
1725
|
-
* bucket's `account`; this one dropped it, so a bucket declared with shared
|
|
1726
|
-
* credentials resolved them on the managed runtime and resolved *nothing* in an
|
|
1727
|
-
* ejected backend — the source was skipped and every upload to it answered 501.
|
|
1728
|
-
*
|
|
1729
|
-
* A field-by-field map is one line away from that failure at all times, so
|
|
1730
|
-
* there is now one line to keep right instead of two to keep equal.
|
|
1731
|
-
*/
|
|
1732
913
|
function resourceToDataSource(declaration) {
|
|
1733
914
|
return {
|
|
1734
915
|
key: declaration.key === "(default)" ? DEFAULT_DATA_SOURCE_KEY : declaration.key,
|
|
@@ -1738,7 +919,6 @@ function resourceToDataSource(declaration) {
|
|
|
1738
919
|
...declaration.label !== void 0 ? { label: declaration.label } : {}
|
|
1739
920
|
};
|
|
1740
921
|
}
|
|
1741
|
-
/** One declaration, as the storage layer's definition. See {@link resourceToDataSource}. */
|
|
1742
922
|
function resourceToStorageSource(declaration) {
|
|
1743
923
|
return {
|
|
1744
924
|
key: declaration.key === "(default)" ? DEFAULT_STORAGE_SOURCE_KEY : declaration.key,
|
|
@@ -1750,12 +930,6 @@ function resourceToStorageSource(declaration) {
|
|
|
1750
930
|
...declaration.label !== void 0 ? { label: declaration.label } : {}
|
|
1751
931
|
};
|
|
1752
932
|
}
|
|
1753
|
-
/**
|
|
1754
|
-
* A bucket's `orphanSweep` option as a definition carries it: `true` is the
|
|
1755
|
-
* defaults, an object keeps only the fields of the right type. The runtime
|
|
1756
|
-
* checks the values (the grace-period floor, the schedule) and refuses a bad
|
|
1757
|
-
* one loudly; this only refuses to invent one.
|
|
1758
|
-
*/
|
|
1759
933
|
function orphanSweepOf(option) {
|
|
1760
934
|
if (option === true) return { orphanSweep: {} };
|
|
1761
935
|
if (!option || typeof option !== "object") return {};
|
|
@@ -1765,31 +939,9 @@ function orphanSweepOf(option) {
|
|
|
1765
939
|
...typeof schedule === "string" ? { schedule } : {}
|
|
1766
940
|
} };
|
|
1767
941
|
}
|
|
1768
|
-
/**
|
|
1769
|
-
* The declared databases, as definitions.
|
|
1770
|
-
*
|
|
1771
|
-
* Both the frontend and a project's own backend entrypoint read this. The
|
|
1772
|
-
* frontend needs to know which sources exist and how they are reached — a
|
|
1773
|
-
* `direct`-transport source is one the browser talks to itself — and it imports
|
|
1774
|
-
* the same config package the backend does. Without these it would mean writing
|
|
1775
|
-
* the list a second time, by hand, next to the declarations, which is precisely
|
|
1776
|
-
* the two-homes problem this model removed everywhere else.
|
|
1777
|
-
*
|
|
1778
|
-
* ```tsx
|
|
1779
|
-
* import "../config/resources"; // registers them
|
|
1780
|
-
* import { declaredDataSources, declaredStorageSources } from "@rebasepro/types";
|
|
1781
|
-
*
|
|
1782
|
-
* <Rebase dataSources={declaredDataSources()} storageSources={declaredStorageSources()} />
|
|
1783
|
-
* ```
|
|
1784
|
-
*
|
|
1785
|
-
* The import is what registers them, so a bundler that drops an unused module
|
|
1786
|
-
* would leave this empty — hence the side-effect import above rather than a
|
|
1787
|
-
* bare re-export.
|
|
1788
|
-
*/
|
|
1789
942
|
function declaredDataSources() {
|
|
1790
943
|
return declaredResources("database").map(resourceToDataSource);
|
|
1791
944
|
}
|
|
1792
|
-
/** The declared buckets, as definitions. */
|
|
1793
945
|
function declaredStorageSources() {
|
|
1794
946
|
return declaredResources("bucket").map(resourceToStorageSource);
|
|
1795
947
|
}
|
|
@@ -1807,40 +959,6 @@ var NO = /* @__PURE__ */ new Set([
|
|
|
1807
959
|
"no",
|
|
1808
960
|
"off"
|
|
1809
961
|
]);
|
|
1810
|
-
/**
|
|
1811
|
-
* Read a boolean environment variable — one spelling rule for every reader.
|
|
1812
|
-
*
|
|
1813
|
-
* `true`, `1`, `yes` and `on` are true; `false`, `0`, `no` and `off` are
|
|
1814
|
-
* false. Case and surrounding whitespace are ignored. Anything else — unset,
|
|
1815
|
-
* blank, or a value that spells neither — is `undefined`, so the caller's
|
|
1816
|
-
* default decides and a typo lands on the side the caller chose:
|
|
1817
|
-
*
|
|
1818
|
-
* ```ts
|
|
1819
|
-
* parseEnvBoolean(env.FORCE_LOCAL_STORAGE) === true // off unless said
|
|
1820
|
-
* parseEnvBoolean(env.REBASE_MCP_OPEN_REGISTRATION) !== false // on unless said
|
|
1821
|
-
* ```
|
|
1822
|
-
*
|
|
1823
|
-
* It exists because every reader used to spell this itself, and they
|
|
1824
|
-
* disagreed. The reader that mattered tested the raw string for truthiness —
|
|
1825
|
-
* `!process.env.FORCE_LOCAL_STORAGE` — and every non-empty string is truthy,
|
|
1826
|
-
* so `FORCE_LOCAL_STORAGE=false`, written to say "there is no durable volume
|
|
1827
|
-
* here", switched the production storage guard off and sent uploads to a
|
|
1828
|
-
* container filesystem the next redeploy erased. Beside it, `=== "true"` made
|
|
1829
|
-
* `DISABLE_DB_ROLE_SWITCHING=1` do nothing and `!== "false"` made
|
|
1830
|
-
* `REBASE_MCP_OPEN_REGISTRATION=0` leave registration open.
|
|
1831
|
-
*
|
|
1832
|
-
* The boot schemas in `@rebasepro/server` (`loadEnv`, `loadBootEnv`) accept a
|
|
1833
|
-
* strict subset — `true`, `false` and blank — and refuse any other value
|
|
1834
|
-
* before the server starts. On that subset they read exactly what this reads,
|
|
1835
|
-
* so a variable a schema declares and something else reads lazily cannot mean
|
|
1836
|
-
* two different things.
|
|
1837
|
-
*
|
|
1838
|
-
* It lives in this package, with no dependencies, for the reason
|
|
1839
|
-
* {@link storageEnvSuffix} does: the runtime, its drivers and the CLI all read
|
|
1840
|
-
* these variables, and a second parser is a second chance to disagree.
|
|
1841
|
-
*
|
|
1842
|
-
* @group Models
|
|
1843
|
-
*/
|
|
1844
962
|
function parseEnvBoolean(value) {
|
|
1845
963
|
if (value === void 0) return void 0;
|
|
1846
964
|
const spelled = value.trim().toLowerCase();
|
|
@@ -1849,81 +967,12 @@ function parseEnvBoolean(value) {
|
|
|
1849
967
|
}
|
|
1850
968
|
//#endregion
|
|
1851
969
|
//#region src/types/auth_adapter.ts
|
|
1852
|
-
/**
|
|
1853
|
-
* The request header that asks for a data-plane request to run as another
|
|
1854
|
-
* user, named by uid.
|
|
1855
|
-
*
|
|
1856
|
-
* The server honours it only on a signed-in administrator's own session —
|
|
1857
|
-
* never on an API key or the service key — and only through an adapter that
|
|
1858
|
-
* implements {@link AuthAdapter.resolveUser}. Everywhere else a request that
|
|
1859
|
-
* carries it is refused, never run as its caller.
|
|
1860
|
-
*
|
|
1861
|
-
* @group Auth
|
|
1862
|
-
*/
|
|
1863
970
|
var IMPERSONATE_HEADER = "x-rebase-impersonate";
|
|
1864
|
-
/**
|
|
1865
|
-
* The request header a client sends to the auth routes to say where it keeps
|
|
1866
|
-
* its refresh token. `json` asks for the token in the response body, and has
|
|
1867
|
-
* the token it presents read from the request body.
|
|
1868
|
-
*
|
|
1869
|
-
* It matters only on a server with `cookieAuth`, which otherwise puts the
|
|
1870
|
-
* token in an HttpOnly cookie and answers the body's with `""`, so a client
|
|
1871
|
-
* with no cookie jar (Node, React Native), or one that keeps its own sign-in
|
|
1872
|
-
* apart from the page's cookie session, held nothing to renew with. A request
|
|
1873
|
-
* that sends it is answered as a server without `cookieAuth` answers: the
|
|
1874
|
-
* cookie is neither read nor set. So it can never turn a cookie the page's
|
|
1875
|
-
* script cannot read into a token it can.
|
|
1876
|
-
*
|
|
1877
|
-
* `@rebasepro/client` sends it on every auth request in `authFlowMode: "json"`.
|
|
1878
|
-
*
|
|
1879
|
-
* @group Auth
|
|
1880
|
-
*/
|
|
1881
971
|
var AUTH_FLOW_HEADER = "x-rebase-auth-flow";
|
|
1882
|
-
/**
|
|
1883
|
-
* The request header that asks for a data-plane request to run as a role —
|
|
1884
|
-
* the RLS simulator's "view as". Alone it runs as a signed-in holder of that
|
|
1885
|
-
* role who owns no rows; with {@link SIMULATE_USER_ID_HEADER} it runs as that
|
|
1886
|
-
* uid holding that role, whether or not such an account exists.
|
|
1887
|
-
*
|
|
1888
|
-
* `anon` (or `anonymous`) runs as a caller with no session at all.
|
|
1889
|
-
*
|
|
1890
|
-
* Like {@link IMPERSONATE_HEADER}, only a signed-in administrator's own session
|
|
1891
|
-
* may send it; anyone else is refused with 403, never answered as themselves.
|
|
1892
|
-
*
|
|
1893
|
-
* @group Auth
|
|
1894
|
-
*/
|
|
1895
972
|
var SIMULATE_ROLE_HEADER = "x-rebase-simulate-role";
|
|
1896
|
-
/**
|
|
1897
|
-
* The uid a simulated request runs as. With {@link SIMULATE_ROLE_HEADER} it is
|
|
1898
|
-
* a hypothetical — "u_1 holding customer" — and need not name an account;
|
|
1899
|
-
* without it, the uid must be an active user and runs with their roles now.
|
|
1900
|
-
*
|
|
1901
|
-
* @group Auth
|
|
1902
|
-
*/
|
|
1903
973
|
var SIMULATE_USER_ID_HEADER = "x-rebase-simulate-user-id";
|
|
1904
|
-
/**
|
|
1905
|
-
* The id of a service API key a simulated request runs as: the key's identity,
|
|
1906
|
-
* its RLS roles and its scopes, exactly as a request presenting the key would.
|
|
1907
|
-
* Excludes the other two simulation headers.
|
|
1908
|
-
*
|
|
1909
|
-
* @group Auth
|
|
1910
|
-
*/
|
|
1911
974
|
var SIMULATE_API_KEY_ID_HEADER = "x-rebase-simulate-api-key-id";
|
|
1912
|
-
/**
|
|
1913
|
-
* The response header naming what a simulated request ran as:
|
|
1914
|
-
* `role=<role>;sub=<uid>;masked_columns=<a,b>`, plus `api_key=<id>` and
|
|
1915
|
-
* `collection=<slug>` when they apply. Every value is URI-encoded. Read it
|
|
1916
|
-
* with {@link parseSimulatedContext}.
|
|
1917
|
-
*
|
|
1918
|
-
* @group Auth
|
|
1919
|
-
*/
|
|
1920
975
|
var SIMULATED_CONTEXT_HEADER = "x-rebase-simulated-context";
|
|
1921
|
-
/**
|
|
1922
|
-
* The request headers for an {@link AccessSimulation}. Empty when it asks for
|
|
1923
|
-
* nothing, so spreading it into a header set is always safe.
|
|
1924
|
-
*
|
|
1925
|
-
* @group Auth
|
|
1926
|
-
*/
|
|
1927
976
|
function simulationHeaders(simulation) {
|
|
1928
977
|
if (!simulation) return {};
|
|
1929
978
|
const headers = {};
|
|
@@ -1932,11 +981,6 @@ function simulationHeaders(simulation) {
|
|
|
1932
981
|
if (simulation.apiKeyId) headers[SIMULATE_API_KEY_ID_HEADER] = simulation.apiKeyId;
|
|
1933
982
|
return headers;
|
|
1934
983
|
}
|
|
1935
|
-
/**
|
|
1936
|
-
* Write a {@link SimulatedContext} as the header value.
|
|
1937
|
-
*
|
|
1938
|
-
* @group Auth
|
|
1939
|
-
*/
|
|
1940
984
|
function formatSimulatedContext(context) {
|
|
1941
985
|
const parts = [
|
|
1942
986
|
`role=${encodeURIComponent(context.role)}`,
|
|
@@ -1947,12 +991,6 @@ function formatSimulatedContext(context) {
|
|
|
1947
991
|
if (context.collection) parts.push(`collection=${encodeURIComponent(context.collection)}`);
|
|
1948
992
|
return parts.join(";");
|
|
1949
993
|
}
|
|
1950
|
-
/**
|
|
1951
|
-
* Read {@link SIMULATED_CONTEXT_HEADER}. `undefined` for an absent header or one
|
|
1952
|
-
* missing `role` or `sub`.
|
|
1953
|
-
*
|
|
1954
|
-
* @group Auth
|
|
1955
|
-
*/
|
|
1956
994
|
function parseSimulatedContext(value) {
|
|
1957
995
|
if (!value) return void 0;
|
|
1958
996
|
const fields = /* @__PURE__ */ new Map();
|
|
@@ -1983,37 +1021,6 @@ function parseSimulatedContext(value) {
|
|
|
1983
1021
|
}
|
|
1984
1022
|
//#endregion
|
|
1985
1023
|
//#region src/types/scopes.ts
|
|
1986
|
-
/**
|
|
1987
|
-
* Scopes — what a credential may do, named `resource:action`.
|
|
1988
|
-
*
|
|
1989
|
-
* One vocabulary for every way of reaching a Rebase backend: a person's
|
|
1990
|
-
* session, a service key, a personal key and an OAuth token for `/mcp` all
|
|
1991
|
-
* answer "may this caller do X?" with the same strings, so a grant reads the
|
|
1992
|
-
* same on a key, on a role and on a consent screen.
|
|
1993
|
-
*
|
|
1994
|
-
* A scope may carry a target — `data:read:posts` is `data:read` on the `posts`
|
|
1995
|
-
* collection only. The unqualified scope covers every target. Only the data
|
|
1996
|
-
* plane and app scopes take targets; see {@link SCOPE_TARGETS}.
|
|
1997
|
-
*
|
|
1998
|
-
* Two planes, held differently:
|
|
1999
|
-
*
|
|
2000
|
-
* - **The data plane** (`data:*`, `storage:*`, `functions:invoke`). Every
|
|
2001
|
-
* signed-in person holds all of it, because what a person may do with data
|
|
2002
|
-
* is decided row by row by the collection's `securityRules` and by storage
|
|
2003
|
-
* policies, never by a scope. On a key or a token these scopes narrow: a key
|
|
2004
|
-
* holding `data:read:posts` reaches nothing else, whatever RLS would allow.
|
|
2005
|
-
* - **The admin plane** (everything else). Nobody holds it implicitly. The
|
|
2006
|
-
* `admin` role holds all of it; any other role holds what the app declares
|
|
2007
|
-
* for it under `auth.roles` on the users collection.
|
|
2008
|
-
*
|
|
2009
|
-
* Apps declare their own scopes too (`auth.scopes`), named the same way —
|
|
2010
|
-
* `project:deploy`. Every signed-in person holds every app scope: like the data
|
|
2011
|
-
* plane, the function behind it decides whether the person may act, and the
|
|
2012
|
-
* scope exists so a key can be narrowed to that one action.
|
|
2013
|
-
*
|
|
2014
|
-
* @module
|
|
2015
|
-
*/
|
|
2016
|
-
/** @group Auth */
|
|
2017
1024
|
var DATA_PLANE_SCOPES = [
|
|
2018
1025
|
"data:read",
|
|
2019
1026
|
"data:write",
|
|
@@ -2023,7 +1030,6 @@ var DATA_PLANE_SCOPES = [
|
|
|
2023
1030
|
"storage:delete",
|
|
2024
1031
|
"functions:invoke"
|
|
2025
1032
|
];
|
|
2026
|
-
/** @group Auth */
|
|
2027
1033
|
var ADMIN_SCOPES = [
|
|
2028
1034
|
"users:read",
|
|
2029
1035
|
"users:write",
|
|
@@ -2038,29 +1044,9 @@ var ADMIN_SCOPES = [
|
|
|
2038
1044
|
"keys:read",
|
|
2039
1045
|
"keys:write"
|
|
2040
1046
|
];
|
|
2041
|
-
/** Every scope Rebase itself defines, in display order. @group Auth */
|
|
2042
1047
|
var BUILT_IN_SCOPES = [...DATA_PLANE_SCOPES, ...ADMIN_SCOPES];
|
|
2043
|
-
/**
|
|
2044
|
-
* Scopes no key may hold.
|
|
2045
|
-
*
|
|
2046
|
-
* A key that could manage keys could mint its own successor, widen itself, or
|
|
2047
|
-
* revoke the keys other integrations run on — and revoking it would undo none
|
|
2048
|
-
* of that. Managing keys is for a person (or the service key).
|
|
2049
|
-
*
|
|
2050
|
-
* @group Auth
|
|
2051
|
-
*/
|
|
2052
1048
|
var KEY_MANAGEMENT_SCOPES = ["keys:read", "keys:write"];
|
|
2053
|
-
/** The one built-in role. It holds every scope and is the RLS `admin` role. @group Auth */
|
|
2054
1049
|
var ADMIN_ROLE = "admin";
|
|
2055
|
-
/**
|
|
2056
|
-
* The built-in scopes that accept a target, and what the target names.
|
|
2057
|
-
*
|
|
2058
|
-
* - `data:*` — a collection slug
|
|
2059
|
-
* - `storage:*` — a storage source id (`(default)` for the default source)
|
|
2060
|
-
* - `functions:invoke` — a custom function's name
|
|
2061
|
-
*
|
|
2062
|
-
* @group Auth
|
|
2063
|
-
*/
|
|
2064
1050
|
var SCOPE_TARGETS = {
|
|
2065
1051
|
"data:read": "collection",
|
|
2066
1052
|
"data:write": "collection",
|
|
@@ -2070,7 +1056,6 @@ var SCOPE_TARGETS = {
|
|
|
2070
1056
|
"storage:delete": "bucket",
|
|
2071
1057
|
"functions:invoke": "function"
|
|
2072
1058
|
};
|
|
2073
|
-
/** @group Auth */
|
|
2074
1059
|
var BUILT_IN_SCOPE_DESCRIPTIONS = {
|
|
2075
1060
|
"data:read": {
|
|
2076
1061
|
label: "Read data",
|
|
@@ -2126,7 +1111,7 @@ var BUILT_IN_SCOPE_DESCRIPTIONS = {
|
|
|
2126
1111
|
},
|
|
2127
1112
|
"backups:read": {
|
|
2128
1113
|
label: "Download backups",
|
|
2129
|
-
description: "List and download database backups
|
|
1114
|
+
description: "List and download database backups \u2014 every row, outside row-level security."
|
|
2130
1115
|
},
|
|
2131
1116
|
"cron:read": {
|
|
2132
1117
|
label: "See cron jobs",
|
|
@@ -2149,20 +1134,11 @@ var BUILT_IN_SCOPE_DESCRIPTIONS = {
|
|
|
2149
1134
|
description: "Create, change and revoke the project's service keys. Never grantable to a key."
|
|
2150
1135
|
}
|
|
2151
1136
|
};
|
|
2152
|
-
/** The access model of an app that declares nothing: built-ins only. @group Auth */
|
|
2153
1137
|
var EMPTY_ACCESS_MODEL = {
|
|
2154
1138
|
roles: {},
|
|
2155
1139
|
scopes: {}
|
|
2156
1140
|
};
|
|
2157
1141
|
var SCOPE_PART = /^[a-z][a-z0-9-]*$/;
|
|
2158
|
-
/**
|
|
2159
|
-
* Split `resource:action[:target]`. Returns null for anything else.
|
|
2160
|
-
*
|
|
2161
|
-
* The target is everything after the second colon, so a target may itself
|
|
2162
|
-
* contain colons. Resource and action are lower-case words.
|
|
2163
|
-
*
|
|
2164
|
-
* @group Auth
|
|
2165
|
-
*/
|
|
2166
1142
|
function parseScope(value) {
|
|
2167
1143
|
if (typeof value !== "string") return null;
|
|
2168
1144
|
const first = value.indexOf(":");
|
|
@@ -2179,50 +1155,24 @@ function parseScope(value) {
|
|
|
2179
1155
|
target
|
|
2180
1156
|
};
|
|
2181
1157
|
}
|
|
2182
|
-
/** @group Auth */
|
|
2183
1158
|
function isBuiltInScope(scope) {
|
|
2184
1159
|
return BUILT_IN_SCOPES.includes(scope);
|
|
2185
1160
|
}
|
|
2186
|
-
/** @group Auth */
|
|
2187
1161
|
function isDataPlaneScope(scope) {
|
|
2188
1162
|
return DATA_PLANE_SCOPES.includes(scope);
|
|
2189
1163
|
}
|
|
2190
|
-
/** @group Auth */
|
|
2191
1164
|
function isAdminScope(scope) {
|
|
2192
1165
|
return ADMIN_SCOPES.includes(scope);
|
|
2193
1166
|
}
|
|
2194
|
-
/** Does this list of roles include the built-in `admin` role? @group Auth */
|
|
2195
1167
|
function hasAdminRole(roles) {
|
|
2196
1168
|
return !!roles?.includes(ADMIN_ROLE);
|
|
2197
1169
|
}
|
|
2198
|
-
/**
|
|
2199
|
-
* Why `name` cannot be written as a role, or `undefined` when it can.
|
|
2200
|
-
*
|
|
2201
|
-
* No naming pattern is imposed — an app may call its roles anything. What is
|
|
2202
|
-
* refused is a name that would be read back as *other* roles: a role travels as
|
|
2203
|
-
* one element of a Postgres `text[]` and as one entry of the comma-joined
|
|
2204
|
-
* `app.user_roles` setting that RLS policies split with
|
|
2205
|
-
* `string_to_array(…, ',')`. Written as `"support,admin"`, a role comes back as
|
|
2206
|
-
* `admin`; braces, quotes and backslashes are array-literal syntax, so they are
|
|
2207
|
-
* refused too, as are empty names and control characters.
|
|
2208
|
-
*
|
|
2209
|
-
* @group Auth
|
|
2210
|
-
*/
|
|
2211
1170
|
function roleNameProblem(name) {
|
|
2212
1171
|
if (typeof name !== "string") return "is not a string";
|
|
2213
1172
|
if (name.trim() === "") return "is empty";
|
|
2214
1173
|
if (/[,{}"\\]/.test(name)) return "contains , { } \" or \\";
|
|
2215
1174
|
if (/[\u0000-\u001f\u007f]/.test(name)) return "contains a control character";
|
|
2216
1175
|
}
|
|
2217
|
-
/**
|
|
2218
|
-
* Does a set of held scopes grant `scope`, optionally on one `target`?
|
|
2219
|
-
*
|
|
2220
|
-
* The unqualified grant covers every target. A qualified grant covers its own
|
|
2221
|
-
* target only, and never answers an unqualified question: a key holding
|
|
2222
|
-
* `data:read:posts` is not asked "may you read data?" and told yes.
|
|
2223
|
-
*
|
|
2224
|
-
* @group Auth
|
|
2225
|
-
*/
|
|
2226
1176
|
function scopeGrants(held, scope, target) {
|
|
2227
1177
|
for (const entry of held) {
|
|
2228
1178
|
if (entry === scope) return true;
|
|
@@ -2230,24 +1180,10 @@ function scopeGrants(held, scope, target) {
|
|
|
2230
1180
|
}
|
|
2231
1181
|
return false;
|
|
2232
1182
|
}
|
|
2233
|
-
/**
|
|
2234
|
-
* Does a set of held scopes grant `scope` on at least one target?
|
|
2235
|
-
*
|
|
2236
|
-
* For a surface that lists what is reachable — the collections an MCP client
|
|
2237
|
-
* may query — and filters per item afterwards.
|
|
2238
|
-
*
|
|
2239
|
-
* @group Auth
|
|
2240
|
-
*/
|
|
2241
1183
|
function scopeGrantsAny(held, scope) {
|
|
2242
1184
|
const prefix = `${scope}:`;
|
|
2243
1185
|
return held.some((entry) => entry === scope || entry.startsWith(prefix));
|
|
2244
1186
|
}
|
|
2245
|
-
/**
|
|
2246
|
-
* The targets a held set narrows `scope` to: `"all"` when it holds the
|
|
2247
|
-
* unqualified scope, otherwise the listed targets (possibly none).
|
|
2248
|
-
*
|
|
2249
|
-
* @group Auth
|
|
2250
|
-
*/
|
|
2251
1187
|
function scopeTargets(held, scope) {
|
|
2252
1188
|
const prefix = `${scope}:`;
|
|
2253
1189
|
const targets = [];
|
|
@@ -2257,15 +1193,6 @@ function scopeTargets(held, scope) {
|
|
|
2257
1193
|
}
|
|
2258
1194
|
return targets;
|
|
2259
1195
|
}
|
|
2260
|
-
/**
|
|
2261
|
-
* Every scope a person holding `roles` has.
|
|
2262
|
-
*
|
|
2263
|
-
* The data plane and every app scope always; the whole admin plane with the
|
|
2264
|
-
* `admin` role; otherwise each declared role's scopes. A role nobody declared
|
|
2265
|
-
* adds nothing — it may still mean something to an RLS policy.
|
|
2266
|
-
*
|
|
2267
|
-
* @group Auth
|
|
2268
|
-
*/
|
|
2269
1196
|
function scopesForRoles(roles, model = EMPTY_ACCESS_MODEL) {
|
|
2270
1197
|
const held = /* @__PURE__ */ new Set([...DATA_PLANE_SCOPES, ...Object.keys(model.scopes)]);
|
|
2271
1198
|
if (hasAdminRole(roles)) {
|
|
@@ -2278,26 +1205,13 @@ function scopesForRoles(roles, model = EMPTY_ACCESS_MODEL) {
|
|
|
2278
1205
|
}
|
|
2279
1206
|
return [...held];
|
|
2280
1207
|
}
|
|
2281
|
-
/**
|
|
2282
|
-
* Every scope this access model knows, unqualified: the built-ins, then the
|
|
2283
|
-
* app's own.
|
|
2284
|
-
*
|
|
2285
|
-
* @group Auth
|
|
2286
|
-
*/
|
|
2287
1208
|
function knownScopes(model = EMPTY_ACCESS_MODEL) {
|
|
2288
1209
|
return [...BUILT_IN_SCOPES, ...Object.keys(model.scopes)];
|
|
2289
1210
|
}
|
|
2290
|
-
/** Does this scope accept a target? @group Auth */
|
|
2291
1211
|
function scopeAcceptsTarget(scope, model = EMPTY_ACCESS_MODEL) {
|
|
2292
1212
|
if (isBuiltInScope(scope)) return SCOPE_TARGETS[scope] !== void 0;
|
|
2293
1213
|
return (Object.prototype.hasOwnProperty.call(model.scopes, scope) ? model.scopes[scope] : void 0)?.target !== void 0;
|
|
2294
1214
|
}
|
|
2295
|
-
/**
|
|
2296
|
-
* Check a list of scope strings against an access model. Returns the
|
|
2297
|
-
* problems, empty when every entry is a known scope with an acceptable target.
|
|
2298
|
-
*
|
|
2299
|
-
* @group Auth
|
|
2300
|
-
*/
|
|
2301
1215
|
function validateScopes(values, model = EMPTY_ACCESS_MODEL) {
|
|
2302
1216
|
const known = new Set(knownScopes(model));
|
|
2303
1217
|
const problems = [];
|
|
@@ -2319,15 +1233,6 @@ function validateScopes(values, model = EMPTY_ACCESS_MODEL) {
|
|
|
2319
1233
|
}
|
|
2320
1234
|
return problems;
|
|
2321
1235
|
}
|
|
2322
|
-
/**
|
|
2323
|
-
* The entries of `requested` that `held` does not cover — what a credential
|
|
2324
|
-
* would hold beyond its minter. Empty means the request is within reach.
|
|
2325
|
-
*
|
|
2326
|
-
* `data:read:posts` is covered by `data:read`; `data:read` is not covered by
|
|
2327
|
-
* `data:read:posts`.
|
|
2328
|
-
*
|
|
2329
|
-
* @group Auth
|
|
2330
|
-
*/
|
|
2331
1236
|
function scopesBeyond(requested, held) {
|
|
2332
1237
|
return requested.filter((entry) => {
|
|
2333
1238
|
const parsed = parseScope(entry);
|
|
@@ -2335,23 +1240,10 @@ function scopesBeyond(requested, held) {
|
|
|
2335
1240
|
return !scopeGrants(held, parsed.scope, parsed.target);
|
|
2336
1241
|
});
|
|
2337
1242
|
}
|
|
2338
|
-
/**
|
|
2339
|
-
* Narrow `requested` to what `held` covers, entry by entry. What a personal
|
|
2340
|
-
* key holds today when its owner has lost a role since it was minted.
|
|
2341
|
-
*
|
|
2342
|
-
* @group Auth
|
|
2343
|
-
*/
|
|
2344
1243
|
function intersectScopes(requested, held) {
|
|
2345
1244
|
const beyond = new Set(scopesBeyond(requested, held));
|
|
2346
1245
|
return requested.filter((entry) => !beyond.has(entry));
|
|
2347
1246
|
}
|
|
2348
|
-
/**
|
|
2349
|
-
* How a scope is worded for a person: the built-in description, the app's
|
|
2350
|
-
* declared label, or the raw string when nothing describes it. A target is
|
|
2351
|
-
* named after the label.
|
|
2352
|
-
*
|
|
2353
|
-
* @group Auth
|
|
2354
|
-
*/
|
|
2355
1247
|
function describeScope(value, model = EMPTY_ACCESS_MODEL) {
|
|
2356
1248
|
const parsed = parseScope(value);
|
|
2357
1249
|
if (!parsed) return {
|
|
@@ -2373,7 +1265,6 @@ function describeScope(value, model = EMPTY_ACCESS_MODEL) {
|
|
|
2373
1265
|
description: base?.description ?? ""
|
|
2374
1266
|
};
|
|
2375
1267
|
}
|
|
2376
|
-
/** The roles of an access model, `admin` first. @group Auth */
|
|
2377
1268
|
function summarizeRoles(model = EMPTY_ACCESS_MODEL) {
|
|
2378
1269
|
return [{
|
|
2379
1270
|
id: ADMIN_ROLE,
|
|
@@ -2389,7 +1280,6 @@ function summarizeRoles(model = EMPTY_ACCESS_MODEL) {
|
|
|
2389
1280
|
builtIn: false
|
|
2390
1281
|
}))];
|
|
2391
1282
|
}
|
|
2392
|
-
/** Every scope of an access model, described, in display order. @group Auth */
|
|
2393
1283
|
function summarizeScopes(model = EMPTY_ACCESS_MODEL) {
|
|
2394
1284
|
const builtIn = BUILT_IN_SCOPES.map((scope) => ({
|
|
2395
1285
|
scope,
|
|
@@ -2408,21 +1298,16 @@ function summarizeScopes(model = EMPTY_ACCESS_MODEL) {
|
|
|
2408
1298
|
}
|
|
2409
1299
|
//#endregion
|
|
2410
1300
|
//#region src/types/project_manifest.ts
|
|
2411
|
-
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
|
|
2415
|
-
|
|
2416
|
-
|
|
2417
|
-
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
* checks it so a developer finds out while editing `rebase.json`; the control
|
|
2422
|
-
* plane checks it again at deploy intake, because the front door's correctness
|
|
2423
|
-
* cannot rest on a check that ran in somebody else's CLI — and a repository can
|
|
2424
|
-
* be deployed by a CLI older than this rule.
|
|
2425
|
-
*/
|
|
1301
|
+
var STATIC_REDIRECT_STATUSES = [
|
|
1302
|
+
301,
|
|
1303
|
+
302,
|
|
1304
|
+
307,
|
|
1305
|
+
308
|
|
1306
|
+
];
|
|
1307
|
+
var DEFAULT_STATIC_REDIRECT_STATUS = 308;
|
|
1308
|
+
function isStaticRedirectStatus(value) {
|
|
1309
|
+
return STATIC_REDIRECT_STATUSES.some((status) => status === value);
|
|
1310
|
+
}
|
|
2426
1311
|
var RESERVED_BACKEND_PREFIXES = [
|
|
2427
1312
|
"/api",
|
|
2428
1313
|
"/health",
|
|
@@ -2431,36 +1316,15 @@ var RESERVED_BACKEND_PREFIXES = [
|
|
|
2431
1316
|
"/readyz",
|
|
2432
1317
|
"/metrics"
|
|
2433
1318
|
];
|
|
2434
|
-
/**
|
|
2435
|
-
* Whether `path` collides with a prefix the backend owns.
|
|
2436
|
-
*
|
|
2437
|
-
* Compares at segment boundaries, so `/api` and `/api/v2` collide while
|
|
2438
|
-
* `/apidocs` does not — the same rule the router matches with, because a check
|
|
2439
|
-
* that is stricter than the router rejects paths that would have worked, and one
|
|
2440
|
-
* that is looser admits paths that will not.
|
|
2441
|
-
*/
|
|
2442
1319
|
function reservedPrefixFor(path) {
|
|
2443
1320
|
const normalized = path.endsWith("/") && path !== "/" ? path.slice(0, -1) : path;
|
|
2444
1321
|
return RESERVED_BACKEND_PREFIXES.find((reserved) => normalized === reserved || normalized.startsWith(`${reserved}/`));
|
|
2445
1322
|
}
|
|
2446
|
-
/**
|
|
2447
|
-
* Split a static app's declared `path` into the hostname it claims and the path
|
|
2448
|
-
* under it.
|
|
2449
|
-
*
|
|
2450
|
-
* `"/admin"` is `{ path: "/admin" }`, returned as written: the path rules
|
|
2451
|
-
* (leading slash, no `..`, reserved prefixes) belong to the caller, which
|
|
2452
|
-
* applies them to the path part of either form. `"https://admin.example.com/cms"`
|
|
2453
|
-
* is `{ host: "admin.example.com", path: "/cms" }`.
|
|
2454
|
-
*
|
|
2455
|
-
* Shared because three parties must read the same value the same way: the CLI
|
|
2456
|
-
* while `rebase.json` is edited, the control plane at deploy intake (a bundle can
|
|
2457
|
-
* come from any CLI, or none), and the runtime choosing which app answers.
|
|
2458
|
-
*/
|
|
2459
1323
|
function parseAppAddress(value) {
|
|
2460
1324
|
if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) {
|
|
2461
1325
|
if (!value.startsWith("/") && isValidAppHost(value.toLowerCase().replace(/\/.*$/, ""))) return {
|
|
2462
1326
|
ok: false,
|
|
2463
|
-
reason: `looks like a hostname
|
|
1327
|
+
reason: `looks like a hostname \u2014 write it as a URL: "https://${value}"`
|
|
2464
1328
|
};
|
|
2465
1329
|
return {
|
|
2466
1330
|
ok: true,
|
|
@@ -2474,7 +1338,7 @@ function parseAppAddress(value) {
|
|
|
2474
1338
|
const authority = value.slice(value.indexOf("//") + 2).split(/[/?#]/)[0];
|
|
2475
1339
|
if (/:[^@]*$/.test(authority) && !authority.startsWith("[")) return {
|
|
2476
1340
|
ok: false,
|
|
2477
|
-
reason: "must not name a port
|
|
1341
|
+
reason: "must not name a port \u2014 a hostname is served on 443"
|
|
2478
1342
|
};
|
|
2479
1343
|
let url;
|
|
2480
1344
|
try {
|
|
@@ -2487,7 +1351,7 @@ function parseAppAddress(value) {
|
|
|
2487
1351
|
}
|
|
2488
1352
|
if (url.protocol !== "https:") return {
|
|
2489
1353
|
ok: false,
|
|
2490
|
-
reason: `must use https
|
|
1354
|
+
reason: `must use https \u2014 the platform serves every hostname over TLS: "https://${url.host}${url.pathname === "/" ? "" : url.pathname}"`
|
|
2491
1355
|
};
|
|
2492
1356
|
if (url.username || url.password) return {
|
|
2493
1357
|
ok: false,
|
|
@@ -2495,7 +1359,7 @@ function parseAppAddress(value) {
|
|
|
2495
1359
|
};
|
|
2496
1360
|
if (url.port) return {
|
|
2497
1361
|
ok: false,
|
|
2498
|
-
reason: "must not name a port
|
|
1362
|
+
reason: "must not name a port \u2014 a hostname is served on 443"
|
|
2499
1363
|
};
|
|
2500
1364
|
if (url.search || url.hash || /[?#]/.test(value)) return {
|
|
2501
1365
|
ok: false,
|
|
@@ -2515,11 +1379,6 @@ function parseAppAddress(value) {
|
|
|
2515
1379
|
}
|
|
2516
1380
|
};
|
|
2517
1381
|
}
|
|
2518
|
-
/**
|
|
2519
|
-
* Whether `host` is a public DNS name an app can be given: lowercase labels of
|
|
2520
|
-
* letters, digits and hyphens, at least two of them, not an IP address and not
|
|
2521
|
-
* `localhost`. Internationalised names arrive here already in punycode.
|
|
2522
|
-
*/
|
|
2523
1382
|
function isValidAppHost(host) {
|
|
2524
1383
|
if (host.length === 0 || host.length > 253 || host !== host.toLowerCase()) return false;
|
|
2525
1384
|
const labels = host.split(".");
|
|
@@ -2528,39 +1387,12 @@ function isValidAppHost(host) {
|
|
|
2528
1387
|
if (!labels.every((part) => label.test(part))) return false;
|
|
2529
1388
|
return !/^[0-9]+$/.test(labels[labels.length - 1]);
|
|
2530
1389
|
}
|
|
2531
|
-
/** Whether `path` is `parent`, or a path beneath it, at segment boundaries. */
|
|
2532
1390
|
function isPathUnder(path, parent) {
|
|
2533
1391
|
if (parent === "/") return true;
|
|
2534
1392
|
return path === parent || path.startsWith(`${parent}/`);
|
|
2535
1393
|
}
|
|
2536
|
-
/**
|
|
2537
|
-
* The characters a route's path may hold: unreserved and sub-delimiters, `:`,
|
|
2538
|
-
* `@` and `/`. A request path arrives percent-encoded and is matched as it
|
|
2539
|
-
* arrives, so a route written with a space, a `%` or a non-ASCII letter could
|
|
2540
|
-
* never match anything.
|
|
2541
|
-
*/
|
|
2542
1394
|
var ROUTE_PATH_CHARACTERS = /^\/[A-Za-z0-9\-._~!$&'()+,;=:@/]*$/;
|
|
2543
|
-
/** A function's name as it appears in `/api/functions/<name>`: one path segment. */
|
|
2544
1395
|
var FUNCTION_NAME = /^[A-Za-z0-9_-][A-Za-z0-9_.-]*$/;
|
|
2545
|
-
/**
|
|
2546
|
-
* Validate one of a static app's routes against the app's own path (the path
|
|
2547
|
-
* part of its address).
|
|
2548
|
-
*
|
|
2549
|
-
* Shared for the reason {@link parseAppAddress} is: the CLI checks a route
|
|
2550
|
-
* while `rebase.json` is edited, and the runtime checks it again when it loads
|
|
2551
|
-
* a bundle, which any program could have written. The rules:
|
|
2552
|
-
*
|
|
2553
|
-
* - `path` is absolute, with no `..`, empty segment or trailing slash, and
|
|
2554
|
-
* ends in `/*` or holds no `*` at all.
|
|
2555
|
-
* - No segment starts with a dot: `/.well-known` is the backend's, and a
|
|
2556
|
-
* static app serves no dot-file.
|
|
2557
|
-
* - It is not under a prefix the backend owns ({@link RESERVED_BACKEND_PREFIXES}),
|
|
2558
|
-
* because the API answers there on every hostname.
|
|
2559
|
-
* - It is inside the app's path, since the app is what answers there, and a
|
|
2560
|
-
* wildcard does not cover the whole app, which would leave nothing of the
|
|
2561
|
-
* build to serve.
|
|
2562
|
-
* - `function` is one path segment, as a function's file name is.
|
|
2563
|
-
*/
|
|
2564
1396
|
function validateStaticRoute(value, appPath) {
|
|
2565
1397
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return {
|
|
2566
1398
|
ok: false,
|
|
@@ -2582,7 +1414,7 @@ function validateStaticRoute(value, appPath) {
|
|
|
2582
1414
|
if (!ROUTE_PATH_CHARACTERS.test(prefix)) return {
|
|
2583
1415
|
ok: false,
|
|
2584
1416
|
field: "path",
|
|
2585
|
-
reason: "may hold letters, digits, \"/\" and - . _ ~ ! $ & ' ( ) + , ; = : @ only
|
|
1417
|
+
reason: "may hold letters, digits, \"/\" and - . _ ~ ! $ & ' ( ) + , ; = : @ only \u2014 no spaces, \"?\", \"#\" or \"%\""
|
|
2586
1418
|
};
|
|
2587
1419
|
if (prefix.includes("//") || prefix !== "/" && prefix.endsWith("/")) return {
|
|
2588
1420
|
ok: false,
|
|
@@ -2592,18 +1424,18 @@ function validateStaticRoute(value, appPath) {
|
|
|
2592
1424
|
if (prefix.split("/").some((segment) => segment.startsWith("."))) return {
|
|
2593
1425
|
ok: false,
|
|
2594
1426
|
field: "path",
|
|
2595
|
-
reason: "must have no segment starting with \".\"
|
|
1427
|
+
reason: "must have no segment starting with \".\" \u2014 an app serves no dot-file; for /.well-known, put the file in the .well-known/ folder of the build and the app at \"/\" serves it"
|
|
2596
1428
|
};
|
|
2597
1429
|
const reserved = reservedPrefixFor(prefix);
|
|
2598
1430
|
if (reserved) return {
|
|
2599
1431
|
ok: false,
|
|
2600
1432
|
field: "path",
|
|
2601
|
-
reason: `cannot be "${reserved}" or nest under it
|
|
1433
|
+
reason: `cannot be "${reserved}" or nest under it \u2014 the backend serves that path on every hostname`
|
|
2602
1434
|
};
|
|
2603
1435
|
if (!isPathUnder(prefix, appPath)) return {
|
|
2604
1436
|
ok: false,
|
|
2605
1437
|
field: "path",
|
|
2606
|
-
reason: `must be inside this app's path, "${appPath}"
|
|
1438
|
+
reason: `must be inside this app's path, "${appPath}" \u2014 the app is what answers there`
|
|
2607
1439
|
};
|
|
2608
1440
|
if (wildcard && prefix === appPath) return {
|
|
2609
1441
|
ok: false,
|
|
@@ -2623,14 +1455,6 @@ function validateStaticRoute(value, appPath) {
|
|
|
2623
1455
|
}
|
|
2624
1456
|
};
|
|
2625
1457
|
}
|
|
2626
|
-
/**
|
|
2627
|
-
* Whether `route` answers `requestPath`, and with what path under its
|
|
2628
|
-
* function: `""` for the route's own path, `/rest` beneath a wildcard.
|
|
2629
|
-
* `undefined` when it does not match.
|
|
2630
|
-
*
|
|
2631
|
-
* Compared as the path arrives, percent-encoding and all, and at segment
|
|
2632
|
-
* boundaries: `/blog/*` matches `/blog` and `/blog/x`, not `/blogroll`.
|
|
2633
|
-
*/
|
|
2634
1458
|
function matchStaticRoute(route, requestPath) {
|
|
2635
1459
|
if (!route.path.endsWith("/*")) return requestPath === route.path ? "" : void 0;
|
|
2636
1460
|
const prefix = route.path.slice(0, -2);
|
|
@@ -2638,36 +1462,332 @@ function matchStaticRoute(route, requestPath) {
|
|
|
2638
1462
|
if (requestPath === prefix) return "";
|
|
2639
1463
|
return requestPath.startsWith(`${prefix}/`) ? requestPath.slice(prefix.length) : void 0;
|
|
2640
1464
|
}
|
|
2641
|
-
/**
|
|
2642
|
-
* Order routes so the first match is the most specific: exact paths first,
|
|
2643
|
-
* then wildcards by the length of their prefix, longest first. Declaration
|
|
2644
|
-
* order breaks ties, which only equal wildcards can have.
|
|
2645
|
-
*/
|
|
2646
1465
|
function compareStaticRoutes(a, b) {
|
|
2647
1466
|
const aWild = a.path.endsWith("/*");
|
|
2648
1467
|
if (aWild !== b.path.endsWith("/*")) return aWild ? 1 : -1;
|
|
2649
1468
|
return aWild ? b.path.length - a.path.length : 0;
|
|
2650
1469
|
}
|
|
2651
|
-
|
|
1470
|
+
var REDIRECT_PARAM_SEGMENT = /^:([A-Za-z_][A-Za-z0-9_]*)(\*)?$/;
|
|
1471
|
+
var REDIRECT_PARAM_IN_TO = /(\/)?:([A-Za-z_][A-Za-z0-9_]*)(\*)?/g;
|
|
1472
|
+
var REDIRECT_LITERAL_FORBIDDEN = /[?#\\*:\s\u0000-\u001f\u007f]/;
|
|
1473
|
+
function encodePathSegment(segment) {
|
|
1474
|
+
return new URL(`http://h/${segment}`).pathname.slice(1);
|
|
1475
|
+
}
|
|
1476
|
+
function parseRedirectFrom(from) {
|
|
1477
|
+
if (from === "/") return {
|
|
1478
|
+
ok: true,
|
|
1479
|
+
segments: []
|
|
1480
|
+
};
|
|
1481
|
+
if (from.startsWith("//")) return {
|
|
1482
|
+
ok: false,
|
|
1483
|
+
reason: "must be a path, not a URL without its scheme \u2014 match a hostname with \"host\""
|
|
1484
|
+
};
|
|
1485
|
+
const parts = from.slice(1).split("/");
|
|
1486
|
+
if (parts.some((part) => part === "")) return {
|
|
1487
|
+
ok: false,
|
|
1488
|
+
reason: "must have no empty segment and no trailing slash \u2014 a request's trailing slash is ignored anyway"
|
|
1489
|
+
};
|
|
1490
|
+
const segments = [];
|
|
1491
|
+
const names = /* @__PURE__ */ new Set();
|
|
1492
|
+
for (const [index, part] of parts.entries()) {
|
|
1493
|
+
if (part.startsWith(":")) {
|
|
1494
|
+
const param = REDIRECT_PARAM_SEGMENT.exec(part);
|
|
1495
|
+
if (!param) return {
|
|
1496
|
+
ok: false,
|
|
1497
|
+
reason: `has "${part}", which is not a parameter: write ":name" for one segment or ":name*" for the rest of the path`
|
|
1498
|
+
};
|
|
1499
|
+
const [, name, star] = param;
|
|
1500
|
+
if (star && index !== parts.length - 1) return {
|
|
1501
|
+
ok: false,
|
|
1502
|
+
reason: `has ":${name}*" before its last segment \u2014 a parameter matching the rest of the path comes last`
|
|
1503
|
+
};
|
|
1504
|
+
if (names.has(name)) return {
|
|
1505
|
+
ok: false,
|
|
1506
|
+
reason: `names ":${name}" twice`
|
|
1507
|
+
};
|
|
1508
|
+
names.add(name);
|
|
1509
|
+
segments.push({
|
|
1510
|
+
kind: "param",
|
|
1511
|
+
name,
|
|
1512
|
+
rest: Boolean(star)
|
|
1513
|
+
});
|
|
1514
|
+
continue;
|
|
1515
|
+
}
|
|
1516
|
+
if (part.startsWith(".")) return {
|
|
1517
|
+
ok: false,
|
|
1518
|
+
reason: "must have no segment starting with \".\" \u2014 an app serves no dot-file; for /.well-known, put the file in the .well-known/ folder of the build and the app at \"/\" serves it"
|
|
1519
|
+
};
|
|
1520
|
+
if (REDIRECT_LITERAL_FORBIDDEN.test(part)) return {
|
|
1521
|
+
ok: false,
|
|
1522
|
+
reason: `has "${part}", which holds a space, "?", "#", "\\", "*" or ":" \u2014 a ":" starts a parameter, which is a whole segment, and a query is matched with "query"`
|
|
1523
|
+
};
|
|
1524
|
+
const encoded = encodePathSegment(part);
|
|
1525
|
+
if (encoded === "") return {
|
|
1526
|
+
ok: false,
|
|
1527
|
+
reason: `has "${part}", which is "." or ".." written with escapes \u2014 a request never arrives with one`
|
|
1528
|
+
};
|
|
1529
|
+
segments.push({
|
|
1530
|
+
kind: "literal",
|
|
1531
|
+
value: encoded
|
|
1532
|
+
});
|
|
1533
|
+
}
|
|
1534
|
+
return {
|
|
1535
|
+
ok: true,
|
|
1536
|
+
segments
|
|
1537
|
+
};
|
|
1538
|
+
}
|
|
1539
|
+
function literalPrefixOf(segments) {
|
|
1540
|
+
const literals = [];
|
|
1541
|
+
for (const segment of segments) {
|
|
1542
|
+
if (segment.kind !== "literal") break;
|
|
1543
|
+
literals.push(segment.value);
|
|
1544
|
+
}
|
|
1545
|
+
return `/${literals.join("/")}`;
|
|
1546
|
+
}
|
|
1547
|
+
function compileStaticRedirect(redirect) {
|
|
1548
|
+
const parsed = parseRedirectFrom(redirect.from);
|
|
1549
|
+
if (!parsed.ok) throw new Error(`Redirect from ${JSON.stringify(redirect.from)} ${parsed.reason}.`);
|
|
1550
|
+
const names = [];
|
|
1551
|
+
let body = "";
|
|
1552
|
+
for (const segment of parsed.segments) if (segment.kind === "literal") body += `/${segment.value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`;
|
|
1553
|
+
else {
|
|
1554
|
+
names.push(segment.name);
|
|
1555
|
+
body += segment.rest ? "(?:/([^/]+(?:/[^/]+)*))?" : "/([^/]+)";
|
|
1556
|
+
}
|
|
1557
|
+
const pattern = new RegExp(`^${body}/?$`);
|
|
1558
|
+
const status = redirect.status ?? 308;
|
|
1559
|
+
const conditions = Object.entries(redirect.query ?? {});
|
|
1560
|
+
const absolute = /^https?:\/\//i.test(redirect.to);
|
|
1561
|
+
return (request) => {
|
|
1562
|
+
if (redirect.host !== void 0 && redirect.host !== request.host) return void 0;
|
|
1563
|
+
if (redirect.notHost !== void 0 && redirect.notHost === request.host) return void 0;
|
|
1564
|
+
const match = pattern.exec(request.path);
|
|
1565
|
+
if (!match) return void 0;
|
|
1566
|
+
if (conditions.length > 0) {
|
|
1567
|
+
const query = new URLSearchParams(request.search);
|
|
1568
|
+
if (!conditions.every(([key, value]) => query.getAll(key).includes(value))) return void 0;
|
|
1569
|
+
}
|
|
1570
|
+
const params = new Map(names.map((name, index) => [name, match[index + 1] ?? ""]));
|
|
1571
|
+
let location = redirect.to.replace(REDIRECT_PARAM_IN_TO, (_whole, slash, name) => {
|
|
1572
|
+
const value = params.get(name) ?? "";
|
|
1573
|
+
return value === "" ? "" : `${slash ?? ""}${value}`;
|
|
1574
|
+
});
|
|
1575
|
+
if (!absolute) {
|
|
1576
|
+
if (location === "" || location.startsWith("?") || location.startsWith("#")) location = `/${location}`;
|
|
1577
|
+
if (/^[/\\]{2}/.test(location)) return void 0;
|
|
1578
|
+
}
|
|
1579
|
+
const hashAt = location.indexOf("#");
|
|
1580
|
+
const beforeHash = hashAt === -1 ? location : location.slice(0, hashAt);
|
|
1581
|
+
if (!beforeHash.includes("?") && request.search.length > 1) location = `${beforeHash}${request.search}${hashAt === -1 ? "" : location.slice(hashAt)}`;
|
|
1582
|
+
return {
|
|
1583
|
+
status,
|
|
1584
|
+
location
|
|
1585
|
+
};
|
|
1586
|
+
};
|
|
1587
|
+
}
|
|
1588
|
+
function compileStaticRedirects(redirects) {
|
|
1589
|
+
const compiled = redirects.map(compileStaticRedirect);
|
|
1590
|
+
return (request) => {
|
|
1591
|
+
for (const answer of compiled) {
|
|
1592
|
+
const match = answer(request);
|
|
1593
|
+
if (match) return match;
|
|
1594
|
+
}
|
|
1595
|
+
};
|
|
1596
|
+
}
|
|
1597
|
+
function validateStaticRedirect(value, app) {
|
|
1598
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return {
|
|
1599
|
+
ok: false,
|
|
1600
|
+
reason: "must be an object like { \"from\": \"/old\", \"to\": \"/new\" }"
|
|
1601
|
+
};
|
|
1602
|
+
const { from, to, status, host, notHost, query, source, destination } = value;
|
|
1603
|
+
if (from === void 0 && source !== void 0) return {
|
|
1604
|
+
ok: false,
|
|
1605
|
+
field: "from",
|
|
1606
|
+
reason: "is missing \u2014 Vercel's \"source\" is \"from\" here"
|
|
1607
|
+
};
|
|
1608
|
+
if (to === void 0 && destination !== void 0) return {
|
|
1609
|
+
ok: false,
|
|
1610
|
+
field: "to",
|
|
1611
|
+
reason: "is missing \u2014 Vercel's \"destination\" is \"to\" here"
|
|
1612
|
+
};
|
|
1613
|
+
if (typeof from !== "string" || !from.startsWith("/")) return {
|
|
1614
|
+
ok: false,
|
|
1615
|
+
field: "from",
|
|
1616
|
+
reason: "must be an absolute path like \"/old\" or \"/blog/:slug\""
|
|
1617
|
+
};
|
|
1618
|
+
const parsed = parseRedirectFrom(from);
|
|
1619
|
+
if (!parsed.ok) return {
|
|
1620
|
+
ok: false,
|
|
1621
|
+
field: "from",
|
|
1622
|
+
reason: parsed.reason
|
|
1623
|
+
};
|
|
1624
|
+
const prefix = literalPrefixOf(parsed.segments);
|
|
1625
|
+
const reserved = reservedPrefixFor(prefix);
|
|
1626
|
+
if (reserved) return {
|
|
1627
|
+
ok: false,
|
|
1628
|
+
field: "from",
|
|
1629
|
+
reason: `cannot be "${reserved}" or under it \u2014 the backend answers that path on every hostname`
|
|
1630
|
+
};
|
|
1631
|
+
if (!isPathUnder(prefix, app.path) && !isPathUnder(app.path, prefix)) return {
|
|
1632
|
+
ok: false,
|
|
1633
|
+
field: "from",
|
|
1634
|
+
reason: `must be inside this app's path, "${app.path}" \u2014 the app is what answers there`
|
|
1635
|
+
};
|
|
1636
|
+
if (!isPathUnder(prefix, app.path)) return {
|
|
1637
|
+
ok: false,
|
|
1638
|
+
field: "from",
|
|
1639
|
+
reason: `must start with this app's path, "${app.path}" \u2014 write "${app.path}${from === "/" ? "" : from}" if that is what you mean`
|
|
1640
|
+
};
|
|
1641
|
+
if (typeof to !== "string" || to === "") return {
|
|
1642
|
+
ok: false,
|
|
1643
|
+
field: "to",
|
|
1644
|
+
reason: "must be a path like \"/new\" or a URL like \"https://www.example.com/:path*\""
|
|
1645
|
+
};
|
|
1646
|
+
if (/[\s\\\u0000-\u001f\u007f]/.test(to)) return {
|
|
1647
|
+
ok: false,
|
|
1648
|
+
field: "to",
|
|
1649
|
+
reason: "must not contain spaces, control characters or backslashes"
|
|
1650
|
+
};
|
|
1651
|
+
const absolute = /^https?:\/\//i.test(to);
|
|
1652
|
+
if (!absolute) {
|
|
1653
|
+
if (!to.startsWith("/")) return {
|
|
1654
|
+
ok: false,
|
|
1655
|
+
field: "to",
|
|
1656
|
+
reason: "must be a path starting with \"/\" or an absolute URL starting with \"https://\""
|
|
1657
|
+
};
|
|
1658
|
+
if (to.startsWith("//")) return {
|
|
1659
|
+
ok: false,
|
|
1660
|
+
field: "to",
|
|
1661
|
+
reason: `must be a path, not a URL without its scheme \u2014 write "https:${to}"`
|
|
1662
|
+
};
|
|
1663
|
+
} else {
|
|
1664
|
+
const authority = to.slice(to.indexOf("//") + 2).split(/[/?#]/)[0];
|
|
1665
|
+
if (/:[A-Za-z_]/.test(authority)) return {
|
|
1666
|
+
ok: false,
|
|
1667
|
+
field: "to",
|
|
1668
|
+
reason: "may name parameters in its path and query only, not in its scheme, host or port"
|
|
1669
|
+
};
|
|
1670
|
+
try {
|
|
1671
|
+
const url = new URL(to.replace(REDIRECT_PARAM_IN_TO, (_whole, slash) => `${slash ?? ""}x`));
|
|
1672
|
+
if (url.username || url.password) return {
|
|
1673
|
+
ok: false,
|
|
1674
|
+
field: "to",
|
|
1675
|
+
reason: "must not contain credentials"
|
|
1676
|
+
};
|
|
1677
|
+
} catch {
|
|
1678
|
+
return {
|
|
1679
|
+
ok: false,
|
|
1680
|
+
field: "to",
|
|
1681
|
+
reason: "is not a valid URL"
|
|
1682
|
+
};
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
1685
|
+
const declared = new Set(parsed.segments.flatMap((segment) => segment.kind === "param" ? [segment.name] : []));
|
|
1686
|
+
for (const [, , name] of to.matchAll(REDIRECT_PARAM_IN_TO)) if (!declared.has(name)) return {
|
|
1687
|
+
ok: false,
|
|
1688
|
+
field: "to",
|
|
1689
|
+
reason: `names ":${name}", which "from" does not declare` + (declared.size > 0 ? ` \u2014 it declares ${[...declared].map((n) => `":${n}"`).join(", ")}` : "")
|
|
1690
|
+
};
|
|
1691
|
+
if (status !== void 0 && !isStaticRedirectStatus(status)) return {
|
|
1692
|
+
ok: false,
|
|
1693
|
+
field: "status",
|
|
1694
|
+
reason: "must be 301, 302, 307 or 308 \u2014 308 when left out"
|
|
1695
|
+
};
|
|
1696
|
+
if (host !== void 0) {
|
|
1697
|
+
if (typeof host !== "string" || !isValidAppHost(host)) return {
|
|
1698
|
+
ok: false,
|
|
1699
|
+
field: "host",
|
|
1700
|
+
reason: "must be a lowercase public hostname like \"example.com\" \u2014 no scheme, port or path"
|
|
1701
|
+
};
|
|
1702
|
+
if (app.host !== void 0 && host !== app.host) return {
|
|
1703
|
+
ok: false,
|
|
1704
|
+
field: "host",
|
|
1705
|
+
reason: `can never match: this app answers only on "${app.host}"`
|
|
1706
|
+
};
|
|
1707
|
+
}
|
|
1708
|
+
if (notHost !== void 0) {
|
|
1709
|
+
if (typeof notHost !== "string" || !isValidAppHost(notHost)) return {
|
|
1710
|
+
ok: false,
|
|
1711
|
+
field: "notHost",
|
|
1712
|
+
reason: "must be a lowercase public hostname like \"example.com\" \u2014 no scheme, port or path"
|
|
1713
|
+
};
|
|
1714
|
+
if (host !== void 0) return {
|
|
1715
|
+
ok: false,
|
|
1716
|
+
field: "notHost",
|
|
1717
|
+
reason: "cannot be set with \"host\", which already names the only hostname this redirect answers on"
|
|
1718
|
+
};
|
|
1719
|
+
if (app.host !== void 0 && notHost === app.host) return {
|
|
1720
|
+
ok: false,
|
|
1721
|
+
field: "notHost",
|
|
1722
|
+
reason: `can never match: this app answers only on "${app.host}"`
|
|
1723
|
+
};
|
|
1724
|
+
}
|
|
1725
|
+
let conditions;
|
|
1726
|
+
if (query !== void 0) {
|
|
1727
|
+
if (typeof query !== "object" || query === null || Array.isArray(query)) return {
|
|
1728
|
+
ok: false,
|
|
1729
|
+
field: "query",
|
|
1730
|
+
reason: "must be an object of exact values like { \"lang\": \"es\" }"
|
|
1731
|
+
};
|
|
1732
|
+
conditions = {};
|
|
1733
|
+
for (const [key, expected] of Object.entries(query)) {
|
|
1734
|
+
if (key === "" || typeof expected !== "string") return {
|
|
1735
|
+
ok: false,
|
|
1736
|
+
field: "query",
|
|
1737
|
+
reason: "must map each parameter name to the exact string it holds, like { \"lang\": \"es\" }"
|
|
1738
|
+
};
|
|
1739
|
+
conditions[key] = expected;
|
|
1740
|
+
}
|
|
1741
|
+
}
|
|
1742
|
+
const redirect = {
|
|
1743
|
+
from,
|
|
1744
|
+
to,
|
|
1745
|
+
...isStaticRedirectStatus(status) ? { status } : {},
|
|
1746
|
+
...typeof host === "string" ? { host } : {},
|
|
1747
|
+
...typeof notHost === "string" ? { notHost } : {},
|
|
1748
|
+
...conditions ? { query: conditions } : {}
|
|
1749
|
+
};
|
|
1750
|
+
if (!absolute) {
|
|
1751
|
+
const answer = compileStaticRedirect(redirect);
|
|
1752
|
+
const samplePath = parsed.segments.length === 0 ? "/" : parsed.segments.map((segment) => `/${segment.kind === "literal" ? segment.value : "x"}`).join("");
|
|
1753
|
+
const sampleSearch = conditions && Object.keys(conditions).length > 0 ? `?${new URLSearchParams(conditions).toString()}` : "";
|
|
1754
|
+
const sampleHost = redirect.host ?? app.host ?? (redirect.notHost === "example.com" ? "example.net" : "example.com");
|
|
1755
|
+
const first = answer({
|
|
1756
|
+
host: sampleHost,
|
|
1757
|
+
path: samplePath,
|
|
1758
|
+
search: sampleSearch
|
|
1759
|
+
});
|
|
1760
|
+
if (first) {
|
|
1761
|
+
const target = new URL(first.location, `https://${sampleHost}`);
|
|
1762
|
+
if (answer({
|
|
1763
|
+
host: sampleHost,
|
|
1764
|
+
path: target.pathname,
|
|
1765
|
+
search: target.search
|
|
1766
|
+
})) return {
|
|
1767
|
+
ok: false,
|
|
1768
|
+
field: "to",
|
|
1769
|
+
reason: `sends "${samplePath}${sampleSearch}" to "${first.location}", which "from" matches again \u2014 every request it answers would be redirected forever. Narrow "from", or send it somewhere "from" does not match`
|
|
1770
|
+
};
|
|
1771
|
+
}
|
|
1772
|
+
}
|
|
1773
|
+
return {
|
|
1774
|
+
ok: true,
|
|
1775
|
+
redirect
|
|
1776
|
+
};
|
|
1777
|
+
}
|
|
1778
|
+
function cleanUrlFor(requestPath) {
|
|
1779
|
+
if (!requestPath.endsWith(".html")) return void 0;
|
|
1780
|
+
const slash = requestPath.lastIndexOf("/");
|
|
1781
|
+
const name = requestPath.slice(slash + 1);
|
|
1782
|
+
if (name === ".html") return void 0;
|
|
1783
|
+
if (name === "index.html") return requestPath.slice(0, slash + 1);
|
|
1784
|
+
return requestPath.slice(0, -5);
|
|
1785
|
+
}
|
|
2652
1786
|
var LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
|
|
2653
1787
|
"localhost",
|
|
2654
1788
|
"127.0.0.1",
|
|
2655
1789
|
"[::1]"
|
|
2656
1790
|
]);
|
|
2657
|
-
/**
|
|
2658
|
-
* Validate one entry of a static app's `frameAncestors`: a single origin that
|
|
2659
|
-
* may frame the app.
|
|
2660
|
-
*
|
|
2661
|
-
* The value ends up inside a `Content-Security-Policy` header, so it is held
|
|
2662
|
-
* to the exact serialisation of an origin — `new URL(value).origin` has to
|
|
2663
|
-
* give it back unchanged. That leaves nothing that could close the directive
|
|
2664
|
-
* or open another one, and turns every near miss (a trailing slash, a
|
|
2665
|
-
* capital, a default port, a path) into a refusal that names the fix.
|
|
2666
|
-
*
|
|
2667
|
-
* `https://` with a public hostname, or `localhost`; plain `http://` only for
|
|
2668
|
-
* a loopback host. Never a wildcard or a keyword: this is a list of the
|
|
2669
|
-
* origins an operator chose, and `'self'` is always on it.
|
|
2670
|
-
*/
|
|
2671
1791
|
function parseFrameAncestor(value) {
|
|
2672
1792
|
const example = "must be an origin like \"https://admin.example.com\"";
|
|
2673
1793
|
if (typeof value !== "string" || value === "") return {
|
|
@@ -2676,11 +1796,11 @@ function parseFrameAncestor(value) {
|
|
|
2676
1796
|
};
|
|
2677
1797
|
if (value.includes("*")) return {
|
|
2678
1798
|
ok: false,
|
|
2679
|
-
reason: "must name one origin
|
|
1799
|
+
reason: "must name one origin \u2014 wildcards are not accepted, so list each origin that may frame this app"
|
|
2680
1800
|
};
|
|
2681
1801
|
if (value.startsWith("'")) return {
|
|
2682
1802
|
ok: false,
|
|
2683
|
-
reason: `${example}
|
|
1803
|
+
reason: `${example} \u2014 keywords are not accepted, and 'self' is always allowed`
|
|
2684
1804
|
};
|
|
2685
1805
|
let url;
|
|
2686
1806
|
try {
|
|
@@ -2698,7 +1818,7 @@ function parseFrameAncestor(value) {
|
|
|
2698
1818
|
const loopback = LOOPBACK_HOSTS.has(url.hostname);
|
|
2699
1819
|
if (url.protocol === "http:" && !loopback) return {
|
|
2700
1820
|
ok: false,
|
|
2701
|
-
reason: `must use https
|
|
1821
|
+
reason: `must use https \u2014 plain http is accepted for localhost only: "https://${url.host}"`
|
|
2702
1822
|
};
|
|
2703
1823
|
if (!loopback && !isValidAppHost(url.hostname)) return {
|
|
2704
1824
|
ok: false,
|
|
@@ -2706,122 +1826,19 @@ function parseFrameAncestor(value) {
|
|
|
2706
1826
|
};
|
|
2707
1827
|
if (url.origin !== value) return {
|
|
2708
1828
|
ok: false,
|
|
2709
|
-
reason: `must be the origin alone
|
|
1829
|
+
reason: `must be the origin alone \u2014 scheme, hostname and an optional port, lowercase, with nothing after it: "${url.origin}"`
|
|
2710
1830
|
};
|
|
2711
1831
|
return {
|
|
2712
1832
|
ok: true,
|
|
2713
1833
|
origin: value
|
|
2714
1834
|
};
|
|
2715
1835
|
}
|
|
2716
|
-
/**
|
|
2717
|
-
* Version of the bundle *format* itself.
|
|
2718
|
-
*
|
|
2719
|
-
* Bumped only when the on-disk layout changes in a way an older runtime could
|
|
2720
|
-
* not read. A runtime accepts any bundle whose `bundleFormat` is less than or
|
|
2721
|
-
* equal to its own — old bundles keep booting on new runtimes, which is the
|
|
2722
|
-
* whole point of separating the artifact from the engine.
|
|
2723
|
-
*
|
|
2724
|
-
* - **1** — `mode: "cms" | "baas" | "static"`, `entry.static` a single directory
|
|
2725
|
-
* string, `entry.admin` for a bundled admin panel.
|
|
2726
|
-
* - **2** — `kind: "backend" | "static"`, `entry.static` a list of
|
|
2727
|
-
* {@link RebaseBundleStatic}, `entry.admin` removed. A format-1 runtime reading
|
|
2728
|
-
* one of these would find no `mode` and an array where it expects a string, so
|
|
2729
|
-
* the bump is what turns that into a refusal to boot instead of a bundle that
|
|
2730
|
-
* starts and serves nothing.
|
|
2731
|
-
* - **3** — the schema is `entry.tables` (the compiled `backend/schema`
|
|
2732
|
-
* directory, whose `index` exports the tables), beside `entry.resources`,
|
|
2733
|
-
* `entry.storage` and `entry.hooks`. There is no config package any more:
|
|
2734
|
-
* `entry.config`, `entry.collections` and `entry.usersCollection` are not
|
|
2735
|
-
* written. A format-2 runtime would find none of the keys it boots from and
|
|
2736
|
-
* introspect the database instead of serving the declared tables — so the
|
|
2737
|
-
* bump turns that into a refusal.
|
|
2738
|
-
*
|
|
2739
|
-
* **Format 2 bundles are refused, not upgraded.** Unlike 1 → 2, which was a
|
|
2740
|
-
* renaming, a format-2 bundle carries `config/collections` — `defineCollection`
|
|
2741
|
-
* objects — and a runtime that reads only `backend/schema` has nothing to read
|
|
2742
|
-
* them with. It refuses them at boot with {@link LEGACY_LAYOUT_REMEDY} in the
|
|
2743
|
-
* error: run the codemod on the project's source, then rebuild.
|
|
2744
|
-
*/
|
|
2745
1836
|
var BUNDLE_FORMAT_VERSION = 3;
|
|
2746
|
-
/**
|
|
2747
|
-
* What to do about a project on the `config/collections` layout — the words
|
|
2748
|
-
* every refusal of that layout ends with.
|
|
2749
|
-
*
|
|
2750
|
-
* Shared because two parties refuse it and must say the same thing: the CLI,
|
|
2751
|
-
* for a `rebase.json` that still names `config` or `usersCollection`, and the
|
|
2752
|
-
* runtime, for a format-2 / contract-1 bundle built from `config/collections`.
|
|
2753
|
-
*/
|
|
2754
1837
|
var LEGACY_LAYOUT_REMEDY = "run `rebase migrate collections-to-tables` (in the Rebase repository: tooling/scripts/migrate-collections-to-tables.mts), which rewrites config/collections as backend/schema (and the admin presentation as frontend/src/cms), carries the collection callbacks into the tables as hooks, moves resources.ts and storage.ts to backend/, and proves the generated SQL unchanged; then rebuild";
|
|
2755
|
-
/**
|
|
2756
|
-
* The runtime contract major.
|
|
2757
|
-
*
|
|
2758
|
-
* Distinct from the `@rebasepro/server` package version: the package may release
|
|
2759
|
-
* any number of minors and patches while this stays put. It changes only when
|
|
2760
|
-
* the bundle/runtime contract breaks compatibility, and a project's
|
|
2761
|
-
* `manifest.runtime` range is matched against *this*.
|
|
2762
|
-
*
|
|
2763
|
-
* ## v2 — tables, not collections
|
|
2764
|
-
*
|
|
2765
|
-
* The runtime reads the project's schema from `backend/schema` (bundle format
|
|
2766
|
-
* 3, `entry.tables`): `defineTable` / `defineAuthTable` / `defineView` exports
|
|
2767
|
-
* and `defaultRls`. It no longer loads `config/collections`, and it no longer
|
|
2768
|
-
* reads a config package's `collections` / `callbacks` exports or a
|
|
2769
|
-
* `usersCollection` module; global table hooks come from `backend/hooks.ts`,
|
|
2770
|
-
* `storageAuthorize` from `backend/storage.ts`, declared resources from
|
|
2771
|
-
* `backend/resources.ts`.
|
|
2772
|
-
*
|
|
2773
|
-
* So, plainly: **a format-2 / contract-1 bundle — one built from
|
|
2774
|
-
* `config/collections` — is refused by a contract-2 runtime**, at boot, with
|
|
2775
|
-
* {@link LEGACY_LAYOUT_REMEDY} in the message. There is no in-runtime adapter
|
|
2776
|
-
* from collections to tables; the project's source is migrated once with the
|
|
2777
|
-
* codemod and rebuilt. On the managed tier that means the platform keeps such a
|
|
2778
|
-
* tenant on a contract-1 image until it is rebuilt — the release order below
|
|
2779
|
-
* applies unchanged.
|
|
2780
|
-
*
|
|
2781
|
-
* This has to be a major, and the reason is the managed tier: it moves projects
|
|
2782
|
-
* onto new images WITHOUT rebuilding them. Without the bump, one image rollout
|
|
2783
|
-
* would crash-loop every tenant whose bundle predates the change, in a wave,
|
|
2784
|
-
* with the cause in a container log nobody is watching. With it, an older
|
|
2785
|
-
* bundle on a newer runtime is refused by `readBundleManifest` with the remedy
|
|
2786
|
-
* in the message, and the platform keeps it on an image of its own major until
|
|
2787
|
-
* it is rebuilt. That is the whole purpose of this number.
|
|
2788
|
-
*
|
|
2789
|
-
* (Declared resources — `database()` / `bucket()` replacing
|
|
2790
|
-
* `RebaseBackendConfig.dataSources` / `.storageSources` — once took this number
|
|
2791
|
-
* to 2 and were taken back to 1 before launch, when there was no fleet for the
|
|
2792
|
-
* major to protect. They are part of v1.)
|
|
2793
|
-
*
|
|
2794
|
-
* **Release order matters and is not optional.** The control plane is the side
|
|
2795
|
-
* that rejects, so it ships FIRST: raise `SUPPORTED_RUNTIME_CONTRACT` in the
|
|
2796
|
-
* saas repo (it rejects only `contract >` its own, so it then accepts both),
|
|
2797
|
-
* deploy that, and only then release a runtime implementing v2. Shipping the
|
|
2798
|
-
* runtime first turns every deploy into a rejected intake blaming the tenant's
|
|
2799
|
-
* bundle.
|
|
2800
|
-
*/
|
|
2801
1838
|
var RUNTIME_CONTRACT_VERSION = 2;
|
|
2802
|
-
/** Header carrying the schema version an SDK was generated from. */
|
|
2803
1839
|
var SCHEMA_VERSION_HEADER = "x-rebase-schema";
|
|
2804
1840
|
//#endregion
|
|
2805
1841
|
//#region src/types/content_hash.ts
|
|
2806
|
-
/**
|
|
2807
|
-
* Whether a static build's file name carries a content hash: the files the
|
|
2808
|
-
* runtime serves `immutable` for a year, and the ones `rebase build` writes
|
|
2809
|
-
* `.br` and `.gz` beside. One rule for both, so a file is never precompressed
|
|
2810
|
-
* and revalidated, or cached for a year and compressed on every request.
|
|
2811
|
-
*
|
|
2812
|
-
* Two shapes count:
|
|
2813
|
-
*
|
|
2814
|
-
* - **Vite's own**, `[name]-[hash]`: the last eight characters of the name,
|
|
2815
|
-
* after a `-`. They are base64url, an alphabet with `-` and `_` in it, so
|
|
2816
|
-
* about one hash in eight holds a `-` (`index-C-WpENHZ.js`,
|
|
2817
|
-
* `page10-D6Dq--fD.js`), and the last `-` is not where it starts.
|
|
2818
|
-
* - **A longer one** with no `-` in it, eight characters or more after the last
|
|
2819
|
-
* `-` (`[hash:12]`, another bundler's names).
|
|
2820
|
-
*
|
|
2821
|
-
* Either must hold a digit or a capital. That is the evidence of a hash: a
|
|
2822
|
-
* hand-written `vendor-analytics.js` is not taken for one, and gets revalidated
|
|
2823
|
-
* rather than pinned in every visitor's cache with no way to recall it.
|
|
2824
|
-
*/
|
|
2825
1842
|
function isContentHashedFileName(fileName) {
|
|
2826
1843
|
const dot = fileName.lastIndexOf(".");
|
|
2827
1844
|
if (dot <= 0) return false;
|
|
@@ -2832,73 +1849,20 @@ function isContentHashedFileName(fileName) {
|
|
|
2832
1849
|
const suffix = stem.slice(dash + 1);
|
|
2833
1850
|
return suffix.length >= 8 && looksLikeHash(suffix);
|
|
2834
1851
|
}
|
|
2835
|
-
/** Base64url throughout, with a digit or a capital somewhere in it. */
|
|
2836
1852
|
function looksLikeHash(text) {
|
|
2837
1853
|
return /^[A-Za-z0-9_-]+$/.test(text) && /[0-9A-Z]/.test(text);
|
|
2838
1854
|
}
|
|
2839
1855
|
//#endregion
|
|
2840
1856
|
//#region src/types/schema_version.ts
|
|
2841
|
-
/**
|
|
2842
|
-
* The schema version stamp.
|
|
2843
|
-
*
|
|
2844
|
-
* One function, used in three places that must agree or the whole drift-detection
|
|
2845
|
-
* story is noise: `rebase build` writes it into a bundle manifest, the runtime
|
|
2846
|
-
* serves it from the contract endpoint and stamps it into the database it
|
|
2847
|
-
* provisions, and a generated SDK records the value it was built from. If any
|
|
2848
|
-
* two of those computed it differently, every client would look permanently out
|
|
2849
|
-
* of date.
|
|
2850
|
-
*
|
|
2851
|
-
* It covers **tables only** — their compiled descriptors — so editing a hook's
|
|
2852
|
-
* code or a server function never invalidates every SDK in every repository.
|
|
2853
|
-
* That is a deliberate narrowing, not an oversight.
|
|
2854
|
-
*
|
|
2855
|
-
* Versions are prefixed `v2:` (descriptors, since 0.31); `v1:` versions were
|
|
2856
|
-
* computed from collections — see {@link LEGACY_SCHEMA_VERSION_PREFIX}.
|
|
2857
|
-
*/
|
|
2858
|
-
/** Stable stringify: object keys sorted at every level, so key order cannot alter the hash. */
|
|
2859
1857
|
function canonicalize(value) {
|
|
2860
1858
|
if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
|
|
2861
1859
|
if (Array.isArray(value)) return `[${value.map(canonicalize).join(",")}]`;
|
|
2862
1860
|
return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonicalize(v)}`).join(",")}}`;
|
|
2863
1861
|
}
|
|
2864
|
-
/**
|
|
2865
|
-
* The prefix of a version computed before 0.31, from collections.
|
|
2866
|
-
*
|
|
2867
|
-
* A database stamped with one was provisioned under the collection model. Its
|
|
2868
|
-
* version can never equal a descriptor version, so the first boot of a 0.31
|
|
2869
|
-
* runtime against it reports a mismatch once — and says why, and how to
|
|
2870
|
-
* restamp.
|
|
2871
|
-
*/
|
|
2872
1862
|
var LEGACY_SCHEMA_VERSION_PREFIX = "v1:";
|
|
2873
|
-
/**
|
|
2874
|
-
* Compute the canonical string a schema version hashes: the tables'
|
|
2875
|
-
* descriptors, ordered by slug, every object's keys sorted.
|
|
2876
|
-
*
|
|
2877
|
-
* A descriptor is the compiled table — every default applied, every name
|
|
2878
|
-
* derived, `rls` resolved against `defaultRls` — so the same source compiles to
|
|
2879
|
-
* the same descriptor before or after anything loads it, and a build-time
|
|
2880
|
-
* stamp can match the server that serves it. It is plain JSON by
|
|
2881
|
-
* construction: hooks appear only as presence flags (`hooks.afterRead: true`),
|
|
2882
|
-
* so editing what a hook does never moves the version, while adding or
|
|
2883
|
-
* removing one does.
|
|
2884
|
-
*
|
|
2885
|
-
* Ordered by slug, so the order the tables were exported in cannot alter it.
|
|
2886
|
-
*
|
|
2887
|
-
* Exposed separately so the hashing itself can differ by environment: Node has
|
|
2888
|
-
* `crypto`, and callers without it can still compare canonical forms directly.
|
|
2889
|
-
*/
|
|
2890
1863
|
function canonicalSchemaPayload(tables) {
|
|
2891
1864
|
return canonicalize([...tables].sort((a, b) => a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0));
|
|
2892
1865
|
}
|
|
2893
|
-
/**
|
|
2894
|
-
* A short, non-cryptographic digest of the canonical payload.
|
|
2895
|
-
*
|
|
2896
|
-
* FNV-1a style, 64 bits, as two 32-bit halves. This is an identity, not a
|
|
2897
|
-
* security boundary: nothing trusts a schema version to prove anything, it only
|
|
2898
|
-
* answers "is this the same schema as before". A hand-rolled hash keeps this
|
|
2899
|
-
* module free of `node:crypto`, so the identical function runs in the browser,
|
|
2900
|
-
* in the CLI, and in the runtime — which is the property that actually matters.
|
|
2901
|
-
*/
|
|
2902
1866
|
function computeSchemaVersion(tables) {
|
|
2903
1867
|
const payload = canonicalSchemaPayload(tables);
|
|
2904
1868
|
let h1 = 2166136261;
|
|
@@ -2914,24 +1878,24 @@ function computeSchemaVersion(tables) {
|
|
|
2914
1878
|
return `v2:${hex(h1)}${hex(h2)}`;
|
|
2915
1879
|
}
|
|
2916
1880
|
//#endregion
|
|
1881
|
+
//#region src/types/storage_authorize.ts
|
|
1882
|
+
var RECOMMENDED_STORAGE_RULES = Object.freeze([
|
|
1883
|
+
{
|
|
1884
|
+
path: "public/**",
|
|
1885
|
+
operations: ["read"],
|
|
1886
|
+
allow: "public"
|
|
1887
|
+
},
|
|
1888
|
+
{
|
|
1889
|
+
path: "users/:uid/**",
|
|
1890
|
+
allow: "owner"
|
|
1891
|
+
},
|
|
1892
|
+
{
|
|
1893
|
+
path: "**",
|
|
1894
|
+
allow: { roles: ["admin"] }
|
|
1895
|
+
}
|
|
1896
|
+
]);
|
|
1897
|
+
//#endregion
|
|
2917
1898
|
//#region src/types/mcp_app_modules.ts
|
|
2918
|
-
/**
|
|
2919
|
-
* The modules an app Claude writes for show_app may import, and from each the
|
|
2920
|
-
* names the MCP view serves.
|
|
2921
|
-
*
|
|
2922
|
-
* An app imports the real package names, so the code reads — and pastes into
|
|
2923
|
-
* a project — like every other piece of Rebase code. Inside the view each
|
|
2924
|
-
* name is the package's own part: `"*"` serves the whole module, a list
|
|
2925
|
-
* serves exactly those exports. The one list three readers share, so none
|
|
2926
|
-
* can drift from the others:
|
|
2927
|
-
*
|
|
2928
|
-
* - the view's module registry (`@rebasepro/cms/mcp-view`), which hands an
|
|
2929
|
-
* app these exports and no others;
|
|
2930
|
-
* - the server's compiler for show_app, which refuses any other import
|
|
2931
|
-
* before the app opens, naming it;
|
|
2932
|
-
* - show_app's guide (`SHOW_APP_CODE_GUIDE` in `@rebasepro/server`), which a
|
|
2933
|
-
* test holds to this list.
|
|
2934
|
-
*/
|
|
2935
1899
|
var MCP_APP_MODULES = {
|
|
2936
1900
|
"react": "*",
|
|
2937
1901
|
"react/jsx-runtime": "*",
|
|
@@ -2959,12 +1923,6 @@ var MCP_APP_MODULES = {
|
|
|
2959
1923
|
};
|
|
2960
1924
|
//#endregion
|
|
2961
1925
|
//#region src/types/ui_preferences.ts
|
|
2962
|
-
/**
|
|
2963
|
-
* Every key a {@link UiTablePreferences} may hold, as data: what the server
|
|
2964
|
-
* validates a stored preference by.
|
|
2965
|
-
*
|
|
2966
|
-
* @group UI preferences
|
|
2967
|
-
*/
|
|
2968
1926
|
var UI_PREFERENCE_TABLE_KEYS = [
|
|
2969
1927
|
"alwaysApplyDefaultValues",
|
|
2970
1928
|
"customViews",
|
|
@@ -3002,11 +1960,6 @@ var UI_PREFERENCE_TABLE_KEYS = [
|
|
|
3002
1960
|
"singularName",
|
|
3003
1961
|
"sort"
|
|
3004
1962
|
];
|
|
3005
|
-
/**
|
|
3006
|
-
* Every key a {@link UiFieldPreferences} may hold, as data.
|
|
3007
|
-
*
|
|
3008
|
-
* @group UI preferences
|
|
3009
|
-
*/
|
|
3010
1963
|
var UI_PREFERENCE_FIELD_KEYS = [
|
|
3011
1964
|
"canAddElements",
|
|
3012
1965
|
"clearable",
|
|
@@ -3087,11 +2040,6 @@ var fieldMap = (value, path, out) => {
|
|
|
3087
2040
|
}
|
|
3088
2041
|
for (const [key, field] of Object.entries(value)) fieldProblems(field, `${path}.${key}`, out);
|
|
3089
2042
|
};
|
|
3090
|
-
/**
|
|
3091
|
-
* The checks, built on first use: module-level calls would keep this file in
|
|
3092
|
-
* every bundle that imports `@rebasepro/types`, whether it validates a
|
|
3093
|
-
* preference or not.
|
|
3094
|
-
*/
|
|
3095
2043
|
var builtChecks;
|
|
3096
2044
|
function checks() {
|
|
3097
2045
|
builtChecks ??= {
|
|
@@ -3221,13 +2169,6 @@ function fieldProblems(value, path, out) {
|
|
|
3221
2169
|
checks().field[key](entry, `${path}.${key}`, out);
|
|
3222
2170
|
}
|
|
3223
2171
|
}
|
|
3224
|
-
/**
|
|
3225
|
-
* Every problem with a table's preference delta as it arrived: a key that is
|
|
3226
|
-
* not a preference (a schema fact, a component, a misspelling) or a value of
|
|
3227
|
-
* the wrong shape. Empty when it may be stored.
|
|
3228
|
-
*
|
|
3229
|
-
* @group UI preferences
|
|
3230
|
-
*/
|
|
3231
2172
|
function uiTablePreferencesProblems(value) {
|
|
3232
2173
|
const out = [];
|
|
3233
2174
|
if (!isRecord$1(value)) return [{
|
|
@@ -3247,20 +2188,9 @@ function uiTablePreferencesProblems(value) {
|
|
|
3247
2188
|
}
|
|
3248
2189
|
return out;
|
|
3249
2190
|
}
|
|
3250
|
-
/**
|
|
3251
|
-
* Whether a value is a well-formed {@link UiTablePreferences} delta.
|
|
3252
|
-
*
|
|
3253
|
-
* @group UI preferences
|
|
3254
|
-
*/
|
|
3255
2191
|
function isUiTablePreferences(value) {
|
|
3256
2192
|
return uiTablePreferencesProblems(value).length === 0;
|
|
3257
2193
|
}
|
|
3258
|
-
/**
|
|
3259
|
-
* One delta over another: what `over` names replaces what `base` says, key by
|
|
3260
|
-
* key, and `fields` (and a field's nested `fields` / `of`) field by field.
|
|
3261
|
-
*
|
|
3262
|
-
* @group UI preferences
|
|
3263
|
-
*/
|
|
3264
2194
|
function mergeUiTablePreferences(base, over) {
|
|
3265
2195
|
const out = {
|
|
3266
2196
|
...base,
|
|
@@ -3289,98 +2219,14 @@ function mergeField(base, over) {
|
|
|
3289
2219
|
}
|
|
3290
2220
|
//#endregion
|
|
3291
2221
|
//#region src/controllers/data.ts
|
|
3292
|
-
/**
|
|
3293
|
-
* Hops an {@link IncludeSpec} may nest. `comments.author` is two.
|
|
3294
|
-
*
|
|
3295
|
-
* @group Data
|
|
3296
|
-
*/
|
|
3297
2222
|
var MAX_INCLUDE_DEPTH = 3;
|
|
3298
|
-
/**
|
|
3299
|
-
* SDK table client — returns flat rows, no Entity wrapper.
|
|
3300
|
-
*
|
|
3301
|
-
* This is the public API surface for app developers using
|
|
3302
|
-
* `createRebaseClient()`.
|
|
3303
|
-
*
|
|
3304
|
-
* Type parameters:
|
|
3305
|
-
* - `M` — the **Row** shape returned by reads (`find`, `findById`, `listen`).
|
|
3306
|
-
* - `I` — the **Insert** shape accepted by {@link create}. Defaults to
|
|
3307
|
-
* `Partial<M>`; the generated SDK supplies a dedicated `Insert` type where
|
|
3308
|
-
* required columns are required and auto-generated / read-only columns are
|
|
3309
|
-
* omitted, so `create({})` on a table with required fields is a compile error.
|
|
3310
|
-
* - `U` — the **Update** shape accepted by {@link update}. Defaults to
|
|
3311
|
-
* `Partial<M>`; the generated SDK supplies a dedicated `Update` type.
|
|
3312
|
-
*
|
|
3313
|
-
* @example
|
|
3314
|
-
* const { data: posts } = await rebase.data.posts.find();
|
|
3315
|
-
* console.log(posts[0].title); // flat access
|
|
3316
|
-
* console.log(posts[0].id); // id at top level
|
|
3317
|
-
*
|
|
3318
|
-
* const post = await rebase.data.posts.findById(1);
|
|
3319
|
-
* console.log(post?.title); // no .values needed
|
|
3320
|
-
*
|
|
3321
|
-
* @group Data
|
|
3322
|
-
*/
|
|
3323
|
-
/**
|
|
3324
|
-
* A change expressed as an operation on the column's current value, rather than
|
|
3325
|
-
* as the value to store.
|
|
3326
|
-
*
|
|
3327
|
-
* `{ views: 5 }` says what the number becomes; `{ views: { $inc: 1 } }` says
|
|
3328
|
-
* what happens to it. The difference is the read the caller no longer has to
|
|
3329
|
-
* make — and the race that read opens. Two requests that each read `4`, add one
|
|
3330
|
-
* and write `5` lose an increment between them; `SET views = views + 1` cannot,
|
|
3331
|
-
* because the arithmetic happens inside the statement holding the row lock.
|
|
3332
|
-
*
|
|
3333
|
-
* Exactly one operator per field. `{ views: { $inc: 1, $push: "x" } }` is
|
|
3334
|
-
* refused rather than applied in an order the caller cannot see.
|
|
3335
|
-
*
|
|
3336
|
-
* @group Data
|
|
3337
|
-
*/
|
|
3338
|
-
/**
|
|
3339
|
-
* The operator names, as a value.
|
|
3340
|
-
*
|
|
3341
|
-
* A runtime list beside the type because three layers have to *recognise* an
|
|
3342
|
-
* operation, not just accept one: the REST validator, the driver that compiles
|
|
3343
|
-
* it, and the offline queue that must refuse to apply one locally. Three copies
|
|
3344
|
-
* of four strings is three chances for one of them to miss an operator added to
|
|
3345
|
-
* the other two, and the failure is silent in the worst direction — an
|
|
3346
|
-
* unrecognised marker is written to the column as a JSON document.
|
|
3347
|
-
*
|
|
3348
|
-
* @group Data
|
|
3349
|
-
*/
|
|
3350
2223
|
var FIELD_OPERATORS = [
|
|
3351
2224
|
"$inc",
|
|
3352
2225
|
"$push",
|
|
3353
2226
|
"$pull",
|
|
3354
2227
|
"$merge"
|
|
3355
2228
|
];
|
|
3356
|
-
/**
|
|
3357
|
-
* The key of a {@link BatchRef}. Declared here, beside the field operators,
|
|
3358
|
-
* because the two share one namespace: a `$`-prefixed key in a write payload is
|
|
3359
|
-
* a marker, and every reader of that namespace has to know all of it.
|
|
3360
|
-
*
|
|
3361
|
-
* @group Data
|
|
3362
|
-
*/
|
|
3363
2229
|
var BATCH_REF_KEY = "$ref";
|
|
3364
|
-
/**
|
|
3365
|
-
* Whether a value is *trying* to be a field operation — including a misspelled
|
|
3366
|
-
* one, which is the case worth catching.
|
|
3367
|
-
*
|
|
3368
|
-
* Any `$`-prefixed key counts, because `{ $increment: 1 }` written to a number
|
|
3369
|
-
* column as a JSON document is the failure this exists to prevent.
|
|
3370
|
-
*
|
|
3371
|
-
* Except on a `map` (pass `propertyType`): a map's value is a JSON document,
|
|
3372
|
-
* and one may legitimately carry `$` keys — a JSON Schema's `$schema`, a
|
|
3373
|
-
* document exported from another database. There, only a single-key object whose key is one of
|
|
3374
|
-
* {@link FIELD_OPERATORS} is an operation, and anything else is data. A caller
|
|
3375
|
-
* that does not know the property type gets the strict reading.
|
|
3376
|
-
*
|
|
3377
|
-
* The one exception is `{ $ref: … }`, the batch's backward reference. It stands
|
|
3378
|
-
* where a *value* goes and is resolved to one before the row is written, so it
|
|
3379
|
-
* is not an operation on a column — reading it as a misspelled operator refused
|
|
3380
|
-
* every `$ref` in a batch with "unknown field operator '$ref'".
|
|
3381
|
-
*
|
|
3382
|
-
* @group Data
|
|
3383
|
-
*/
|
|
3384
2230
|
function isFieldOperation(value, propertyType) {
|
|
3385
2231
|
if (typeof value !== "object" || value === null || Array.isArray(value) || value instanceof Date) return false;
|
|
3386
2232
|
const keys = Object.keys(value);
|
|
@@ -3388,27 +2234,15 @@ function isFieldOperation(value, propertyType) {
|
|
|
3388
2234
|
if (propertyType === "map") return keys.length === 1 && FIELD_OPERATORS.includes(keys[0]);
|
|
3389
2235
|
return keys.some((key) => key.startsWith("$"));
|
|
3390
2236
|
}
|
|
3391
|
-
/** True when any value in a write payload is (or is attempting to be) one. @group Data */
|
|
3392
2237
|
function hasFieldOperation(values) {
|
|
3393
2238
|
return !!values && Object.values(values).some((value) => isFieldOperation(value));
|
|
3394
2239
|
}
|
|
3395
2240
|
//#endregion
|
|
3396
2241
|
//#region src/controllers/data_driver.ts
|
|
3397
|
-
/** Rows returned for a plain / text-search list read when the client sends no `limit`. */
|
|
3398
2242
|
var DEFAULT_LIST_LIMIT = 50;
|
|
3399
|
-
/** Rows returned for a vector-search list read when the client sends no `limit`. */
|
|
3400
2243
|
var DEFAULT_VECTOR_LIST_LIMIT = 10;
|
|
3401
|
-
/** Largest `limit` a client may ask for on any surface. Above it, the read is refused. */
|
|
3402
2244
|
var MAX_LIST_LIMIT = 1e3;
|
|
3403
|
-
/**
|
|
3404
|
-
* Thrown by {@link resolveClientListLimit} for a `limit` the platform will not
|
|
3405
|
-
* serve. Carries an HTTP status so an ingress that speaks HTTP can forward it
|
|
3406
|
-
* verbatim, and `maxLimit` so one can be built without re-deriving the ceiling.
|
|
3407
|
-
*
|
|
3408
|
-
* @group Errors
|
|
3409
|
-
*/
|
|
3410
2245
|
var ListLimitError = class ListLimitError extends RebaseApiError {
|
|
3411
|
-
/** The ceiling that was exceeded — what the caller should page by instead. */
|
|
3412
2246
|
maxLimit;
|
|
3413
2247
|
constructor(message, maxLimit) {
|
|
3414
2248
|
super(message, {
|
|
@@ -3420,74 +2254,23 @@ var ListLimitError = class ListLimitError extends RebaseApiError {
|
|
|
3420
2254
|
Object.setPrototypeOf(this, ListLimitError.prototype);
|
|
3421
2255
|
}
|
|
3422
2256
|
};
|
|
3423
|
-
/**
|
|
3424
|
-
* Resolve a client-supplied list `limit` into a safe, always-defined value.
|
|
3425
|
-
*
|
|
3426
|
-
* - An absent / blank limit falls back to the mode default:
|
|
3427
|
-
* `vectorDefaultLimit` for a vector search, otherwise `defaultLimit`.
|
|
3428
|
-
* - A limit that is present must be an integer in `[1, maxLimit]`. Anything
|
|
3429
|
-
* else — `0`, a negative, `1.5`, `abc`, `100000000` — throws
|
|
3430
|
-
* {@link ListLimitError} rather than being coerced into range, because every
|
|
3431
|
-
* coercion answers a question the caller did not ask with a page it cannot
|
|
3432
|
-
* tell apart from the whole collection.
|
|
3433
|
-
*
|
|
3434
|
-
* The return is never `undefined` — no ingress that routes its client limit
|
|
3435
|
-
* through this can produce an unbounded read.
|
|
3436
|
-
*
|
|
3437
|
-
* @throws {ListLimitError} when a present `limit` is not an integer in range.
|
|
3438
|
-
*/
|
|
3439
2257
|
function resolveClientListLimit(rawLimit, opts = {}) {
|
|
3440
2258
|
const maxLimit = opts.maxLimit ?? 1e3;
|
|
3441
2259
|
if (rawLimit != null && String(rawLimit).trim() !== "") {
|
|
3442
2260
|
const parsed = typeof rawLimit === "number" ? rawLimit : Number(String(rawLimit).trim());
|
|
3443
2261
|
if (!Number.isInteger(parsed) || parsed < 1) throw new ListLimitError(`Invalid \`limit\`: ${String(rawLimit)}. Expected a whole number between 1 and ${maxLimit}.`, maxLimit);
|
|
3444
|
-
if (parsed > maxLimit) throw new ListLimitError(`\`limit\` ${parsed} is above the maximum of ${maxLimit}. Ask for at most ${maxLimit} rows per read and page through the rest with \`offset\`
|
|
2262
|
+
if (parsed > maxLimit) throw new ListLimitError(`\`limit\` ${parsed} is above the maximum of ${maxLimit}. Ask for at most ${maxLimit} rows per read and page through the rest with \`offset\` \u2014 answering with a smaller page would be indistinguishable from there being no more rows.`, maxLimit);
|
|
3445
2263
|
return parsed;
|
|
3446
2264
|
}
|
|
3447
2265
|
return opts.vectorSearch ? opts.vectorDefaultLimit ?? 10 : opts.defaultLimit ?? 50;
|
|
3448
2266
|
}
|
|
3449
2267
|
//#endregion
|
|
3450
2268
|
//#region src/controllers/storage.ts
|
|
3451
|
-
/**
|
|
3452
|
-
* Path prefix that marks an object as **public**. Files stored under this
|
|
3453
|
-
* prefix are served without any auth token via a stable, permanent,
|
|
3454
|
-
* CDN-cacheable URL (see {@link StorageSource.getSignedUrl}). Shared by the
|
|
3455
|
-
* client SDK and the backend so both agree on which objects are public.
|
|
3456
|
-
*
|
|
3457
|
-
* @group Models
|
|
3458
|
-
*/
|
|
3459
2269
|
var PUBLIC_STORAGE_PREFIX = "public/";
|
|
3460
|
-
/**
|
|
3461
|
-
* True when a storage **key** is public: it lies under
|
|
3462
|
-
* {@link PUBLIC_STORAGE_PREFIX}.
|
|
3463
|
-
*
|
|
3464
|
-
* The key is read exactly as it is — the canonical key within its bucket, the
|
|
3465
|
-
* one the server stores, serves, and hands a `storageAuthorize` hook as
|
|
3466
|
-
* `key` — and nothing is parsed out of it. That is the difference from
|
|
3467
|
-
* {@link isPublicStoragePath}, which reads a client-side *path* and so strips
|
|
3468
|
-
* a `scheme://` and a leading `default/` bucket segment first. On a key both are
|
|
3469
|
-
* wrong: `default/public/x` is a key in a folder called `default`, and a
|
|
3470
|
-
* request path `notes://public/x` names the key `notes:/public/x`. Neither is
|
|
3471
|
-
* public, and the server decides on this function so that it never says they
|
|
3472
|
-
* are.
|
|
3473
|
-
*
|
|
3474
|
-
* @group Models
|
|
3475
|
-
*/
|
|
3476
2270
|
function isPublicStorageKey(key) {
|
|
3477
2271
|
if (!key || !key.startsWith("public/")) return false;
|
|
3478
2272
|
return !key.split(/[\\/]/).includes("..");
|
|
3479
2273
|
}
|
|
3480
|
-
/**
|
|
3481
|
-
* True when a storage key or client-side path points at a public object
|
|
3482
|
-
* (lives under {@link PUBLIC_STORAGE_PREFIX}).
|
|
3483
|
-
*
|
|
3484
|
-
* For a path as a client holds it: a `scheme://` prefix and a single leading
|
|
3485
|
-
* `default/` bucket segment are stripped first. The server and a
|
|
3486
|
-
* `storageAuthorize` hook, which hold the canonical key, use
|
|
3487
|
-
* {@link isPublicStorageKey}.
|
|
3488
|
-
*
|
|
3489
|
-
* @group Models
|
|
3490
|
-
*/
|
|
3491
2274
|
function isPublicStoragePath(path) {
|
|
3492
2275
|
if (!path) return false;
|
|
3493
2276
|
let p = path;
|
|
@@ -3497,29 +2280,6 @@ function isPublicStoragePath(path) {
|
|
|
3497
2280
|
if (p.split("/").some((seg) => seg === "..")) return false;
|
|
3498
2281
|
return p.startsWith("public/") || p.startsWith(`default/public/`);
|
|
3499
2282
|
}
|
|
3500
|
-
/**
|
|
3501
|
-
* The path the storage routes address an object by, from a key or from the
|
|
3502
|
-
* `storageUrl` an upload returned (`<scheme>://<bucket>/<key>`, which is what a
|
|
3503
|
-
* property with `includeBucketUrl: true` keeps in its column).
|
|
3504
|
-
*
|
|
3505
|
-
* The routes address a source's objects by key. On S3 and GCS the bucket in a
|
|
3506
|
-
* `storageUrl` is always the source's own — the server refuses any other — so
|
|
3507
|
-
* it is dropped: sent along, `s3://acme-media/products/a.png` reached the
|
|
3508
|
-
* server as the key `acme-media/products/a.png`, the preview found nothing and
|
|
3509
|
-
* a delete reported success while the object stayed. It worked on local disk
|
|
3510
|
-
* only, because `local://default/<key>` happens to carry the one bucket
|
|
3511
|
-
* segment the routes recognise — which is kept, as is any other local bucket.
|
|
3512
|
-
*
|
|
3513
|
-
* A bare key whose first folder is `default` is sent behind that bucket
|
|
3514
|
-
* segment. The routes read one leading `default/` (in any case) as the bucket,
|
|
3515
|
-
* so the key `default/photo.png` sent as it is names the root `photo.png`:
|
|
3516
|
-
* {@link defaultBucketPath} is the spelling that names the key itself.
|
|
3517
|
-
*
|
|
3518
|
-
* Shared by every storage source that talks to those routes, so they address
|
|
3519
|
-
* an object alike.
|
|
3520
|
-
*
|
|
3521
|
-
* @group Models
|
|
3522
|
-
*/
|
|
3523
2283
|
function storageObjectPath(keyOrUrl, bucket) {
|
|
3524
2284
|
let filePath = keyOrUrl;
|
|
3525
2285
|
let bucketQualified = false;
|
|
@@ -3537,71 +2297,21 @@ function storageObjectPath(keyOrUrl, bucket) {
|
|
|
3537
2297
|
}
|
|
3538
2298
|
return bucketQualified ? filePath : defaultBucketPath(filePath);
|
|
3539
2299
|
}
|
|
3540
|
-
/**
|
|
3541
|
-
* The request path of a key in the default bucket: the key itself, unless the
|
|
3542
|
-
* routes would read its first folder as the bucket — a first folder named
|
|
3543
|
-
* `default`, matched as the routes match it (case-insensitively, and only when
|
|
3544
|
-
* something follows it). Then the bucket segment goes in front, so exactly the
|
|
3545
|
-
* one segment the routes strip is the one added.
|
|
3546
|
-
*/
|
|
3547
2300
|
function defaultBucketPath(key) {
|
|
3548
2301
|
const segments = key.split("/");
|
|
3549
2302
|
return segments.length > 1 && segments[0].toLowerCase() === "default" ? `default/${key}` : key;
|
|
3550
2303
|
}
|
|
3551
2304
|
//#endregion
|
|
3552
2305
|
//#region src/controllers/storage-references.ts
|
|
3553
|
-
/**
|
|
3554
|
-
* The scheme of a **storage reference**: a stored object named inside text.
|
|
3555
|
-
*
|
|
3556
|
-
* Text that embeds a file — a markdown body above all — cannot hold a private
|
|
3557
|
-
* object's URL: that URL carries a download token which expires in minutes,
|
|
3558
|
-
* after which every reader of the text gets a 401 for an image that is still in
|
|
3559
|
-
* the bucket. It holds a reference instead,
|
|
3560
|
-
* `rebase-storage:posts/cover.png` (`?storageId=media` for a named source),
|
|
3561
|
-
* and whoever renders the text exchanges each reference for a fresh URL with
|
|
3562
|
-
* {@link resolveStorageReferences} — `resolveStorageReferences(text, client)`
|
|
3563
|
-
* from `@rebasepro/client` on a site.
|
|
3564
|
-
*
|
|
3565
|
-
* @group Models
|
|
3566
|
-
*/
|
|
3567
2306
|
var STORAGE_REFERENCE_SCHEME = "rebase-storage:";
|
|
3568
|
-
/**
|
|
3569
|
-
* `encodeURIComponent`, plus the five characters it leaves alone that end or
|
|
3570
|
-
* break a markdown link destination: `(`, `)`, `'`, `!` and `*`.
|
|
3571
|
-
*/
|
|
3572
2307
|
var encodeReferencePart = (part) => encodeURIComponent(part).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
3573
|
-
/**
|
|
3574
|
-
* A reference as it appears in text: the scheme, then the characters
|
|
3575
|
-
* {@link storageReference} writes. Kept beside {@link STORAGE_REFERENCE_SCHEME};
|
|
3576
|
-
* the test round-trips names chosen to break it.
|
|
3577
|
-
*/
|
|
3578
2308
|
var STORAGE_REFERENCE_PATTERN = /rebase-storage:[A-Za-z0-9\-._~%/?=&]+/g;
|
|
3579
|
-
/**
|
|
3580
|
-
* The reference for an object — what text stores in place of its URL.
|
|
3581
|
-
*
|
|
3582
|
-
* Every part is percent-encoded, so the reference contains no space,
|
|
3583
|
-
* parenthesis or quote and survives as one markdown link destination whatever
|
|
3584
|
-
* the file was called.
|
|
3585
|
-
*
|
|
3586
|
-
* @group Models
|
|
3587
|
-
*/
|
|
3588
2309
|
function storageReference(key, storageId) {
|
|
3589
2310
|
return `${STORAGE_REFERENCE_SCHEME}${key.replace(/^\/+/, "").split("/").map(encodeReferencePart).join("/")}${storageId && storageId !== "(default)" ? `?storageId=${encodeReferencePart(storageId)}` : ""}`;
|
|
3590
2311
|
}
|
|
3591
|
-
/**
|
|
3592
|
-
* Whether a string — an image's `src`, a link's `href` — is a storage reference.
|
|
3593
|
-
*
|
|
3594
|
-
* @group Models
|
|
3595
|
-
*/
|
|
3596
2312
|
function isStorageReference(value) {
|
|
3597
2313
|
return typeof value === "string" && value.startsWith("rebase-storage:");
|
|
3598
2314
|
}
|
|
3599
|
-
/**
|
|
3600
|
-
* The object a storage reference names, or `null` for anything else — a URL, a
|
|
3601
|
-
* bare key, or a reference whose key would climb out of its prefix.
|
|
3602
|
-
*
|
|
3603
|
-
* @group Models
|
|
3604
|
-
*/
|
|
3605
2315
|
function parseStorageReference(value) {
|
|
3606
2316
|
if (!isStorageReference(value)) return null;
|
|
3607
2317
|
const rest = value.slice(15);
|
|
@@ -3625,7 +2335,6 @@ function parseStorageReference(value) {
|
|
|
3625
2335
|
storageId
|
|
3626
2336
|
} : { key };
|
|
3627
2337
|
}
|
|
3628
|
-
/** The JSON in a JWT's payload segment, or `undefined` for anything else. */
|
|
3629
2338
|
function jwtPayload(token) {
|
|
3630
2339
|
const segments = token.split(".");
|
|
3631
2340
|
if (segments.length !== 3) return void 0;
|
|
@@ -3639,20 +2348,6 @@ function jwtPayload(token) {
|
|
|
3639
2348
|
return;
|
|
3640
2349
|
}
|
|
3641
2350
|
}
|
|
3642
|
-
/**
|
|
3643
|
-
* The object a private file's download URL was minted for, or `null` for any
|
|
3644
|
-
* other URL.
|
|
3645
|
-
*
|
|
3646
|
-
* Text written before storage references stored such URLs —
|
|
3647
|
-
* `…/storage/file/posts/cover.png?token=…` — and their tokens expired minutes
|
|
3648
|
-
* later. The token still names the object it was minted for, so the URL can be
|
|
3649
|
-
* traded for a fresh one, or for a reference. Read without verifying the
|
|
3650
|
-
* token: it grants nothing here, it only says which object is meant, and the
|
|
3651
|
-
* key in the URL must agree with it. Host-agnostic, since a URL written
|
|
3652
|
-
* through one origin may be read through another.
|
|
3653
|
-
*
|
|
3654
|
-
* @group Models
|
|
3655
|
-
*/
|
|
3656
2351
|
function storageTargetOfDownloadUrl(url) {
|
|
3657
2352
|
let parsed;
|
|
3658
2353
|
try {
|
|
@@ -3680,13 +2375,7 @@ function storageTargetOfDownloadUrl(url) {
|
|
|
3680
2375
|
storageId: named
|
|
3681
2376
|
} : { key };
|
|
3682
2377
|
}
|
|
3683
|
-
/**
|
|
3684
|
-
* A private file's download URL as it may appear in text. Parentheses are
|
|
3685
|
-
* allowed in the path, where an unencoded file name puts them; the query, a
|
|
3686
|
-
* token, has none, so the match ends where a markdown destination does.
|
|
3687
|
-
*/
|
|
3688
2378
|
var DOWNLOAD_URL_PATTERN = /(?:https?:\/\/[^\s()<>"'\]]+)?\/storage\/file\/[^\s<>"'?#\]]+\?[^\s()<>"'#\]]*/g;
|
|
3689
|
-
/** Each download URL in `text` that names an object, with its reference. */
|
|
3690
2379
|
function downloadUrlsIn(text) {
|
|
3691
2380
|
const found = /* @__PURE__ */ new Map();
|
|
3692
2381
|
if (!text.includes("/storage/file/")) return found;
|
|
@@ -3696,49 +2385,14 @@ function downloadUrlsIn(text) {
|
|
|
3696
2385
|
}
|
|
3697
2386
|
return found;
|
|
3698
2387
|
}
|
|
3699
|
-
/**
|
|
3700
|
-
* Every object `text` names: its storage references, and the private files'
|
|
3701
|
-
* download URLs saved in it before references existed. An object named more
|
|
3702
|
-
* than once may be listed more than once.
|
|
3703
|
-
*
|
|
3704
|
-
* @group Models
|
|
3705
|
-
*/
|
|
3706
2388
|
function storageTargetsInText(text) {
|
|
3707
2389
|
return [...text.includes("rebase-storage:") ? text.match(STORAGE_REFERENCE_PATTERN) ?? [] : [], ...downloadUrlsIn(text).values()].map((reference) => parseStorageReference(reference)).filter((target) => target !== null);
|
|
3708
2390
|
}
|
|
3709
|
-
/**
|
|
3710
|
-
* `text` with every private file's download URL replaced by the storage
|
|
3711
|
-
* reference for its object — for rewriting text saved before references, so
|
|
3712
|
-
* it stores what new text stores. Any other URL is left as it is.
|
|
3713
|
-
*
|
|
3714
|
-
* @group Models
|
|
3715
|
-
*/
|
|
3716
2391
|
function storageReferencesForDownloadUrls(text) {
|
|
3717
2392
|
const urls = downloadUrlsIn(text);
|
|
3718
2393
|
if (urls.size === 0) return text;
|
|
3719
2394
|
return text.replace(DOWNLOAD_URL_PATTERN, (url) => urls.get(url) ?? url);
|
|
3720
2395
|
}
|
|
3721
|
-
/**
|
|
3722
|
-
* Exchange every storage reference in `text` for a URL, at the moment the text
|
|
3723
|
-
* is rendered.
|
|
3724
|
-
*
|
|
3725
|
-
* ```ts
|
|
3726
|
-
* const html = markdown.render(await resolveStorageReferences(post.body, client));
|
|
3727
|
-
* ```
|
|
3728
|
-
*
|
|
3729
|
-
* Each distinct object is asked for once — `getSignedUrl(key)` on its source —
|
|
3730
|
-
* so a private object gets a freshly minted download URL every time the text is
|
|
3731
|
-
* rendered. A reference that cannot be resolved (no such object, an unknown
|
|
3732
|
-
* source) is left as it was, so a missing object reads as a missing image
|
|
3733
|
-
* rather than as a failed render.
|
|
3734
|
-
*
|
|
3735
|
-
* A private file's download URL saved in the text before references existed
|
|
3736
|
-
* is renewed the same way: its expired token still names the object (see
|
|
3737
|
-
* {@link storageTargetOfDownloadUrl}). One that cannot be resolved is left as
|
|
3738
|
-
* it was.
|
|
3739
|
-
*
|
|
3740
|
-
* @group Models
|
|
3741
|
-
*/
|
|
3742
2396
|
async function resolveStorageReferences(text, from) {
|
|
3743
2397
|
if (!text) return text;
|
|
3744
2398
|
const downloadUrls = downloadUrlsIn(text);
|
|
@@ -3764,14 +2418,7 @@ async function resolveStorageReferences(text, from) {
|
|
|
3764
2418
|
return url === void 0 ? reference : asLinkDestination(url);
|
|
3765
2419
|
});
|
|
3766
2420
|
}
|
|
3767
|
-
/**
|
|
3768
|
-
* A URL as one markdown link destination: whitespace, parentheses, angle
|
|
3769
|
-
* brackets and quotes percent-encoded, since any of them ends the destination
|
|
3770
|
-
* and turns the image into literal text. The URL means the same thing either
|
|
3771
|
-
* way.
|
|
3772
|
-
*/
|
|
3773
2421
|
var asLinkDestination = (url) => url.replace(/[\s()<>"']/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`);
|
|
3774
|
-
/** A resolver over a client's storage sources, one source per named key. */
|
|
3775
2422
|
function resolverFromSources(client) {
|
|
3776
2423
|
const named = /* @__PURE__ */ new Map();
|
|
3777
2424
|
return async ({ key, storageId }) => {
|
|
@@ -3787,7 +2434,6 @@ function resolverFromSources(client) {
|
|
|
3787
2434
|
}
|
|
3788
2435
|
//#endregion
|
|
3789
2436
|
//#region src/controllers/aggregates.ts
|
|
3790
|
-
/** Every aggregate function, by its SDK name: what `?select=` accepts too. */
|
|
3791
2437
|
var AGGREGATE_FUNCTIONS = [
|
|
3792
2438
|
"count",
|
|
3793
2439
|
"sum",
|
|
@@ -3800,9 +2446,7 @@ var AGGREGATE_FUNCTIONS = [
|
|
|
3800
2446
|
"distinct",
|
|
3801
2447
|
"fingerprint"
|
|
3802
2448
|
];
|
|
3803
|
-
/** The functions that take no field. */
|
|
3804
2449
|
var FIELDLESS_AGGREGATES = /* @__PURE__ */ new Set(["count", "fingerprint"]);
|
|
3805
|
-
/** Every `groupBy` transform. */
|
|
3806
2450
|
var AGGREGATE_GROUP_TRANSFORMS = [
|
|
3807
2451
|
"lower",
|
|
3808
2452
|
"upper",
|
|
@@ -3811,38 +2455,18 @@ var AGGREGATE_GROUP_TRANSFORMS = [
|
|
|
3811
2455
|
"month",
|
|
3812
2456
|
"day"
|
|
3813
2457
|
];
|
|
3814
|
-
/** A function's name in its result key: the SDK's camelCase in SQL's spelling. */
|
|
3815
2458
|
var ALIAS_NAMES = { countDistinct: "count_distinct" };
|
|
3816
|
-
/**
|
|
3817
|
-
* `percentile`'s `p` as it reads in a key: `0.95` → `95`, `0.5` → `50`,
|
|
3818
|
-
* `0.995` → `99_5`.
|
|
3819
|
-
*/
|
|
3820
2459
|
function percentileLabel(p) {
|
|
3821
2460
|
return String(Math.round(p * 1e3) / 10).replace(".", "_");
|
|
3822
2461
|
}
|
|
3823
|
-
/**
|
|
3824
|
-
* The key an aggregate comes back under.
|
|
3825
|
-
*
|
|
3826
|
-
* `sum(total)` → `sum_total`, `count()` → `count`, `countDistinct(sid)` →
|
|
3827
|
-
* `count_distinct_sid`, `percentile(fame, 0.95)` → `p95_fame`. One function,
|
|
3828
|
-
* because the SDK, the REST parser and the HTTP client all derive it and have
|
|
3829
|
-
* to agree — a caller reading `row.sum_total` off an SDK result and off an HTTP
|
|
3830
|
-
* response is reading the same key or the SDK is broken.
|
|
3831
|
-
*/
|
|
3832
2462
|
function aggregateAlias(fn, field, p) {
|
|
3833
2463
|
if (fn === "percentile") return `p${percentileLabel(p ?? 0)}_${field ?? ""}`;
|
|
3834
2464
|
const name = ALIAS_NAMES[fn] ?? fn;
|
|
3835
2465
|
return field ? `${name}_${field}` : name;
|
|
3836
2466
|
}
|
|
3837
|
-
/** `percentile`'s `p`, refused unless it is a fraction a key can name (0–1, at most three decimals). */
|
|
3838
2467
|
function isPercentileFraction(p) {
|
|
3839
2468
|
return typeof p === "number" && Number.isFinite(p) && p >= 0 && p <= 1 && Math.abs(Math.round(p * 1e3) - p * 1e3) < 1e-9;
|
|
3840
2469
|
}
|
|
3841
|
-
/**
|
|
3842
|
-
* An `AggregateSelect` as a driver is handed it — but for its `where`, which
|
|
3843
|
-
* the caller decodes into the driver's `filter` (this package has no filter
|
|
3844
|
-
* codec).
|
|
3845
|
-
*/
|
|
3846
2470
|
function toDriverAggregate(select) {
|
|
3847
2471
|
const field = "field" in select ? select.field : void 0;
|
|
3848
2472
|
const p = select.fn === "percentile" ? select.p : void 0;
|
|
@@ -3853,7 +2477,6 @@ function toDriverAggregate(select) {
|
|
|
3853
2477
|
alias: select.as ?? aggregateAlias(select.fn, field, p)
|
|
3854
2478
|
};
|
|
3855
2479
|
}
|
|
3856
|
-
/** Whether `timeZone` names a time zone this runtime knows: an IANA name such as `Europe/Madrid`, or `UTC`. */
|
|
3857
2480
|
function isTimeZoneName(timeZone) {
|
|
3858
2481
|
if (typeof timeZone !== "string" || !/^[A-Za-z][A-Za-z0-9_+\-/]*$/.test(timeZone)) return false;
|
|
3859
2482
|
try {
|
|
@@ -3863,11 +2486,9 @@ function isTimeZoneName(timeZone) {
|
|
|
3863
2486
|
return false;
|
|
3864
2487
|
}
|
|
3865
2488
|
}
|
|
3866
|
-
/** The key a group comes back under: the column's name, or `<transform>_<field>`. */
|
|
3867
2489
|
function aggregateGroupKey(group) {
|
|
3868
2490
|
return typeof group === "string" ? group : `${group.transform}_${group.field}`;
|
|
3869
2491
|
}
|
|
3870
|
-
/** A `groupBy` entry as a driver is handed it. */
|
|
3871
2492
|
function toDriverAggregateGroup(group) {
|
|
3872
2493
|
return typeof group === "string" ? group : {
|
|
3873
2494
|
field: group.field,
|
|
@@ -3877,6 +2498,23 @@ function toDriverAggregateGroup(group) {
|
|
|
3877
2498
|
};
|
|
3878
2499
|
}
|
|
3879
2500
|
//#endregion
|
|
2501
|
+
//#region src/users/import.ts
|
|
2502
|
+
var MAX_USERS_PER_IMPORT = 100;
|
|
2503
|
+
var MAX_IMPORTED_USER_ID_LENGTH = 128;
|
|
2504
|
+
var RESERVED_USER_IDS = /* @__PURE__ */ new Set([
|
|
2505
|
+
"anonymous",
|
|
2506
|
+
"anon",
|
|
2507
|
+
"service",
|
|
2508
|
+
"default"
|
|
2509
|
+
]);
|
|
2510
|
+
function importedUserIdProblem(id) {
|
|
2511
|
+
if (typeof id !== "string") return "is not a string";
|
|
2512
|
+
if (id === "") return "is empty";
|
|
2513
|
+
if (id.length > 128) return `is longer than 128 characters`;
|
|
2514
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9_.:|-]*$/.test(id)) return "may hold only letters, digits and _ - . : |, starting with a letter or a digit";
|
|
2515
|
+
if (RESERVED_USER_IDS.has(id.toLowerCase())) return "is reserved: it names a caller who is not an account";
|
|
2516
|
+
}
|
|
2517
|
+
//#endregion
|
|
3880
2518
|
//#region src/schema/column_type.ts
|
|
3881
2519
|
var TEXT_KINDS = [
|
|
3882
2520
|
"text",
|
|
@@ -3899,46 +2537,18 @@ var TEMPORAL_KINDS = [
|
|
|
3899
2537
|
"date",
|
|
3900
2538
|
"time"
|
|
3901
2539
|
];
|
|
3902
|
-
/**
|
|
3903
|
-
* Whether a column type is stored as text (`text`, `varchar`, `char`).
|
|
3904
|
-
*
|
|
3905
|
-
* @group Schema
|
|
3906
|
-
*/
|
|
3907
2540
|
function isTextColumnType(type) {
|
|
3908
2541
|
return TEXT_KINDS.includes(type.kind);
|
|
3909
2542
|
}
|
|
3910
|
-
/**
|
|
3911
|
-
* Whether a column type is read and written as a JavaScript `number`.
|
|
3912
|
-
*
|
|
3913
|
-
* @group Schema
|
|
3914
|
-
*/
|
|
3915
2543
|
function isNumericColumnType(type) {
|
|
3916
2544
|
return NUMERIC_KINDS.includes(type.kind);
|
|
3917
2545
|
}
|
|
3918
|
-
/**
|
|
3919
|
-
* Whether a column type holds an instant, a day or a time of day.
|
|
3920
|
-
*
|
|
3921
|
-
* @group Schema
|
|
3922
|
-
*/
|
|
3923
2546
|
function isTemporalColumnType(type) {
|
|
3924
2547
|
return TEMPORAL_KINDS.includes(type.kind);
|
|
3925
2548
|
}
|
|
3926
|
-
/**
|
|
3927
|
-
* Whether a column type is a JSON document (`json`, `jsonb`).
|
|
3928
|
-
*
|
|
3929
|
-
* @group Schema
|
|
3930
|
-
*/
|
|
3931
2549
|
function isJsonColumnType(type) {
|
|
3932
2550
|
return type.kind === "json" || type.kind === "jsonb";
|
|
3933
2551
|
}
|
|
3934
|
-
/**
|
|
3935
|
-
* The SQL spelling of a column type, for messages and generated comments.
|
|
3936
|
-
*
|
|
3937
|
-
* Not the DDL renderer: an enum prints as `enum(a, b)` because its type name
|
|
3938
|
-
* belongs to the table it is planned in.
|
|
3939
|
-
*
|
|
3940
|
-
* @group Schema
|
|
3941
|
-
*/
|
|
3942
2552
|
function columnTypeLabel(type) {
|
|
3943
2553
|
switch (type.kind) {
|
|
3944
2554
|
case "varchar": return `varchar(${type.length})`;
|
|
@@ -3956,20 +2566,8 @@ function columnTypeLabel(type) {
|
|
|
3956
2566
|
}
|
|
3957
2567
|
//#endregion
|
|
3958
2568
|
//#region src/schema/column_options.ts
|
|
3959
|
-
/**
|
|
3960
|
-
* Per-role access in its stored form, checked: `read` and `write` must each be
|
|
3961
|
-
* a list of non-empty role names, and nothing else may be given.
|
|
3962
|
-
*
|
|
3963
|
-
* Checked at runtime because a JavaScript caller writing
|
|
3964
|
-
* `.access({ read: "admin" })` would otherwise have the string spread into
|
|
3965
|
-
* one role per character, silently.
|
|
3966
|
-
*
|
|
3967
|
-
* @param where What is being configured, for the error: `column "title"`.
|
|
3968
|
-
*
|
|
3969
|
-
* @group Schema
|
|
3970
|
-
*/
|
|
3971
2569
|
function normalizeColumnAccess(access, where) {
|
|
3972
|
-
const expected = "Write `{ read?: [\"role\",
|
|
2570
|
+
const expected = "Write `{ read?: [\"role\", \u2026], write?: [\"role\", \u2026] }`.";
|
|
3973
2571
|
if (typeof access !== "object" || access === null || Array.isArray(access)) throw new Error(`The access of ${where} must be an object of role lists, got ${JSON.stringify(access)}. ${expected}`);
|
|
3974
2572
|
const stored = {};
|
|
3975
2573
|
for (const [key, value] of Object.entries(access)) {
|
|
@@ -3981,13 +2579,6 @@ function normalizeColumnAccess(access, where) {
|
|
|
3981
2579
|
return stored;
|
|
3982
2580
|
}
|
|
3983
2581
|
var isoOf = (value) => value instanceof Date ? value.toISOString() : value;
|
|
3984
|
-
/**
|
|
3985
|
-
* Validation rules in their stored form: a `RegExp` becomes its source and
|
|
3986
|
-
* flags, a `Date` bound becomes an ISO string. What a builder keeps is then
|
|
3987
|
-
* exactly what the wire carries.
|
|
3988
|
-
*
|
|
3989
|
-
* @group Schema
|
|
3990
|
-
*/
|
|
3991
2582
|
function normalizeValidation(rules) {
|
|
3992
2583
|
const out = {};
|
|
3993
2584
|
for (const [key, value] of Object.entries(rules)) {
|
|
@@ -4012,15 +2603,6 @@ var BYTE_UNITS = {
|
|
|
4012
2603
|
gb: 1024 ** 3,
|
|
4013
2604
|
tb: 1024 ** 4
|
|
4014
2605
|
};
|
|
4015
|
-
/**
|
|
4016
|
-
* A size in bytes, from a number or from `"10MB"` / `"512 kb"` / `"1.5GB"`.
|
|
4017
|
-
*
|
|
4018
|
-
* Binary multiples (1 MB = 1,048,576 bytes), the unit a storage limit is
|
|
4019
|
-
* enforced in. Throws on anything else: a limit that silently parsed to `NaN`
|
|
4020
|
-
* is a limit that is never applied.
|
|
4021
|
-
*
|
|
4022
|
-
* @group Schema
|
|
4023
|
-
*/
|
|
4024
2606
|
function parseByteSize(size) {
|
|
4025
2607
|
if (typeof size === "number") {
|
|
4026
2608
|
if (!Number.isFinite(size) || size < 0) throw new Error(`A byte size must be a non-negative number, got ${size}.`);
|
|
@@ -4031,11 +2613,6 @@ function parseByteSize(size) {
|
|
|
4031
2613
|
const unit = (match[2] ?? "b").toLowerCase();
|
|
4032
2614
|
return Math.round(Number(match[1]) * BYTE_UNITS[unit]);
|
|
4033
2615
|
}
|
|
4034
|
-
/**
|
|
4035
|
-
* Storage options in their stored form.
|
|
4036
|
-
*
|
|
4037
|
-
* @group Schema
|
|
4038
|
-
*/
|
|
4039
2616
|
function normalizeStorage(options) {
|
|
4040
2617
|
if (typeof options.path !== "string" || options.path.length === 0) throw new Error("A storage column needs a `path`: where its files go, e.g. `col.storage({ path: \"posts/heroes/\" })`.");
|
|
4041
2618
|
const out = { path: options.path };
|
|
@@ -4052,15 +2629,7 @@ function normalizeStorage(options) {
|
|
|
4052
2629
|
}
|
|
4053
2630
|
//#endregion
|
|
4054
2631
|
//#region src/schema/json.ts
|
|
4055
|
-
/** The brand every JSON field builder carries, so one built by another copy of this package is still recognised. */
|
|
4056
2632
|
var JSON_FIELD_BRAND = "rebase.json-field";
|
|
4057
|
-
/**
|
|
4058
|
-
* One field of a JSON document: `json.string()`, `json.object({...})`, ….
|
|
4059
|
-
*
|
|
4060
|
-
* Immutable: every modifier returns a new field.
|
|
4061
|
-
*
|
|
4062
|
-
* @group Schema
|
|
4063
|
-
*/
|
|
4064
2633
|
var JsonField = class JsonField {
|
|
4065
2634
|
shape;
|
|
4066
2635
|
brand = JSON_FIELD_BRAND;
|
|
@@ -4070,48 +2639,34 @@ var JsonField = class JsonField {
|
|
|
4070
2639
|
with(patch) {
|
|
4071
2640
|
return new JsonField(Object.assign({}, this.shape, patch));
|
|
4072
2641
|
}
|
|
4073
|
-
/** The key must be present in the document. */
|
|
4074
2642
|
required() {
|
|
4075
2643
|
return this.with({ required: true });
|
|
4076
2644
|
}
|
|
4077
|
-
/** The value written when the key is absent on create. */
|
|
4078
2645
|
default(value) {
|
|
4079
2646
|
return this.with({ default: value });
|
|
4080
2647
|
}
|
|
4081
|
-
/** What the value is, for OpenAPI and MCP. */
|
|
4082
2648
|
describe(description) {
|
|
4083
2649
|
return this.with({ description });
|
|
4084
2650
|
}
|
|
4085
|
-
/** Rules the API checks before a write. */
|
|
4086
2651
|
validate(rules) {
|
|
4087
2652
|
const input = rules;
|
|
4088
2653
|
return this.with({ validate: normalizeValidation(input) });
|
|
4089
2654
|
}
|
|
4090
|
-
/** A closed set of accepted values. */
|
|
4091
2655
|
oneOf(values) {
|
|
4092
2656
|
return this.with({ oneOf: [...values] });
|
|
4093
2657
|
}
|
|
4094
|
-
/** The server writes the current time into the field when the row is created. */
|
|
4095
2658
|
onCreateNow() {
|
|
4096
2659
|
return this.with({ stamp: "create" });
|
|
4097
2660
|
}
|
|
4098
|
-
/** The server writes the current time into the field on every write. */
|
|
4099
2661
|
onUpdateNow() {
|
|
4100
2662
|
return this.with({ stamp: "update" });
|
|
4101
2663
|
}
|
|
4102
|
-
/** The server writes the caller's user id into the field when the row is created. */
|
|
4103
2664
|
onCreateUser() {
|
|
4104
2665
|
return this.with({ stamp: "createUser" });
|
|
4105
2666
|
}
|
|
4106
|
-
/** The server writes the caller's user id into the field on every write. */
|
|
4107
2667
|
onUpdateUser() {
|
|
4108
2668
|
return this.with({ stamp: "updateUser" });
|
|
4109
2669
|
}
|
|
4110
|
-
/**
|
|
4111
|
-
* The field holds the id of a user. The panel offers a user picker for it,
|
|
4112
|
-
* and callers who may write the table may look users up to fill it.
|
|
4113
|
-
* Only on `json.string()`; anything else throws.
|
|
4114
|
-
*/
|
|
4115
2670
|
userId() {
|
|
4116
2671
|
if (this.shape.kind !== "string" || this.shape.storage !== void 0) {
|
|
4117
2672
|
const what = this.shape.kind === "string" ? "`json.storage()`" : `a \`json.${this.shape.kind}()\` field`;
|
|
@@ -4119,14 +2674,6 @@ var JsonField = class JsonField {
|
|
|
4119
2674
|
}
|
|
4120
2675
|
return this.with({ semantic: "user" });
|
|
4121
2676
|
}
|
|
4122
|
-
/**
|
|
4123
|
-
* Field-level hooks. They run on the server only.
|
|
4124
|
-
*
|
|
4125
|
-
* The value is `TData | undefined` on a field not (yet) marked
|
|
4126
|
-
* `.required()` — the key can be absent from the document — and `TData` on
|
|
4127
|
-
* one that is; see {@link JsonTransformValue}. Chain `.required()` before
|
|
4128
|
-
* `.transform()` to get the narrower type.
|
|
4129
|
-
*/
|
|
4130
2677
|
transform(transform) {
|
|
4131
2678
|
const erased = transform;
|
|
4132
2679
|
return this.with({ transform: erased });
|
|
@@ -4137,54 +2684,28 @@ var shapesOf = (fields) => {
|
|
|
4137
2684
|
for (const [key, field] of Object.entries(fields)) out[key] = field.shape;
|
|
4138
2685
|
return out;
|
|
4139
2686
|
};
|
|
4140
|
-
/**
|
|
4141
|
-
* Builders for the shape of a `json`/`jsonb` document.
|
|
4142
|
-
*
|
|
4143
|
-
* ```ts
|
|
4144
|
-
* metadata: col.jsonb(json.object({
|
|
4145
|
-
* seoTitle: json.string().validate({ max: 60 }),
|
|
4146
|
-
* canonicalUrl: json.string().validate({ url: true }),
|
|
4147
|
-
* })),
|
|
4148
|
-
* content: col.jsonb(json.array(json.oneOf({
|
|
4149
|
-
* text: json.string(),
|
|
4150
|
-
* image: json.storage({ path: "posts/content/" }),
|
|
4151
|
-
* }))),
|
|
4152
|
-
* ```
|
|
4153
|
-
*
|
|
4154
|
-
* `col.jsonb().$type<T>()` on its own types the document statically; a shape also
|
|
4155
|
-
* tells the server what is inside it.
|
|
4156
|
-
*
|
|
4157
|
-
* @group Schema
|
|
4158
|
-
*/
|
|
4159
2687
|
var json = {
|
|
4160
|
-
/** A string. */
|
|
4161
2688
|
string() {
|
|
4162
2689
|
return new JsonField({ kind: "string" });
|
|
4163
2690
|
},
|
|
4164
|
-
/** A number. */
|
|
4165
2691
|
number() {
|
|
4166
2692
|
return new JsonField({ kind: "number" });
|
|
4167
2693
|
},
|
|
4168
|
-
/** A boolean. */
|
|
4169
2694
|
boolean() {
|
|
4170
2695
|
return new JsonField({ kind: "boolean" });
|
|
4171
2696
|
},
|
|
4172
|
-
/** An instant, stored as an ISO string. */
|
|
4173
2697
|
date() {
|
|
4174
2698
|
return new JsonField({ kind: "date" });
|
|
4175
2699
|
},
|
|
4176
|
-
/** A point on Earth: `{ latitude, longitude }`. */
|
|
4177
2700
|
geopoint() {
|
|
4178
2701
|
return new JsonField({ kind: "geopoint" });
|
|
4179
2702
|
},
|
|
4180
|
-
/** The path of a stored file. Counted by the orphan sweep like a `col.storage()` column. */
|
|
4181
2703
|
storage(options) {
|
|
4182
2704
|
return new JsonField({
|
|
4183
2705
|
kind: "string",
|
|
4184
2706
|
storage: normalizeStorage(options)
|
|
4185
2707
|
});
|
|
4186
2708
|
},
|
|
4187
|
-
/** An object with known keys. `additional: true` also accepts keys it does not name. */
|
|
4188
2709
|
object(fields, options = {}) {
|
|
4189
2710
|
const shape = {
|
|
4190
2711
|
kind: "object",
|
|
@@ -4193,17 +2714,12 @@ var json = {
|
|
|
4193
2714
|
if (options.additional) shape.additional = true;
|
|
4194
2715
|
return new JsonField(shape);
|
|
4195
2716
|
},
|
|
4196
|
-
/** An array of one shape. */
|
|
4197
2717
|
array(of) {
|
|
4198
2718
|
return new JsonField({
|
|
4199
2719
|
kind: "array",
|
|
4200
2720
|
of: of.shape
|
|
4201
2721
|
});
|
|
4202
2722
|
},
|
|
4203
|
-
/**
|
|
4204
|
-
* A typed block: `{ type: "<variant>", value: <its shape> }`. The keys are
|
|
4205
|
-
* `type` and `value` unless `typeField` / `valueField` say otherwise.
|
|
4206
|
-
*/
|
|
4207
2723
|
oneOf(variants, options = {}) {
|
|
4208
2724
|
return new JsonField({
|
|
4209
2725
|
kind: "oneOf",
|
|
@@ -4212,25 +2728,13 @@ var json = {
|
|
|
4212
2728
|
variants: shapesOf(variants)
|
|
4213
2729
|
});
|
|
4214
2730
|
},
|
|
4215
|
-
/** Anything. */
|
|
4216
2731
|
unknown() {
|
|
4217
2732
|
return new JsonField({ kind: "unknown" });
|
|
4218
2733
|
}
|
|
4219
2734
|
};
|
|
4220
|
-
/**
|
|
4221
|
-
* Whether a value is a JSON field builder, from this copy of the package or
|
|
4222
|
-
* another.
|
|
4223
|
-
*
|
|
4224
|
-
* @group Schema
|
|
4225
|
-
*/
|
|
4226
2735
|
function isJsonField(value) {
|
|
4227
2736
|
return typeof value === "object" && value !== null && "brand" in value && value.brand === "rebase.json-field";
|
|
4228
2737
|
}
|
|
4229
|
-
/**
|
|
4230
|
-
* A JSON shape without its hooks: what the wire carries.
|
|
4231
|
-
*
|
|
4232
|
-
* @group Schema
|
|
4233
|
-
*/
|
|
4234
2738
|
function describeJsonShape(shape) {
|
|
4235
2739
|
const { transform: _transform, ...rest } = shape;
|
|
4236
2740
|
switch (rest.kind) {
|
|
@@ -4259,87 +2763,39 @@ function describeJsonShape(shape) {
|
|
|
4259
2763
|
}
|
|
4260
2764
|
//#endregion
|
|
4261
2765
|
//#region src/schema/columns.ts
|
|
4262
|
-
/**
|
|
4263
|
-
* Every Drizzle spelling Rebase refuses, with the instruction it shows.
|
|
4264
|
-
*
|
|
4265
|
-
* Each text is used twice: as a string-literal *type* placed where the
|
|
4266
|
-
* developer wrote the refused thing (a `this` parameter, a config key, an
|
|
4267
|
-
* argument), so TypeScript prints the instruction verbatim; and as the message
|
|
4268
|
-
* thrown at run time, for a JavaScript caller the types do not reach. See
|
|
4269
|
-
* `drizzle-alignment.md` for the table of Drizzle spellings.
|
|
4270
|
-
*
|
|
4271
|
-
* @group Schema
|
|
4272
|
-
*/
|
|
4273
2766
|
var DRIZZLE_REFUSALS = {
|
|
4274
|
-
/** `col.timestamp()` without `withTimezone: true`: Drizzle's timestamp WITHOUT time zone. */
|
|
4275
2767
|
timestamp: "Rebase stores instants as timestamptz: write `col.timestamp({ withTimezone: true })`. For a timestamp without time zone write `col.custom({ dataType: \"timestamp\" })`.",
|
|
4276
|
-
/** `col.timestamp({ mode: "date" })`: Drizzle's Date-typed mode. */
|
|
4277
2768
|
timestampMode: "Rebase serves a timestamp as an ISO string: leave `mode` out or write `mode: \"string\"`.",
|
|
4278
|
-
/** `col.timestamp({ precision })`. */
|
|
4279
2769
|
timestampPrecision: "Rebase does not state a timestamp's precision: leave `precision` out, or write `col.custom({ dataType: \"timestamp(3) with time zone\" })`.",
|
|
4280
|
-
/** `col.date({ mode: "date" })`: Drizzle's Date-typed mode. */
|
|
4281
2770
|
dateMode: "Rebase serves a date as a `YYYY-MM-DD` string: leave `mode` out or write `mode: \"string\"`.",
|
|
4282
|
-
/** `col.time({ withTimezone: true })`: a `timetz`. */
|
|
4283
2771
|
timeZone: "`col.time()` is a time without time zone: leave `withTimezone` out, or write `col.custom({ dataType: \"timetz\" })`.",
|
|
4284
|
-
/** `col.time({ precision })`. */
|
|
4285
2772
|
timePrecision: "Rebase does not state a time's precision: leave `precision` out, or write `col.custom({ dataType: \"time(3)\" })`.",
|
|
4286
|
-
/** `col.numeric({ mode: "string" | "bigint" })`: our value is a JSON number. */
|
|
4287
2773
|
numericMode: "Rebase reads and writes numeric as a JSON number: leave `mode` out or write `mode: \"number\"`. For exact decimals kept as text write `col.text()`.",
|
|
4288
|
-
/** `col.bigint({ mode: "bigint" })`: our value is a JSON number. */
|
|
4289
2774
|
bigintMode: "Rebase serves bigint as a JSON number: write `{ mode: \"number\" }`. For exact 64-bit values write `col.numeric()` or `col.text()`.",
|
|
4290
|
-
/** `col.varchar("name")` / `col.varchar({ enum })` without a length. */
|
|
4291
2775
|
varcharLength: "`col.varchar()` needs a length (a bare varchar is unbounded in Postgres and Drizzle): write `col.varchar({ length: 255 })`, or `col.text()` for text of any length.",
|
|
4292
|
-
/** `col.char("name")` / `col.char({ enum })` without a length. */
|
|
4293
2776
|
charLength: "`col.char()` needs a length (a bare char is char(1) in Postgres and Drizzle): write `col.char({ length: 2 })`.",
|
|
4294
|
-
/** `.generatedAlwaysAsIdentity()`: the planner creates BY DEFAULT identities only. */
|
|
4295
2777
|
identityAlways: "Rebase creates identity columns GENERATED BY DEFAULT: write `.generatedByDefaultAsIdentity()`.",
|
|
4296
|
-
/** `.generatedByDefaultAsIdentity({ … })`: sequence options. */
|
|
4297
2778
|
identityOptions: "Rebase does not take sequence options: write `.generatedByDefaultAsIdentity()` with no argument.",
|
|
4298
|
-
/** `.references(() => …)`: a foreign key is a `rel.belongsTo`. */
|
|
4299
2779
|
references: "A foreign key is a relation in Rebase: write `relations: { author: rel.belongsTo(() => users, { localKey: \"author_id\", onDelete: \"cascade\" }) }`. The relation's key is what `include` names.",
|
|
4300
|
-
|
|
4301
|
-
defaultFn: "Rebase's schema is data, not code: a default is `.default(value)` or `.default(sql`…`)`; the time is `.defaultNow()` or `.onCreateNow()`, the caller `.onCreateUser()`; anything else belongs in `hooks.beforeSave`.",
|
|
4302
|
-
/** `.$onUpdate()` / `.$onUpdateFn()`: a run-time update function. */
|
|
2780
|
+
defaultFn: "Rebase's schema is data, not code: a default is `.default(value)` or `.default(sql`\u2026`)`; the time is `.defaultNow()` or `.onCreateNow()`, the caller `.onCreateUser()`; anything else belongs in `hooks.beforeSave`, with `.serverDefault()` on the column it fills.",
|
|
4303
2781
|
onUpdateFn: "Rebase's schema is data, not code: write `.onUpdateNow()` for the time, `.onUpdateUser()` for the caller; anything else belongs in `hooks.beforeSave`.",
|
|
4304
|
-
/** `.unique(name, { nulls })`: a named or NULLS NOT DISTINCT constraint. */
|
|
4305
2782
|
uniqueName: "Rebase derives constraint names and keeps NULLs distinct: write `.unique()`, or a unique index under `indexes`.",
|
|
4306
|
-
|
|
4307
|
-
generatedValue: "`.generatedAlwaysAs()` takes a SQL expression: write `.generatedAlwaysAs(sql`…`)`.",
|
|
4308
|
-
/** `.array(size)`. */
|
|
2783
|
+
generatedValue: "`.generatedAlwaysAs()` takes a SQL expression: write `.generatedAlwaysAs(sql`\u2026`)`.",
|
|
4309
2784
|
arraySize: "Postgres ignores array sizes: write `.array()`.",
|
|
4310
|
-
/** `.notNull()` & co. before `.array()`. */
|
|
4311
2785
|
arrayOrder: "`.notNull()`, a default, `.primaryKey()`, `.readOnly()` and `.private()` before `.array()` would describe each item: write them after it, as in `col.text().array().notNull()`.",
|
|
4312
|
-
/** `.array().array()`. */
|
|
4313
2786
|
arrayOfArray: "An array of arrays is not supported: use `col.jsonb()` for nested lists.",
|
|
4314
|
-
|
|
4315
|
-
sqlInterpolation: "`sql` writes its text into the DDL verbatim: write the expression inline, without `${…}`.",
|
|
4316
|
-
/** `col.bigint()` / `col.bigserial()` without `{ mode }`. */
|
|
2787
|
+
sqlInterpolation: "`sql` writes its text into the DDL verbatim: write the expression inline, without `${\u2026}`.",
|
|
4317
2788
|
bigintModeMissing: "`col.bigint()` and `col.bigserial()` take Drizzle's `{ mode: \"number\" }`: write `col.bigint({ mode: \"number\" })`.",
|
|
4318
|
-
/** `col.numeric(10, 2)`: positional precision and scale. */
|
|
4319
2789
|
numericPositional: "`col.numeric()` takes a config object: write `col.numeric({ precision: 10, scale: 2 })`.",
|
|
4320
|
-
/** `col.vector(1536)`: positional dimensions. */
|
|
4321
2790
|
vectorPositional: "`col.vector()` takes a config object: write `col.vector({ dimensions: 1536 })`.",
|
|
4322
|
-
/** `col.enum(values, { name })`: a named enum type. */
|
|
4323
2791
|
enumName: "A named Postgres enum type is declared once with `pgEnum`: write `const postStatus = pgEnum(\"post_status\", [...])`, then `postStatus()` in the column.",
|
|
4324
|
-
/** `col.custom("inet")`: a lone string is the SQL column name. */
|
|
4325
2792
|
customDataType: "`col.custom()` names its Postgres type in a config object: write `col.custom({ dataType: \"inet\" })`, or `col.custom(\"ip\", { dataType: \"inet\" })` with a SQL column name.",
|
|
4326
|
-
/** `pgEnum(name, { A: "a" })`: Drizzle's object form. */
|
|
4327
2793
|
pgEnumObject: "`pgEnum(name, values)` takes the list of labels: write `pgEnum(\"post_status\", [\"draft\", \"published\"])`."
|
|
4328
2794
|
};
|
|
4329
2795
|
function unsupportedMessage(type) {
|
|
4330
2796
|
return `Rebase has no \`col.${type}()\`: write \`col.custom({ dataType: "${type}" })\`. The value passes through as the driver returns it (a string).`;
|
|
4331
2797
|
}
|
|
4332
|
-
/** The brand of a {@link sql} expression. */
|
|
4333
2798
|
var SQL_BRAND = "rebase.sql";
|
|
4334
|
-
/**
|
|
4335
|
-
* A SQL expression for a default or a generated column, as Drizzle writes it:
|
|
4336
|
-
* `.default(sql\`gen_short_id()\`)`, `.generatedAlwaysAs(sql\`lower(email)\`)`.
|
|
4337
|
-
*
|
|
4338
|
-
* The text goes into the DDL verbatim, so it takes no interpolation: write the
|
|
4339
|
-
* expression inline.
|
|
4340
|
-
*
|
|
4341
|
-
* @group Schema
|
|
4342
|
-
*/
|
|
4343
2799
|
function sql(strings, ...values) {
|
|
4344
2800
|
if (values.length > 0 || strings.length !== 1) throw new Error(DRIZZLE_REFUSALS.sqlInterpolation);
|
|
4345
2801
|
const text = strings[0] ?? strings.raw[0];
|
|
@@ -4349,11 +2805,6 @@ function sql(strings, ...values) {
|
|
|
4349
2805
|
text
|
|
4350
2806
|
};
|
|
4351
2807
|
}
|
|
4352
|
-
/**
|
|
4353
|
-
* Whether a value is a {@link sql} expression, from this copy of the package or another.
|
|
4354
|
-
*
|
|
4355
|
-
* @group Schema
|
|
4356
|
-
*/
|
|
4357
2808
|
function isSqlTemplate(value) {
|
|
4358
2809
|
return typeof value === "object" && value !== null && "brand" in value && value.brand === "rebase.sql" && "text" in value && typeof value.text === "string";
|
|
4359
2810
|
}
|
|
@@ -4363,7 +2814,6 @@ var STAMP_METHODS = {
|
|
|
4363
2814
|
"create:user": ".onCreateUser",
|
|
4364
2815
|
"update:user": ".onUpdateUser"
|
|
4365
2816
|
};
|
|
4366
|
-
/** The brand every column builder carries, so one built by another copy of this package is still recognised. */
|
|
4367
2817
|
var COLUMN_BRAND = "rebase.column";
|
|
4368
2818
|
var baseDef = (type) => ({
|
|
4369
2819
|
type,
|
|
@@ -4373,19 +2823,6 @@ var baseDef = (type) => ({
|
|
|
4373
2823
|
readOnly: false,
|
|
4374
2824
|
private: false
|
|
4375
2825
|
});
|
|
4376
|
-
/**
|
|
4377
|
-
* One column of a table: `col.text()`, `col.uuid().primaryKey()`, ….
|
|
4378
|
-
*
|
|
4379
|
-
* Immutable — every modifier returns a new builder — so a column can be shared
|
|
4380
|
-
* between tables. Columns are nullable until `.notNull()` or `.primaryKey()`
|
|
4381
|
-
* says otherwise, as in SQL.
|
|
4382
|
-
*
|
|
4383
|
-
* @typeParam TData The TypeScript type of a value on the wire.
|
|
4384
|
-
* @typeParam TKind Which builder made it; decides which modifiers apply.
|
|
4385
|
-
* @typeParam F What has been said about it so far.
|
|
4386
|
-
*
|
|
4387
|
-
* @group Schema
|
|
4388
|
-
*/
|
|
4389
2826
|
var ColumnBuilder = class ColumnBuilder {
|
|
4390
2827
|
def;
|
|
4391
2828
|
brand = COLUMN_BRAND;
|
|
@@ -4398,52 +2835,27 @@ var ColumnBuilder = class ColumnBuilder {
|
|
|
4398
2835
|
...patch
|
|
4399
2836
|
});
|
|
4400
2837
|
}
|
|
4401
|
-
/**
|
|
4402
|
-
* The patch that sets a stamp, refusing a second, different one: a column
|
|
4403
|
-
* holds one stamp, so `.onCreateNow().onUpdateNow()` would otherwise keep
|
|
4404
|
-
* whichever came last without a word.
|
|
4405
|
-
*/
|
|
4406
2838
|
stamped(stamp, method) {
|
|
4407
2839
|
const current = this.def.stamp;
|
|
4408
2840
|
if (current && (current.on !== stamp.on || current.value !== stamp.value)) throw new Error(`\`.${method}()\` on a column that already has \`${STAMP_METHODS[`${current.on}:${current.value}`]}()\`: a column holds one stamp. \`.onUpdateNow()\` alone also stamps the row when it is created.`);
|
|
4409
2841
|
return { stamp };
|
|
4410
2842
|
}
|
|
4411
|
-
/**
|
|
4412
|
-
* Types the value without changing the column, as Drizzle's `$type`:
|
|
4413
|
-
* `col.jsonb().$type<{ seoTitle?: string }>()`, `col.integer().$type<UserId>()`.
|
|
4414
|
-
* Nothing is checked at run time; use `col.jsonb(json.object({...}))` for
|
|
4415
|
-
* a shape the server enforces.
|
|
4416
|
-
*/
|
|
4417
2843
|
$type() {
|
|
4418
2844
|
return this.with({});
|
|
4419
2845
|
}
|
|
4420
|
-
/** `NOT NULL`. The API requires the column on create unless it has a default. */
|
|
4421
2846
|
notNull() {
|
|
4422
2847
|
return this.with({ notNull: true });
|
|
4423
2848
|
}
|
|
4424
|
-
/**
|
|
4425
|
-
* Part of the primary key. Several columns marked this way form a composite
|
|
4426
|
-
* key, in declaration order.
|
|
4427
|
-
*/
|
|
4428
2849
|
primaryKey() {
|
|
4429
2850
|
return this.with({
|
|
4430
2851
|
primaryKey: true,
|
|
4431
2852
|
notNull: true
|
|
4432
2853
|
});
|
|
4433
2854
|
}
|
|
4434
|
-
/**
|
|
4435
|
-
* A single-column `UNIQUE` constraint. Its name is derived; Drizzle's
|
|
4436
|
-
* `.unique(name, { nulls })` arguments are refused.
|
|
4437
|
-
*/
|
|
4438
2855
|
unique(name, config) {
|
|
4439
2856
|
if (name !== void 0 || config !== void 0) throw new Error(DRIZZLE_REFUSALS.uniqueName);
|
|
4440
2857
|
return this.with({ unique: true });
|
|
4441
2858
|
}
|
|
4442
|
-
/**
|
|
4443
|
-
* A default: a value, written as the column's DDL default and applied by
|
|
4444
|
-
* the driver on create, so a row comes out the same whoever inserts it — or
|
|
4445
|
-
* an expression Postgres evaluates, `.default(sql\`gen_short_id()\`)`.
|
|
4446
|
-
*/
|
|
4447
2859
|
default(value) {
|
|
4448
2860
|
if (isSqlTemplate(value)) return this.with({ default: {
|
|
4449
2861
|
kind: "sql",
|
|
@@ -4455,41 +2867,27 @@ var ColumnBuilder = class ColumnBuilder {
|
|
|
4455
2867
|
value: stored
|
|
4456
2868
|
} });
|
|
4457
2869
|
}
|
|
4458
|
-
/** Refused: Drizzle's run-time default function. See {@link DRIZZLE_REFUSALS}. */
|
|
4459
2870
|
$defaultFn(..._args) {
|
|
4460
2871
|
throw new Error(DRIZZLE_REFUSALS.defaultFn);
|
|
4461
2872
|
}
|
|
4462
|
-
/** Refused: Drizzle's alias of `$defaultFn`. See {@link DRIZZLE_REFUSALS}. */
|
|
4463
2873
|
$default(..._args) {
|
|
4464
2874
|
throw new Error(DRIZZLE_REFUSALS.defaultFn);
|
|
4465
2875
|
}
|
|
4466
|
-
/** Refused: Drizzle's run-time update function. See {@link DRIZZLE_REFUSALS}. */
|
|
4467
2876
|
$onUpdate(..._args) {
|
|
4468
2877
|
throw new Error(DRIZZLE_REFUSALS.onUpdateFn);
|
|
4469
2878
|
}
|
|
4470
|
-
/** Refused: Drizzle's run-time update function. See {@link DRIZZLE_REFUSALS}. */
|
|
4471
2879
|
$onUpdateFn(..._args) {
|
|
4472
2880
|
throw new Error(DRIZZLE_REFUSALS.onUpdateFn);
|
|
4473
2881
|
}
|
|
4474
|
-
/**
|
|
4475
|
-
* Refused: a foreign key is a relation, `rel.belongsTo(() => users, {...})`
|
|
4476
|
-
* under `relations`, whose key is what `include` names.
|
|
4477
|
-
*/
|
|
4478
2882
|
references(..._args) {
|
|
4479
2883
|
throw new Error(DRIZZLE_REFUSALS.references);
|
|
4480
2884
|
}
|
|
4481
|
-
/**
|
|
4482
|
-
* The database already holds a default for this column that Rebase does not
|
|
4483
|
-
* state. A create may omit the column, and a schema push leaves the default
|
|
4484
|
-
* alone.
|
|
4485
|
-
*/
|
|
4486
2885
|
dbDefault() {
|
|
4487
2886
|
return this.with({ default: { kind: "database" } });
|
|
4488
2887
|
}
|
|
4489
|
-
|
|
4490
|
-
|
|
4491
|
-
|
|
4492
|
-
*/
|
|
2888
|
+
serverDefault() {
|
|
2889
|
+
return this.with({ default: { kind: "server" } });
|
|
2890
|
+
}
|
|
4493
2891
|
generatedAlwaysAs(as) {
|
|
4494
2892
|
const expression = typeof as === "function" ? as() : as;
|
|
4495
2893
|
if (!isSqlTemplate(expression)) throw new Error(DRIZZLE_REFUSALS.generatedValue);
|
|
@@ -4498,34 +2896,18 @@ var ColumnBuilder = class ColumnBuilder {
|
|
|
4498
2896
|
readOnly: true
|
|
4499
2897
|
});
|
|
4500
2898
|
}
|
|
4501
|
-
/**
|
|
4502
|
-
* Client writes are refused on create and update. The database (a default,
|
|
4503
|
-
* a trigger) and the server's own code still fill it.
|
|
4504
|
-
*/
|
|
4505
2899
|
readOnly() {
|
|
4506
2900
|
return this.with({ readOnly: true });
|
|
4507
2901
|
}
|
|
4508
|
-
/**
|
|
4509
|
-
* Never leaves the server: absent from every row on the wire, from the SDK
|
|
4510
|
-
* and from OpenAPI, and refused in filters and sorts. Hooks and server code
|
|
4511
|
-
* still see it.
|
|
4512
|
-
*/
|
|
4513
2902
|
private() {
|
|
4514
2903
|
return this.with({ private: true });
|
|
4515
2904
|
}
|
|
4516
|
-
/**
|
|
4517
|
-
* Who may read and who may write the column, by role. Enforced on every
|
|
4518
|
-
* door into the table, not only in the panel. `read` and `write` are lists
|
|
4519
|
-
* of role names; anything else throws.
|
|
4520
|
-
*/
|
|
4521
2905
|
access(access) {
|
|
4522
2906
|
return this.with({ access: normalizeColumnAccess(access, "a column (`.access()`)") });
|
|
4523
2907
|
}
|
|
4524
|
-
/** What the column holds, for OpenAPI and MCP tool descriptions. */
|
|
4525
2908
|
describe(description) {
|
|
4526
2909
|
return this.with({ description });
|
|
4527
2910
|
}
|
|
4528
|
-
/** Rules the API checks before a write. */
|
|
4529
2911
|
validate(rules) {
|
|
4530
2912
|
const input = rules;
|
|
4531
2913
|
return this.with({ validate: {
|
|
@@ -4533,27 +2915,10 @@ var ColumnBuilder = class ColumnBuilder {
|
|
|
4533
2915
|
...normalizeValidation(input)
|
|
4534
2916
|
} });
|
|
4535
2917
|
}
|
|
4536
|
-
/**
|
|
4537
|
-
* Field-level hooks: `beforeSave` returns the value to store, `afterRead`
|
|
4538
|
-
* the value to serve. They run on the server, for every caller.
|
|
4539
|
-
*
|
|
4540
|
-
* The value is `TData | null` on a column not (yet) marked `.notNull()` /
|
|
4541
|
-
* `.primaryKey()` — a nullable column hands the hook `null` — and `TData`
|
|
4542
|
-
* on one that is; see {@link ColumnTransformValue}. Chain `.notNull()`
|
|
4543
|
-
* before `.transform()` to get the narrower type.
|
|
4544
|
-
*/
|
|
4545
2918
|
transform(transform) {
|
|
4546
2919
|
const erased = transform;
|
|
4547
2920
|
return this.with({ transform: erased });
|
|
4548
2921
|
}
|
|
4549
|
-
/**
|
|
4550
|
-
* A closed set of accepted values that is *not* a Postgres enum type: the
|
|
4551
|
-
* API refuses anything else and the SDK types the column as their union.
|
|
4552
|
-
* Use `col.enum()` when the database should enforce it too.
|
|
4553
|
-
*
|
|
4554
|
-
* On a number column. On a text column write Drizzle's spelling,
|
|
4555
|
-
* `col.text({ enum: [...] })`.
|
|
4556
|
-
*/
|
|
4557
2922
|
oneOf(values) {
|
|
4558
2923
|
const stored = [];
|
|
4559
2924
|
for (const value of values) {
|
|
@@ -4562,27 +2927,16 @@ var ColumnBuilder = class ColumnBuilder {
|
|
|
4562
2927
|
}
|
|
4563
2928
|
return this.with({ oneOf: stored });
|
|
4564
2929
|
}
|
|
4565
|
-
/** `DEFAULT gen_random_uuid()`. */
|
|
4566
2930
|
defaultRandom() {
|
|
4567
2931
|
return this.with({ default: { kind: "random-uuid" } });
|
|
4568
2932
|
}
|
|
4569
|
-
/** `GENERATED BY DEFAULT AS IDENTITY`. Sequence options are refused. */
|
|
4570
2933
|
generatedByDefaultAsIdentity(sequence) {
|
|
4571
2934
|
if (sequence !== void 0) throw new Error(DRIZZLE_REFUSALS.identityOptions);
|
|
4572
2935
|
return this.with({ default: { kind: "identity" } });
|
|
4573
2936
|
}
|
|
4574
|
-
/** Refused: Rebase creates identity columns `GENERATED BY DEFAULT`. See {@link DRIZZLE_REFUSALS}. */
|
|
4575
2937
|
generatedAlwaysAsIdentity(..._args) {
|
|
4576
2938
|
throw new Error(DRIZZLE_REFUSALS.identityAlways);
|
|
4577
2939
|
}
|
|
4578
|
-
/**
|
|
4579
|
-
* A Postgres array of this column's type, as Drizzle writes it:
|
|
4580
|
-
* `col.text().array()` is `TEXT[]`. What is chained before `.array()`
|
|
4581
|
-
* describes each item (`col.text({ enum: [...] }).array()`,
|
|
4582
|
-
* `col.integer().validate({ min: 0 }).array()`); column modifiers come
|
|
4583
|
-
* after it (`.array().notNull().default([])`). A leading SQL name
|
|
4584
|
-
* (`col.text("tag_list").array()`) names the array column.
|
|
4585
|
-
*/
|
|
4586
2940
|
array(size) {
|
|
4587
2941
|
if (size !== void 0) throw new Error(DRIZZLE_REFUSALS.arraySize);
|
|
4588
2942
|
if (!isColumnBuilder(this)) throw new Error("`.array()` is called on a column builder.");
|
|
@@ -4592,57 +2946,36 @@ var ColumnBuilder = class ColumnBuilder {
|
|
|
4592
2946
|
if (column !== void 0) def.column = column;
|
|
4593
2947
|
return new ColumnBuilder(def);
|
|
4594
2948
|
}
|
|
4595
|
-
/**
|
|
4596
|
-
* `DEFAULT now()`, as Drizzle's `defaultNow()`: a DDL default a client may
|
|
4597
|
-
* still override. `.onCreateNow()` is the server stamp the client cannot.
|
|
4598
|
-
*/
|
|
4599
2949
|
defaultNow() {
|
|
4600
2950
|
return this.with({ default: {
|
|
4601
2951
|
kind: "sql",
|
|
4602
2952
|
expression: "now()"
|
|
4603
2953
|
} });
|
|
4604
2954
|
}
|
|
4605
|
-
/** The server stamps the current time when the row is created (`DEFAULT now()`). */
|
|
4606
2955
|
onCreateNow() {
|
|
4607
2956
|
return this.with(this.stamped({
|
|
4608
2957
|
on: "create",
|
|
4609
2958
|
value: "now"
|
|
4610
2959
|
}, "onCreateNow"));
|
|
4611
2960
|
}
|
|
4612
|
-
/**
|
|
4613
|
-
* The server stamps the current time on every write: `DEFAULT now()`, a
|
|
4614
|
-
* `BEFORE UPDATE` trigger, and the driver's own stamp.
|
|
4615
|
-
*/
|
|
4616
2961
|
onUpdateNow() {
|
|
4617
2962
|
return this.with(this.stamped({
|
|
4618
2963
|
on: "update",
|
|
4619
2964
|
value: "now"
|
|
4620
2965
|
}, "onUpdateNow"));
|
|
4621
2966
|
}
|
|
4622
|
-
/** The server writes the caller's id when the row is created. */
|
|
4623
2967
|
onCreateUser() {
|
|
4624
2968
|
return this.with(this.stamped({
|
|
4625
2969
|
on: "create",
|
|
4626
2970
|
value: "user"
|
|
4627
2971
|
}, "onCreateUser"));
|
|
4628
2972
|
}
|
|
4629
|
-
/** The server writes the caller's id on every write. */
|
|
4630
2973
|
onUpdateUser() {
|
|
4631
2974
|
return this.with(this.stamped({
|
|
4632
2975
|
on: "update",
|
|
4633
2976
|
value: "user"
|
|
4634
2977
|
}, "onUpdateUser"));
|
|
4635
2978
|
}
|
|
4636
|
-
/**
|
|
4637
|
-
* The column holds the id of a user. The panel offers a user picker for it,
|
|
4638
|
-
* and callers who may write the table may look users up to fill it (the
|
|
4639
|
-
* user picker's read answers them even though row-level security hides
|
|
4640
|
-
* other users' rows).
|
|
4641
|
-
*
|
|
4642
|
-
* Only on `col.text()`, `col.varchar()`, `col.char()` and `col.uuid()`;
|
|
4643
|
-
* anything else throws. It declares no foreign key: use
|
|
4644
|
-
* `rel.belongsTo(() => users)` when the database should enforce one.
|
|
4645
|
-
*/
|
|
4646
2979
|
userId() {
|
|
4647
2980
|
const kind = this.def.type.kind;
|
|
4648
2981
|
if (kind !== "text" && kind !== "varchar" && kind !== "char" && kind !== "uuid" || this.def.storage !== void 0) {
|
|
@@ -4651,7 +2984,6 @@ var ColumnBuilder = class ColumnBuilder {
|
|
|
4651
2984
|
}
|
|
4652
2985
|
return this.with({ semantic: "user" });
|
|
4653
2986
|
}
|
|
4654
|
-
/** The column holds several files: `TEXT[]` of paths. */
|
|
4655
2987
|
multiple() {
|
|
4656
2988
|
const { storage, validate, ...rest } = this.def;
|
|
4657
2989
|
return new ColumnBuilder({
|
|
@@ -4669,30 +3001,25 @@ var ColumnBuilder = class ColumnBuilder {
|
|
|
4669
3001
|
});
|
|
4670
3002
|
}
|
|
4671
3003
|
};
|
|
4672
|
-
/** The SQL column name a builder's leading argument gives, checked. */
|
|
4673
3004
|
function sqlName(name, builder) {
|
|
4674
3005
|
if (name === void 0) return void 0;
|
|
4675
|
-
if (typeof name !== "string" || name.length === 0) throw new Error(`\`col.${builder}(name,
|
|
3006
|
+
if (typeof name !== "string" || name.length === 0) throw new Error(`\`col.${builder}(name, \u2026)\`: the leading argument is the SQL column name, a non-empty string.`);
|
|
4676
3007
|
return name;
|
|
4677
3008
|
}
|
|
4678
|
-
/** A fresh definition, named by the builder's leading argument when it has one. */
|
|
4679
3009
|
function namedDef(type, name, builder) {
|
|
4680
3010
|
const def = baseDef(type);
|
|
4681
3011
|
const column = sqlName(name, builder);
|
|
4682
3012
|
if (column !== void 0) def.column = column;
|
|
4683
3013
|
return def;
|
|
4684
3014
|
}
|
|
4685
|
-
/** Drizzle's `(name?, config?)` arguments, either of which may be left out. */
|
|
4686
3015
|
function nameAndConfig(first, second) {
|
|
4687
3016
|
return typeof first === "string" ? [first, second] : [void 0, first];
|
|
4688
3017
|
}
|
|
4689
|
-
/** A config object, checked at run time: JavaScript callers bypass the types. */
|
|
4690
3018
|
function configOf(value, builder) {
|
|
4691
3019
|
if (value === void 0) return {};
|
|
4692
3020
|
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`\`col.${builder}()\` takes an optional SQL column name and a config object, got ${JSON.stringify(value)}.`);
|
|
4693
3021
|
return { ...value };
|
|
4694
3022
|
}
|
|
4695
|
-
/** The definition of an array of `item`: what `col.text().array()` builds. */
|
|
4696
3023
|
function arrayDef(item) {
|
|
4697
3024
|
if (item.type.kind === "array") throw new Error(DRIZZLE_REFUSALS.arrayOfArray);
|
|
4698
3025
|
const def = baseDef({
|
|
@@ -4703,7 +3030,6 @@ function arrayDef(item) {
|
|
|
4703
3030
|
if (item.storage) def.storage = item.storage;
|
|
4704
3031
|
return def;
|
|
4705
3032
|
}
|
|
4706
|
-
/** A list of string labels: an enum's values, Drizzle's `{ enum: [...] }`. */
|
|
4707
3033
|
function labelsOf(values, where) {
|
|
4708
3034
|
if (!Array.isArray(values) || values.length === 0 || values.some((value) => typeof value !== "string")) throw new Error(`${where} takes a non-empty list of strings, got ${JSON.stringify(values)}.`);
|
|
4709
3035
|
return values.filter((value) => typeof value === "string");
|
|
@@ -4734,7 +3060,6 @@ function text(first, second) {
|
|
|
4734
3060
|
if (config.enum !== void 0) def.oneOf = labelsOf(config.enum, "`col.text({ enum })`");
|
|
4735
3061
|
return new ColumnBuilder(def);
|
|
4736
3062
|
}
|
|
4737
|
-
/** `varchar` / `char`: Drizzle's `(name?, { length, enum? })`. A length is required. */
|
|
4738
3063
|
function stringColumn(kind, first, second) {
|
|
4739
3064
|
const name = typeof first === "string" ? first : void 0;
|
|
4740
3065
|
const raw = typeof first === "string" ? second : first;
|
|
@@ -4770,7 +3095,6 @@ function enumColumn(first, second) {
|
|
|
4770
3095
|
values: [...first]
|
|
4771
3096
|
}));
|
|
4772
3097
|
}
|
|
4773
|
-
/** `numeric`, Drizzle's `(name?, { precision, scale, mode })`. */
|
|
4774
3098
|
function numericColumn(builder, first, second) {
|
|
4775
3099
|
if (typeof first === "number" || typeof second === "number") throw new Error(DRIZZLE_REFUSALS.numericPositional);
|
|
4776
3100
|
const name = typeof first === "string" ? first : void 0;
|
|
@@ -4795,7 +3119,6 @@ function numeric(first, second) {
|
|
|
4795
3119
|
function decimal(first, second) {
|
|
4796
3120
|
return numericColumn("decimal", first, second);
|
|
4797
3121
|
}
|
|
4798
|
-
/** `bigint` / `bigserial`, Drizzle's `(name?, { mode })`. */
|
|
4799
3122
|
function bigColumn(kind, first, second) {
|
|
4800
3123
|
const name = typeof first === "string" ? first : void 0;
|
|
4801
3124
|
const raw = typeof first === "string" ? second : first;
|
|
@@ -4862,143 +3185,58 @@ function custom(first, second) {
|
|
|
4862
3185
|
sqlType: customSqlType(config.dataType)
|
|
4863
3186
|
}, name, "custom"));
|
|
4864
3187
|
}
|
|
4865
|
-
/** A builder for a Drizzle column type Rebase serves only through `col.custom()`: refused with the spelling. */
|
|
4866
3188
|
function unsupported(type) {
|
|
4867
3189
|
return () => {
|
|
4868
3190
|
throw new Error(unsupportedMessage(type));
|
|
4869
3191
|
};
|
|
4870
3192
|
}
|
|
4871
|
-
/** A builder that takes only the optional SQL column name. */
|
|
4872
3193
|
function simple(kind, type) {
|
|
4873
3194
|
return (name) => new ColumnBuilder(namedDef(type, name, kind));
|
|
4874
3195
|
}
|
|
4875
|
-
/**
|
|
4876
|
-
* The column builders, spelled as Drizzle's `pg-core` spells them: the
|
|
4877
|
-
* optional SQL column name first, then Drizzle's config object, then the
|
|
4878
|
-
* chain.
|
|
4879
|
-
*
|
|
4880
|
-
* ```ts
|
|
4881
|
-
* columns: {
|
|
4882
|
-
* id: col.uuid().primaryKey().defaultRandom(),
|
|
4883
|
-
* title: col.text().notNull().validate({ min: 3, max: 200 }),
|
|
4884
|
-
* slug: col.varchar({ length: 160 }).notNull().unique(),
|
|
4885
|
-
* status: postStatus().notNull().default("draft"), // const postStatus = pgEnum("post_status", [...])
|
|
4886
|
-
* tags: col.text().array().notNull().default([]),
|
|
4887
|
-
* heroImage: col.storage({ path: "posts/heroes/", accept: ["image/*"], maxBytes: "10MB" }),
|
|
4888
|
-
* createdAt: col.timestamp({ withTimezone: true }).notNull().defaultNow(),
|
|
4889
|
-
* }
|
|
4890
|
-
* ```
|
|
4891
|
-
*
|
|
4892
|
-
* @group Schema
|
|
4893
|
-
*/
|
|
4894
3196
|
var col = {
|
|
4895
|
-
/** `UUID`. */
|
|
4896
3197
|
uuid: simple("uuid", { kind: "uuid" }),
|
|
4897
|
-
/** `TEXT`. `col.text({ enum: [...] })` accepts only those values. */
|
|
4898
3198
|
text,
|
|
4899
|
-
/** `VARCHAR(n)`: `col.varchar({ length: n })`. */
|
|
4900
3199
|
varchar,
|
|
4901
|
-
/** `CHAR(n)`: `col.char({ length: n })`. */
|
|
4902
3200
|
char,
|
|
4903
|
-
/**
|
|
4904
|
-
* A Postgres enum type of its own, created as `<table>_<column>`. A type
|
|
4905
|
-
* with a stated name, shared by several columns, is `pgEnum(name, values)`.
|
|
4906
|
-
*/
|
|
4907
3201
|
enum: enumColumn,
|
|
4908
|
-
/** `SMALLINT`. */
|
|
4909
3202
|
smallint: simple("smallint", { kind: "smallint" }),
|
|
4910
|
-
/** `INTEGER`. */
|
|
4911
3203
|
integer: simple("integer", { kind: "integer" }),
|
|
4912
|
-
/** `BIGINT`, read and written as a JavaScript number: `col.bigint({ mode: "number" })`. */
|
|
4913
3204
|
bigint,
|
|
4914
|
-
/** `SMALLSERIAL`. Prefer `col.smallint().generatedByDefaultAsIdentity()` in a new schema. */
|
|
4915
3205
|
smallserial(name) {
|
|
4916
3206
|
return new ColumnBuilder(namedDef({ kind: "smallserial" }, name, "smallserial"));
|
|
4917
3207
|
},
|
|
4918
|
-
/** `SERIAL`. Prefer `col.integer().generatedByDefaultAsIdentity()` in a new schema. */
|
|
4919
3208
|
serial(name) {
|
|
4920
3209
|
return new ColumnBuilder(namedDef({ kind: "serial" }, name, "serial"));
|
|
4921
3210
|
},
|
|
4922
|
-
/** `BIGSERIAL`: `col.bigserial({ mode: "number" })`. Prefer an identity column in a new schema. */
|
|
4923
3211
|
bigserial,
|
|
4924
|
-
/** `REAL`. */
|
|
4925
3212
|
real: simple("real", { kind: "real" }),
|
|
4926
|
-
/** `DOUBLE PRECISION`. */
|
|
4927
3213
|
doublePrecision: simple("doublePrecision", { kind: "doublePrecision" }),
|
|
4928
|
-
/** `NUMERIC`, `NUMERIC(p)` or `NUMERIC(p, s)`: `col.numeric({ precision, scale })`. A JSON number. */
|
|
4929
3214
|
numeric,
|
|
4930
|
-
/** Drizzle's alias of `col.numeric()`. */
|
|
4931
3215
|
decimal,
|
|
4932
|
-
/** `BOOLEAN`. */
|
|
4933
3216
|
boolean: simple("boolean", { kind: "boolean" }),
|
|
4934
|
-
/** `TIMESTAMPTZ`: `col.timestamp({ withTimezone: true })`. An ISO string on the wire. */
|
|
4935
3217
|
timestamp,
|
|
4936
|
-
/** `DATE`. `YYYY-MM-DD` on the wire. */
|
|
4937
3218
|
date,
|
|
4938
|
-
/** `TIME`. `HH:MM:SS` on the wire. */
|
|
4939
3219
|
time,
|
|
4940
|
-
/**
|
|
4941
|
-
* `JSONB`. `col.jsonb().$type<T>()` types the document;
|
|
4942
|
-
* `col.jsonb(json.object({...}))` also tells the server its shape, so
|
|
4943
|
-
* nested fields are validated, stamped and searchable.
|
|
4944
|
-
*/
|
|
4945
3220
|
jsonb,
|
|
4946
|
-
/** `JSON`. As `col.jsonb`, for a column that must keep the text it was given. */
|
|
4947
3221
|
json: json$1,
|
|
4948
|
-
/**
|
|
4949
|
-
* `vector(dimensions)` (pgvector): `col.vector({ dimensions: 1536 })`. An
|
|
4950
|
-
* HNSW cosine index is created unless `index` says otherwise; `index: false`
|
|
4951
|
-
* creates none.
|
|
4952
|
-
*/
|
|
4953
3222
|
vector,
|
|
4954
|
-
/** `BYTEA`. Base64 on the wire. */
|
|
4955
3223
|
bytea: simple("bytea", { kind: "bytea" }),
|
|
4956
|
-
/** A point on Earth, stored as `JSONB` `{ latitude, longitude }`. */
|
|
4957
3224
|
geopoint(name) {
|
|
4958
3225
|
const def = namedDef({ kind: "jsonb" }, name, "geopoint");
|
|
4959
3226
|
def.semantic = "geopoint";
|
|
4960
3227
|
return new ColumnBuilder(def);
|
|
4961
3228
|
},
|
|
4962
|
-
/**
|
|
4963
|
-
* The path of a stored file, as `TEXT` — or several with `.multiple()`. The
|
|
4964
|
-
* upload route enforces `accept` and `maxBytes`, and the orphan sweep counts
|
|
4965
|
-
* the file as referenced.
|
|
4966
|
-
*/
|
|
4967
3229
|
storage,
|
|
4968
|
-
/**
|
|
4969
|
-
* A column of a Postgres type no other builder names —
|
|
4970
|
-
* `col.custom({ dataType: "inet" })`, `col.custom({ dataType: "citext" })`,
|
|
4971
|
-
* `col.custom({ dataType: "geometry(Point, 4326)" })`. What
|
|
4972
|
-
* `rebase schema introspect` writes for a column of such a type, so a
|
|
4973
|
-
* project generated from an existing database keeps it.
|
|
4974
|
-
*
|
|
4975
|
-
* Rebase names the type in DDL, verbatim, and does nothing else with it: it
|
|
4976
|
-
* does not create, alter or drop the type's definition (an extension or a
|
|
4977
|
-
* `CREATE TYPE` the database already holds provides it), it does not
|
|
4978
|
-
* validate values, and it passes every value through exactly as the
|
|
4979
|
-
* driver returns it — a string for most types. `.$type<T>()` types it for
|
|
4980
|
-
* the SDK when the driver returns something else.
|
|
4981
|
-
*/
|
|
4982
3230
|
custom,
|
|
4983
|
-
/** Refused: write `col.custom({ dataType: "interval" })`. */
|
|
4984
3231
|
interval: unsupported("interval"),
|
|
4985
|
-
/** Refused: write `col.custom({ dataType: "inet" })`. */
|
|
4986
3232
|
inet: unsupported("inet"),
|
|
4987
|
-
/** Refused: write `col.custom({ dataType: "cidr" })`. */
|
|
4988
3233
|
cidr: unsupported("cidr"),
|
|
4989
|
-
/** Refused: write `col.custom({ dataType: "macaddr" })`. */
|
|
4990
3234
|
macaddr: unsupported("macaddr"),
|
|
4991
|
-
/** Refused: write `col.custom({ dataType: "macaddr8" })`. */
|
|
4992
3235
|
macaddr8: unsupported("macaddr8"),
|
|
4993
|
-
/** Refused: write `col.custom({ dataType: "point" })`. */
|
|
4994
3236
|
point: unsupported("point"),
|
|
4995
|
-
/** Refused: write `col.custom({ dataType: "line" })`. */
|
|
4996
3237
|
line: unsupported("line"),
|
|
4997
|
-
/** Refused: write `col.custom({ dataType: "halfvec" })`. */
|
|
4998
3238
|
halfvec: unsupported("halfvec"),
|
|
4999
|
-
/** Refused: write `col.custom({ dataType: "sparsevec" })`. */
|
|
5000
3239
|
sparsevec: unsupported("sparsevec"),
|
|
5001
|
-
/** Refused: write `col.custom({ dataType: "bit" })`. */
|
|
5002
3240
|
bit: unsupported("bit")
|
|
5003
3241
|
};
|
|
5004
3242
|
function pgEnum(enumName, values) {
|
|
@@ -5018,35 +3256,23 @@ function pgEnum(enumName, values) {
|
|
|
5018
3256
|
function isLabelTuple(values) {
|
|
5019
3257
|
return Array.isArray(values) && values.length > 0 && values.every((value) => typeof value === "string");
|
|
5020
3258
|
}
|
|
5021
|
-
/**
|
|
5022
|
-
* The type name `col.custom()` puts into DDL: trimmed, and refused when it is
|
|
5023
|
-
* empty or could end the statement it is written into.
|
|
5024
|
-
*/
|
|
5025
3259
|
function customSqlType(sqlType) {
|
|
5026
3260
|
const trimmed = typeof sqlType === "string" ? sqlType.trim() : "";
|
|
5027
3261
|
if (trimmed.length === 0) throw new Error("`col.custom()` takes the Postgres type, e.g. `col.custom({ dataType: \"inet\" })`.");
|
|
5028
3262
|
if (/;|--|\/\*/.test(trimmed)) throw new Error(`\`col.custom({ dataType: ${JSON.stringify(sqlType)} })\`: a type name holds no \`;\` and no comment.`);
|
|
5029
3263
|
return trimmed;
|
|
5030
3264
|
}
|
|
5031
|
-
/**
|
|
5032
|
-
* Whether a value is a column builder, from this copy of the package or
|
|
5033
|
-
* another.
|
|
5034
|
-
*
|
|
5035
|
-
* @group Schema
|
|
5036
|
-
*/
|
|
5037
3265
|
function isColumnBuilder(value) {
|
|
5038
3266
|
return typeof value === "object" && value !== null && "brand" in value && value.brand === "rebase.column";
|
|
5039
3267
|
}
|
|
5040
3268
|
//#endregion
|
|
5041
3269
|
//#region src/schema/relations.ts
|
|
5042
|
-
/** The brand every relation builder result carries. */
|
|
5043
3270
|
var RELATION_BRAND = "rebase.relation";
|
|
5044
|
-
/** The options with `access` checked and copied: a role list, never a string spread into characters. */
|
|
5045
3271
|
function withCheckedAccess(kind, options) {
|
|
5046
3272
|
if (options.access === void 0) return options;
|
|
5047
3273
|
return {
|
|
5048
3274
|
...options,
|
|
5049
|
-
access: normalizeColumnAccess(options.access, `a relation (\`rel.${kind}(
|
|
3275
|
+
access: normalizeColumnAccess(options.access, `a relation (\`rel.${kind}(\u2026, { access })\`)`)
|
|
5050
3276
|
};
|
|
5051
3277
|
}
|
|
5052
3278
|
function belongsTo(target, options = {}) {
|
|
@@ -5057,27 +3283,8 @@ function belongsTo(target, options = {}) {
|
|
|
5057
3283
|
target
|
|
5058
3284
|
};
|
|
5059
3285
|
}
|
|
5060
|
-
/**
|
|
5061
|
-
* The relation builders. All five kinds; the target is a thunk, so two tables
|
|
5062
|
-
* can point at each other whatever order their modules load in — and, being a
|
|
5063
|
-
* {@link TableThunk}, without a type annotation on either side.
|
|
5064
|
-
*
|
|
5065
|
-
* ```ts
|
|
5066
|
-
* relations: {
|
|
5067
|
-
* author: rel.belongsTo(() => users, { localKey: "author_id", notNull: true, onDelete: "restrict" }),
|
|
5068
|
-
* tags: rel.manyToMany(() => tags, { through: "posts_tags", pivot: { sortOrder: col.integer().default(0) } }),
|
|
5069
|
-
* }
|
|
5070
|
-
* ```
|
|
5071
|
-
*
|
|
5072
|
-
* @group Schema
|
|
5073
|
-
*/
|
|
5074
3286
|
var rel = {
|
|
5075
|
-
/**
|
|
5076
|
-
* This table holds the foreign key. Binds to the column in `columns` whose
|
|
5077
|
-
* SQL name is `localKey`, or derives that column and indexes it.
|
|
5078
|
-
*/
|
|
5079
3287
|
belongsTo,
|
|
5080
|
-
/** The target holds a unique foreign key pointing here. */
|
|
5081
3288
|
hasOne(target, options = {}) {
|
|
5082
3289
|
return {
|
|
5083
3290
|
...withCheckedAccess("hasOne", options),
|
|
@@ -5086,7 +3293,6 @@ var rel = {
|
|
|
5086
3293
|
target
|
|
5087
3294
|
};
|
|
5088
3295
|
},
|
|
5089
|
-
/** The target holds a foreign key pointing here. */
|
|
5090
3296
|
hasMany(target, options = {}) {
|
|
5091
3297
|
return {
|
|
5092
3298
|
...withCheckedAccess("hasMany", options),
|
|
@@ -5095,10 +3301,6 @@ var rel = {
|
|
|
5095
3301
|
target
|
|
5096
3302
|
};
|
|
5097
3303
|
},
|
|
5098
|
-
/**
|
|
5099
|
-
* Linked through a junction table, which is created with its own row-level
|
|
5100
|
-
* security. `pivot` columns are read and written as `_pivot`.
|
|
5101
|
-
*/
|
|
5102
3304
|
manyToMany(target, options = {}) {
|
|
5103
3305
|
return {
|
|
5104
3306
|
...withCheckedAccess("manyToMany", options),
|
|
@@ -5107,7 +3309,6 @@ var rel = {
|
|
|
5107
3309
|
target
|
|
5108
3310
|
};
|
|
5109
3311
|
},
|
|
5110
|
-
/** A read-only traversal across several joins. */
|
|
5111
3312
|
via(target, options) {
|
|
5112
3313
|
if (!options.steps || options.steps.length === 0) throw new Error("`rel.via(target, { steps })` needs at least one join step.");
|
|
5113
3314
|
return {
|
|
@@ -5118,26 +3319,19 @@ var rel = {
|
|
|
5118
3319
|
};
|
|
5119
3320
|
}
|
|
5120
3321
|
};
|
|
5121
|
-
/**
|
|
5122
|
-
* Whether a value is the result of a `rel.*` call.
|
|
5123
|
-
*
|
|
5124
|
-
* @group Schema
|
|
5125
|
-
*/
|
|
5126
3322
|
function isRelationDef(value) {
|
|
5127
3323
|
return typeof value === "object" && value !== null && "brand" in value && value.brand === "rebase.relation";
|
|
5128
3324
|
}
|
|
5129
3325
|
//#endregion
|
|
5130
3326
|
//#region src/schema/table.ts
|
|
5131
|
-
/** The brand of a `defineTable` / `defineAuthTable` result. */
|
|
5132
3327
|
var TABLE_BRAND = "rebase.table";
|
|
5133
|
-
/** The brand of a `defineView` result. */
|
|
5134
3328
|
var VIEW_BRAND = "rebase.view";
|
|
5135
|
-
var IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
3329
|
+
var IDENTIFIER$1 = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
5136
3330
|
function assertTableShape(builder, name, config) {
|
|
5137
3331
|
if (typeof name !== "string" || name.length === 0) throw new Error(`\`${builder}(name, config)\` needs the table's name as its first argument.`);
|
|
5138
3332
|
if (typeof config !== "object" || config === null) throw new Error(`\`${builder}("${name}", config)\` needs a config object.`);
|
|
5139
3333
|
const columns = "columns" in config ? config.columns : void 0;
|
|
5140
|
-
if (typeof columns !== "object" || columns === null || Object.keys(columns).length === 0) throw new Error(`Table "${name}" declares no columns. Add \`columns: { id: col.uuid().primaryKey().defaultRandom(),
|
|
3334
|
+
if (typeof columns !== "object" || columns === null || Object.keys(columns).length === 0) throw new Error(`Table "${name}" declares no columns. Add \`columns: { id: col.uuid().primaryKey().defaultRandom(), \u2026 }\`.`);
|
|
5141
3335
|
for (const [key, column] of Object.entries(columns)) if (!isColumnBuilder(column)) throw new Error(`Column "${key}" of table "${name}" is not a \`col.*\` builder.`);
|
|
5142
3336
|
const relations = "relations" in config ? config.relations : void 0;
|
|
5143
3337
|
if (relations !== void 0) {
|
|
@@ -5149,37 +3343,14 @@ function assertTableShape(builder, name, config) {
|
|
|
5149
3343
|
}
|
|
5150
3344
|
for (const key of ["schema", "table"]) {
|
|
5151
3345
|
const value = key in config ? Reflect.get(config, key) : void 0;
|
|
5152
|
-
if (value !== void 0 && (typeof value !== "string" || !IDENTIFIER.test(value))) throw new Error(`\`${key}\` of table "${name}" must be a plain SQL identifier, got ${JSON.stringify(value)}.`);
|
|
3346
|
+
if (value !== void 0 && (typeof value !== "string" || !IDENTIFIER$1.test(value))) throw new Error(`\`${key}\` of table "${name}" must be a plain SQL identifier, got ${JSON.stringify(value)}.`);
|
|
5153
3347
|
}
|
|
5154
3348
|
}
|
|
5155
3349
|
function assertRlsDeclared(builder, name, config) {
|
|
5156
3350
|
const rls = "rls" in config ? config.rls : void 0;
|
|
5157
3351
|
if (rls === "admin-only" || rls === "inherit" || Array.isArray(rls) && rls.length > 0) return;
|
|
5158
|
-
throw new Error(`\`${builder}("${name}",
|
|
5159
|
-
}
|
|
5160
|
-
/**
|
|
5161
|
-
* Define a Postgres table.
|
|
5162
|
-
*
|
|
5163
|
-
* The name is the SQL table and the API slug; `rls` is mandatory. The result
|
|
5164
|
-
* is what the backend reads from `backend/schema/index.ts` — it generates the
|
|
5165
|
-
* DDL and the policies, serves the REST, realtime and MCP surfaces, and types
|
|
5166
|
-
* the SDK.
|
|
5167
|
-
*
|
|
5168
|
-
* ```ts
|
|
5169
|
-
* export const posts = defineTable("posts", {
|
|
5170
|
-
* columns: {
|
|
5171
|
-
* id: col.uuid().primaryKey().defaultRandom(),
|
|
5172
|
-
* title: col.text().notNull(),
|
|
5173
|
-
* },
|
|
5174
|
-
* rls: [
|
|
5175
|
-
* { operation: "select", access: "public" },
|
|
5176
|
-
* { operations: ["insert", "update", "delete"], roles: ["editor"] },
|
|
5177
|
-
* ],
|
|
5178
|
-
* });
|
|
5179
|
-
* ```
|
|
5180
|
-
*
|
|
5181
|
-
* @group Schema
|
|
5182
|
-
*/
|
|
3352
|
+
throw new Error(`\`${builder}("${name}", \u2026)\` has no usable \`rls\`. ${Array.isArray(rls) ? "`rls: []` grants nothing and says nothing. Write `rls: \"admin-only\"` to lock the table to admins." : "Every table needs an explicit row-level security posture."} Accepted: \`"admin-only"\`, \`"inherit"\` (the \`defaultRls\` exported from backend/schema/index.ts), or a non-empty list of rules.`);
|
|
3353
|
+
}
|
|
5183
3354
|
function defineTable(name, config) {
|
|
5184
3355
|
assertTableShape("defineTable", name, config);
|
|
5185
3356
|
assertRlsDeclared("defineTable", name, config);
|
|
@@ -5189,16 +3360,6 @@ function defineTable(name, config) {
|
|
|
5189
3360
|
config
|
|
5190
3361
|
};
|
|
5191
3362
|
}
|
|
5192
|
-
/**
|
|
5193
|
-
* Define the table users are stored in.
|
|
5194
|
-
*
|
|
5195
|
-
* A `defineTable` that auth reads and writes: the columns auth needs are added
|
|
5196
|
-
* when the table does not declare them, a signed-in user can read their own
|
|
5197
|
-
* row, and the privilege columns (`roles`) can only be written by an admin —
|
|
5198
|
-
* whatever `rls` says. A project has at most one.
|
|
5199
|
-
*
|
|
5200
|
-
* @group Schema
|
|
5201
|
-
*/
|
|
5202
3363
|
function defineAuthTable(name, config) {
|
|
5203
3364
|
assertTableShape("defineAuthTable", name, config);
|
|
5204
3365
|
assertRlsDeclared("defineAuthTable", name, config);
|
|
@@ -5210,15 +3371,6 @@ function defineAuthTable(name, config) {
|
|
|
5210
3371
|
auth: auth ?? {}
|
|
5211
3372
|
};
|
|
5212
3373
|
}
|
|
5213
|
-
/**
|
|
5214
|
-
* Define a SQL view, served read-only.
|
|
5215
|
-
*
|
|
5216
|
-
* A plain view is created `WITH (security_invoker = true)`: the row-level
|
|
5217
|
-
* security of the tables it reads decides what each caller sees. A
|
|
5218
|
-
* materialized view stores its rows, so it is gated by `roles` instead.
|
|
5219
|
-
*
|
|
5220
|
-
* @group Schema
|
|
5221
|
-
*/
|
|
5222
3374
|
function defineView(name, config) {
|
|
5223
3375
|
assertTableShape("defineView", name, config);
|
|
5224
3376
|
if (typeof config.query !== "string" || config.query.trim().length === 0) throw new Error(`View "${name}" needs a \`query\`: the SELECT that defines it.`);
|
|
@@ -5229,34 +3381,80 @@ function defineView(name, config) {
|
|
|
5229
3381
|
config
|
|
5230
3382
|
};
|
|
5231
3383
|
}
|
|
5232
|
-
/**
|
|
5233
|
-
* Whether a value is the result of `defineTable` or `defineAuthTable`, from
|
|
5234
|
-
* this copy of the package or another.
|
|
5235
|
-
*
|
|
5236
|
-
* @group Schema
|
|
5237
|
-
*/
|
|
5238
3384
|
function isTableDef(value) {
|
|
5239
3385
|
return typeof value === "object" && value !== null && "brand" in value && value.brand === "rebase.table";
|
|
5240
3386
|
}
|
|
5241
|
-
/**
|
|
5242
|
-
* Whether a value is the result of `defineAuthTable`.
|
|
5243
|
-
*
|
|
5244
|
-
* @group Schema
|
|
5245
|
-
*/
|
|
5246
3387
|
function isAuthTableDef(value) {
|
|
5247
3388
|
return isTableDef(value) && value.auth !== void 0;
|
|
5248
3389
|
}
|
|
5249
|
-
/**
|
|
5250
|
-
* Whether a value is the result of `defineView`.
|
|
5251
|
-
*
|
|
5252
|
-
* @group Schema
|
|
5253
|
-
*/
|
|
5254
3390
|
function isViewDef(value) {
|
|
5255
3391
|
return typeof value === "object" && value !== null && "brand" in value && value.brand === "rebase.view";
|
|
5256
3392
|
}
|
|
5257
3393
|
//#endregion
|
|
3394
|
+
//#region src/schema/rpc.ts
|
|
3395
|
+
var RPC_BRAND = "rebase.rpc";
|
|
3396
|
+
var DEFAULT_PUBLIC_RPC_RATE_LIMIT = {
|
|
3397
|
+
limit: 120,
|
|
3398
|
+
windowMs: 6e4
|
|
3399
|
+
};
|
|
3400
|
+
var IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
3401
|
+
var RESERVED_SCHEMAS = /* @__PURE__ */ new Set([
|
|
3402
|
+
"rebase",
|
|
3403
|
+
"pg_catalog",
|
|
3404
|
+
"information_schema",
|
|
3405
|
+
"pg_toast"
|
|
3406
|
+
]);
|
|
3407
|
+
function writeOnlyModifier(shape) {
|
|
3408
|
+
if (shape.transform !== void 0) return "`.transform()`";
|
|
3409
|
+
if ((shape.kind === "string" || shape.kind === "date") && shape.stamp !== void 0) return shape.stamp === "createUser" || shape.stamp === "updateUser" ? "`.onCreateUser()` / `.onUpdateUser()`" : "`.onCreateNow()` / `.onUpdateNow()`";
|
|
3410
|
+
if (shape.kind === "object") for (const field of Object.values(shape.fields)) {
|
|
3411
|
+
const found = writeOnlyModifier(field);
|
|
3412
|
+
if (found) return found;
|
|
3413
|
+
}
|
|
3414
|
+
if (shape.kind === "array") return writeOnlyModifier(shape.of);
|
|
3415
|
+
if (shape.kind === "oneOf") for (const variant of Object.values(shape.variants)) {
|
|
3416
|
+
const found = writeOnlyModifier(variant);
|
|
3417
|
+
if (found) return found;
|
|
3418
|
+
}
|
|
3419
|
+
}
|
|
3420
|
+
function assertRateLimit(name, rateLimit) {
|
|
3421
|
+
if (rateLimit === void 0) return;
|
|
3422
|
+
if (typeof rateLimit !== "object" || rateLimit === null) throw new Error(`RPC "${name}": \`rateLimit\` is \`{ limit, windowMs }\`. A public RPC is always limited; to loosen it, raise \`limit\`.`);
|
|
3423
|
+
const limit = Reflect.get(rateLimit, "limit");
|
|
3424
|
+
const windowMs = Reflect.get(rateLimit, "windowMs");
|
|
3425
|
+
if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1) throw new Error(`RPC "${name}": \`rateLimit.limit\` must be a positive integer.`);
|
|
3426
|
+
if (typeof windowMs !== "number" || !Number.isFinite(windowMs) || windowMs <= 0) throw new Error(`RPC "${name}": \`rateLimit.windowMs\` must be a positive number of milliseconds.`);
|
|
3427
|
+
}
|
|
3428
|
+
function defineRpc(name, config) {
|
|
3429
|
+
if (typeof name !== "string" || !IDENTIFIER.test(name)) throw new Error(`defineRpc: ${JSON.stringify(name)} is not a function name an RPC can have. Use the SQL function's name as Postgres stores it: letters, digits and _, not starting with a digit (an unquoted \`CREATE FUNCTION getProposal\` is stored as \`getproposal\`).`);
|
|
3430
|
+
if (typeof config !== "object" || config === null) throw new Error(`RPC "${name}" needs a config: \`defineRpc("${name}", { access: "public" | "authenticated" })\`.`);
|
|
3431
|
+
const access = config.access;
|
|
3432
|
+
if (access !== "public" && access !== "authenticated") throw new Error(`RPC "${name}": \`access\` must be "public" or "authenticated" (received ${JSON.stringify(access)}). It is required: who may call a function is a decision, not a default.`);
|
|
3433
|
+
const schema = config.schema ?? "public";
|
|
3434
|
+
if (typeof schema !== "string" || !IDENTIFIER.test(schema)) throw new Error(`RPC "${name}": \`schema\` ${JSON.stringify(schema)} is not a schema name (letters, digits and _).`);
|
|
3435
|
+
if (RESERVED_SCHEMAS.has(schema)) throw new Error(`RPC "${name}": the "${schema}" schema holds the database's or the server's own functions, which are never exposed as RPCs.`);
|
|
3436
|
+
if (config.args !== void 0) {
|
|
3437
|
+
if (typeof config.args !== "object" || config.args === null || Array.isArray(config.args)) throw new Error(`RPC "${name}": \`args\` is an object of \`json.*\` fields, one per named argument.`);
|
|
3438
|
+
for (const [key, field] of Object.entries(config.args)) {
|
|
3439
|
+
if (!IDENTIFIER.test(key)) throw new Error(`RPC "${name}": argument ${JSON.stringify(key)} is not a SQL parameter name (letters, digits and _).`);
|
|
3440
|
+
if (!isJsonField(field)) throw new Error(`RPC "${name}": argument "${key}" must be a \`json.*\` field, such as \`json.string()\`.`);
|
|
3441
|
+
const modifier = writeOnlyModifier(field.shape);
|
|
3442
|
+
if (modifier) throw new Error(`RPC "${name}": argument "${key}" uses ${modifier}, which applies to a row being written, not to a call. Read the caller inside the function instead (\`auth.uid()\`, \`now()\`).`);
|
|
3443
|
+
}
|
|
3444
|
+
}
|
|
3445
|
+
if (config.write !== void 0 && typeof config.write !== "boolean") throw new Error(`RPC "${name}": \`write\` is true or false.`);
|
|
3446
|
+
assertRateLimit(name, config.rateLimit);
|
|
3447
|
+
return {
|
|
3448
|
+
brand: RPC_BRAND,
|
|
3449
|
+
name,
|
|
3450
|
+
config
|
|
3451
|
+
};
|
|
3452
|
+
}
|
|
3453
|
+
function isRpcDef(value) {
|
|
3454
|
+
return typeof value === "object" && value !== null && "brand" in value && value.brand === "rebase.rpc";
|
|
3455
|
+
}
|
|
3456
|
+
//#endregion
|
|
5258
3457
|
//#region src/schema/table_patch.ts
|
|
5259
|
-
/** The keys of {@link TableOptionValues}, in the order a table prints them. */
|
|
5260
3458
|
var TABLE_OPTION_KEYS = [
|
|
5261
3459
|
"description",
|
|
5262
3460
|
"defaultPolicies",
|
|
@@ -5269,11 +3467,6 @@ var TABLE_OPTION_KEYS = [
|
|
|
5269
3467
|
"strictWrites",
|
|
5270
3468
|
"metadata"
|
|
5271
3469
|
];
|
|
5272
|
-
/**
|
|
5273
|
-
* A list of table edits that cannot be applied, with every problem found.
|
|
5274
|
-
*
|
|
5275
|
-
* @group Schema
|
|
5276
|
-
*/
|
|
5277
3470
|
var TablePatchError = class TablePatchError extends Error {
|
|
5278
3471
|
problems;
|
|
5279
3472
|
code = "TABLE_PATCH_INVALID";
|
|
@@ -5291,13 +3484,7 @@ var TablePatchError = class TablePatchError extends Error {
|
|
|
5291
3484
|
return `The schema edit cannot be applied (${problems.length === 1 ? "1 problem" : `${problems.length} problems`}):\n${lines.join("\n")}`;
|
|
5292
3485
|
}
|
|
5293
3486
|
};
|
|
5294
|
-
/**
|
|
5295
|
-
* A name that reaches SQL as an identifier, or becomes a file name: letters,
|
|
5296
|
-
* digits, underscores and dollar signs, not starting with a digit. The same
|
|
5297
|
-
* alphabet the DDL builders accept, so a name accepted here is one they take.
|
|
5298
|
-
*/
|
|
5299
3487
|
var SQL_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_$]*$/;
|
|
5300
|
-
/** A key on the JSON row: any non-empty string without control characters. */
|
|
5301
3488
|
var isRowKey = (key) => key.length > 0 && [...key].every((char) => char.charCodeAt(0) >= 32);
|
|
5302
3489
|
var COLUMN_KINDS = /* @__PURE__ */ new Set([
|
|
5303
3490
|
"text",
|
|
@@ -5366,7 +3553,6 @@ var RELATION_OPTION_KEYS = {
|
|
|
5366
3553
|
"private"
|
|
5367
3554
|
]
|
|
5368
3555
|
};
|
|
5369
|
-
/** The relation options that name a SQL column or table. */
|
|
5370
3556
|
var RELATION_IDENTIFIER_KEYS = [
|
|
5371
3557
|
"localKey",
|
|
5372
3558
|
"foreignKey",
|
|
@@ -5382,12 +3568,11 @@ var MIGRATION_KEYS = {
|
|
|
5382
3568
|
name: "The table's name is its file and its default SQL name; renaming it moves data, which is a migration, not an edit. Write the rename in code together with a migration.",
|
|
5383
3569
|
database: "Moving the table to another database moves its rows, which is a migration, not an edit."
|
|
5384
3570
|
};
|
|
5385
|
-
/** Problems with a column definition sent on the wire. */
|
|
5386
3571
|
function columnProblems(value, where) {
|
|
5387
3572
|
if (!isRecord(value)) return [`${where} must be a column definition object.`];
|
|
5388
3573
|
const problems = [];
|
|
5389
3574
|
const type = value.type;
|
|
5390
|
-
if (!isRecord(type) || typeof type.kind !== "string" || !COLUMN_KINDS.has(type.kind)) problems.push(`${where}.type must be a column type, \`{ kind: "text" }\`, \`{ kind: "varchar", length: 160 }\`
|
|
3575
|
+
if (!isRecord(type) || typeof type.kind !== "string" || !COLUMN_KINDS.has(type.kind)) problems.push(`${where}.type must be a column type, \`{ kind: "text" }\`, \`{ kind: "varchar", length: 160 }\` \u2026`);
|
|
5391
3576
|
else if (type.kind === "array") {
|
|
5392
3577
|
if (!isRecord(type.of)) problems.push(`${where}.type.of must be the type of each item.`);
|
|
5393
3578
|
} else if ((type.kind === "varchar" || type.kind === "char") && typeof type.length !== "number") problems.push(`${where}.type.length must be a number.`);
|
|
@@ -5407,7 +3592,6 @@ function columnProblems(value, where) {
|
|
|
5407
3592
|
if (value.json !== void 0 && !isRecord(value.json)) problems.push(`${where}.json must be a JSON shape.`);
|
|
5408
3593
|
return problems;
|
|
5409
3594
|
}
|
|
5410
|
-
/** Problems with a table description sent to be adopted. */
|
|
5411
3595
|
function adoptedTableProblems(spec) {
|
|
5412
3596
|
const out = [];
|
|
5413
3597
|
for (const key of [
|
|
@@ -5465,7 +3649,6 @@ function adoptedTableProblems(spec) {
|
|
|
5465
3649
|
if (spec.auth !== void 0 || spec.view !== void 0) out.push({ message: "an auth table or a view is not adopted here: declare it in code." });
|
|
5466
3650
|
return out;
|
|
5467
3651
|
}
|
|
5468
|
-
/** Problems with a relation sent on the wire. */
|
|
5469
3652
|
function relationProblems(value, where) {
|
|
5470
3653
|
if (!isRecord(value)) return [`${where} must be a relation object.`];
|
|
5471
3654
|
const kind = value.kind;
|
|
@@ -5486,14 +3669,12 @@ function relationProblems(value, where) {
|
|
|
5486
3669
|
else for (const [key, column] of Object.entries(value.pivot)) problems.push(...columnProblems(column, `${where}.pivot.${key}`));
|
|
5487
3670
|
return problems;
|
|
5488
3671
|
}
|
|
5489
|
-
/** Problems with an `rls` value sent on the wire. */
|
|
5490
3672
|
function rlsProblems(value, where) {
|
|
5491
3673
|
if (value === "admin-only" || value === "inherit") return [];
|
|
5492
3674
|
if (!Array.isArray(value)) return [`${where} must be "admin-only", "inherit" or a list of rules.`];
|
|
5493
3675
|
if (value.length === 0) return [`${where} is an empty list of rules, which leaves nobody a policy. Send "admin-only" instead.`];
|
|
5494
3676
|
return value.flatMap((rule, index) => isRecord(rule) ? [] : [`${where}[${index}] must be a rule object.`]);
|
|
5495
3677
|
}
|
|
5496
|
-
/** Problems with a table-level option's value. */
|
|
5497
3678
|
function optionProblems(option, value, where) {
|
|
5498
3679
|
if (value === null) return [];
|
|
5499
3680
|
switch (option) {
|
|
@@ -5511,7 +3692,6 @@ function optionProblems(option, value, where) {
|
|
|
5511
3692
|
}
|
|
5512
3693
|
var isOptionKey = (value) => typeof value === "string" && TABLE_OPTION_KEYS.includes(value);
|
|
5513
3694
|
var isIndex = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
|
|
5514
|
-
/** The problems of one operation. */
|
|
5515
3695
|
function operationProblems(value, index) {
|
|
5516
3696
|
if (!isRecord(value)) return [{
|
|
5517
3697
|
index,
|
|
@@ -5582,7 +3762,7 @@ function operationProblems(value, index) {
|
|
|
5582
3762
|
if (!isRecord(spec)) return [{
|
|
5583
3763
|
index,
|
|
5584
3764
|
table: "",
|
|
5585
|
-
message: "`table` must be the description of the table to adopt, as `GET
|
|
3765
|
+
message: "`table` must be the description of the table to adopt, as `GET \u2026/unmapped-tables/:schema/:table` serves it."
|
|
5586
3766
|
}];
|
|
5587
3767
|
const name = typeof spec.slug === "string" ? spec.slug : "";
|
|
5588
3768
|
return adoptedTableProblems(spec).map((found) => ({
|
|
@@ -5637,13 +3817,6 @@ function operationProblems(value, index) {
|
|
|
5637
3817
|
default: return [problem(`\`op\` ${JSON.stringify(op)} is not a schema edit. Send one of createTable, adoptTable, deleteTable, addColumn, changeColumn, renameColumn, removeColumn, moveColumn, addRelation, changeRelation, removeRelation, setRls, addRule, replaceRule, removeRule, setOption.`)];
|
|
5638
3818
|
}
|
|
5639
3819
|
}
|
|
5640
|
-
/**
|
|
5641
|
-
* Every problem with a list of table edits as it arrived, in operation order.
|
|
5642
|
-
* Empty when the list is well formed — which says nothing about whether the
|
|
5643
|
-
* result compiles: the server compiles it before writing anything.
|
|
5644
|
-
*
|
|
5645
|
-
* @group Schema
|
|
5646
|
-
*/
|
|
5647
3820
|
function tablePatchProblems(value) {
|
|
5648
3821
|
if (!Array.isArray(value)) return [{
|
|
5649
3822
|
index: 0,
|
|
@@ -5657,30 +3830,13 @@ function tablePatchProblems(value) {
|
|
|
5657
3830
|
}];
|
|
5658
3831
|
return value.flatMap((operation, index) => operationProblems(operation, index));
|
|
5659
3832
|
}
|
|
5660
|
-
/**
|
|
5661
|
-
* Whether a value is a well-formed list of {@link TablePatch} operations.
|
|
5662
|
-
*
|
|
5663
|
-
* @group Schema
|
|
5664
|
-
*/
|
|
5665
3833
|
function isTablePatchList(value) {
|
|
5666
3834
|
return tablePatchProblems(value).length === 0;
|
|
5667
3835
|
}
|
|
5668
|
-
/**
|
|
5669
|
-
* A list of edits as it arrived, checked: the list, or a
|
|
5670
|
-
* {@link TablePatchError} naming every problem.
|
|
5671
|
-
*
|
|
5672
|
-
* @group Schema
|
|
5673
|
-
*/
|
|
5674
3836
|
function parseTablePatches(value) {
|
|
5675
3837
|
if (isTablePatchList(value)) return value;
|
|
5676
3838
|
throw new TablePatchError(tablePatchProblems(value));
|
|
5677
3839
|
}
|
|
5678
|
-
/**
|
|
5679
|
-
* The column definition a {@link WireColumnDef} stands for, the flags it left
|
|
5680
|
-
* out `false`.
|
|
5681
|
-
*
|
|
5682
|
-
* @group Schema
|
|
5683
|
-
*/
|
|
5684
3840
|
function columnDefFromWire(column) {
|
|
5685
3841
|
const { element, json, notNull, primaryKey, unique, readOnly, private: isPrivate, ...rest } = column;
|
|
5686
3842
|
const def = {
|
|
@@ -5695,7 +3851,6 @@ function columnDefFromWire(column) {
|
|
|
5695
3851
|
if (json !== void 0) def.json = json;
|
|
5696
3852
|
return def;
|
|
5697
3853
|
}
|
|
5698
|
-
/** Deep equality of JSON-like values: what a rule read from the wire is compared by. */
|
|
5699
3854
|
function sameValue(a, b) {
|
|
5700
3855
|
if (a === b) return true;
|
|
5701
3856
|
if (Array.isArray(a) || Array.isArray(b)) return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((item, i) => sameValue(item, b[i]));
|
|
@@ -5704,19 +3859,6 @@ function sameValue(a, b) {
|
|
|
5704
3859
|
const otherKeys = Object.keys(b).filter((key) => b[key] !== void 0);
|
|
5705
3860
|
return keys.length === otherKeys.length && keys.every((key) => sameValue(a[key], b[key]));
|
|
5706
3861
|
}
|
|
5707
|
-
/**
|
|
5708
|
-
* The rule operations that turn one list of rules into another, touching only
|
|
5709
|
-
* the rules that changed.
|
|
5710
|
-
*
|
|
5711
|
-
* A policy's name is a hash of its rule as written, so an editor that sends
|
|
5712
|
-
* the whole list back (one `setRls`) would rewrite every rule's text and risk
|
|
5713
|
-
* renaming policies it never changed. This pairs the lists by position: an
|
|
5714
|
-
* equal rule is left alone, a different one is replaced, a longer list adds
|
|
5715
|
-
* rules and a shorter one removes from the end. Positions are those of the
|
|
5716
|
-
* list as it is when each operation runs.
|
|
5717
|
-
*
|
|
5718
|
-
* @group Schema
|
|
5719
|
-
*/
|
|
5720
3862
|
function rulePatches(table, before, after) {
|
|
5721
3863
|
const out = [];
|
|
5722
3864
|
const shared = Math.min(before.length, after.length);
|
|
@@ -5740,6 +3882,6 @@ function rulePatches(table, before, after) {
|
|
|
5740
3882
|
return out;
|
|
5741
3883
|
}
|
|
5742
3884
|
//#endregion
|
|
5743
|
-
export { ADMIN_ROLE, ADMIN_SCOPES, AGGREGATE_FUNCTIONS, AGGREGATE_GROUP_TRANSFORMS, ALL_WHERE_FILTER_OPS, ANONYMOUS_USER_ID, ANONYMOUS_USER_IDS, AUTH_FLOW_HEADER, BATCH_REF_KEY, BUILT_IN_SCOPES, BUILT_IN_SCOPE_DESCRIPTIONS, BUNDLE_FORMAT_VERSION, CANONICAL_TO_REST, COLUMN_BRAND, ColumnBuilder, DATA_PLANE_SCOPES, DEFAULT_CAPABILITIES, DEFAULT_COMMIT_PATHS, DEFAULT_DATA_SOURCE_KEY, DEFAULT_FILTERABLE_RELATION_KINDS, DEFAULT_FUZZY_THRESHOLD, DEFAULT_LIST_LIMIT, DEFAULT_RESOURCE_KEY, DEFAULT_SEARCH_COLUMN, DEFAULT_SEARCH_LANGUAGE, DEFAULT_SEARCH_MODE, DEFAULT_SEARCH_WEIGHT, DEFAULT_STORAGE_SOURCE_KEY, DEFAULT_TENANT_BYPASS_ROLES, DEFAULT_VECTOR_LIST_LIMIT, EMPTY_ACCESS_MODEL, FIELDLESS_AGGREGATES, FIELD_OPERATORS, FIREBASE_CAPABILITIES, IMPERSONATE_HEADER, INCLUDE_COUNT_KEY, JSON_FIELD_BRAND, JUNCTION_PIVOT_KEY, JsonField, KEY_MANAGEMENT_SCOPES, LEGACY_LAYOUT_REMEDY, LEGACY_RLS_JWT_SQL, LEGACY_RLS_ROLES_SQL, LEGACY_RLS_SCHEMA, LEGACY_RLS_UID_SQL, LEGACY_SCHEMA_VERSION_PREFIX, LIST_OPS, ListLimitError, MAX_INCLUDE_DEPTH, MAX_LIST_LIMIT, MCP_APP_MODULES, NULL_OPS, POLICY_EXPRESSION_KINDS, POSTGRES_CAPABILITIES, PUBLIC_STORAGE_PREFIX, REBASE_ADMIN_REQUEST_ROLE, REBASE_ADMIN_ROLE, REBASE_SCHEMA, RELATION_BRAND, RELEVANCE_SORT_FIELD, RESERVED_BACKEND_PREFIXES, RESOURCE_GRAPH_VERSION, REST_TO_CANONICAL, RLS_IS_ANONYMOUS_SQL, RLS_IS_REQUEST_ROLE_SQL, RLS_JWT_SQL, RLS_ROLES_SQL, RLS_UID_SQL, RUNTIME_CONTRACT_VERSION, RebaseApiError, RebaseClientError, SCHEMA_VERSION_HEADER, SCOPE_TARGETS, SIMULATED_CONTEXT_HEADER, SIMULATE_API_KEY_ID_HEADER, SIMULATE_ROLE_HEADER, SIMULATE_USER_ID_HEADER, STORAGE_REFERENCE_SCHEME, TABLE_BRAND, TABLE_OPTION_KEYS, TablePatchError, UI_PREFERENCE_FIELD_KEYS, UI_PREFERENCE_TABLE_KEYS, VIEW_BRAND, adminRequestRoleFor, aggregateAlias, aggregateGroupKey, amendResourceKind, bucket, buildResourceGraph, canonicalSchemaPayload, col, columnDefFromWire, columnTypeLabel, compareStaticRoutes, computeSchemaVersion, database, declareCron, declareFunction, declareResource, declaredDataSources, declaredDatabaseExtensions, declaredDatabaseRls, declaredQueueConsumers, declaredResources, declaredRlsPolicyShape, declaredStorageSources, declaredSubscriptions, defineAuthTable, defineTable, defineView, describeJsonShape, describeScope, encodeRelationAggregateSort, envBasesForResource, findEnvSuffixCollision, findStorageSuffixCollision, formatSimulatedContext, getDataSourceCapabilities, hasAdminRole, hasFieldOperation, holdsAdminRole, intersectScopes, isAdminScope, isAnonymousUid, isAuthTableDef, isBranchAdmin, isBuiltInScope, isChannelBusInstance, isColumnBuilder, isContentHashedFileName, isDataPlaneScope, isFieldOperation, isJsonColumnType, isJsonField, isNumericColumnType, isPercentileFraction, isPolicyExpressionKind, isPolicyShorthand, isPublicStorageKey, isPublicStoragePath, isRedactedSecurityRule, isRelationAggregateSort, isRelationDef, isResourceHandle, isSQLAdmin, isSchemaAdmin, isSchemaEditingAdmin, isSqlTemplate, isStorageReference, isTableDef, isTablePatchList, isTemporalColumnType, isTenantClaimSource, isTenantMembershipSource, isTextColumnType, isTimeZoneName, isUiTablePreferences, isUnsupported, isValidAppHost, isValidEngine, isViewDef, joinConditions, json, knownScopes, matchStaticRoute, mergeUiTablePreferences, normalizeColumnAccess, normalizeStorage, normalizeValidation, parseAppAddress, parseByteSize, parseCaseFoldedFieldPath, parseEnvBoolean, parseFrameAncestor, parseRelationAggregateSort, parseScope, parseSimulatedContext, parseStorageReference, parseTablePatches, pgEnum, policy, queue, registerDataSourceCapabilities, registerResourceKind, rel, reservedPrefixFor, resetDeclaredQueueConsumers, resetDeclaredResources, resetDeclaredSubscriptions, resolveClientListLimit, resolveResourceRefs, resolveStorageReferences, resourceEnvSuffix, resourceId, resourceKeyOf, resourceKind, resourceKinds, resourceToDataSource, resourceToStorageSource, rewriteLegacyRlsFunctions, roleNameProblem, rulePatches, scopeAcceptsTarget, scopeGrants, scopeGrantsAny, scopeTargets, scopesBeyond, scopesForRoles, setQueueRuntime, setTopicRuntime, simulationHeaders, soleJoinCondition, sortKeyToString, sql, storageEnvSuffix, storageObjectPath, storageReference, storageReferencesForDownloadUrls, storageTargetOfDownloadUrl, storageTargetsInText, summarizeRoles, summarizeScopes, tablePatchProblems, toCanonicalOp, toDriverAggregate, toDriverAggregateGroup, topic, uiTablePreferencesProblems, unsupportedMethod, usesLegacyRlsFunctions, validateScopes, validateStaticRoute };
|
|
3885
|
+
export { ADMIN_ROLE, ADMIN_SCOPES, AGGREGATE_FUNCTIONS, AGGREGATE_GROUP_TRANSFORMS, ALL_WHERE_FILTER_OPS, ANONYMOUS_USER_ID, ANONYMOUS_USER_IDS, AUTH_FLOW_HEADER, BATCH_REF_KEY, BUILT_IN_SCOPES, BUILT_IN_SCOPE_DESCRIPTIONS, BUNDLE_FORMAT_VERSION, CANONICAL_TO_REST, COLUMN_BRAND, ColumnBuilder, DATA_PLANE_SCOPES, DEFAULT_CAPABILITIES, DEFAULT_COMMIT_PATHS, DEFAULT_DATA_SOURCE_KEY, DEFAULT_FILTERABLE_RELATION_KINDS, DEFAULT_FUZZY_THRESHOLD, DEFAULT_LIST_LIMIT, DEFAULT_PUBLIC_RPC_RATE_LIMIT, DEFAULT_RESOURCE_KEY, DEFAULT_SEARCH_COLUMN, DEFAULT_SEARCH_LANGUAGE, DEFAULT_SEARCH_MODE, DEFAULT_SEARCH_WEIGHT, DEFAULT_STATIC_REDIRECT_STATUS, DEFAULT_STORAGE_SOURCE_KEY, DEFAULT_TENANT_BYPASS_ROLES, DEFAULT_VECTOR_LIST_LIMIT, EMPTY_ACCESS_MODEL, FIELDLESS_AGGREGATES, FIELD_OPERATORS, FIREBASE_CAPABILITIES, IMPERSONATE_HEADER, INCLUDE_COUNT_KEY, JSON_FIELD_BRAND, JUNCTION_PIVOT_KEY, JsonField, KEY_MANAGEMENT_SCOPES, LEGACY_LAYOUT_REMEDY, LEGACY_RLS_JWT_SQL, LEGACY_RLS_ROLES_SQL, LEGACY_RLS_SCHEMA, LEGACY_RLS_UID_SQL, LEGACY_SCHEMA_VERSION_PREFIX, LIST_OPS, ListLimitError, MAX_IMPORTED_USER_ID_LENGTH, MAX_INCLUDE_DEPTH, MAX_LIST_LIMIT, MAX_USERS_PER_IMPORT, MCP_APP_MODULES, NULL_OPS, POLICY_EXPRESSION_KINDS, POSTGRES_CAPABILITIES, PUBLIC_STORAGE_PREFIX, REBASE_ADMIN_REQUEST_ROLE, REBASE_ADMIN_ROLE, REBASE_SCHEMA, RECOMMENDED_STORAGE_RULES, RELATION_BRAND, RELEVANCE_SORT_FIELD, RESERVED_BACKEND_PREFIXES, RESOURCE_GRAPH_VERSION, REST_TO_CANONICAL, RLS_IS_ANONYMOUS_SQL, RLS_IS_REQUEST_ROLE_SQL, RLS_JWT_SQL, RLS_ROLES_SQL, RLS_UID_SQL, RPC_BRAND, RUNTIME_CONTRACT_VERSION, RebaseApiError, RebaseClientError, SCHEMA_VERSION_HEADER, SCOPE_TARGETS, SIMULATED_CONTEXT_HEADER, SIMULATE_API_KEY_ID_HEADER, SIMULATE_ROLE_HEADER, SIMULATE_USER_ID_HEADER, STATIC_REDIRECT_STATUSES, STORAGE_REFERENCE_SCHEME, TABLE_BRAND, TABLE_OPTION_KEYS, TablePatchError, UI_PREFERENCE_FIELD_KEYS, UI_PREFERENCE_TABLE_KEYS, VIEW_BRAND, adminRequestRoleFor, aggregateAlias, aggregateGroupKey, amendResourceKind, bucket, buildResourceGraph, canonicalSchemaPayload, cleanUrlFor, col, columnDefFromWire, columnTypeLabel, compareStaticRoutes, compileStaticRedirects, computeSchemaVersion, database, declareCron, declareFunction, declareResource, declaredDataSources, declaredDatabaseExtensions, declaredDatabaseRls, declaredQueueConsumers, declaredResources, declaredRlsPolicyShape, declaredStorageSources, declaredSubscriptions, defineAuthTable, defineRpc, defineTable, defineView, describeJsonShape, describeScope, encodeRelationAggregateSort, envBasesForResource, findEnvSuffixCollision, findStorageSuffixCollision, formatSimulatedContext, getDataSourceCapabilities, hasAdminRole, hasFieldOperation, holdsAdminRole, importedUserIdProblem, intersectScopes, isAdminScope, isAnonymousUid, isAuthTableDef, isBranchAdmin, isBuiltInScope, isChannelBusInstance, isColumnBuilder, isContentHashedFileName, isDataPlaneScope, isFieldOperation, isJsonColumnType, isJsonField, isNumericColumnType, isPercentileFraction, isPolicyExpressionKind, isPolicyShorthand, isPublicStorageKey, isPublicStoragePath, isRedactedSecurityRule, isRelationAggregateSort, isRelationDef, isResourceHandle, isRpcDef, isSQLAdmin, isSchemaAdmin, isSchemaEditingAdmin, isSqlTemplate, isStaticRedirectStatus, isStorageReference, isTableDef, isTablePatchList, isTemporalColumnType, isTenantClaimSource, isTenantMembershipSource, isTextColumnType, isTimeZoneName, isUiTablePreferences, isUnsupported, isValidAppHost, isValidEngine, isViewDef, joinConditions, json, knownScopes, matchStaticRoute, mergeUiTablePreferences, normalizeColumnAccess, normalizeStorage, normalizeValidation, parseAppAddress, parseByteSize, parseCaseFoldedFieldPath, parseEnvBoolean, parseFrameAncestor, parseRelationAggregateSort, parseScope, parseSimulatedContext, parseStorageReference, parseTablePatches, pgEnum, policy, queue, registerDataSourceCapabilities, registerResourceKind, rel, reservedPrefixFor, resetDeclaredQueueConsumers, resetDeclaredResources, resetDeclaredSubscriptions, resolveClientListLimit, resolveResourceRefs, resolveStorageReferences, resourceEnvSuffix, resourceId, resourceKeyOf, resourceKind, resourceKinds, resourceToDataSource, resourceToStorageSource, rewriteLegacyRlsFunctions, roleNameProblem, rulePatches, scopeAcceptsTarget, scopeGrants, scopeGrantsAny, scopeTargets, scopesBeyond, scopesForRoles, setQueueRuntime, setTopicRuntime, simulationHeaders, soleJoinCondition, sortKeyToString, sql, storageEnvSuffix, storageObjectPath, storageReference, storageReferencesForDownloadUrls, storageTargetOfDownloadUrl, storageTargetsInText, summarizeRoles, summarizeScopes, tablePatchProblems, toCanonicalOp, toDriverAggregate, toDriverAggregateGroup, topic, uiTablePreferencesProblems, unsupportedMethod, usesLegacyRlsFunctions, validateScopes, validateStaticRedirect, validateStaticRoute };
|
|
5744
3886
|
|
|
5745
3887
|
//# sourceMappingURL=index.es.js.map
|