palgres 0.53.0 → 0.54.0
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/chunks/DMGBXJWT.js +309 -0
- package/dist/chunks/MMDAYJKI.js +2 -0
- package/dist/chunks/Q7U5AW6L.js +5 -0
- package/dist/dsl.js +2 -2
- package/dist/index.js +156 -125
- package/dist/testing.js +2 -2
- package/package.json +1 -1
- package/types/access/src/apply.d.ts +96 -0
- package/types/access/src/base.d.ts +49 -0
- package/types/access/src/catalog.d.ts +53 -0
- package/types/access/src/compile.d.ts +120 -0
- package/types/access/src/errors.d.ts +7 -0
- package/types/access/src/index.d.ts +10 -0
- package/types/access/src/model.d.ts +87 -0
- package/types/access/src/reference.d.ts +12 -0
- package/types/access/src/text.d.ts +104 -0
- package/types/access/src/validation.d.ts +22 -0
- package/types/access/src/world.d.ts +43 -0
- package/types/palgres/src/access.d.ts +63 -0
- package/types/palgres/src/connect.d.ts +10 -1
- package/types/palgres/src/dsl/policy.d.ts +24 -0
- package/types/palgres/src/dsl/to-model.d.ts +11 -1
- package/types/palgres/src/forget.d.ts +6 -6
- package/types/palgres/src/index.d.ts +1 -1
- package/types/palgres/src/model.d.ts +8 -0
- package/types/palgres/src/plan.d.ts +5 -1
- package/types/palgres/src/query/access.d.ts +140 -0
- package/types/palgres/src/query/env-gen.d.ts +2 -0
- package/types/palgres/src/query/index.d.ts +9 -7
- package/types/palgres/src/query/surface.d.ts +6 -1
- package/types/palgres/src/query/typed.d.ts +13 -5
- package/dist/chunks/ULLX3GNS.js +0 -2
- package/dist/chunks/X2B6AJ7P.js +0 -5
- package/dist/chunks/XPFGITD6.js +0 -2
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export interface ValidationFailure {
|
|
2
|
+
/** The expectation, as a sentence. */
|
|
3
|
+
expectation: string;
|
|
4
|
+
/** What the schema answers instead. */
|
|
5
|
+
answer: string;
|
|
6
|
+
}
|
|
7
|
+
export interface ValidationResult {
|
|
8
|
+
passed: number;
|
|
9
|
+
failed: ValidationFailure[];
|
|
10
|
+
}
|
|
11
|
+
/** What is wrong with the validation file itself (not with the schema's answers). */
|
|
12
|
+
export declare class ValidationFileError extends Error {
|
|
13
|
+
constructor(message: string);
|
|
14
|
+
}
|
|
15
|
+
/** The schema's text a validation file names, when it does not carry it: the path, for whoever reads files. */
|
|
16
|
+
export declare function schemaPathOf(doc: unknown): string | null;
|
|
17
|
+
/**
|
|
18
|
+
* Answers a validation file's expectations from its own rows and relationships. `schemaText` is the schema it
|
|
19
|
+
* names (read by the caller) — ignored when the file carries its own. Throws AccessError for a schema that does not
|
|
20
|
+
* hold together and ValidationFileError for a file that cannot be read as one.
|
|
21
|
+
*/
|
|
22
|
+
export declare function runValidation(doc: unknown, schemaText: string | null): ValidationResult;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/** How a column's values compare, which is all a schema needs to know of its type. */
|
|
2
|
+
export type Family =
|
|
3
|
+
/** text, varchar and an enum: equal when the same characters. */
|
|
4
|
+
'text'
|
|
5
|
+
/** uuid: 8-4-4-4-12 hexadecimal digits, equal whatever the letters' case. */
|
|
6
|
+
| 'uuid'
|
|
7
|
+
/** smallint, integer, bigint: equal when the same number ("07" is 7). */
|
|
8
|
+
| 'int' | 'bool'
|
|
9
|
+
/** numeric and the floating types: a `where` may compare them; they are no key and no id. */
|
|
10
|
+
| 'numeric';
|
|
11
|
+
export interface TableShape {
|
|
12
|
+
/** The column whose value is the object's id. */
|
|
13
|
+
key: string;
|
|
14
|
+
/** Every column the schema reads, the key among them. */
|
|
15
|
+
columns: Record<string, Family>;
|
|
16
|
+
}
|
|
17
|
+
/** A column's value. An integer is a number or a bigint; a uuid and a text are strings. */
|
|
18
|
+
export type Value = string | number | bigint | boolean | null;
|
|
19
|
+
/** One stored relationship: `subjectType` is 'user' or a type's name. */
|
|
20
|
+
export interface Relationship {
|
|
21
|
+
objectType: string;
|
|
22
|
+
objectId: string;
|
|
23
|
+
relation: string;
|
|
24
|
+
subjectType: string;
|
|
25
|
+
subjectId: string;
|
|
26
|
+
}
|
|
27
|
+
export interface World {
|
|
28
|
+
/** By type name, for each type that names a table. */
|
|
29
|
+
tables: Map<string, {
|
|
30
|
+
shape: TableShape;
|
|
31
|
+
rows: Record<string, Value>[];
|
|
32
|
+
}>;
|
|
33
|
+
relationships: Relationship[];
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* An id as its type writes it, or null when the text is no value of that type: an integer's digits without a sign's
|
|
37
|
+
* zero or leading zeros, a uuid in lower case, a text as it is. Two ids are the same when this is the same — the
|
|
38
|
+
* database compares them the same way. An integer is at most 18 digits here, so that none overflows a bigint; a uuid
|
|
39
|
+
* is the hyphenated form alone.
|
|
40
|
+
*/
|
|
41
|
+
export declare function canonicalId(family: Family, text: string): string | null;
|
|
42
|
+
/** A column's value as an id's text: what `column::text` is in the database. Null stays null. */
|
|
43
|
+
export declare function idOf(family: Family, value: Value): string | null;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { type Compiled } from '../../access/src/index.js';
|
|
2
|
+
import type { Schema } from './model.js';
|
|
3
|
+
export declare const accessToken: (name: string) => string;
|
|
4
|
+
export declare const namesAccess: (text: string | undefined) => boolean;
|
|
5
|
+
/** A name as a policy may say it. */
|
|
6
|
+
export declare const ACCESS_NAME: RegExp;
|
|
7
|
+
/**
|
|
8
|
+
* What a version keeps of its compiled access schema (in its layout), so that the version after it can stand
|
|
9
|
+
* beside it and then take its place without compiling it again: a later compiler may write it otherwise, and what
|
|
10
|
+
* is in the database is what this one wrote.
|
|
11
|
+
*/
|
|
12
|
+
export interface RecordedAccess {
|
|
13
|
+
digest: string;
|
|
14
|
+
/** The compiled schema's name in the database: access_<digest>. */
|
|
15
|
+
schema: string;
|
|
16
|
+
names: {
|
|
17
|
+
type: string;
|
|
18
|
+
name: string;
|
|
19
|
+
view: string;
|
|
20
|
+
idType: string;
|
|
21
|
+
}[];
|
|
22
|
+
tables: {
|
|
23
|
+
type: string;
|
|
24
|
+
schema: string;
|
|
25
|
+
name: string;
|
|
26
|
+
key: string;
|
|
27
|
+
}[];
|
|
28
|
+
/** "The asker holds it on this row", for each name of a type with a table. */
|
|
29
|
+
predicates: {
|
|
30
|
+
type: string;
|
|
31
|
+
name: string;
|
|
32
|
+
sql: string;
|
|
33
|
+
}[];
|
|
34
|
+
/** The relations whose relationships are kept, each with the kinds of subject it takes: type, relation, subject. */
|
|
35
|
+
stored: [string, string, string][];
|
|
36
|
+
}
|
|
37
|
+
export interface AccessRoles {
|
|
38
|
+
authenticated: string;
|
|
39
|
+
service: string;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* The model's access schema, compiled against the model's own tables; null when it has none. Throws AccessError when
|
|
43
|
+
* the schema does not hold together or names a table or a column the model does not declare as it says.
|
|
44
|
+
*/
|
|
45
|
+
export declare function compileAccess(schema: Schema, roles: AccessRoles, aliases?: {
|
|
46
|
+
name: string;
|
|
47
|
+
type: string;
|
|
48
|
+
}[]): Compiled | null;
|
|
49
|
+
/** The digest a model's access schema compiles to: what the model carries, so that a compiler that writes it otherwise is another version. */
|
|
50
|
+
export declare function accessDigest(schema: Omit<Schema, 'access'>, text: string, roles: AccessRoles): string;
|
|
51
|
+
export declare function recordAccess(c: Compiled, text: string): RecordedAccess;
|
|
52
|
+
/**
|
|
53
|
+
* A policy's text with each name it reads replaced by that name's predicate on the table's rows. Answers what is
|
|
54
|
+
* wrong instead when the table is no type's, or the type has no such name.
|
|
55
|
+
*/
|
|
56
|
+
export declare function resolvePolicy(text: string, table: {
|
|
57
|
+
schema: string;
|
|
58
|
+
name: string;
|
|
59
|
+
}, access: Pick<RecordedAccess, 'tables' | 'predicates'> | null): {
|
|
60
|
+
sql: string;
|
|
61
|
+
} | {
|
|
62
|
+
refused: string;
|
|
63
|
+
};
|
|
@@ -18,6 +18,15 @@ export interface Binding {
|
|
|
18
18
|
pooled?: boolean;
|
|
19
19
|
/** Where a table of Postgres schema `name` is read by this version: the schema itself, or its version's views. */
|
|
20
20
|
schema(name: string): string;
|
|
21
|
+
/**
|
|
22
|
+
* The compiled access schema this version asks (its digest), when the app has one: what the app asks
|
|
23
|
+
* (access_<digest>.can, …) is asked of its own. Which version a transaction is, it says as it opens
|
|
24
|
+
* (palgres.version in the bind statement), so that while a migration is open a row policy answers each version
|
|
25
|
+
* by its own rules.
|
|
26
|
+
*/
|
|
27
|
+
access?: string;
|
|
28
|
+
/** That schema's text: what the engine reads the names an app may ask by from (Database.$access). */
|
|
29
|
+
accessText?: string;
|
|
21
30
|
}
|
|
22
31
|
/** The binding, for connections a transaction-mode pooler lends (Binding.pooled). */
|
|
23
32
|
export declare function pooledBinding(b: Binding): Binding;
|
|
@@ -28,7 +37,7 @@ export declare function pooledBinding(b: Binding): Binding;
|
|
|
28
37
|
* (applicationName). A pooled app (Binding.pooled) holds one such.
|
|
29
38
|
*/
|
|
30
39
|
export declare function sayRunning(b: Binding): string;
|
|
31
|
-
export declare function binding(version: number, direct: boolean): Binding;
|
|
40
|
+
export declare function binding(version: number, direct: boolean, access?: string, accessText?: string): Binding;
|
|
32
41
|
export declare class VersionNotMigrated extends Error {
|
|
33
42
|
readonly digest: string;
|
|
34
43
|
constructor(d: string);
|
|
@@ -61,6 +61,15 @@ export type PolicyExpr = {
|
|
|
61
61
|
kind: "isNull";
|
|
62
62
|
expr: PolicyExpr;
|
|
63
63
|
negated: boolean;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* "The asker holds this relation or permission on the row", as the app's
|
|
67
|
+
* access schema says it. The plan writes the compiled predicate in its
|
|
68
|
+
* place; until then it is a name.
|
|
69
|
+
*/
|
|
70
|
+
| {
|
|
71
|
+
kind: "access";
|
|
72
|
+
name: string;
|
|
64
73
|
} | {
|
|
65
74
|
/**
|
|
66
75
|
* A correlated `EXISTS (SELECT 1 FROM <table> <alias> WHERE <predicate>)`
|
|
@@ -234,6 +243,21 @@ export interface PolicyExprCtx<Cols extends string = string> {
|
|
|
234
243
|
auth: {
|
|
235
244
|
uid(): PolicyExprRef;
|
|
236
245
|
};
|
|
246
|
+
/**
|
|
247
|
+
* The asker holds a relation or a permission on this row, as the app's
|
|
248
|
+
* access schema defines it for the type this table carries:
|
|
249
|
+
*
|
|
250
|
+
* ```ts
|
|
251
|
+
* policy("members read").for("select").using(p.can("view"))
|
|
252
|
+
* ```
|
|
253
|
+
*
|
|
254
|
+
* It can stand beside other conditions (`p.or(p.can("view"), …)`). The
|
|
255
|
+
* schema is the app's (`db.access`); a name it does not have, or a table no
|
|
256
|
+
* type of it names, is refused when the migration is planned. Not allowed
|
|
257
|
+
* in a CHECK constraint, nor inside `existsIn` (it is about this table's
|
|
258
|
+
* row).
|
|
259
|
+
*/
|
|
260
|
+
can(name: string): PolicyExprRef;
|
|
237
261
|
/** A plain value, for saying explicitly that one side of a comparison is a literal. */
|
|
238
262
|
lit(v: string | number | boolean | null): PolicyExprRef;
|
|
239
263
|
and(...parts: PolicyExprRef[]): PolicyExprRef;
|
|
@@ -1,6 +1,16 @@
|
|
|
1
1
|
import { type Policy, type Schema, type Table } from '../model.js';
|
|
2
|
+
import { type AccessRoles } from '../access.js';
|
|
2
3
|
import type { SchemaDef } from './schema.js';
|
|
3
4
|
/** One or more schemas (db/public.ts, db/billing.ts, …) as the model. */
|
|
4
|
-
|
|
5
|
+
/**
|
|
6
|
+
* The schema files as the model. `access` is the app's access schema, as its text: it is compiled here against the
|
|
7
|
+
* tables declared (a schema that does not hold together, or names a table or a column they do not have as it says,
|
|
8
|
+
* throws AccessError), and the model carries what it compiled to. `roles` are the database's roles the app's
|
|
9
|
+
* requests take, when they are not the usual two.
|
|
10
|
+
*/
|
|
11
|
+
export declare function toModel(schemas: SchemaDef | SchemaDef[], options?: {
|
|
12
|
+
access?: string;
|
|
13
|
+
roles?: AccessRoles;
|
|
14
|
+
}): Schema;
|
|
5
15
|
/** The columns of `t` a policy's SQL names quoted — as the renderer writes a column; a hand-written policy that quotes nothing names none. */
|
|
6
16
|
export declare function policyColumns(t: Table, p: Policy): string[];
|
|
@@ -9,10 +9,13 @@ interface Begin {
|
|
|
9
9
|
interface Runs {
|
|
10
10
|
query(sql: string, params?: unknown[]): PromiseLike<unknown>;
|
|
11
11
|
}
|
|
12
|
-
|
|
12
|
+
/** What forgetting a user took: rows deleted, rows that forgot them, and — of an app with an access schema — the relationships they held. */
|
|
13
|
+
export interface Forgotten {
|
|
13
14
|
deleted: number;
|
|
14
15
|
detached: number;
|
|
15
|
-
|
|
16
|
+
relationships?: number;
|
|
17
|
+
}
|
|
18
|
+
export declare function forgetUser(sql: Begin, binding: Binding, schema: Schema, userId: string, serviceRole?: string): Promise<Forgotten>;
|
|
16
19
|
/**
|
|
17
20
|
* The same, in a transaction already open as service_role — a delivery's own ($asService(): all its handlers' work, or
|
|
18
21
|
* none, within the request's share of connections): in a savepoint of it, so a failure leaves the rest of the
|
|
@@ -21,8 +24,5 @@ export declare function forgetUser(sql: Begin, binding: Binding, schema: Schema,
|
|
|
21
24
|
*/
|
|
22
25
|
export declare function forgetUserIn(service: {
|
|
23
26
|
attempt<T>(fn: (tx: Runs) => Promise<T>): Promise<T>;
|
|
24
|
-
}, binding: Binding, schema: Schema, userId: string): Promise<
|
|
25
|
-
deleted: number;
|
|
26
|
-
detached: number;
|
|
27
|
-
}>;
|
|
27
|
+
}, binding: Binding, schema: Schema, userId: string): Promise<Forgotten>;
|
|
28
28
|
export {};
|
|
@@ -6,7 +6,7 @@ export { applicationName, cutOff, DEFAULT_ROLES, isDirect, MigrationOpen, Migrat
|
|
|
6
6
|
export type { Adoption, MigratorOptions, Pool, Reserved, StartResult, Status, Version } from './migrate.js';
|
|
7
7
|
export { bind, binding, bindStatement, pooledBinding, sayRunning, VersionNotMigrated } from './connect.js';
|
|
8
8
|
export type { Binding } from './connect.js';
|
|
9
|
-
export { forgetUser, forgetUserIn } from './forget.js';
|
|
9
|
+
export { forgetUser, forgetUserIn, type Forgotten } from './forget.js';
|
|
10
10
|
export { adoptionBaseline, drift, type Baseline } from './adopt.js';
|
|
11
11
|
export { introspect, type Introspected } from './introspect.js';
|
|
12
12
|
export { pullSchema, type Pulled } from './pull.js';
|
|
@@ -5,6 +5,14 @@ export interface Schema {
|
|
|
5
5
|
extensions: string[];
|
|
6
6
|
/** Named SQL the typed schema cannot say (an expression unique index, a function): applied once by name. */
|
|
7
7
|
raw: Raw[];
|
|
8
|
+
/**
|
|
9
|
+
* The app's access schema (who may do what on which object): its text, and the digest it compiles to — carried
|
|
10
|
+
* so that a compiler which writes it otherwise makes another version, and the database is compiled again.
|
|
11
|
+
*/
|
|
12
|
+
access?: {
|
|
13
|
+
text: string;
|
|
14
|
+
compiled: string;
|
|
15
|
+
};
|
|
8
16
|
}
|
|
9
17
|
export interface Table {
|
|
10
18
|
/** The Postgres schema; "public" unless given. */
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type RecordedAccess } from './access.js';
|
|
1
2
|
import { type Raw, type Schema } from './model.js';
|
|
2
3
|
import { type SearchGeneration } from './search.js';
|
|
3
4
|
/** A version's names: each visible table and column of the schema, and where it is in the database. */
|
|
@@ -11,6 +12,8 @@ export interface Layout {
|
|
|
11
12
|
physical: string;
|
|
12
13
|
}[];
|
|
13
14
|
}[];
|
|
15
|
+
/** The version's access schema as it was compiled into the database: what the version after it stands beside, then replaces. */
|
|
16
|
+
access?: RecordedAccess;
|
|
14
17
|
}
|
|
15
18
|
export type Step =
|
|
16
19
|
/** One transaction, under the migrator's lock timeout; tried again as a whole. */
|
|
@@ -111,10 +114,11 @@ export interface Roles {
|
|
|
111
114
|
service: string;
|
|
112
115
|
}
|
|
113
116
|
export interface PlanInput {
|
|
114
|
-
/** The version serving now, or null for a database Palgres has not migrated yet. */
|
|
117
|
+
/** The version serving now, or null for a database Palgres has not migrated yet; `access` is what its layout recorded of its access schema. */
|
|
115
118
|
from: {
|
|
116
119
|
n: number;
|
|
117
120
|
schema: Schema;
|
|
121
|
+
access?: RecordedAccess | null;
|
|
118
122
|
} | null;
|
|
119
123
|
/** The new version's number: past every version the database has recorded, an abandoned one too. */
|
|
120
124
|
next: number;
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/** An object's id: text in the database; a number is written as its digits. */
|
|
2
|
+
export type AccessId = string | number | bigint;
|
|
3
|
+
/** One object of the access schema: its type and its id. */
|
|
4
|
+
export interface AccessObject<K extends string = string> {
|
|
5
|
+
type: K;
|
|
6
|
+
id: AccessId;
|
|
7
|
+
}
|
|
8
|
+
/** Who holds a relation: a user by id (a bare string is one), or an object — `{ type: "team", id }`. */
|
|
9
|
+
export type AccessSubject = string | {
|
|
10
|
+
user: string;
|
|
11
|
+
} | AccessObject;
|
|
12
|
+
export interface AccessRelationship {
|
|
13
|
+
object: {
|
|
14
|
+
type: string;
|
|
15
|
+
id: string;
|
|
16
|
+
};
|
|
17
|
+
relation: string;
|
|
18
|
+
subject: {
|
|
19
|
+
type: string;
|
|
20
|
+
id: string;
|
|
21
|
+
};
|
|
22
|
+
/** When it was given, ISO 8601. */
|
|
23
|
+
since: string;
|
|
24
|
+
}
|
|
25
|
+
export interface AccessHistoryEntry {
|
|
26
|
+
/** ISO 8601. */
|
|
27
|
+
at: string;
|
|
28
|
+
action: 'grant' | 'revoke';
|
|
29
|
+
object: {
|
|
30
|
+
type: string;
|
|
31
|
+
id: string;
|
|
32
|
+
};
|
|
33
|
+
relation: string;
|
|
34
|
+
subject: {
|
|
35
|
+
type: string;
|
|
36
|
+
id: string;
|
|
37
|
+
};
|
|
38
|
+
/** Who did it: what the app said (`by`), else the request's user, else the database login. */
|
|
39
|
+
by: string | null;
|
|
40
|
+
}
|
|
41
|
+
export interface AccessFilter {
|
|
42
|
+
/** Of this object; without an id, of every object of the type. */
|
|
43
|
+
object?: {
|
|
44
|
+
type: string;
|
|
45
|
+
id?: AccessId;
|
|
46
|
+
};
|
|
47
|
+
relation?: string;
|
|
48
|
+
subject?: AccessSubject;
|
|
49
|
+
/** At most this many (default 100, at most 1000). */
|
|
50
|
+
limit?: number;
|
|
51
|
+
}
|
|
52
|
+
export type AccessRefusal = 'no_schema' | 'unknown_type' | 'unknown_name' | 'not_kept' | 'bad_id' | 'no_object' | 'too_many' | 'not_the_service';
|
|
53
|
+
/** What an access question or change was refused for. Thrown before anything is sent wherever the schema alone says so. */
|
|
54
|
+
export declare class AccessRefused extends Error {
|
|
55
|
+
readonly code: AccessRefusal;
|
|
56
|
+
constructor(code: AccessRefusal, message: string, options?: {
|
|
57
|
+
cause?: unknown;
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
type Known<A> = [keyof A] extends [never] ? false : true;
|
|
61
|
+
/** A type of the schema. */
|
|
62
|
+
export type AccessTypeOf<A> = Known<A> extends true ? keyof A & string : string;
|
|
63
|
+
/** A relation or a permission a user can hold on a `K`. */
|
|
64
|
+
export type AccessNameOf<A, K> = K extends keyof A ? (A[K] extends {
|
|
65
|
+
names: infer N extends string;
|
|
66
|
+
} ? N : string) : string;
|
|
67
|
+
/** A relation a `K` keeps relationships of. */
|
|
68
|
+
export type AccessRelationOf<A, K> = K extends keyof A ? (A[K] extends {
|
|
69
|
+
relations: infer R;
|
|
70
|
+
} ? keyof R & string : string) : string;
|
|
71
|
+
/** What holds relation `R` of a `K`: a user (a bare id, or `{ user }`), or an object of a type the relation takes. */
|
|
72
|
+
export type AccessSubjectOf<A, K, R> = K extends keyof A ? A[K] extends {
|
|
73
|
+
relations: infer M;
|
|
74
|
+
} ? R extends keyof M ? M[R] extends infer S extends string ? (S extends 'user' ? string | {
|
|
75
|
+
user: string;
|
|
76
|
+
} : {
|
|
77
|
+
type: S;
|
|
78
|
+
id: AccessId;
|
|
79
|
+
}) : AccessSubject : AccessSubject : AccessSubject : AccessSubject;
|
|
80
|
+
/**
|
|
81
|
+
* `Database.$access`: the app's access schema, asked and changed.
|
|
82
|
+
*
|
|
83
|
+
* `can`, `objects` and `held` are about the request's caller. The rest name a subject or change who holds what, and
|
|
84
|
+
* are the service role's: `Database.$asService().$access` — where those three are still about the caller.
|
|
85
|
+
*/
|
|
86
|
+
export interface AccessOps<A = unknown> {
|
|
87
|
+
/** Whether the caller holds `name` — a relation or a permission — on the object. Nobody is signed in: no. */
|
|
88
|
+
can<K extends AccessTypeOf<A>>(name: AccessNameOf<A, K>, object: AccessObject<K>): Promise<boolean>;
|
|
89
|
+
/** The ids of the objects of `type` the caller holds `name` on. */
|
|
90
|
+
objects<K extends AccessTypeOf<A>>(name: AccessNameOf<A, K>, type: K): Promise<string[]>;
|
|
91
|
+
/** Every relation and permission the caller holds on the object, sorted: what a screen shows or hides, in one statement. */
|
|
92
|
+
held<K extends AccessTypeOf<A>>(object: AccessObject<K>): Promise<AccessNameOf<A, K>[]>;
|
|
93
|
+
/** Whether `subject` (a user's id) holds `name` on the object. The service role's. */
|
|
94
|
+
check<K extends AccessTypeOf<A>>(subject: string, name: AccessNameOf<A, K>, object: AccessObject<K>): Promise<boolean>;
|
|
95
|
+
/** The ids of the objects of `type` that `subject` holds `name` on. The service role's. */
|
|
96
|
+
objectsOf<K extends AccessTypeOf<A>>(subject: string, name: AccessNameOf<A, K>, type: K): Promise<string[]>;
|
|
97
|
+
/** The users who hold `name` on the object, sorted. Refused past 10,000 related subjects: ask `check` then. The service role's. */
|
|
98
|
+
subjects<K extends AccessTypeOf<A>>(name: AccessNameOf<A, K>, object: AccessObject<K>): Promise<string[]>;
|
|
99
|
+
/**
|
|
100
|
+
* Gives `subject` the relation on the object; false when they had it. The object must exist (a type with a table).
|
|
101
|
+
* `by` is who did it, kept in the history: the request's user when it is not said. The service role's.
|
|
102
|
+
*/
|
|
103
|
+
grant<K extends AccessTypeOf<A>, R extends AccessRelationOf<A, K>>(object: AccessObject<K>, relation: R, subject: AccessSubjectOf<A, K, R>, options?: {
|
|
104
|
+
by?: string;
|
|
105
|
+
}): Promise<boolean>;
|
|
106
|
+
/** Takes the relation back; false when they did not have it. In force from the next statement on. The service role's. */
|
|
107
|
+
revoke<K extends AccessTypeOf<A>, R extends AccessRelationOf<A, K>>(object: AccessObject<K>, relation: R, subject: AccessSubjectOf<A, K, R>, options?: {
|
|
108
|
+
by?: string;
|
|
109
|
+
}): Promise<boolean>;
|
|
110
|
+
/** The relationships kept, by object, relation and subject. The service role's. */
|
|
111
|
+
relationships(filter?: AccessFilter): Promise<AccessRelationship[]>;
|
|
112
|
+
/** What was given and taken, the latest first: who, to whom, when. The service role's. */
|
|
113
|
+
history(filter?: AccessFilter): Promise<AccessHistoryEntry[]>;
|
|
114
|
+
}
|
|
115
|
+
/** What a version's access schema lets the app say, read from its text once. */
|
|
116
|
+
export interface AccessNames {
|
|
117
|
+
/** The compiled schema's name in the database. */
|
|
118
|
+
schema: string;
|
|
119
|
+
types: Map<string, {
|
|
120
|
+
names: Set<string>;
|
|
121
|
+
kept: Map<string, Set<string>>;
|
|
122
|
+
}>;
|
|
123
|
+
}
|
|
124
|
+
/** The names of an access schema's text, for the version that compiled it to `digest`. */
|
|
125
|
+
export declare function accessNames(text: string, digest: string): AccessNames;
|
|
126
|
+
/** The app's access schema as an augmentation's body: a type an entry, its names and what its relations take. */
|
|
127
|
+
export declare function accessTypesBlock(text: string, indent: string): string;
|
|
128
|
+
interface Asks {
|
|
129
|
+
query<T = unknown>(sql: string, params?: unknown[]): Promise<T[]>;
|
|
130
|
+
}
|
|
131
|
+
/** Whose transaction asks: nobody's (no one is signed in), a signed-in user's, or the service role's. */
|
|
132
|
+
export type AccessAsker = 'anon' | 'authenticated' | 'service';
|
|
133
|
+
/**
|
|
134
|
+
* The access operations over what asks (`raw`: the transaction current when each is called), for the version whose
|
|
135
|
+
* access schema `names` are — undefined when the app declares none: every operation then says so. `as` is whose
|
|
136
|
+
* transaction it is: nobody (anon) holds nothing and is not the database's to ask, and only the service role's
|
|
137
|
+
* names a subject or changes who holds what — said here, since the database's refusal would end the transaction.
|
|
138
|
+
*/
|
|
139
|
+
export declare function accessOps(raw: () => Asks, names: AccessNames | undefined, as: AccessAsker, unanswered?: string): AccessOps;
|
|
140
|
+
export {};
|
|
@@ -11,6 +11,7 @@ export declare const ENV_BLOCK_END = "// palbase:env:end";
|
|
|
11
11
|
*/
|
|
12
12
|
export declare function makeEnvDts(schemas: readonly SchemaDef[], options?: {
|
|
13
13
|
module?: string;
|
|
14
|
+
access?: string;
|
|
14
15
|
}): string;
|
|
15
16
|
/**
|
|
16
17
|
* The same types as a block of their own, between the markers and holding the
|
|
@@ -20,4 +21,5 @@ export declare function makeEnvDts(schemas: readonly SchemaDef[], options?: {
|
|
|
20
21
|
*/
|
|
21
22
|
export declare function envBlock(schemas: readonly SchemaDef[], options?: {
|
|
22
23
|
module?: string;
|
|
24
|
+
access?: string;
|
|
23
25
|
}): string;
|
|
@@ -55,10 +55,10 @@ export interface DatabaseOptions {
|
|
|
55
55
|
*/
|
|
56
56
|
prepare?: boolean;
|
|
57
57
|
}
|
|
58
|
-
/** One request's — or one job's — database. `T`, `S`: the project's tables (the framework's `Tables`, `Schemas`). */
|
|
59
|
-
export interface RequestDatabase<T, S> {
|
|
60
|
-
/** What a handler reaches as `Database`: typed tables, the `$` operations, $atomic, $asService(). */
|
|
61
|
-
readonly database: EnvTypedDatabase<T, S>;
|
|
58
|
+
/** One request's — or one job's — database. `T`, `S`: the project's tables (the framework's `Tables`, `Schemas`); `A`: its access schema (`Access`). */
|
|
59
|
+
export interface RequestDatabase<T, S, A = unknown> {
|
|
60
|
+
/** What a handler reaches as `Database`: typed tables, the `$` operations, $access, $atomic, $asService(). */
|
|
61
|
+
readonly database: EnvTypedDatabase<T, S, A>;
|
|
62
62
|
/** The string-keyed client the typed surface is built on. */
|
|
63
63
|
readonly client: DBClient;
|
|
64
64
|
/** Commits what was opened — nothing, if nothing was. Once, after the handler returns. */
|
|
@@ -66,9 +66,9 @@ export interface RequestDatabase<T, S> {
|
|
|
66
66
|
/** Rolls back what was opened. Once, when the handler throws. */
|
|
67
67
|
rollback(reason: unknown): Promise<void>;
|
|
68
68
|
}
|
|
69
|
-
export interface AppDatabase<T, S> {
|
|
69
|
+
export interface AppDatabase<T, S, A = unknown> {
|
|
70
70
|
readonly binding: Binding;
|
|
71
|
-
request(identity: Identity, options?: RequestOptions): RequestDatabase<T, S>;
|
|
71
|
+
request(identity: Identity, options?: RequestOptions): RequestDatabase<T, S, A>;
|
|
72
72
|
/**
|
|
73
73
|
* Seals again, with the key in force, every encrypted value sealed with an
|
|
74
74
|
* older one — what follows a rotation of the project's field keys, once the
|
|
@@ -85,9 +85,11 @@ export interface AppDatabase<T, S> {
|
|
|
85
85
|
}[]>;
|
|
86
86
|
}
|
|
87
87
|
/** The engine over `binding`'s version, its `Database` typed by `T` (public's tables) and `S` (the other schemas'). */
|
|
88
|
-
export declare function createDatabase<T = Record<never, never>, S = Record<never, never
|
|
88
|
+
export declare function createDatabase<T = Record<never, never>, S = Record<never, never>, A = unknown>(options: DatabaseOptions): Promise<AppDatabase<T, S, A>>;
|
|
89
89
|
export type { DatabaseAdmissionOptions } from './admission.js';
|
|
90
90
|
export { fieldAddress, type FieldCipher, type FieldsSource } from '../fields.js';
|
|
91
|
+
export { AccessRefused, accessNames, accessTypesBlock } from './access.js';
|
|
92
|
+
export type { AccessFilter, AccessHistoryEntry, AccessId, AccessNameOf, AccessNames, AccessObject, AccessOps, AccessRefusal, AccessRelationOf, AccessRelationship, AccessSubject, AccessSubjectOf, AccessTypeOf } from './access.js';
|
|
91
93
|
export type { AtomicClient, DBClient, DBOps, FindManyOptions, RowLock, SearchOptions } from './client.js';
|
|
92
94
|
export type { Embed } from './search.js';
|
|
93
95
|
export type { DatabaseBudget, DatabaseDiagnostics, DatabaseDiagnosticsOptions, DatabaseQueryEvent } from './diagnostics.js';
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type AccessAsker, type AccessNames } from './access.js';
|
|
1
2
|
import type { DBClient } from './client.js';
|
|
2
3
|
import type { EnvTypedDatabase } from './typed.js';
|
|
3
4
|
/**
|
|
@@ -6,4 +7,8 @@ import type { EnvTypedDatabase } from './typed.js';
|
|
|
6
7
|
* `S` the other schemas'). `$asService()` is built on each call, over the
|
|
7
8
|
* request's one service transaction.
|
|
8
9
|
*/
|
|
9
|
-
export declare function typedDatabase<T, S>(client: DBClient
|
|
10
|
+
export declare function typedDatabase<T, S, A = unknown>(client: DBClient, options?: {
|
|
11
|
+
access?: AccessNames;
|
|
12
|
+
as?: AccessAsker;
|
|
13
|
+
unanswered?: string;
|
|
14
|
+
}): EnvTypedDatabase<T, S, A>;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { ColIsOptionalOnInsert, ColumnBuilder, ColumnType, ColValue } from '../dsl/columns.js';
|
|
2
2
|
import { type SchemaDef, type TableDef, type UniqueKeysOf } from '../dsl/schema.js';
|
|
3
|
+
import type { AccessOps } from './access.js';
|
|
3
4
|
import type { AtomicClient, DBClient, DBOps, RowLock, SearchOptions } from './client.js';
|
|
4
5
|
import type { Search } from '../model.js';
|
|
5
6
|
import { isColRef } from './guards.js';
|
|
@@ -469,9 +470,16 @@ export type DollarOps<T> = {
|
|
|
469
470
|
[K in keyof T as `$${string & K}`]: T[K];
|
|
470
471
|
};
|
|
471
472
|
/** The service_role sibling, and an $atomic scope's handle: the same surface, without $asService. */
|
|
472
|
-
export type EnvServiceDatabase<T, S> = EnvSchemaSurface<T, S> & {
|
|
473
|
+
export type EnvServiceDatabase<T, S, A = unknown> = EnvSchemaSurface<T, S> & {
|
|
473
474
|
/** Commits independently of the request; every retry is a new BEGIN … COMMIT. */
|
|
474
|
-
$atomic<R>(fn: (tx: AtomicDatabase<T, S>) => Promise<R>, options?: AtomicOptions): Promise<R>;
|
|
475
|
+
$atomic<R>(fn: (tx: AtomicDatabase<T, S, A>) => Promise<R>, options?: AtomicOptions): Promise<R>;
|
|
476
|
+
/**
|
|
477
|
+
* The app's access schema, on this transaction: whether the caller holds a
|
|
478
|
+
* permission on an object, and the objects they hold it on; as the service
|
|
479
|
+
* role, the same of any user, who holds one, and giving and taking
|
|
480
|
+
* relationships. `A` is the schema as types (the framework's `Access`).
|
|
481
|
+
*/
|
|
482
|
+
$access: AccessOps<A>;
|
|
475
483
|
$query: DBClient['query'];
|
|
476
484
|
$insert: DBClient['insert'];
|
|
477
485
|
$insertMany: DBClient['insertMany'];
|
|
@@ -505,12 +513,12 @@ export type EnvServiceDatabase<T, S> = EnvSchemaSurface<T, S> & {
|
|
|
505
513
|
* with their claims, anyone else `anon`; `$asService()` is the explicit,
|
|
506
514
|
* greppable way past it (service_role).
|
|
507
515
|
*/
|
|
508
|
-
export type EnvTypedDatabase<T, S> = EnvServiceDatabase<T, S> & {
|
|
516
|
+
export type EnvTypedDatabase<T, S, A = unknown> = EnvServiceDatabase<T, S, A> & {
|
|
509
517
|
/** The RLS-bypassing sibling; it has no $asService of its own. */
|
|
510
|
-
$asService(): EnvServiceDatabase<T, S>;
|
|
518
|
+
$asService(): EnvServiceDatabase<T, S, A>;
|
|
511
519
|
};
|
|
512
520
|
/** One root transaction's handle. */
|
|
513
|
-
export type AtomicDatabase<T, S> = Omit<EnvServiceDatabase<T, S>, '$atomic'>;
|
|
521
|
+
export type AtomicDatabase<T, S, A = unknown> = Omit<EnvServiceDatabase<T, S, A>, '$atomic'>;
|
|
514
522
|
/** A table of a SchemaDef: `search()` where its declaration has one. */
|
|
515
523
|
export type TypedTable<T extends TableDef> = TypedTableOps<T> & (T extends {
|
|
516
524
|
search: Search;
|
package/dist/chunks/ULLX3GNS.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
/*! palgres 0.53.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
-
import{p as q}from"./X2B6AJ7P.js";var Te=Symbol.for("palbase.backend.httpError"),ee=Symbol.for("palbase.backend.engineRaised"),d=Object.freeze({uniqueViolation:"23505",foreignKeyViolation:"23503",serializationFailure:"40001",deadlockDetected:"40P01",queryCancelled:"57014",lockNotAvailable:"55P03",inFailedTransaction:"25P02",insufficientPrivilege:"42501"}),f=class extends Error{[Te]=!0;status;error;errorDescription;data;retryAfter;constructor(n,t,r,i,o){super(r),this.name="HttpError",this.status=n,this.error=t,this.errorDescription=r,i!==void 0&&(this.data=i),o!==void 0&&(this.retryAfter=o)}};function ne(e){return e[ee]=!0,e}function Ue(e){return typeof e=="object"&&e!==null&&e[ee]===!0}function g(e){let n=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2");return n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()}var y=class extends f{constructor(n,t){super(400,"bad_request",t??g("BadRequest"),n),this.name="BadRequest"}},H=class extends f{constructor(n,t,r){super(404,t??"not_found",n??g("NotFound"),r),this.name="NotFound"}},p=class extends f{constructor(n,t,r){super(409,t??"conflict",n??g("Conflict"),r),this.name="Conflict"}},X=class extends p{constraint;sqlstate=d.uniqueViolation;static is(n){return typeof n=="object"&&n!==null&&n.name==="UniqueViolation"&&typeof n.constraint=="string"}constructor(n,t,r,i){super(t??"Unique constraint violated",r??"unique_violation",i),this.name="UniqueViolation",this.constraint=n}};function Ve(e){if(typeof e!="object"||e===null||e.retryable!==!0)return!1;let n=e.sqlstate;return n===d.serializationFailure||n===d.deadlockDetected}var J=class extends p{retryable=!0;sqlstate;static is(n){return typeof n=="object"&&n!==null&&n.name==="SerializationFailure"}constructor(n=d.serializationFailure,t,r){super(t??"the transaction could not be serialized with a concurrent one \u2014 run it again from the start (put the reads a decision rests on and its writes in $atomic, with { retry: n })","serialization_failure",r),this.name="SerializationFailure",this.sqlstate=n}},Q=class extends p{retryable=!0;sqlstate;static is(n){return typeof n=="object"&&n!==null&&n.name==="DeadlockDetected"}constructor(n=d.deadlockDetected,t,r){super(t??"deadlock: two transactions waited on each other's locks and this one was cancelled \u2014 take locks in one order: Database.$lockRows(table, ids) when you have the ids, Database.$lockRowsWhere(table, filter) when you have a filter","deadlock_detected",r),this.name="DeadlockDetected",this.sqlstate=n}},Y=class extends Error{sqlstate=d.inFailedTransaction;static is(n){return typeof n=="object"&&n!==null&&n.name==="TransactionAborted"}constructor(n,t){super(n,{cause:t}),this.name="TransactionAborted"}},Z=class extends f{constructor(n,t){super(429,"too_many_requests",t??g("TooManyRequests"),n,n.retryAfter),this.name="TooManyRequests"}};function te(e){let n=e,t=r=>typeof r=="string"&&/^[0-9A-Z]{5}$/.test(r);if(t(n?.code))return n.code;if(t(n?.errno))return n.errno}var $e=new Set(["57P03","53300","08001","08004","ERR_POSTGRES_CONNECTION_REFUSED","ERR_POSTGRES_CONNECTION_FAILED","ERR_POSTGRES_CONNECTION_TIMEOUT","ECONNREFUSED","CONNECT_TIMEOUT"]),Ee=new Set(["57P01","57P02","08000","08003","08006","08007","08P01","ERR_POSTGRES_CONNECTION_CLOSED","CONNECTION_CLOSED","CONNECTION_DESTROYED","ECONNRESET","ETIMEDOUT","EPIPE"]);function Fe(e){return e instanceof Error&&e.code===void 0&&e.message==="connection must be a PostgresSQLConnection"}function Ke(e){let n=e;for(let t=0;t<4&&typeof n=="object"&&n!==null;t++){let r=te(n),i=n.code,o=s=>r!==void 0&&s.has(r)||typeof i=="string"&&s.has(i);if(o(Ee))return"lost";if(o($e))return"never";n=n.cause}}function ze(e){let n=e;for(let t=0;t<4&&typeof n=="object"&&n!==null;t++){let r=n.sqlstate,i=te(n)??(typeof r=="string"?r:void 0);if(i!==void 0)return!i.startsWith("08")&&!/^57P0[123]$/.test(i);n=n.cause}return!1}function Ge(e){let n=e,t=n?.constraint??n?.constraint_name;if(typeof t=="string"&&t.length>0)return t;let r=String(e?.message??"");return/violates unique constraint "([^"]+)"/.exec(r)?.[1]??""}var Oe=Symbol.for("palbase.data"),Se=globalThis,x=Se[Oe]??=new WeakSet;function re(e){return e instanceof Date||ArrayBuffer.isView(e)||e instanceof ArrayBuffer}function oe(e){let n=[e];for(;n.length>0;){let t=n.pop();if(!(typeof t!="object"||t===null||x.has(t)||re(t))){x.add(t);for(let r of Array.isArray(t)?t:Object.values(t))n.push(r)}}return e}function m(e){return typeof e=="object"&&e!==null&&x.has(e)}function Pe(e){if(!Array.isArray(e))return e;for(let n of e)if(!(typeof n!="object"||n===null))for(let t of Object.values(n))typeof t=="object"&&t!==null&&oe(t);return e}function h(e,n){return m(e)&&x.add(n),n}function Ye(e,n,t){if(!m(e))return;let r=`is data \u2014 sent by a request or read from a row \u2014 and ${t} is written in code: data gives values. Build it in code around the values you checked.`;throw ne(new y({fields:[{field:n,message:r}]},`${n} ${r}`))}var I=Symbol.for("palbase.db.ref"),ue=Symbol.for("palbase.tx.expr");function b(e,n){return Object.defineProperty(e,I,{value:n,enumerable:!1}),e}function w(e){if(!(typeof e!="object"||e===null))return Object.hasOwn(e,I)?e[I]:void 0}function R(e){return w(e)==="col"&&typeof e.$col=="string"}function l(e){if(w(e)!=="sql")return!1;let n=e.$sql;return n!==void 0&&Array.isArray(n.text)&&Array.isArray(n.values)}function nn(e){if(w(e)!=="ref")return!1;let n=e.$ref;return n!==void 0&&typeof n.op=="number"&&typeof n.field=="string"}function tn(e){if(w(e)!=="expr")return!1;let n=e.$expr;return n!==void 0&&(n.fn==="inc"||n.fn==="dec"||n.fn==="now")}function rn(e){if(typeof e!="object"||e===null||w(e)!==void 0)return!1;let n=e.$ref;return n!==void 0&&typeof n=="object"&&n!==null}function on(e){if(typeof e!="object"||e===null||w(e)!==void 0||_(e))return null;let n=e;return typeof n.$col=="string"?"col":n.$sql!==void 0&&typeof n.$sql=="object"&&n.$sql!==null?"sql":n.$expr!==void 0&&typeof n.$expr=="object"&&n.$expr!==null?"expr":null}function _(e){if(typeof e!="object"&&typeof e!="function"||e===null)return!1;try{return e[ue]!==void 0}catch{return!1}}function k(e){if(!_(e))return!1;try{let n=e[ue];return typeof n=="object"&&n!==null&&n.fn==="now"}catch{return!1}}function sn(e,n,t,r){for(let i of t){let o=r[i];if(k(o))throw new Error(`${e}(${n}): "${i}" got now() where a value is expected. To write the server's time when a row is inserted, declare the column defaultNow(); to stamp an existing row, updateMany({ where, set: { ${i}: now() } }) or, in $transaction, tx.public.${n}.updateWhere(where, { ${i}: now() }).`);if(_(o))throw new Error(`${e}(${n}): "${i}" got an expression handle (increment()/decrement()) where a value is expected. To add to a counter use updateMany({ where, set: { ${i}: increment(n) } }) or, in $transaction, tx.public.${n}.updateWhere(where, { ${i}: increment(n) }).`);if(R(o))throw new Error(`${e}(${n}): "${i}" got a col(). A column reference stands only in a filter; to write one column's value into another, use $query.`)}}var Ae=new Set(["gt","gte","lt","lte","neq","in","contains","icontains","startsWith","endsWith","isNull","overlaps"]),ie={eq:'equality is written bare: { <column>: <value> } (or { <column>: col("\u2026") } to compare with a column)'};function se(e,n,t){if(t&&!l(t))for(let[r,i]of Object.entries(t)){if(r==="OR"||r==="AND"||r==="NOT"){let s=r==="NOT"?[i]:i;if(!Array.isArray(s))throw new Error(`${e}(${n}): where.${r} must be an array`);for(let a of s){if(a===null||typeof a!="object")throw new Error(`${e}(${n}): the branches of where.${r} must be filter objects`);se(e,n,a)}continue}if(r==="has"){if(i===null||typeof i!="object"||Array.isArray(i))throw new Error(`${e}(${n}): where.has must be a map of relations ({ <relation>: { \u2026 } })`);for(let[s,a]of Object.entries(i)){if(a===null||typeof a!="object"||Array.isArray(a))throw new Error(`${e}(${n}): where.has.${s} must be a filter object`);se(e,n,a)}continue}if(i===void 0)throw new Error(`${e}(${n}): where.${r} is undefined \u2014 not a filter value. Bound, it is NULL, and '= NULL' matches no row, so the query would answer nothing and say nothing. Leave the key out when there is no value.`);if(i===null||typeof i!="object"||Array.isArray(i)||R(i)||k(i))continue;let o=Object.entries(i);if(o.length===0)throw new Error(`${e}(${n}): where.${r} is an empty operator object ({}) \u2014 it produces no condition, so the column would silently drop out of the filter. Leave the key out when there is no condition.`);for(let[s,a]of o){if(s==="in"){if(!Array.isArray(a))throw new Error(`${e}(${n}): where.${r}.in must be an array`);if(a.some(c=>c===void 0))throw new Error(`${e}(${n}): where.${r}.in holds undefined \u2014 bound as NULL it matches no row. Drop it when building the list.`);continue}if(ie[s]!==void 0)throw new Error(`${e}(${n}): where.${r}.${s} is not in this filter language \u2014 ${ie[s]}`);if(!Ae.has(s))throw new Error(`${e}(${n}): where.${r} has an unknown operator "${s}" (gt/gte/lt/lte/neq/in/contains/icontains/startsWith/endsWith/isNull/overlaps)`);if(a===void 0)throw new Error(`${e}(${n}): where.${r}.${s} is undefined \u2014 the comparison's right side would be NULL and match no row. Leave the condition out.`)}}}var Ne=["days","hours","minutes","seconds"],je=2147483647,ae=e=>typeof e=="number"||typeof e=="boolean"||e===null||e===void 0?String(e):typeof e=="string"?JSON.stringify(e.slice(0,40)):typeof e;function B(e){if(e===null||typeof e!="object"||Array.isArray(e))return{refused:"takes a span: { days?, hours?, minutes?, seconds? }"};let n={};for(let t of Object.keys(e)){if(!Ne.includes(t))return{refused:`${ae(t)} is not a unit of the span \u2014 days, hours, minutes or seconds`};let r=e[t];if(typeof r!="number"||!Number.isSafeInteger(r)||r<0||r>je)return{refused:`${t} is a whole number, 0 or more, got ${ae(r)}${r===void 0?" \u2014 leave the unit out instead":""}`};n[t]=r}return Object.keys(n).length===0?{refused:"was given no span \u2014 ago({}) would be now(); name days, hours, minutes or seconds, or write now()"}:{span:Object.freeze(n)}}function an(e,n,t,r){for(let i of t)if(r[i]===void 0)throw new Error(`${e}(${n}): "${i}" is undefined \u2014 not a value to write. Write null to empty the column; leave the key out to leave the column as it is (a missing request field used to write NULL silently).`)}function le(e,n){let r=(n!==null&&typeof n=="object"?Object.keys(n):[]).filter(o=>o!=="id");if(r.length>0)throw new Error(`update(${e}): where takes the row's id alone, not ${r.map(o=>`"${o}"`).join(", ")} \u2014 a condition beside the id would be dropped. To update the rows a filter matches, updateMany({ where, set }).`);let i=n?.id;if(typeof i!="string"&&typeof i!="number"&&typeof i!="bigint")throw new Error(`update(${e}): where needs the row's id, one value \u2014 { where: { id }, set }. To update the rows a filter matches, updateMany({ where, set }).`);return String(i)}var P=class extends Error{constructor(n){super(n),this.name="TxRefError"}},u=class extends Error{constructor(n){super(n),this.name="TxPlanError"}},$=Symbol.for("palbase.tx.expr"),E=Symbol.for("palbase.tx.ref"),O=Symbol.for("palbase.tx.row"),pe=Symbol.for("palbase.tx.rows"),V=["then","valueOf","toString","toJSON",Symbol.toPrimitive];function F(e,n,t){let r=typeof e=="symbol"?e.description??String(e):e;throw new P(`${n} was used as a value (via \`${r}\`). Nothing in a transaction callback has run yet, so there is no value to read. ${t}`)}function dn(){return W({fn:"now"})}function fn(e){let n=B(e);if("refused"in n)throw new u(`ago() ${n.refused}`);return W(Object.freeze({fn:"now",minus:n.span}))}function he(e,n){if(e.fn!=="now"||e.minus===void 0)return;let t=B(e.minus);if("refused"in t)throw new u(`\`${n}\`: ago() ${t.refused}`)}function wn(e){return ye(e,"increment"),W({fn:"inc",by:e})}function pn(e){return ye(e,"decrement"),W({fn:"dec",by:e})}function ye(e,n){if(typeof e=="string"){if(!/^-?\d+(\.\d+)?$/.test(e))throw new u(`${n}() takes a decimal number as text, got "${e}" \u2014 "12", "12.50"`)}else if(typeof e!="number"||!Number.isFinite(e))throw new u(`${n}() needs a finite number, got ${String(e)}`);if(typeof e=="string"?e.trimStart().startsWith("-"):e<0){let r=n==="increment"?"decrement":"increment";throw new u(`${n}() takes no negative amount ("${String(e)}"). Use ${r}() for the other direction \u2014 a sign kept in the amount is seen by no code that reads the direction.`)}}function hn(e){return C(e)}function W(e){return new Proxy({[$]:e},{get(n,t){if(t===$)return n[$];V.includes(t)&&F(t,"A plan expression","Write it into an operation instead.")}})}function We(e,n){let t={[E]:{op:e,field:n}};return new Proxy(t,{get(r,i){if(i===E)return r[E];V.includes(i)&&F(i,`\`${n}\` of a row this transaction has not written yet`,"Pass it to another operation in the same plan, or return it from the callback and read it after `$transaction` resolves.")}})}function De(e){let n={[O]:e};return new Proxy(n,{get(t,r){if(r===O)return t[O];if(V.includes(r)&&F(r,"A row this transaction has not written yet","Read one of its columns to reference it, or return the row from the callback and read it after `$transaction` resolves."),typeof r!="symbol")return We(e,r)}})}function D(e){if(typeof e!="object"||e===null)return null;let n=e[E];return typeof n=="object"&&n!==null&&typeof n.op=="number"&&typeof n.field=="string"?n:null}function v(e){if(typeof e!="object"||e===null)return null;let n=e[O];return typeof n=="number"?n:null}function C(e){if(typeof e!="object"||e===null)return null;let n=e[$];return typeof n=="object"&&n!==null?n:null}function M(e){return typeof e=="object"&&e!==null&&e[pe]!==void 0}function ve(e,n,t){let r=D(e);if(r)return b({$ref:{op:r.op,field:r.field}},"ref");let i=C(e);if(i){if(i.fn!=="now"&&!t)throw new u(`\`${n}\`: ${i.fn}() reads the column's current value, so it is only valid in updateWhere(where, set).`);return he(i,n),b({$expr:i},"expr")}if(v(e)!==null)throw new u(`\`${n}\`: a row handle is not a value. Read the column you meant (e.g. \`row.id\`).`);if(M(e))throw new u(`\`${n}\`: an operation result is not a value. Declare an expectation first (\`.expectOne(err)\`) and read a column from the row.`);return ge(e,n),e}function U(e,n){let t=D(e);if(t)return b({$ref:{op:t.op,field:t.field}},"ref");let r=C(e);if(r&&r.fn!=="now")throw new u(`\`${n}\`: ${r.fn}() is a WRITE expression, not a comparison \u2014 it cannot stand in a filter. Compare the column with a value or a col().`);if(k(e))return r&&he(r,n),e;if(v(e)!==null)throw new u(`\`${n}\`: a row handle is not a value. Read the column you meant (e.g. \`row.id\`).`);if(M(e))throw new u(`\`${n}\`: an operation result is not a value. Declare an expectation first (\`.expectOne(err)\`) and read a column from the row.`);if(Array.isArray(e))return h(e,e.map(i=>U(i,n)));if(e!==null&&typeof e=="object"&&!(e instanceof Date)&&!R(e)&&!l(e)){let i=h(e,{});for(let[o,s]of Object.entries(e))i[o]=U(s,n);return i}return e}function L(e){if(l(e))return e;let n=h(e,{});for(let t of Object.keys(e).sort()){let r=e[t];if(r===void 0)throw new u(`where.${t} is undefined \u2014 not a filter value. Dropped, the condition would silently go and the filter match more rows than it reads (a missing request field looks like this). Leave the key out when there is no condition; write null for IS NULL.`);n[t]=U(r,t)}return n}function ge(e,n){if(!(typeof e!="object"||e===null||e instanceof Date)){if(D(e)||C(e)||v(e)!==null||M(e))throw new u(`\`${n}\`: a plan handle is nested inside a value. It would be stored as literal JSON, not resolved. Put the reference directly in the column.`);for(let t of Array.isArray(e)?e:Object.values(e))ge(t,n)}}function T(e,n){let t={};for(let r of Object.keys(e).sort()){let i=e[r];if(i===void 0)throw new u(`${r} is undefined \u2014 not a value to write. The key is there but its value is not, so the column would silently not be written (a missing request field looks like this). Leave the key out for the column default; write null for NULL.`);t[r]=ve(i,r,n)}return t}var S=-1,A=class{[pe]=!0;guarded=!1;builder;opIndex;what;constructor(n,t,r){this.builder=n,this.opIndex=t,this.what=r}then(){throw new P(`${this.what} cannot be awaited: a transaction callback builds a plan, it does not run statements. Remove the \`await\`.`)}expectOne(n){if(this.declareGuard("one",1,n),this.opIndex===S)throw n;return De(this.opIndex)}expectNone(n){this.declareGuard("none",0,n)}expectAtLeast(n,t){if(ce(n,"expectAtLeast"),this.declareGuard("atLeast",n,t),this.opIndex===S&&n>0)throw t}expectAtMost(n,t){ce(n,"expectAtMost"),this.declareGuard("atMost",n,t)}declareGuard(n,t,r){if(!(r instanceof Error))throw new u(`${this.what}: an expectation needs the Error to throw when it does not hold (e.g. \`.expect\u2026(new Conflict("already accepted"))\`).`);if(this.guarded)throw new u(`${this.what} already has an expectation. One operation carries one expectation; declare the second on its own operation.`);this.guarded=!0,this.opIndex!==S&&this.builder.attachGuard(this.opIndex,n,t,r)}};function ce(e,n){if(!Number.isInteger(e)||e<0)throw new u(`${n}(n) needs a non-negative integer, got ${String(e)}`)}var de=1e3,fe=5e3,N=class{ops=[];slots=[];table(n){return{insert:t=>{let r=T(t,!1);if(Object.keys(r).length===0)throw new u(`${n}.insert() needs at least one column`);return this.push({op:"insert",table:n,values:r},`${n}.insert()`)},put:(t,r)=>{let i=T(t,!1);if(Object.keys(i).length===0)throw new u(`${n}.put() needs at least one column`);if(r.onConflict.length===0)throw new u(`${n}.put() needs at least one onConflict column`);return this.push({op:"upsert",table:n,values:i,onConflict:r.onConflict},`${n}.put()`)},insertMany:(t,r)=>{if(t.length===0)return new A(this,S,`${n}.insertMany()`);if(t.length>fe)throw new u(`${n}.insertMany() has ${t.length} rows; the limit is ${fe}. Split the write.`);let i=t.map(o=>T(o,!1));return qe(i,n),this.push({op:"insertMany",table:n,rows:i,...Me(r,n)},`${n}.insertMany()`)},updateWhere:(t,r)=>{let i=L(t),o=T(r,!0);if(Object.keys(i).length===0&&!l(i))throw new u(`${n}.updateWhere() needs a filter. An update with no filter rewrites the whole table.`);if(Object.keys(o).length===0)throw new u(`${n}.updateWhere() needs at least one column to set`);return this.push({op:"update",table:n,set:o,where:i},`${n}.updateWhere()`)},deleteWhere:t=>{let r=L(t);if(Object.keys(r).length===0&&!l(r))throw new u(`${n}.deleteWhere() needs a filter. A delete with no filter empties the table.`);return this.push({op:"delete",table:n,where:r},`${n}.deleteWhere()`)},select:(t,r)=>{let i={op:"select",table:n},o=L(t??{});if((Object.keys(o).length>0||l(o))&&(i.where=o),r?.limit!==void 0){if(!Number.isInteger(r.limit)||r.limit<0)throw new u(`${n}.select(): limit needs a non-negative integer, got ${String(r.limit)}`);i.limit=r.limit}return r?.lock!==void 0&&(i.lock=r.lock),this.push(i,`${n}.select()`)}}}push(n,t){if(this.ops.length>=de)throw new u(`this transaction has ${de} operations, the limit. Use insertMany() for bulk writes, or split the work.`);let r=this.ops.length;return this.ops.push(n),new A(this,r,t)}attachGuard(n,t,r,i){let o=this.ops[n];if(!o)throw new u(`internal: expectation on unknown operation ${n}`);let s=this.slots.length;this.slots.push(i),o.guard={kind:t,n:r,slot:s}}body(){return{ops:this.ops}}errorForSlot(n){return this.slots[n]??null}},Ce=e=>typeof e=="string"?JSON.stringify(e.slice(0,40)):typeof e;function Me(e,n){if(e===void 0)return{};if(e.action!==void 0&&e.action!=="ignore"&&e.action!=="update")throw new u(`${n}.insertMany(): a conflict's action is "ignore" or "update", not ${Ce(e.action)}.`);if(e.onConflict===void 0){if(e.action!=="ignore")throw new u(`${n}.insertMany() was given a conflict action with no onConflict columns. An overwrite is matched on columns: name them \u2014 action "ignore" alone skips a collision with any unique key.`);return{action:"ignore"}}if(e.onConflict.length===0)throw new u(`${n}.insertMany() was given an empty onConflict list. A collision is matched on columns: name them, or leave onConflict out with action "ignore" to skip a collision with any unique key.`);return{onConflict:e.onConflict,action:e.action??"ignore"}}function qe(e,n){let t=e[0];if(!t)return;let r=Object.keys(t),i=r.join(",");for(let o=1;o<e.length;o++){let s=Object.keys(e[o]);if(s.join(",")!==i)throw new u(`${n}.insertMany(): every row must set the same columns. Row 0 sets [${r.join(", ")}] but row ${o} sets [${s.join(", ")}]. (A property set to \`undefined\` counts as absent \u2014 use \`null\`.)`)}}function j(e,n){let t=D(e);if(t){let i=we(n,t.op,`\`${t.field}\``);if(!(t.field in i))throw new u(`the transaction's operation ${t.op} returned no column \`${t.field}\`.`);return i[t.field]}let r=v(e);if(r!==null)return we(n,r,"a row");if(M(e))throw new u("an operation result cannot be returned from a transaction callback: its row count is not known until the plan runs. Declare an expectation (`.expectOne(err)`) and return the row, or a column of it.");if(Array.isArray(e))return e.map(i=>j(i,n));if(Ie(e)){let i={};for(let[o,s]of Object.entries(e))i[o]=j(s,n);return i}return e}function we(e,n,t){let r=e[n];if(!r)throw new u(`the transaction returned no result for operation ${n}, so ${t} cannot be read.`);let i=r.rows[0];if(!i)throw new u(`the transaction's operation ${n} returned no row, so ${t} cannot be read.`);return i}function Ie(e){if(typeof e!="object"||e===null)return!1;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}async function xe(e,n,t,r){let i=r(n),o=t.body();if(o.ops.length===0)return j(i,[]);let s;try{s=await e.txPlan(o)}catch(a){throw _e(a,t)}return j(i,s.results)}function _e(e,n){if(typeof e!="object"||e===null)return e;let t=e;return t.error_code!=="tx_guard_failed"||typeof t.slot!="number"?e:n.errorForSlot(t.slot)??e}import{AsyncLocalStorage as Be}from"node:async_hooks";function me(e){let n=e??0;if(!Number.isInteger(n)||n<0||n>10)throw new Error("transaction retry must be an integer between 0 and 10");return n}function gn(e){if(me(e.retry),e.isolation!==void 0&&!["read committed","repeatable read","serializable"].includes(e.isolation))throw new Error("transaction isolation must be read committed, repeatable read or serializable");if(e.readOnly!==void 0&&typeof e.readOnly!="boolean")throw new Error("transaction readOnly must be a boolean");for(let n of["lockTimeoutMs","statementTimeoutMs","timeoutMs"]){let t=e[n];if(t!==void 0&&(!Number.isInteger(t)||t<1||t>2147483647))throw new Error(`transaction ${n} must be a positive integer in milliseconds`)}if(e.signal!==void 0&&(typeof e.signal.aborted!="boolean"||typeof e.signal.addEventListener!="function"))throw new Error("transaction signal must be an AbortSignal")}function be(e){if(me(e?.retry)!==0)throw new Error("Database.$transaction is a savepoint plan on the request transaction and cannot retry its snapshot or COMMIT. Use Database.$atomic(async tx => { ... }, { retry, isolation }) and put all decision reads and writes inside that callback.")}function xn(e){if(e){if(e.returning!==void 0&&typeof e.returning!="boolean")throw new Error("insertMany returning must be a boolean");if(e.action!==void 0&&e.action!=="ignore"&&e.action!=="update")throw new Error("insertMany action must be ignore or update");if(e.onConflict!==void 0&&(!Array.isArray(e.onConflict)||e.onConflict.some(n=>typeof n!="string"||n.length===0)))throw new Error("insertMany onConflict must be an array of column names");if(e.action==="update"&&!e.onConflict?.length)throw new Error('insertMany action "update" overwrites the row a collision is matched on: name its columns in onConflict');if(e.action==="ignore"&&e.onConflict!==void 0&&e.onConflict.length===0)throw new Error('insertMany onConflict is an empty list: name the columns a collision is matched on, or leave it out \u2014 action "ignore" alone skips a collision with any unique key')}}function Re(e,n){return new Proxy({},{get(t,r){if(typeof r!="string")return;let i=`${n}${r}`;return{insert:o=>e().insert(i,o),insertMany:(o,s)=>e().insertMany(i,o,s),aggregate:o=>e().aggregate(i,o),update:o=>e().update(i,le(i,o.where),o.set),delete:o=>e().delete(i,o),findById:o=>e().findById(i,o),findUnique:o=>e().findUnique(i,o.where,{select:o.select,with:o.with,lock:o.lock}),page:o=>{let{where:s,...a}=o??{};return e().page(i,s,a)},findMany:o=>{let{where:s,...a}=o??{};return e().findMany(i,s,a)},put:o=>e().put(i,o.data,{onConflict:o.onConflict}),updateMany:o=>e().updateMany(i,o.where,o.set,o.returning===void 0?void 0:{returning:o.returning}),deleteMany:o=>e().deleteMany(i,o.where),count:o=>e().count(i,o?.where),claim:(o,s)=>e().claim(i,o,s),search:(o,s)=>e().search(i,o,s)}}})}function ke(e,n=""){return new Proxy({},{get(t,r){if(typeof r=="string")return e.table(n+r)}})}function Le(e){let n=ke(e);return new Proxy({},{get(t,r){if(typeof r=="string")return r==="tables"||r==="public"?n:ke(e,q(r,""))}})}function G(e,n,t={}){let i=Object.assign({$query:(o,s)=>e().query(o,s),$diagnostics:()=>e().diagnostics(),$insert:(o,s)=>e().insert(o,s),$insertMany:((o,s,a)=>e().insertMany(o,s,a)),$update:(o,s,a)=>e().update(o,s,a),$delete:(o,s)=>e().delete(o,s),$findById:(o,s)=>e().findById(o,s),$findUnique:(o,s,a)=>e().findUnique(o,s,a),$page:(o,s,a)=>e().page(o,s,a),$findMany:(o,s,a)=>e().findMany(o,s,a),$put:(o,s,a)=>e().put(o,s,a),$updateMany:(o,s,a,c)=>e().updateMany(o,s,a,c),$deleteMany:(o,s)=>e().deleteMany(o,s),$count:(o,s)=>e().count(o,s),$search:(o,s,a)=>e().search(o,s,a),$aggregate:(o,s)=>e().aggregate(o,s),$claim:(o,s,a)=>e().claim(o,s,a),$lockRows:(o,s)=>e().lockRows(o,s),$lockRowsWhere:(o,s,a)=>e().lockRowsWhere(o,s,a),$advisoryXactLock:o=>e().advisoryXactLock(o)},t,{$atomic(o,s){let a=e();if(typeof a.atomic!="function")throw new Error("Database.$atomic owns one transaction and identity; nested roots and $asService are not allowed");return a.atomic(c=>n(c,()=>o(G(()=>c,n))),s)},$attempt:o=>e().attempt(o),$transaction(o,s){be(s);let a=new N;return xe(e(),Le(a),a,o)}});return new Proxy(i,{get(o,s,a){return s==="tables"?Re(e,""):typeof s=="string"&&!s.startsWith("$")&&!(s in o)?Re(e,q(s,"")):Reflect.get(o,s,a)}})}var K=new Be,z=()=>{throw new Error("Database.$atomic owns one transaction and identity; nested roots and $asService are not allowed")};function En(e){let n={},t=()=>{let s=K.getStore();return s?.owner===n?s.tx:e},r=(s,a)=>K.run({owner:n,tx:Object.assign(Object.create(null),s,{atomic:z,asService:z})},a),i=new Proxy(Object.create(null),{get:()=>()=>{throw new Error("Database inside $asService().$atomic: the shared Database would bypass the caller's row-level security there \u2014 use the handle the callback is given")}}),o=(s,a)=>K.run({owner:n,tx:i},a);return G(t,r,{$asService(){let s=t();if(typeof s.asService!="function")return z();let a=s.asService();return G(()=>a,o)}})}export{Te as a,ee as b,d as c,f as d,ne as e,Ue as f,y as g,H as h,p as i,X as j,Ve as k,J as l,Q as m,Y as n,Z as o,te as p,$e as q,Ee as r,Fe as s,Ke as t,ze as u,Ge as v,re as w,oe as x,m as y,Pe as z,h as A,Ye as B,b as C,R as D,l as E,nn as F,tn as G,rn as H,on as I,_ as J,k as K,sn as L,se as M,B as N,an as O,le as P,P as Q,u as R,dn as S,fn as T,wn as U,pn as V,hn as W,N as X,xe as Y,me as Z,gn as _,xn as $,En as aa};
|