@zenstackhq/runtime 3.0.0-alpha.9 → 3.0.0-beta.10

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.
@@ -1,2331 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
-
4
- // src/plugins/policy/errors.ts
5
- var RejectedByPolicyError = class extends Error {
6
- static {
7
- __name(this, "RejectedByPolicyError");
8
- }
9
- model;
10
- reason;
11
- constructor(model, reason) {
12
- super(reason ?? `Operation rejected by policy${model ? ": " + model : ""}`), this.model = model, this.reason = reason;
13
- }
14
- };
15
-
16
- // src/plugins/policy/policy-handler.ts
17
- import { invariant as invariant6 } from "@zenstackhq/common-helpers";
18
- import { AliasNode as AliasNode3, BinaryOperationNode as BinaryOperationNode3, ColumnNode as ColumnNode2, DeleteQueryNode, FromNode as FromNode2, IdentifierNode as IdentifierNode2, InsertQueryNode, OperationNodeTransformer, OperatorNode as OperatorNode3, PrimitiveValueListNode, RawNode, ReturningNode, SelectionNode as SelectionNode2, SelectQueryNode as SelectQueryNode2, TableNode as TableNode3, UpdateQueryNode, ValueNode as ValueNode3, ValuesNode, WhereNode as WhereNode2 } from "kysely";
19
- import { match as match7 } from "ts-pattern";
20
-
21
- // src/client/crud/dialects/index.ts
22
- import { match as match4 } from "ts-pattern";
23
-
24
- // src/client/crud/dialects/postgresql.ts
25
- import { invariant as invariant2 } from "@zenstackhq/common-helpers";
26
- import { sql as sql2 } from "kysely";
27
- import { match as match2 } from "ts-pattern";
28
-
29
- // src/client/errors.ts
30
- var QueryError = class extends Error {
31
- static {
32
- __name(this, "QueryError");
33
- }
34
- constructor(message, cause) {
35
- super(message, {
36
- cause
37
- });
38
- }
39
- };
40
- var InternalError = class extends Error {
41
- static {
42
- __name(this, "InternalError");
43
- }
44
- constructor(message) {
45
- super(message);
46
- }
47
- };
48
-
49
- // src/client/query-utils.ts
50
- function getModel(schema, model) {
51
- return schema.models[model];
52
- }
53
- __name(getModel, "getModel");
54
- function requireModel(schema, model) {
55
- const matchedName = Object.keys(schema.models).find((k) => k.toLowerCase() === model.toLowerCase());
56
- if (!matchedName) {
57
- throw new QueryError(`Model "${model}" not found in schema`);
58
- }
59
- return schema.models[matchedName];
60
- }
61
- __name(requireModel, "requireModel");
62
- function getField(schema, model, field) {
63
- const modelDef = getModel(schema, model);
64
- return modelDef?.fields[field];
65
- }
66
- __name(getField, "getField");
67
- function requireField(schema, model, field) {
68
- const modelDef = requireModel(schema, model);
69
- if (!modelDef.fields[field]) {
70
- throw new QueryError(`Field "${field}" not found in model "${model}"`);
71
- }
72
- return modelDef.fields[field];
73
- }
74
- __name(requireField, "requireField");
75
- function getIdFields(schema, model) {
76
- const modelDef = requireModel(schema, model);
77
- return modelDef?.idFields;
78
- }
79
- __name(getIdFields, "getIdFields");
80
- function getRelationForeignKeyFieldPairs(schema, model, relationField) {
81
- const fieldDef = requireField(schema, model, relationField);
82
- if (!fieldDef?.relation) {
83
- throw new InternalError(`Field "${relationField}" is not a relation`);
84
- }
85
- if (fieldDef.relation.fields) {
86
- if (!fieldDef.relation.references) {
87
- throw new InternalError(`Relation references not defined for field "${relationField}"`);
88
- }
89
- return {
90
- keyPairs: fieldDef.relation.fields.map((f, i) => ({
91
- fk: f,
92
- pk: fieldDef.relation.references[i]
93
- })),
94
- ownedByModel: true
95
- };
96
- } else {
97
- if (!fieldDef.relation.opposite) {
98
- throw new InternalError(`Opposite relation not defined for field "${relationField}"`);
99
- }
100
- const oppositeField = requireField(schema, fieldDef.type, fieldDef.relation.opposite);
101
- if (!oppositeField.relation) {
102
- throw new InternalError(`Field "${fieldDef.relation.opposite}" is not a relation`);
103
- }
104
- if (!oppositeField.relation.fields) {
105
- throw new InternalError(`Relation fields not defined for field "${relationField}"`);
106
- }
107
- if (!oppositeField.relation.references) {
108
- throw new InternalError(`Relation references not defined for field "${relationField}"`);
109
- }
110
- return {
111
- keyPairs: oppositeField.relation.fields.map((f, i) => ({
112
- fk: f,
113
- pk: oppositeField.relation.references[i]
114
- })),
115
- ownedByModel: false
116
- };
117
- }
118
- }
119
- __name(getRelationForeignKeyFieldPairs, "getRelationForeignKeyFieldPairs");
120
- function isRelationField(schema, model, field) {
121
- const fieldDef = requireField(schema, model, field);
122
- return !!fieldDef.relation;
123
- }
124
- __name(isRelationField, "isRelationField");
125
- function getUniqueFields(schema, model) {
126
- const modelDef = requireModel(schema, model);
127
- const result = [];
128
- for (const [key, value] of Object.entries(modelDef.uniqueFields)) {
129
- if (typeof value !== "object") {
130
- throw new InternalError(`Invalid unique field definition for "${key}"`);
131
- }
132
- if (typeof value.type === "string") {
133
- result.push({
134
- name: key,
135
- def: requireField(schema, model, key)
136
- });
137
- } else {
138
- result.push({
139
- name: key,
140
- defs: Object.fromEntries(Object.keys(value).map((k) => [
141
- k,
142
- requireField(schema, model, k)
143
- ]))
144
- });
145
- }
146
- }
147
- return result;
148
- }
149
- __name(getUniqueFields, "getUniqueFields");
150
- function buildFieldRef(schema, model, field, options, eb, modelAlias) {
151
- const fieldDef = requireField(schema, model, field);
152
- if (!fieldDef.computed) {
153
- return eb.ref(modelAlias ? `${modelAlias}.${field}` : field);
154
- } else {
155
- let computer;
156
- if ("computedFields" in options) {
157
- const computedFields = options.computedFields;
158
- computer = computedFields?.[model]?.[field];
159
- }
160
- if (!computer) {
161
- throw new QueryError(`Computed field "${field}" implementation not provided for model "${model}"`);
162
- }
163
- return computer(eb);
164
- }
165
- }
166
- __name(buildFieldRef, "buildFieldRef");
167
- function isEnum(schema, type) {
168
- return !!schema.enums?.[type];
169
- }
170
- __name(isEnum, "isEnum");
171
- function buildJoinPairs(schema, model, modelAlias, relationField, relationModelAlias) {
172
- const { keyPairs, ownedByModel } = getRelationForeignKeyFieldPairs(schema, model, relationField);
173
- return keyPairs.map(({ fk, pk }) => {
174
- if (ownedByModel) {
175
- return [
176
- `${relationModelAlias}.${pk}`,
177
- `${modelAlias}.${fk}`
178
- ];
179
- } else {
180
- return [
181
- `${relationModelAlias}.${fk}`,
182
- `${modelAlias}.${pk}`
183
- ];
184
- }
185
- });
186
- }
187
- __name(buildJoinPairs, "buildJoinPairs");
188
- function makeDefaultOrderBy(schema, model) {
189
- const idFields = getIdFields(schema, model);
190
- return idFields.map((f) => ({
191
- [f]: "asc"
192
- }));
193
- }
194
- __name(makeDefaultOrderBy, "makeDefaultOrderBy");
195
- function getManyToManyRelation(schema, model, field) {
196
- const fieldDef = requireField(schema, model, field);
197
- if (!fieldDef.array || !fieldDef.relation?.opposite) {
198
- return void 0;
199
- }
200
- const oppositeFieldDef = requireField(schema, fieldDef.type, fieldDef.relation.opposite);
201
- if (oppositeFieldDef.array) {
202
- const sortedModelNames = [
203
- model,
204
- fieldDef.type
205
- ].sort();
206
- return {
207
- parentFkName: sortedModelNames[0] === model ? "A" : "B",
208
- otherModel: fieldDef.type,
209
- otherField: fieldDef.relation.opposite,
210
- otherFkName: sortedModelNames[0] === fieldDef.type ? "A" : "B",
211
- joinTable: fieldDef.relation.name ? `_${fieldDef.relation.name}` : `_${sortedModelNames[0]}To${sortedModelNames[1]}`
212
- };
213
- } else {
214
- return void 0;
215
- }
216
- }
217
- __name(getManyToManyRelation, "getManyToManyRelation");
218
- function flattenCompoundUniqueFilters(schema, model, filter) {
219
- if (typeof filter !== "object" || !filter) {
220
- return filter;
221
- }
222
- const uniqueFields = getUniqueFields(schema, model);
223
- const compoundUniques = uniqueFields.filter((u) => "defs" in u);
224
- if (compoundUniques.length === 0) {
225
- return filter;
226
- }
227
- const result = {};
228
- for (const [key, value] of Object.entries(filter)) {
229
- if (compoundUniques.some(({ name }) => name === key)) {
230
- Object.assign(result, value);
231
- } else {
232
- result[key] = value;
233
- }
234
- }
235
- return result;
236
- }
237
- __name(flattenCompoundUniqueFilters, "flattenCompoundUniqueFilters");
238
-
239
- // src/client/crud/dialects/base.ts
240
- import { invariant, isPlainObject } from "@zenstackhq/common-helpers";
241
- import { sql } from "kysely";
242
- import { match, P } from "ts-pattern";
243
-
244
- // src/utils/enumerate.ts
245
- function enumerate(x) {
246
- if (x === null || x === void 0) {
247
- return [];
248
- } else if (Array.isArray(x)) {
249
- return x;
250
- } else {
251
- return [
252
- x
253
- ];
254
- }
255
- }
256
- __name(enumerate, "enumerate");
257
-
258
- // src/client/crud/dialects/base.ts
259
- var BaseCrudDialect = class {
260
- static {
261
- __name(this, "BaseCrudDialect");
262
- }
263
- schema;
264
- options;
265
- constructor(schema, options) {
266
- this.schema = schema;
267
- this.options = options;
268
- }
269
- transformPrimitive(value, _type, _forArrayField) {
270
- return value;
271
- }
272
- buildFilter(eb, model, modelAlias, where) {
273
- if (where === true || where === void 0) {
274
- return this.true(eb);
275
- }
276
- if (where === false) {
277
- return this.false(eb);
278
- }
279
- let result = this.true(eb);
280
- const _where = flattenCompoundUniqueFilters(this.schema, model, where);
281
- for (const [key, payload] of Object.entries(_where)) {
282
- if (payload === void 0) {
283
- continue;
284
- }
285
- if (key.startsWith("$")) {
286
- continue;
287
- }
288
- if (key === "AND" || key === "OR" || key === "NOT") {
289
- result = this.and(eb, result, this.buildCompositeFilter(eb, model, modelAlias, key, payload));
290
- continue;
291
- }
292
- const fieldDef = requireField(this.schema, model, key);
293
- if (fieldDef.relation) {
294
- result = this.and(eb, result, this.buildRelationFilter(eb, model, modelAlias, key, fieldDef, payload));
295
- } else if (fieldDef.array) {
296
- result = this.and(eb, result, this.buildArrayFilter(eb, model, modelAlias, key, fieldDef, payload));
297
- } else {
298
- result = this.and(eb, result, this.buildPrimitiveFilter(eb, model, modelAlias, key, fieldDef, payload));
299
- }
300
- }
301
- if ("$expr" in _where && typeof _where["$expr"] === "function") {
302
- result = this.and(eb, result, _where["$expr"](eb));
303
- }
304
- return result;
305
- }
306
- buildCompositeFilter(eb, model, modelAlias, key, payload) {
307
- return match(key).with("AND", () => this.and(eb, ...enumerate(payload).map((subPayload) => this.buildFilter(eb, model, modelAlias, subPayload)))).with("OR", () => this.or(eb, ...enumerate(payload).map((subPayload) => this.buildFilter(eb, model, modelAlias, subPayload)))).with("NOT", () => eb.not(this.buildCompositeFilter(eb, model, modelAlias, "AND", payload))).exhaustive();
308
- }
309
- buildRelationFilter(eb, model, modelAlias, field, fieldDef, payload) {
310
- if (!fieldDef.array) {
311
- return this.buildToOneRelationFilter(eb, model, modelAlias, field, fieldDef, payload);
312
- } else {
313
- return this.buildToManyRelationFilter(eb, model, modelAlias, field, fieldDef, payload);
314
- }
315
- }
316
- buildToOneRelationFilter(eb, model, table, field, fieldDef, payload) {
317
- if (payload === null) {
318
- const { ownedByModel, keyPairs } = getRelationForeignKeyFieldPairs(this.schema, model, field);
319
- if (ownedByModel) {
320
- return this.and(eb, ...keyPairs.map(({ fk }) => eb(sql.ref(`${table}.${fk}`), "is", null)));
321
- } else {
322
- return this.buildToOneRelationFilter(eb, model, table, field, fieldDef, {
323
- is: null
324
- });
325
- }
326
- }
327
- const joinAlias = `${table}$${field}`;
328
- const joinPairs = buildJoinPairs(this.schema, model, table, field, joinAlias);
329
- const filterResultField = `${field}$filter`;
330
- const joinSelect = eb.selectFrom(`${fieldDef.type} as ${joinAlias}`).where(() => this.and(eb, ...joinPairs.map(([left, right]) => eb(sql.ref(left), "=", sql.ref(right))))).select(() => eb.fn.count(eb.lit(1)).as(filterResultField));
331
- const conditions = [];
332
- if ("is" in payload || "isNot" in payload) {
333
- if ("is" in payload) {
334
- if (payload.is === null) {
335
- conditions.push(eb(joinSelect, "=", 0));
336
- } else {
337
- conditions.push(eb(joinSelect.where(() => this.buildFilter(eb, fieldDef.type, joinAlias, payload.is)), ">", 0));
338
- }
339
- }
340
- if ("isNot" in payload) {
341
- if (payload.isNot === null) {
342
- conditions.push(eb(joinSelect, ">", 0));
343
- } else {
344
- conditions.push(this.or(
345
- eb,
346
- // is null
347
- eb(joinSelect, "=", 0),
348
- // found one that matches the filter
349
- eb(joinSelect.where(() => this.buildFilter(eb, fieldDef.type, joinAlias, payload.isNot)), "=", 0)
350
- ));
351
- }
352
- }
353
- } else {
354
- conditions.push(eb(joinSelect.where(() => this.buildFilter(eb, fieldDef.type, joinAlias, payload)), ">", 0));
355
- }
356
- return this.and(eb, ...conditions);
357
- }
358
- buildToManyRelationFilter(eb, model, table, field, fieldDef, payload) {
359
- if (payload === null) {
360
- return eb(sql.ref(`${table}.${field}`), "is", null);
361
- }
362
- const relationModel = fieldDef.type;
363
- const buildPkFkWhereRefs = /* @__PURE__ */ __name((eb2) => {
364
- const m2m = getManyToManyRelation(this.schema, model, field);
365
- if (m2m) {
366
- const modelIdField = getIdFields(this.schema, model)[0];
367
- const relationIdField = getIdFields(this.schema, relationModel)[0];
368
- return eb2(sql.ref(`${relationModel}.${relationIdField}`), "in", eb2.selectFrom(m2m.joinTable).select(`${m2m.joinTable}.${m2m.otherFkName}`).whereRef(sql.ref(`${m2m.joinTable}.${m2m.parentFkName}`), "=", sql.ref(`${table}.${modelIdField}`)));
369
- } else {
370
- const relationKeyPairs = getRelationForeignKeyFieldPairs(this.schema, model, field);
371
- let result2 = this.true(eb2);
372
- for (const { fk, pk } of relationKeyPairs.keyPairs) {
373
- if (relationKeyPairs.ownedByModel) {
374
- result2 = this.and(eb2, result2, eb2(sql.ref(`${table}.${fk}`), "=", sql.ref(`${relationModel}.${pk}`)));
375
- } else {
376
- result2 = this.and(eb2, result2, eb2(sql.ref(`${table}.${pk}`), "=", sql.ref(`${relationModel}.${fk}`)));
377
- }
378
- }
379
- return result2;
380
- }
381
- }, "buildPkFkWhereRefs");
382
- let result = this.true(eb);
383
- for (const [key, subPayload] of Object.entries(payload)) {
384
- if (!subPayload) {
385
- continue;
386
- }
387
- switch (key) {
388
- case "some": {
389
- result = this.and(eb, result, eb(eb.selectFrom(relationModel).select((eb1) => eb1.fn.count(eb1.lit(1)).as("count")).where(buildPkFkWhereRefs(eb)).where((eb1) => this.buildFilter(eb1, relationModel, relationModel, subPayload)), ">", 0));
390
- break;
391
- }
392
- case "every": {
393
- result = this.and(eb, result, eb(eb.selectFrom(relationModel).select((eb1) => eb1.fn.count(eb1.lit(1)).as("count")).where(buildPkFkWhereRefs(eb)).where((eb1) => eb1.not(this.buildFilter(eb1, relationModel, relationModel, subPayload))), "=", 0));
394
- break;
395
- }
396
- case "none": {
397
- result = this.and(eb, result, eb(eb.selectFrom(relationModel).select((eb1) => eb1.fn.count(eb1.lit(1)).as("count")).where(buildPkFkWhereRefs(eb)).where((eb1) => this.buildFilter(eb1, relationModel, relationModel, subPayload)), "=", 0));
398
- break;
399
- }
400
- }
401
- }
402
- return result;
403
- }
404
- buildArrayFilter(eb, model, modelAlias, field, fieldDef, payload) {
405
- const clauses = [];
406
- const fieldType = fieldDef.type;
407
- const fieldRef = buildFieldRef(this.schema, model, field, this.options, eb, modelAlias);
408
- for (const [key, _value] of Object.entries(payload)) {
409
- if (_value === void 0) {
410
- continue;
411
- }
412
- const value = this.transformPrimitive(_value, fieldType, !!fieldDef.array);
413
- switch (key) {
414
- case "equals": {
415
- clauses.push(this.buildLiteralFilter(eb, fieldRef, fieldType, eb.val(value)));
416
- break;
417
- }
418
- case "has": {
419
- clauses.push(eb(fieldRef, "@>", eb.val([
420
- value
421
- ])));
422
- break;
423
- }
424
- case "hasEvery": {
425
- clauses.push(eb(fieldRef, "@>", eb.val(value)));
426
- break;
427
- }
428
- case "hasSome": {
429
- clauses.push(eb(fieldRef, "&&", eb.val(value)));
430
- break;
431
- }
432
- case "isEmpty": {
433
- clauses.push(eb(fieldRef, value === true ? "=" : "!=", eb.val([])));
434
- break;
435
- }
436
- default: {
437
- throw new InternalError(`Invalid array filter key: ${key}`);
438
- }
439
- }
440
- }
441
- return this.and(eb, ...clauses);
442
- }
443
- buildPrimitiveFilter(eb, model, modelAlias, field, fieldDef, payload) {
444
- if (payload === null) {
445
- return eb(sql.ref(`${modelAlias}.${field}`), "is", null);
446
- }
447
- if (isEnum(this.schema, fieldDef.type)) {
448
- return this.buildEnumFilter(eb, modelAlias, field, fieldDef, payload);
449
- }
450
- return match(fieldDef.type).with("String", () => this.buildStringFilter(eb, modelAlias, field, payload)).with(P.union("Int", "Float", "Decimal", "BigInt"), (type) => this.buildNumberFilter(eb, model, modelAlias, field, type, payload)).with("Boolean", () => this.buildBooleanFilter(eb, modelAlias, field, payload)).with("DateTime", () => this.buildDateTimeFilter(eb, modelAlias, field, payload)).with("Bytes", () => this.buildBytesFilter(eb, modelAlias, field, payload)).with("Json", () => {
451
- throw new InternalError("JSON filters are not supported yet");
452
- }).with("Unsupported", () => {
453
- throw new QueryError(`Unsupported field cannot be used in filters`);
454
- }).exhaustive();
455
- }
456
- buildLiteralFilter(eb, lhs, type, rhs) {
457
- return eb(lhs, "=", rhs !== null && rhs !== void 0 ? this.transformPrimitive(rhs, type, false) : rhs);
458
- }
459
- buildStandardFilter(eb, type, payload, lhs, getRhs, recurse, throwIfInvalid = false, onlyForKeys = void 0) {
460
- if (payload === null || !isPlainObject(payload)) {
461
- return {
462
- conditions: [
463
- this.buildLiteralFilter(eb, lhs, type, payload)
464
- ],
465
- consumedKeys: []
466
- };
467
- }
468
- const conditions = [];
469
- const consumedKeys = [];
470
- for (const [op, value] of Object.entries(payload)) {
471
- if (onlyForKeys && !onlyForKeys.includes(op)) {
472
- continue;
473
- }
474
- const rhs = Array.isArray(value) ? value.map(getRhs) : getRhs(value);
475
- const condition = match(op).with("equals", () => rhs === null ? eb(lhs, "is", null) : eb(lhs, "=", rhs)).with("in", () => {
476
- invariant(Array.isArray(rhs), "right hand side must be an array");
477
- if (rhs.length === 0) {
478
- return this.false(eb);
479
- } else {
480
- return eb(lhs, "in", rhs);
481
- }
482
- }).with("notIn", () => {
483
- invariant(Array.isArray(rhs), "right hand side must be an array");
484
- if (rhs.length === 0) {
485
- return this.true(eb);
486
- } else {
487
- return eb.not(eb(lhs, "in", rhs));
488
- }
489
- }).with("lt", () => eb(lhs, "<", rhs)).with("lte", () => eb(lhs, "<=", rhs)).with("gt", () => eb(lhs, ">", rhs)).with("gte", () => eb(lhs, ">=", rhs)).with("not", () => eb.not(recurse(value))).otherwise(() => {
490
- if (throwIfInvalid) {
491
- throw new QueryError(`Invalid filter key: ${op}`);
492
- } else {
493
- return void 0;
494
- }
495
- });
496
- if (condition) {
497
- conditions.push(condition);
498
- consumedKeys.push(op);
499
- }
500
- }
501
- return {
502
- conditions,
503
- consumedKeys
504
- };
505
- }
506
- buildStringFilter(eb, table, field, payload) {
507
- const fieldDef = getField(this.schema, table, field);
508
- let fieldRef = fieldDef?.computed ? sql.ref(field) : sql.ref(`${table}.${field}`);
509
- let insensitive = false;
510
- if (payload && typeof payload === "object" && "mode" in payload && payload.mode === "insensitive") {
511
- insensitive = true;
512
- fieldRef = eb.fn("lower", [
513
- fieldRef
514
- ]);
515
- }
516
- const { conditions, consumedKeys } = this.buildStandardFilter(eb, "String", payload, fieldRef, (value) => this.prepStringCasing(eb, value, insensitive), (value) => this.buildStringFilter(eb, table, field, value));
517
- if (payload && typeof payload === "object") {
518
- for (const [key, value] of Object.entries(payload)) {
519
- if (key === "mode" || consumedKeys.includes(key)) {
520
- continue;
521
- }
522
- const condition = match(key).with("contains", () => insensitive ? eb(fieldRef, "ilike", sql.lit(`%${value}%`)) : eb(fieldRef, "like", sql.lit(`%${value}%`))).with("startsWith", () => insensitive ? eb(fieldRef, "ilike", sql.lit(`${value}%`)) : eb(fieldRef, "like", sql.lit(`${value}%`))).with("endsWith", () => insensitive ? eb(fieldRef, "ilike", sql.lit(`%${value}`)) : eb(fieldRef, "like", sql.lit(`%${value}`))).otherwise(() => {
523
- throw new Error(`Invalid string filter key: ${key}`);
524
- });
525
- if (condition) {
526
- conditions.push(condition);
527
- }
528
- }
529
- }
530
- return this.and(eb, ...conditions);
531
- }
532
- prepStringCasing(eb, value, toLower = true) {
533
- if (typeof value === "string") {
534
- return toLower ? eb.fn("lower", [
535
- sql.lit(value)
536
- ]) : sql.lit(value);
537
- } else if (Array.isArray(value)) {
538
- return value.map((v) => this.prepStringCasing(eb, v, toLower));
539
- } else {
540
- return value === null ? null : sql.lit(value);
541
- }
542
- }
543
- buildNumberFilter(eb, model, table, field, type, payload) {
544
- const { conditions } = this.buildStandardFilter(eb, type, payload, buildFieldRef(this.schema, model, field, this.options, eb), (value) => this.transformPrimitive(value, type, false), (value) => this.buildNumberFilter(eb, model, table, field, type, value));
545
- return this.and(eb, ...conditions);
546
- }
547
- buildBooleanFilter(eb, table, field, payload) {
548
- const { conditions } = this.buildStandardFilter(eb, "Boolean", payload, sql.ref(`${table}.${field}`), (value) => this.transformPrimitive(value, "Boolean", false), (value) => this.buildBooleanFilter(eb, table, field, value), true, [
549
- "equals",
550
- "not"
551
- ]);
552
- return this.and(eb, ...conditions);
553
- }
554
- buildDateTimeFilter(eb, table, field, payload) {
555
- const { conditions } = this.buildStandardFilter(eb, "DateTime", payload, sql.ref(`${table}.${field}`), (value) => this.transformPrimitive(value, "DateTime", false), (value) => this.buildDateTimeFilter(eb, table, field, value), true);
556
- return this.and(eb, ...conditions);
557
- }
558
- buildBytesFilter(eb, table, field, payload) {
559
- const conditions = this.buildStandardFilter(eb, "Bytes", payload, sql.ref(`${table}.${field}`), (value) => this.transformPrimitive(value, "Bytes", false), (value) => this.buildBytesFilter(eb, table, field, value), true, [
560
- "equals",
561
- "in",
562
- "notIn",
563
- "not"
564
- ]);
565
- return this.and(eb, ...conditions.conditions);
566
- }
567
- buildEnumFilter(eb, table, field, fieldDef, payload) {
568
- const conditions = this.buildStandardFilter(eb, "String", payload, sql.ref(`${table}.${field}`), (value) => value, (value) => this.buildEnumFilter(eb, table, field, fieldDef, value), true, [
569
- "equals",
570
- "in",
571
- "notIn",
572
- "not"
573
- ]);
574
- return this.and(eb, ...conditions.conditions);
575
- }
576
- buildOrderBy(query, model, modelAlias, orderBy, useDefaultIfEmpty, negated) {
577
- if (!orderBy) {
578
- if (useDefaultIfEmpty) {
579
- orderBy = makeDefaultOrderBy(this.schema, model);
580
- } else {
581
- return query;
582
- }
583
- }
584
- let result = query;
585
- enumerate(orderBy).forEach((orderBy2) => {
586
- for (const [field, value] of Object.entries(orderBy2)) {
587
- if (!value) {
588
- continue;
589
- }
590
- if ([
591
- "_count",
592
- "_avg",
593
- "_sum",
594
- "_min",
595
- "_max"
596
- ].includes(field)) {
597
- invariant(value && typeof value === "object", `invalid orderBy value for field "${field}"`);
598
- for (const [k, v] of Object.entries(value)) {
599
- invariant(v === "asc" || v === "desc", `invalid orderBy value for field "${field}"`);
600
- result = result.orderBy((eb) => eb.fn(field.slice(1), [
601
- sql.ref(k)
602
- ]), sql.raw(this.negateSort(v, negated)));
603
- }
604
- continue;
605
- }
606
- switch (field) {
607
- case "_count": {
608
- invariant(value && typeof value === "object", 'invalid orderBy value for field "_count"');
609
- for (const [k, v] of Object.entries(value)) {
610
- invariant(v === "asc" || v === "desc", `invalid orderBy value for field "${field}"`);
611
- result = result.orderBy((eb) => eb.fn.count(sql.ref(k)), sql.raw(this.negateSort(v, negated)));
612
- }
613
- continue;
614
- }
615
- default:
616
- break;
617
- }
618
- const fieldDef = requireField(this.schema, model, field);
619
- if (!fieldDef.relation) {
620
- if (value === "asc" || value === "desc") {
621
- result = result.orderBy(sql.ref(`${modelAlias}.${field}`), this.negateSort(value, negated));
622
- } else if (value && typeof value === "object" && "nulls" in value && "sort" in value && (value.sort === "asc" || value.sort === "desc") && (value.nulls === "first" || value.nulls === "last")) {
623
- result = result.orderBy(sql.ref(`${modelAlias}.${field}`), sql.raw(`${this.negateSort(value.sort, negated)} nulls ${value.nulls}`));
624
- }
625
- } else {
626
- const relationModel = fieldDef.type;
627
- if (fieldDef.array) {
628
- if (typeof value !== "object") {
629
- throw new QueryError(`invalid orderBy value for field "${field}"`);
630
- }
631
- if ("_count" in value) {
632
- invariant(value._count === "asc" || value._count === "desc", 'invalid orderBy value for field "_count"');
633
- const sort = this.negateSort(value._count, negated);
634
- result = result.orderBy((eb) => {
635
- let subQuery = eb.selectFrom(relationModel);
636
- const joinPairs = buildJoinPairs(this.schema, model, modelAlias, field, relationModel);
637
- subQuery = subQuery.where(() => this.and(eb, ...joinPairs.map(([left, right]) => eb(sql.ref(left), "=", sql.ref(right)))));
638
- subQuery = subQuery.select(() => eb.fn.count(eb.lit(1)).as("_count"));
639
- return subQuery;
640
- }, sort);
641
- }
642
- } else {
643
- result = result.leftJoin(relationModel, (join) => {
644
- const joinPairs = buildJoinPairs(this.schema, model, modelAlias, field, relationModel);
645
- return join.on((eb) => this.and(eb, ...joinPairs.map(([left, right]) => eb(sql.ref(left), "=", sql.ref(right)))));
646
- });
647
- result = this.buildOrderBy(result, fieldDef.type, relationModel, value, false, negated);
648
- }
649
- }
650
- }
651
- });
652
- return result;
653
- }
654
- negateSort(sort, negated) {
655
- return negated ? sort === "asc" ? "desc" : "asc" : sort;
656
- }
657
- true(eb) {
658
- return eb.lit(this.transformPrimitive(true, "Boolean", false));
659
- }
660
- false(eb) {
661
- return eb.lit(this.transformPrimitive(false, "Boolean", false));
662
- }
663
- isTrue(expression) {
664
- const node = expression.toOperationNode();
665
- if (node.kind !== "ValueNode") {
666
- return false;
667
- }
668
- return node.value === true || node.value === 1;
669
- }
670
- isFalse(expression) {
671
- const node = expression.toOperationNode();
672
- if (node.kind !== "ValueNode") {
673
- return false;
674
- }
675
- return node.value === false || node.value === 0;
676
- }
677
- and(eb, ...args) {
678
- const nonTrueArgs = args.filter((arg) => !this.isTrue(arg));
679
- if (nonTrueArgs.length === 0) {
680
- return this.true(eb);
681
- } else if (nonTrueArgs.length === 1) {
682
- return nonTrueArgs[0];
683
- } else {
684
- return eb.and(nonTrueArgs);
685
- }
686
- }
687
- or(eb, ...args) {
688
- const nonFalseArgs = args.filter((arg) => !this.isFalse(arg));
689
- if (nonFalseArgs.length === 0) {
690
- return this.false(eb);
691
- } else if (nonFalseArgs.length === 1) {
692
- return nonFalseArgs[0];
693
- } else {
694
- return eb.or(nonFalseArgs);
695
- }
696
- }
697
- not(eb, ...args) {
698
- return eb.not(this.and(eb, ...args));
699
- }
700
- };
701
-
702
- // src/client/crud/dialects/postgresql.ts
703
- var PostgresCrudDialect = class extends BaseCrudDialect {
704
- static {
705
- __name(this, "PostgresCrudDialect");
706
- }
707
- get provider() {
708
- return "postgresql";
709
- }
710
- transformPrimitive(value, type, forArrayField) {
711
- if (value === void 0) {
712
- return value;
713
- }
714
- if (Array.isArray(value)) {
715
- if (type === "Json" && !forArrayField) {
716
- return JSON.stringify(value);
717
- } else {
718
- return value.map((v) => this.transformPrimitive(v, type, false));
719
- }
720
- } else {
721
- return match2(type).with("DateTime", () => value instanceof Date ? value : typeof value === "string" ? new Date(value) : value).with("Decimal", () => value !== null ? value.toString() : value).otherwise(() => value);
722
- }
723
- }
724
- buildRelationSelection(query, model, relationField, parentAlias, payload) {
725
- const joinedQuery = this.buildRelationJSON(model, query, relationField, parentAlias, payload);
726
- return joinedQuery.select(`${parentAlias}$${relationField}.$j as ${relationField}`);
727
- }
728
- buildRelationJSON(model, qb, relationField, parentName, payload) {
729
- const relationFieldDef = requireField(this.schema, model, relationField);
730
- const relationModel = relationFieldDef.type;
731
- return qb.leftJoinLateral((eb) => {
732
- const joinTableName = `${parentName}$${relationField}`;
733
- let result = eb.selectFrom(`${relationModel} as ${joinTableName}`);
734
- result = eb.selectFrom(() => {
735
- let subQuery = eb.selectFrom(`${relationModel}`).selectAll();
736
- if (payload && typeof payload === "object") {
737
- if (payload.where) {
738
- subQuery = subQuery.where((eb2) => this.buildFilter(eb2, relationModel, relationModel, payload.where));
739
- }
740
- const skip = payload.skip;
741
- let take = payload.take;
742
- let negateOrderBy = false;
743
- if (take !== void 0 && take < 0) {
744
- negateOrderBy = true;
745
- take = -take;
746
- }
747
- subQuery = this.buildSkipTake(subQuery, skip, take);
748
- subQuery = this.buildOrderBy(subQuery, relationModel, relationModel, payload.orderBy, skip !== void 0 || take !== void 0, negateOrderBy);
749
- }
750
- const m2m = getManyToManyRelation(this.schema, model, relationField);
751
- if (m2m) {
752
- const parentIds = getIdFields(this.schema, model);
753
- const relationIds = getIdFields(this.schema, relationModel);
754
- invariant2(parentIds.length === 1, "many-to-many relation must have exactly one id field");
755
- invariant2(relationIds.length === 1, "many-to-many relation must have exactly one id field");
756
- subQuery = subQuery.where(eb(eb.ref(`${relationModel}.${relationIds[0]}`), "in", eb.selectFrom(m2m.joinTable).select(`${m2m.joinTable}.${m2m.otherFkName}`).whereRef(`${parentName}.${parentIds[0]}`, "=", `${m2m.joinTable}.${m2m.parentFkName}`)));
757
- } else {
758
- const joinPairs = buildJoinPairs(this.schema, model, parentName, relationField, relationModel);
759
- subQuery = subQuery.where((eb2) => this.and(eb2, ...joinPairs.map(([left, right]) => eb2(sql2.ref(left), "=", sql2.ref(right)))));
760
- }
761
- return subQuery.as(joinTableName);
762
- });
763
- result = this.buildRelationObjectSelect(relationModel, relationField, relationFieldDef, result, payload, parentName);
764
- result = this.buildRelationJoins(relationModel, relationField, result, payload, parentName);
765
- return result.as(joinTableName);
766
- }, (join) => join.onTrue());
767
- }
768
- buildRelationObjectSelect(relationModel, relationField, relationFieldDef, qb, payload, parentName) {
769
- qb = qb.select((eb) => {
770
- const objArgs = this.buildRelationObjectArgs(relationModel, relationField, eb, payload, parentName);
771
- if (relationFieldDef.array) {
772
- return eb.fn.coalesce(sql2`jsonb_agg(jsonb_build_object(${sql2.join(objArgs)}))`, sql2`'[]'::jsonb`).as("$j");
773
- } else {
774
- return sql2`jsonb_build_object(${sql2.join(objArgs)})`.as("$j");
775
- }
776
- });
777
- return qb;
778
- }
779
- buildRelationObjectArgs(relationModel, relationField, eb, payload, parentName) {
780
- const relationModelDef = requireModel(this.schema, relationModel);
781
- const objArgs = [];
782
- if (payload === true || !payload.select) {
783
- objArgs.push(...Object.entries(relationModelDef.fields).filter(([, value]) => !value.relation).filter(([name]) => !(typeof payload === "object" && payload.omit?.[name] === true)).map(([field]) => [
784
- sql2.lit(field),
785
- buildFieldRef(this.schema, relationModel, field, this.options, eb)
786
- ]).flatMap((v) => v));
787
- } else if (payload.select) {
788
- objArgs.push(...Object.entries(payload.select).filter(([, value]) => value).map(([field]) => {
789
- const fieldDef = requireField(this.schema, relationModel, field);
790
- const fieldValue = fieldDef.relation ? eb.ref(`${parentName}$${relationField}$${field}.$j`) : buildFieldRef(this.schema, relationModel, field, this.options, eb);
791
- return [
792
- sql2.lit(field),
793
- fieldValue
794
- ];
795
- }).flatMap((v) => v));
796
- }
797
- if (typeof payload === "object" && payload.include && typeof payload.include === "object") {
798
- objArgs.push(...Object.entries(payload.include).filter(([, value]) => value).map(([field]) => [
799
- sql2.lit(field),
800
- // reference the synthesized JSON field
801
- eb.ref(`${parentName}$${relationField}$${field}.$j`)
802
- ]).flatMap((v) => v));
803
- }
804
- return objArgs;
805
- }
806
- buildRelationJoins(relationModel, relationField, qb, payload, parentName) {
807
- let result = qb;
808
- if (typeof payload === "object") {
809
- const selectInclude = payload.include ?? payload.select;
810
- if (selectInclude && typeof selectInclude === "object") {
811
- Object.entries(selectInclude).filter(([, value]) => value).filter(([field]) => isRelationField(this.schema, relationModel, field)).forEach(([field, value]) => {
812
- result = this.buildRelationJSON(relationModel, result, field, `${parentName}$${relationField}`, value);
813
- });
814
- }
815
- }
816
- return result;
817
- }
818
- buildSkipTake(query, skip, take) {
819
- if (take !== void 0) {
820
- query = query.limit(take);
821
- }
822
- if (skip !== void 0) {
823
- query = query.offset(skip);
824
- }
825
- return query;
826
- }
827
- buildJsonObject(eb, value) {
828
- return eb.fn("jsonb_build_object", Object.entries(value).flatMap(([key, value2]) => [
829
- sql2.lit(key),
830
- value2
831
- ]));
832
- }
833
- get supportsUpdateWithLimit() {
834
- return false;
835
- }
836
- get supportsDeleteWithLimit() {
837
- return false;
838
- }
839
- get supportsDistinctOn() {
840
- return true;
841
- }
842
- buildArrayLength(eb, array) {
843
- return eb.fn("array_length", [
844
- array
845
- ]);
846
- }
847
- buildArrayLiteralSQL(values) {
848
- if (values.length === 0) {
849
- return "{}";
850
- } else {
851
- return `ARRAY[${values.map((v) => typeof v === "string" ? `'${v}'` : v)}]`;
852
- }
853
- }
854
- };
855
-
856
- // src/client/crud/dialects/sqlite.ts
857
- import { invariant as invariant3 } from "@zenstackhq/common-helpers";
858
- import { sql as sql3 } from "kysely";
859
- import { match as match3 } from "ts-pattern";
860
- var SqliteCrudDialect = class extends BaseCrudDialect {
861
- static {
862
- __name(this, "SqliteCrudDialect");
863
- }
864
- get provider() {
865
- return "sqlite";
866
- }
867
- transformPrimitive(value, type, _forArrayField) {
868
- if (value === void 0) {
869
- return value;
870
- }
871
- if (Array.isArray(value)) {
872
- return value.map((v) => this.transformPrimitive(v, type, false));
873
- } else {
874
- return match3(type).with("Boolean", () => value ? 1 : 0).with("DateTime", () => value instanceof Date ? value.toISOString() : value).with("Decimal", () => value.toString()).with("Bytes", () => Buffer.from(value)).with("Json", () => JSON.stringify(value)).otherwise(() => value);
875
- }
876
- }
877
- buildRelationSelection(query, model, relationField, parentAlias, payload) {
878
- return query.select((eb) => this.buildRelationJSON(model, eb, relationField, parentAlias, payload).as(relationField));
879
- }
880
- buildRelationJSON(model, eb, relationField, parentName, payload) {
881
- const relationFieldDef = requireField(this.schema, model, relationField);
882
- const relationModel = relationFieldDef.type;
883
- const relationModelDef = requireModel(this.schema, relationModel);
884
- const subQueryName = `${parentName}$${relationField}`;
885
- let tbl = eb.selectFrom(() => {
886
- let subQuery = eb.selectFrom(relationModel).selectAll();
887
- if (payload && typeof payload === "object") {
888
- if (payload.where) {
889
- subQuery = subQuery.where((eb2) => this.buildFilter(eb2, relationModel, relationModel, payload.where));
890
- }
891
- const skip = payload.skip;
892
- let take = payload.take;
893
- let negateOrderBy = false;
894
- if (take !== void 0 && take < 0) {
895
- negateOrderBy = true;
896
- take = -take;
897
- }
898
- subQuery = this.buildSkipTake(subQuery, skip, take);
899
- subQuery = this.buildOrderBy(subQuery, relationModel, relationModel, payload.orderBy, skip !== void 0 || take !== void 0, negateOrderBy);
900
- }
901
- const m2m = getManyToManyRelation(this.schema, model, relationField);
902
- if (m2m) {
903
- const parentIds = getIdFields(this.schema, model);
904
- const relationIds = getIdFields(this.schema, relationModel);
905
- invariant3(parentIds.length === 1, "many-to-many relation must have exactly one id field");
906
- invariant3(relationIds.length === 1, "many-to-many relation must have exactly one id field");
907
- subQuery = subQuery.where(eb(eb.ref(`${relationModel}.${relationIds[0]}`), "in", eb.selectFrom(m2m.joinTable).select(`${m2m.joinTable}.${m2m.otherFkName}`).whereRef(`${parentName}.${parentIds[0]}`, "=", `${m2m.joinTable}.${m2m.parentFkName}`)));
908
- } else {
909
- const { keyPairs, ownedByModel } = getRelationForeignKeyFieldPairs(this.schema, model, relationField);
910
- keyPairs.forEach(({ fk, pk }) => {
911
- if (ownedByModel) {
912
- subQuery = subQuery.whereRef(`${relationModel}.${pk}`, "=", `${parentName}.${fk}`);
913
- } else {
914
- subQuery = subQuery.whereRef(`${relationModel}.${fk}`, "=", `${parentName}.${pk}`);
915
- }
916
- });
917
- }
918
- return subQuery.as(subQueryName);
919
- });
920
- tbl = tbl.select(() => {
921
- const objArgs = [];
922
- if (payload === true || !payload.select) {
923
- objArgs.push(...Object.entries(relationModelDef.fields).filter(([, value]) => !value.relation).filter(([name]) => !(typeof payload === "object" && payload.omit?.[name] === true)).map(([field]) => [
924
- sql3.lit(field),
925
- buildFieldRef(this.schema, relationModel, field, this.options, eb)
926
- ]).flatMap((v) => v));
927
- } else if (payload.select) {
928
- objArgs.push(...Object.entries(payload.select).filter(([, value]) => value).map(([field, value]) => {
929
- const fieldDef = requireField(this.schema, relationModel, field);
930
- if (fieldDef.relation) {
931
- const subJson = this.buildRelationJSON(relationModel, eb, field, `${parentName}$${relationField}`, value);
932
- return [
933
- sql3.lit(field),
934
- subJson
935
- ];
936
- } else {
937
- return [
938
- sql3.lit(field),
939
- buildFieldRef(this.schema, relationModel, field, this.options, eb)
940
- ];
941
- }
942
- }).flatMap((v) => v));
943
- }
944
- if (typeof payload === "object" && payload.include && typeof payload.include === "object") {
945
- objArgs.push(...Object.entries(payload.include).filter(([, value]) => value).map(([field, value]) => {
946
- const subJson = this.buildRelationJSON(relationModel, eb, field, `${parentName}$${relationField}`, value);
947
- return [
948
- sql3.lit(field),
949
- subJson
950
- ];
951
- }).flatMap((v) => v));
952
- }
953
- if (relationFieldDef.array) {
954
- return eb.fn.coalesce(sql3`json_group_array(json_object(${sql3.join(objArgs)}))`, sql3`json_array()`).as("$j");
955
- } else {
956
- return sql3`json_object(${sql3.join(objArgs)})`.as("data");
957
- }
958
- });
959
- return tbl;
960
- }
961
- buildSkipTake(query, skip, take) {
962
- if (take !== void 0) {
963
- query = query.limit(take);
964
- }
965
- if (skip !== void 0) {
966
- query = query.offset(skip);
967
- if (take === void 0) {
968
- query = query.limit(-1);
969
- }
970
- }
971
- return query;
972
- }
973
- buildJsonObject(eb, value) {
974
- return eb.fn("json_object", Object.entries(value).flatMap(([key, value2]) => [
975
- sql3.lit(key),
976
- value2
977
- ]));
978
- }
979
- get supportsUpdateWithLimit() {
980
- return false;
981
- }
982
- get supportsDeleteWithLimit() {
983
- return false;
984
- }
985
- get supportsDistinctOn() {
986
- return false;
987
- }
988
- buildArrayLength(eb, array) {
989
- return eb.fn("json_array_length", [
990
- array
991
- ]);
992
- }
993
- buildArrayLiteralSQL(_values) {
994
- throw new Error("SQLite does not support array literals");
995
- }
996
- };
997
-
998
- // src/client/crud/dialects/index.ts
999
- function getCrudDialect(schema, options) {
1000
- return match4(schema.provider.type).with("sqlite", () => new SqliteCrudDialect(schema, options)).with("postgresql", () => new PostgresCrudDialect(schema, options)).exhaustive();
1001
- }
1002
- __name(getCrudDialect, "getCrudDialect");
1003
-
1004
- // src/schema/expression.ts
1005
- var ExpressionUtils = {
1006
- literal: /* @__PURE__ */ __name((value) => {
1007
- return {
1008
- kind: "literal",
1009
- value
1010
- };
1011
- }, "literal"),
1012
- array: /* @__PURE__ */ __name((items) => {
1013
- return {
1014
- kind: "array",
1015
- items
1016
- };
1017
- }, "array"),
1018
- call: /* @__PURE__ */ __name((functionName, args) => {
1019
- return {
1020
- kind: "call",
1021
- function: functionName,
1022
- args
1023
- };
1024
- }, "call"),
1025
- binary: /* @__PURE__ */ __name((left, op, right) => {
1026
- return {
1027
- kind: "binary",
1028
- op,
1029
- left,
1030
- right
1031
- };
1032
- }, "binary"),
1033
- unary: /* @__PURE__ */ __name((op, operand) => {
1034
- return {
1035
- kind: "unary",
1036
- op,
1037
- operand
1038
- };
1039
- }, "unary"),
1040
- field: /* @__PURE__ */ __name((field) => {
1041
- return {
1042
- kind: "field",
1043
- field
1044
- };
1045
- }, "field"),
1046
- member: /* @__PURE__ */ __name((receiver, members) => {
1047
- return {
1048
- kind: "member",
1049
- receiver,
1050
- members
1051
- };
1052
- }, "member"),
1053
- _this: /* @__PURE__ */ __name(() => {
1054
- return {
1055
- kind: "this"
1056
- };
1057
- }, "_this"),
1058
- _null: /* @__PURE__ */ __name(() => {
1059
- return {
1060
- kind: "null"
1061
- };
1062
- }, "_null"),
1063
- and: /* @__PURE__ */ __name((expr2, ...expressions) => {
1064
- return expressions.reduce((acc, exp) => ExpressionUtils.binary(acc, "&&", exp), expr2);
1065
- }, "and"),
1066
- or: /* @__PURE__ */ __name((expr2, ...expressions) => {
1067
- return expressions.reduce((acc, exp) => ExpressionUtils.binary(acc, "||", exp), expr2);
1068
- }, "or"),
1069
- is: /* @__PURE__ */ __name((value, kind) => {
1070
- return !!value && typeof value === "object" && "kind" in value && value.kind === kind;
1071
- }, "is"),
1072
- isLiteral: /* @__PURE__ */ __name((value) => ExpressionUtils.is(value, "literal"), "isLiteral"),
1073
- isArray: /* @__PURE__ */ __name((value) => ExpressionUtils.is(value, "array"), "isArray"),
1074
- isCall: /* @__PURE__ */ __name((value) => ExpressionUtils.is(value, "call"), "isCall"),
1075
- isNull: /* @__PURE__ */ __name((value) => ExpressionUtils.is(value, "null"), "isNull"),
1076
- isThis: /* @__PURE__ */ __name((value) => ExpressionUtils.is(value, "this"), "isThis"),
1077
- isUnary: /* @__PURE__ */ __name((value) => ExpressionUtils.is(value, "unary"), "isUnary"),
1078
- isBinary: /* @__PURE__ */ __name((value) => ExpressionUtils.is(value, "binary"), "isBinary"),
1079
- isField: /* @__PURE__ */ __name((value) => ExpressionUtils.is(value, "field"), "isField"),
1080
- isMember: /* @__PURE__ */ __name((value) => ExpressionUtils.is(value, "member"), "isMember")
1081
- };
1082
-
1083
- // src/utils/default-operation-node-visitor.ts
1084
- import { OperationNodeVisitor } from "kysely";
1085
- var DefaultOperationNodeVisitor = class extends OperationNodeVisitor {
1086
- static {
1087
- __name(this, "DefaultOperationNodeVisitor");
1088
- }
1089
- defaultVisit(node) {
1090
- Object.values(node).forEach((value) => {
1091
- if (!value) {
1092
- return;
1093
- }
1094
- if (Array.isArray(value)) {
1095
- value.forEach((el) => this.defaultVisit(el));
1096
- }
1097
- if (typeof value === "object" && "kind" in value && typeof value.kind === "string") {
1098
- this.visitNode(value);
1099
- }
1100
- });
1101
- }
1102
- visitSelectQuery(node) {
1103
- this.defaultVisit(node);
1104
- }
1105
- visitSelection(node) {
1106
- this.defaultVisit(node);
1107
- }
1108
- visitColumn(node) {
1109
- this.defaultVisit(node);
1110
- }
1111
- visitAlias(node) {
1112
- this.defaultVisit(node);
1113
- }
1114
- visitTable(node) {
1115
- this.defaultVisit(node);
1116
- }
1117
- visitFrom(node) {
1118
- this.defaultVisit(node);
1119
- }
1120
- visitReference(node) {
1121
- this.defaultVisit(node);
1122
- }
1123
- visitAnd(node) {
1124
- this.defaultVisit(node);
1125
- }
1126
- visitOr(node) {
1127
- this.defaultVisit(node);
1128
- }
1129
- visitValueList(node) {
1130
- this.defaultVisit(node);
1131
- }
1132
- visitParens(node) {
1133
- this.defaultVisit(node);
1134
- }
1135
- visitJoin(node) {
1136
- this.defaultVisit(node);
1137
- }
1138
- visitRaw(node) {
1139
- this.defaultVisit(node);
1140
- }
1141
- visitWhere(node) {
1142
- this.defaultVisit(node);
1143
- }
1144
- visitInsertQuery(node) {
1145
- this.defaultVisit(node);
1146
- }
1147
- visitDeleteQuery(node) {
1148
- this.defaultVisit(node);
1149
- }
1150
- visitReturning(node) {
1151
- this.defaultVisit(node);
1152
- }
1153
- visitCreateTable(node) {
1154
- this.defaultVisit(node);
1155
- }
1156
- visitAddColumn(node) {
1157
- this.defaultVisit(node);
1158
- }
1159
- visitColumnDefinition(node) {
1160
- this.defaultVisit(node);
1161
- }
1162
- visitDropTable(node) {
1163
- this.defaultVisit(node);
1164
- }
1165
- visitOrderBy(node) {
1166
- this.defaultVisit(node);
1167
- }
1168
- visitOrderByItem(node) {
1169
- this.defaultVisit(node);
1170
- }
1171
- visitGroupBy(node) {
1172
- this.defaultVisit(node);
1173
- }
1174
- visitGroupByItem(node) {
1175
- this.defaultVisit(node);
1176
- }
1177
- visitUpdateQuery(node) {
1178
- this.defaultVisit(node);
1179
- }
1180
- visitColumnUpdate(node) {
1181
- this.defaultVisit(node);
1182
- }
1183
- visitLimit(node) {
1184
- this.defaultVisit(node);
1185
- }
1186
- visitOffset(node) {
1187
- this.defaultVisit(node);
1188
- }
1189
- visitOnConflict(node) {
1190
- this.defaultVisit(node);
1191
- }
1192
- visitOnDuplicateKey(node) {
1193
- this.defaultVisit(node);
1194
- }
1195
- visitCheckConstraint(node) {
1196
- this.defaultVisit(node);
1197
- }
1198
- visitDataType(node) {
1199
- this.defaultVisit(node);
1200
- }
1201
- visitSelectAll(node) {
1202
- this.defaultVisit(node);
1203
- }
1204
- visitIdentifier(node) {
1205
- this.defaultVisit(node);
1206
- }
1207
- visitSchemableIdentifier(node) {
1208
- this.defaultVisit(node);
1209
- }
1210
- visitValue(node) {
1211
- this.defaultVisit(node);
1212
- }
1213
- visitPrimitiveValueList(node) {
1214
- this.defaultVisit(node);
1215
- }
1216
- visitOperator(node) {
1217
- this.defaultVisit(node);
1218
- }
1219
- visitCreateIndex(node) {
1220
- this.defaultVisit(node);
1221
- }
1222
- visitDropIndex(node) {
1223
- this.defaultVisit(node);
1224
- }
1225
- visitList(node) {
1226
- this.defaultVisit(node);
1227
- }
1228
- visitPrimaryKeyConstraint(node) {
1229
- this.defaultVisit(node);
1230
- }
1231
- visitUniqueConstraint(node) {
1232
- this.defaultVisit(node);
1233
- }
1234
- visitReferences(node) {
1235
- this.defaultVisit(node);
1236
- }
1237
- visitWith(node) {
1238
- this.defaultVisit(node);
1239
- }
1240
- visitCommonTableExpression(node) {
1241
- this.defaultVisit(node);
1242
- }
1243
- visitCommonTableExpressionName(node) {
1244
- this.defaultVisit(node);
1245
- }
1246
- visitHaving(node) {
1247
- this.defaultVisit(node);
1248
- }
1249
- visitCreateSchema(node) {
1250
- this.defaultVisit(node);
1251
- }
1252
- visitDropSchema(node) {
1253
- this.defaultVisit(node);
1254
- }
1255
- visitAlterTable(node) {
1256
- this.defaultVisit(node);
1257
- }
1258
- visitDropColumn(node) {
1259
- this.defaultVisit(node);
1260
- }
1261
- visitRenameColumn(node) {
1262
- this.defaultVisit(node);
1263
- }
1264
- visitAlterColumn(node) {
1265
- this.defaultVisit(node);
1266
- }
1267
- visitModifyColumn(node) {
1268
- this.defaultVisit(node);
1269
- }
1270
- visitAddConstraint(node) {
1271
- this.defaultVisit(node);
1272
- }
1273
- visitDropConstraint(node) {
1274
- this.defaultVisit(node);
1275
- }
1276
- visitForeignKeyConstraint(node) {
1277
- this.defaultVisit(node);
1278
- }
1279
- visitCreateView(node) {
1280
- this.defaultVisit(node);
1281
- }
1282
- visitDropView(node) {
1283
- this.defaultVisit(node);
1284
- }
1285
- visitGenerated(node) {
1286
- this.defaultVisit(node);
1287
- }
1288
- visitDefaultValue(node) {
1289
- this.defaultVisit(node);
1290
- }
1291
- visitOn(node) {
1292
- this.defaultVisit(node);
1293
- }
1294
- visitValues(node) {
1295
- this.defaultVisit(node);
1296
- }
1297
- visitSelectModifier(node) {
1298
- this.defaultVisit(node);
1299
- }
1300
- visitCreateType(node) {
1301
- this.defaultVisit(node);
1302
- }
1303
- visitDropType(node) {
1304
- this.defaultVisit(node);
1305
- }
1306
- visitExplain(node) {
1307
- this.defaultVisit(node);
1308
- }
1309
- visitDefaultInsertValue(node) {
1310
- this.defaultVisit(node);
1311
- }
1312
- visitAggregateFunction(node) {
1313
- this.defaultVisit(node);
1314
- }
1315
- visitOver(node) {
1316
- this.defaultVisit(node);
1317
- }
1318
- visitPartitionBy(node) {
1319
- this.defaultVisit(node);
1320
- }
1321
- visitPartitionByItem(node) {
1322
- this.defaultVisit(node);
1323
- }
1324
- visitSetOperation(node) {
1325
- this.defaultVisit(node);
1326
- }
1327
- visitBinaryOperation(node) {
1328
- this.defaultVisit(node);
1329
- }
1330
- visitUnaryOperation(node) {
1331
- this.defaultVisit(node);
1332
- }
1333
- visitUsing(node) {
1334
- this.defaultVisit(node);
1335
- }
1336
- visitFunction(node) {
1337
- this.defaultVisit(node);
1338
- }
1339
- visitCase(node) {
1340
- this.defaultVisit(node);
1341
- }
1342
- visitWhen(node) {
1343
- this.defaultVisit(node);
1344
- }
1345
- visitJSONReference(node) {
1346
- this.defaultVisit(node);
1347
- }
1348
- visitJSONPath(node) {
1349
- this.defaultVisit(node);
1350
- }
1351
- visitJSONPathLeg(node) {
1352
- this.defaultVisit(node);
1353
- }
1354
- visitJSONOperatorChain(node) {
1355
- this.defaultVisit(node);
1356
- }
1357
- visitTuple(node) {
1358
- this.defaultVisit(node);
1359
- }
1360
- visitMergeQuery(node) {
1361
- this.defaultVisit(node);
1362
- }
1363
- visitMatched(node) {
1364
- this.defaultVisit(node);
1365
- }
1366
- visitAddIndex(node) {
1367
- this.defaultVisit(node);
1368
- }
1369
- visitCast(node) {
1370
- this.defaultVisit(node);
1371
- }
1372
- visitFetch(node) {
1373
- this.defaultVisit(node);
1374
- }
1375
- visitTop(node) {
1376
- this.defaultVisit(node);
1377
- }
1378
- visitOutput(node) {
1379
- this.defaultVisit(node);
1380
- }
1381
- };
1382
-
1383
- // src/plugins/policy/column-collector.ts
1384
- var ColumnCollector = class extends DefaultOperationNodeVisitor {
1385
- static {
1386
- __name(this, "ColumnCollector");
1387
- }
1388
- columns = [];
1389
- collect(node) {
1390
- this.columns = [];
1391
- this.visitNode(node);
1392
- return this.columns;
1393
- }
1394
- visitColumn(node) {
1395
- if (!this.columns.includes(node.column.name)) {
1396
- this.columns.push(node.column.name);
1397
- }
1398
- }
1399
- };
1400
-
1401
- // src/plugins/policy/expression-transformer.ts
1402
- import { invariant as invariant5 } from "@zenstackhq/common-helpers";
1403
- import { AliasNode as AliasNode2, BinaryOperationNode as BinaryOperationNode2, ColumnNode, expressionBuilder, FromNode, FunctionNode as FunctionNode2, IdentifierNode, OperatorNode as OperatorNode2, ReferenceNode as ReferenceNode2, SelectionNode, SelectQueryNode, TableNode as TableNode2, ValueListNode, ValueNode as ValueNode2, WhereNode } from "kysely";
1404
- import { match as match6 } from "ts-pattern";
1405
-
1406
- // src/plugins/policy/expression-evaluator.ts
1407
- import { invariant as invariant4 } from "@zenstackhq/common-helpers";
1408
- import { match as match5 } from "ts-pattern";
1409
- var ExpressionEvaluator = class {
1410
- static {
1411
- __name(this, "ExpressionEvaluator");
1412
- }
1413
- evaluate(expression, context) {
1414
- const result = match5(expression).when(ExpressionUtils.isArray, (expr2) => this.evaluateArray(expr2, context)).when(ExpressionUtils.isBinary, (expr2) => this.evaluateBinary(expr2, context)).when(ExpressionUtils.isField, (expr2) => this.evaluateField(expr2, context)).when(ExpressionUtils.isLiteral, (expr2) => this.evaluateLiteral(expr2)).when(ExpressionUtils.isMember, (expr2) => this.evaluateMember(expr2, context)).when(ExpressionUtils.isUnary, (expr2) => this.evaluateUnary(expr2, context)).when(ExpressionUtils.isCall, (expr2) => this.evaluateCall(expr2, context)).when(ExpressionUtils.isThis, () => context.thisValue).when(ExpressionUtils.isNull, () => null).exhaustive();
1415
- return result ?? null;
1416
- }
1417
- evaluateCall(expr2, context) {
1418
- if (expr2.function === "auth") {
1419
- return context.auth;
1420
- } else {
1421
- throw new Error(`Unsupported call expression function: ${expr2.function}`);
1422
- }
1423
- }
1424
- evaluateUnary(expr2, context) {
1425
- return match5(expr2.op).with("!", () => !this.evaluate(expr2.operand, context)).exhaustive();
1426
- }
1427
- evaluateMember(expr2, context) {
1428
- let val = this.evaluate(expr2.receiver, context);
1429
- for (const member of expr2.members) {
1430
- val = val?.[member];
1431
- }
1432
- return val;
1433
- }
1434
- evaluateLiteral(expr2) {
1435
- return expr2.value;
1436
- }
1437
- evaluateField(expr2, context) {
1438
- return context.thisValue?.[expr2.field];
1439
- }
1440
- evaluateArray(expr2, context) {
1441
- return expr2.items.map((item) => this.evaluate(item, context));
1442
- }
1443
- evaluateBinary(expr2, context) {
1444
- if (expr2.op === "?" || expr2.op === "!" || expr2.op === "^") {
1445
- return this.evaluateCollectionPredicate(expr2, context);
1446
- }
1447
- const left = this.evaluate(expr2.left, context);
1448
- const right = this.evaluate(expr2.right, context);
1449
- return match5(expr2.op).with("==", () => left === right).with("!=", () => left !== right).with(">", () => left > right).with(">=", () => left >= right).with("<", () => left < right).with("<=", () => left <= right).with("&&", () => left && right).with("||", () => left || right).with("in", () => {
1450
- const _right = right ?? [];
1451
- invariant4(Array.isArray(_right), 'expected array for "in" operator');
1452
- return _right.includes(left);
1453
- }).exhaustive();
1454
- }
1455
- evaluateCollectionPredicate(expr2, context) {
1456
- const op = expr2.op;
1457
- invariant4(op === "?" || op === "!" || op === "^", 'expected "?" or "!" or "^" operator');
1458
- const left = this.evaluate(expr2.left, context);
1459
- if (!left) {
1460
- return false;
1461
- }
1462
- invariant4(Array.isArray(left), "expected array");
1463
- return match5(op).with("?", () => left.some((item) => this.evaluate(expr2.right, {
1464
- ...context,
1465
- thisValue: item
1466
- }))).with("!", () => left.every((item) => this.evaluate(expr2.right, {
1467
- ...context,
1468
- thisValue: item
1469
- }))).with("^", () => !left.some((item) => this.evaluate(expr2.right, {
1470
- ...context,
1471
- thisValue: item
1472
- }))).exhaustive();
1473
- }
1474
- };
1475
-
1476
- // src/plugins/policy/utils.ts
1477
- import { AliasNode, AndNode, BinaryOperationNode, FunctionNode, OperatorNode, OrNode, ParensNode, ReferenceNode, TableNode, UnaryOperationNode, ValueNode } from "kysely";
1478
- function trueNode(dialect) {
1479
- return ValueNode.createImmediate(dialect.transformPrimitive(true, "Boolean", false));
1480
- }
1481
- __name(trueNode, "trueNode");
1482
- function falseNode(dialect) {
1483
- return ValueNode.createImmediate(dialect.transformPrimitive(false, "Boolean", false));
1484
- }
1485
- __name(falseNode, "falseNode");
1486
- function isTrueNode(node) {
1487
- return ValueNode.is(node) && (node.value === true || node.value === 1);
1488
- }
1489
- __name(isTrueNode, "isTrueNode");
1490
- function isFalseNode(node) {
1491
- return ValueNode.is(node) && (node.value === false || node.value === 0);
1492
- }
1493
- __name(isFalseNode, "isFalseNode");
1494
- function conjunction(dialect, nodes) {
1495
- if (nodes.some(isFalseNode)) {
1496
- return falseNode(dialect);
1497
- }
1498
- const items = nodes.filter((n) => !isTrueNode(n));
1499
- if (items.length === 0) {
1500
- return trueNode(dialect);
1501
- }
1502
- return items.reduce((acc, node) => OrNode.is(node) ? AndNode.create(acc, ParensNode.create(node)) : AndNode.create(acc, node));
1503
- }
1504
- __name(conjunction, "conjunction");
1505
- function disjunction(dialect, nodes) {
1506
- if (nodes.some(isTrueNode)) {
1507
- return trueNode(dialect);
1508
- }
1509
- const items = nodes.filter((n) => !isFalseNode(n));
1510
- if (items.length === 0) {
1511
- return falseNode(dialect);
1512
- }
1513
- return items.reduce((acc, node) => AndNode.is(node) ? OrNode.create(acc, ParensNode.create(node)) : OrNode.create(acc, node));
1514
- }
1515
- __name(disjunction, "disjunction");
1516
- function logicalNot(node) {
1517
- return UnaryOperationNode.create(OperatorNode.create("not"), AndNode.is(node) || OrNode.is(node) ? ParensNode.create(node) : node);
1518
- }
1519
- __name(logicalNot, "logicalNot");
1520
- function buildIsFalse(node, dialect) {
1521
- if (isFalseNode(node)) {
1522
- return trueNode(dialect);
1523
- } else if (isTrueNode(node)) {
1524
- return falseNode(dialect);
1525
- }
1526
- return BinaryOperationNode.create(
1527
- // coalesce so null is treated as false
1528
- FunctionNode.create("coalesce", [
1529
- node,
1530
- falseNode(dialect)
1531
- ]),
1532
- OperatorNode.create("="),
1533
- falseNode(dialect)
1534
- );
1535
- }
1536
- __name(buildIsFalse, "buildIsFalse");
1537
- function getTableName(node) {
1538
- if (!node) {
1539
- return node;
1540
- }
1541
- if (TableNode.is(node)) {
1542
- return node.table.identifier.name;
1543
- } else if (AliasNode.is(node)) {
1544
- return getTableName(node.node);
1545
- } else if (ReferenceNode.is(node) && node.table) {
1546
- return getTableName(node.table);
1547
- }
1548
- return void 0;
1549
- }
1550
- __name(getTableName, "getTableName");
1551
-
1552
- // src/plugins/policy/expression-transformer.ts
1553
- function _ts_decorate(decorators, target, key, desc) {
1554
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1555
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1556
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1557
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1558
- }
1559
- __name(_ts_decorate, "_ts_decorate");
1560
- function _ts_metadata(k, v) {
1561
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1562
- }
1563
- __name(_ts_metadata, "_ts_metadata");
1564
- var expressionHandlers = /* @__PURE__ */ new Map();
1565
- function expr(kind) {
1566
- return function(_target, _propertyKey, descriptor) {
1567
- if (!expressionHandlers.get(kind)) {
1568
- expressionHandlers.set(kind, descriptor);
1569
- }
1570
- return descriptor;
1571
- };
1572
- }
1573
- __name(expr, "expr");
1574
- var ExpressionTransformer = class {
1575
- static {
1576
- __name(this, "ExpressionTransformer");
1577
- }
1578
- schema;
1579
- clientOptions;
1580
- auth;
1581
- dialect;
1582
- constructor(schema, clientOptions, auth) {
1583
- this.schema = schema;
1584
- this.clientOptions = clientOptions;
1585
- this.auth = auth;
1586
- this.dialect = getCrudDialect(this.schema, this.clientOptions);
1587
- }
1588
- get authType() {
1589
- if (!this.schema.authType) {
1590
- throw new InternalError('Schema does not have an "authType" specified');
1591
- }
1592
- return this.schema.authType;
1593
- }
1594
- transform(expression, context) {
1595
- const handler = expressionHandlers.get(expression.kind);
1596
- if (!handler) {
1597
- throw new Error(`Unsupported expression kind: ${expression.kind}`);
1598
- }
1599
- return handler.value.call(this, expression, context);
1600
- }
1601
- _literal(expr2) {
1602
- return this.transformValue(expr2.value, typeof expr2.value === "string" ? "String" : typeof expr2.value === "boolean" ? "Boolean" : "Int");
1603
- }
1604
- _array(expr2, context) {
1605
- return ValueListNode.create(expr2.items.map((item) => this.transform(item, context)));
1606
- }
1607
- _field(expr2, context) {
1608
- const fieldDef = requireField(this.schema, context.model, expr2.field);
1609
- if (!fieldDef.relation) {
1610
- if (context.thisEntity) {
1611
- return context.thisEntity[expr2.field];
1612
- } else {
1613
- return this.createColumnRef(expr2.field, context);
1614
- }
1615
- } else {
1616
- const { memberFilter, memberSelect, ...restContext } = context;
1617
- const relation = this.transformRelationAccess(expr2.field, fieldDef.type, restContext);
1618
- return {
1619
- ...relation,
1620
- where: this.mergeWhere(relation.where, memberFilter),
1621
- selections: memberSelect ? [
1622
- memberSelect
1623
- ] : relation.selections
1624
- };
1625
- }
1626
- }
1627
- mergeWhere(where, memberFilter) {
1628
- if (!where) {
1629
- return WhereNode.create(memberFilter ?? trueNode(this.dialect));
1630
- }
1631
- if (!memberFilter) {
1632
- return where;
1633
- }
1634
- return WhereNode.create(conjunction(this.dialect, [
1635
- where.where,
1636
- memberFilter
1637
- ]));
1638
- }
1639
- _null() {
1640
- return ValueNode2.createImmediate(null);
1641
- }
1642
- _binary(expr2, context) {
1643
- if (expr2.op === "&&") {
1644
- return conjunction(this.dialect, [
1645
- this.transform(expr2.left, context),
1646
- this.transform(expr2.right, context)
1647
- ]);
1648
- } else if (expr2.op === "||") {
1649
- return disjunction(this.dialect, [
1650
- this.transform(expr2.left, context),
1651
- this.transform(expr2.right, context)
1652
- ]);
1653
- }
1654
- if (this.isAuthCall(expr2.left) || this.isAuthCall(expr2.right)) {
1655
- return this.transformAuthBinary(expr2);
1656
- }
1657
- const op = expr2.op;
1658
- if (op === "?" || op === "!" || op === "^") {
1659
- return this.transformCollectionPredicate(expr2, context);
1660
- }
1661
- const left = this.transform(expr2.left, context);
1662
- const right = this.transform(expr2.right, context);
1663
- if (op === "in") {
1664
- if (this.isNullNode(left)) {
1665
- return this.transformValue(false, "Boolean");
1666
- } else {
1667
- if (ValueListNode.is(right)) {
1668
- return BinaryOperationNode2.create(left, OperatorNode2.create("in"), right);
1669
- } else {
1670
- return BinaryOperationNode2.create(left, OperatorNode2.create("="), FunctionNode2.create("any", [
1671
- right
1672
- ]));
1673
- }
1674
- }
1675
- }
1676
- if (this.isNullNode(right)) {
1677
- return expr2.op === "==" ? BinaryOperationNode2.create(left, OperatorNode2.create("is"), right) : BinaryOperationNode2.create(left, OperatorNode2.create("is not"), right);
1678
- } else if (this.isNullNode(left)) {
1679
- return expr2.op === "==" ? BinaryOperationNode2.create(right, OperatorNode2.create("is"), ValueNode2.createImmediate(null)) : BinaryOperationNode2.create(right, OperatorNode2.create("is not"), ValueNode2.createImmediate(null));
1680
- }
1681
- return BinaryOperationNode2.create(left, this.transformOperator(op), right);
1682
- }
1683
- transformCollectionPredicate(expr2, context) {
1684
- invariant5(expr2.op === "?" || expr2.op === "!" || expr2.op === "^", 'expected "?" or "!" or "^" operator');
1685
- if (this.isAuthCall(expr2.left) || this.isAuthMember(expr2.left)) {
1686
- const value = new ExpressionEvaluator().evaluate(expr2, {
1687
- auth: this.auth
1688
- });
1689
- return this.transformValue(value, "Boolean");
1690
- }
1691
- invariant5(ExpressionUtils.isField(expr2.left) || ExpressionUtils.isMember(expr2.left), "left operand must be field or member access");
1692
- let newContextModel;
1693
- if (ExpressionUtils.isField(expr2.left)) {
1694
- const fieldDef = requireField(this.schema, context.model, expr2.left.field);
1695
- newContextModel = fieldDef.type;
1696
- } else {
1697
- invariant5(ExpressionUtils.isField(expr2.left.receiver));
1698
- const fieldDef = requireField(this.schema, context.model, expr2.left.receiver.field);
1699
- newContextModel = fieldDef.type;
1700
- for (const member of expr2.left.members) {
1701
- const memberDef = requireField(this.schema, newContextModel, member);
1702
- newContextModel = memberDef.type;
1703
- }
1704
- }
1705
- let predicateFilter = this.transform(expr2.right, {
1706
- ...context,
1707
- model: newContextModel,
1708
- alias: void 0,
1709
- thisEntity: void 0
1710
- });
1711
- if (expr2.op === "!") {
1712
- predicateFilter = logicalNot(predicateFilter);
1713
- }
1714
- const count = FunctionNode2.create("count", [
1715
- ValueNode2.createImmediate(1)
1716
- ]);
1717
- const predicateResult = match6(expr2.op).with("?", () => BinaryOperationNode2.create(count, OperatorNode2.create(">"), ValueNode2.createImmediate(0))).with("!", () => BinaryOperationNode2.create(count, OperatorNode2.create("="), ValueNode2.createImmediate(0))).with("^", () => BinaryOperationNode2.create(count, OperatorNode2.create("="), ValueNode2.createImmediate(0))).exhaustive();
1718
- return this.transform(expr2.left, {
1719
- ...context,
1720
- memberSelect: SelectionNode.create(AliasNode2.create(predicateResult, IdentifierNode.create("$t"))),
1721
- memberFilter: predicateFilter
1722
- });
1723
- }
1724
- transformAuthBinary(expr2) {
1725
- if (expr2.op !== "==" && expr2.op !== "!=") {
1726
- throw new Error(`Unsupported operator for auth call: ${expr2.op}`);
1727
- }
1728
- let other;
1729
- if (this.isAuthCall(expr2.left)) {
1730
- other = expr2.right;
1731
- } else {
1732
- other = expr2.left;
1733
- }
1734
- if (ExpressionUtils.isNull(other)) {
1735
- return this.transformValue(expr2.op === "==" ? !this.auth : !!this.auth, "Boolean");
1736
- } else {
1737
- throw new Error("Unsupported binary expression with `auth()`");
1738
- }
1739
- }
1740
- transformValue(value, type) {
1741
- return ValueNode2.create(this.dialect.transformPrimitive(value, type, false) ?? null);
1742
- }
1743
- _unary(expr2, context) {
1744
- invariant5(expr2.op === "!", 'only "!" operator is supported');
1745
- return BinaryOperationNode2.create(this.transform(expr2.operand, context), this.transformOperator("!="), trueNode(this.dialect));
1746
- }
1747
- transformOperator(op) {
1748
- const mappedOp = match6(op).with("==", () => "=").otherwise(() => op);
1749
- return OperatorNode2.create(mappedOp);
1750
- }
1751
- _call(expr2, context) {
1752
- const result = this.transformCall(expr2, context);
1753
- return result.toOperationNode();
1754
- }
1755
- transformCall(expr2, context) {
1756
- const func = this.clientOptions.functions?.[expr2.function];
1757
- if (!func) {
1758
- throw new QueryError(`Function not implemented: ${expr2.function}`);
1759
- }
1760
- const eb = expressionBuilder();
1761
- return func(eb, (expr2.args ?? []).map((arg) => this.transformCallArg(eb, arg, context)), {
1762
- dialect: this.dialect,
1763
- model: context.model,
1764
- operation: context.operation
1765
- });
1766
- }
1767
- transformCallArg(eb, arg, context) {
1768
- if (ExpressionUtils.isLiteral(arg)) {
1769
- return eb.val(arg.value);
1770
- }
1771
- if (ExpressionUtils.isField(arg)) {
1772
- return context.thisEntityRaw ? eb.val(context.thisEntityRaw[arg.field]) : eb.ref(arg.field);
1773
- }
1774
- if (ExpressionUtils.isCall(arg)) {
1775
- return this.transformCall(arg, context);
1776
- }
1777
- if (this.isAuthMember(arg)) {
1778
- const valNode = this.valueMemberAccess(context.auth, arg, this.authType);
1779
- return valNode ? eb.val(valNode.value) : eb.val(null);
1780
- }
1781
- throw new InternalError(`Unsupported argument expression: ${arg.kind}`);
1782
- }
1783
- _member(expr2, context) {
1784
- if (this.isAuthCall(expr2.receiver)) {
1785
- return this.valueMemberAccess(this.auth, expr2, this.authType);
1786
- }
1787
- invariant5(ExpressionUtils.isField(expr2.receiver), "expect receiver to be field expression");
1788
- const { memberFilter, memberSelect, ...restContext } = context;
1789
- const receiver = this.transform(expr2.receiver, restContext);
1790
- invariant5(SelectQueryNode.is(receiver), "expected receiver to be select query");
1791
- const receiverField = requireField(this.schema, context.model, expr2.receiver.field);
1792
- const memberFields = [];
1793
- let currType = receiverField.type;
1794
- for (const member of expr2.members) {
1795
- const fieldDef = requireField(this.schema, currType, member);
1796
- memberFields.push({
1797
- fieldDef,
1798
- fromModel: currType
1799
- });
1800
- currType = fieldDef.type;
1801
- }
1802
- let currNode = void 0;
1803
- for (let i = expr2.members.length - 1; i >= 0; i--) {
1804
- const member = expr2.members[i];
1805
- const { fieldDef, fromModel } = memberFields[i];
1806
- if (fieldDef.relation) {
1807
- const relation = this.transformRelationAccess(member, fieldDef.type, {
1808
- ...restContext,
1809
- model: fromModel,
1810
- alias: void 0,
1811
- thisEntity: void 0
1812
- });
1813
- if (currNode) {
1814
- invariant5(SelectQueryNode.is(currNode), "expected select query node");
1815
- currNode = {
1816
- ...relation,
1817
- selections: [
1818
- SelectionNode.create(AliasNode2.create(currNode, IdentifierNode.create(expr2.members[i + 1])))
1819
- ]
1820
- };
1821
- } else {
1822
- currNode = {
1823
- ...relation,
1824
- where: this.mergeWhere(relation.where, memberFilter),
1825
- selections: memberSelect ? [
1826
- memberSelect
1827
- ] : relation.selections
1828
- };
1829
- }
1830
- } else {
1831
- invariant5(i === expr2.members.length - 1, "plain field access must be the last segment");
1832
- invariant5(!currNode, "plain field access must be the last segment");
1833
- currNode = ColumnNode.create(member);
1834
- }
1835
- }
1836
- return {
1837
- ...receiver,
1838
- selections: [
1839
- SelectionNode.create(AliasNode2.create(currNode, IdentifierNode.create("$t")))
1840
- ]
1841
- };
1842
- }
1843
- valueMemberAccess(receiver, expr2, receiverType) {
1844
- if (!receiver) {
1845
- return ValueNode2.createImmediate(null);
1846
- }
1847
- if (expr2.members.length !== 1) {
1848
- throw new Error(`Only single member access is supported`);
1849
- }
1850
- const field = expr2.members[0];
1851
- const fieldDef = requireField(this.schema, receiverType, field);
1852
- const fieldValue = receiver[field] ?? null;
1853
- return this.transformValue(fieldValue, fieldDef.type);
1854
- }
1855
- transformRelationAccess(field, relationModel, context) {
1856
- const fromModel = context.model;
1857
- const { keyPairs, ownedByModel } = getRelationForeignKeyFieldPairs(this.schema, fromModel, field);
1858
- if (context.thisEntity) {
1859
- let condition;
1860
- if (ownedByModel) {
1861
- condition = conjunction(this.dialect, keyPairs.map(({ fk, pk }) => BinaryOperationNode2.create(ReferenceNode2.create(ColumnNode.create(pk), TableNode2.create(relationModel)), OperatorNode2.create("="), context.thisEntity[fk])));
1862
- } else {
1863
- condition = conjunction(this.dialect, keyPairs.map(({ fk, pk }) => BinaryOperationNode2.create(ReferenceNode2.create(ColumnNode.create(fk), TableNode2.create(relationModel)), OperatorNode2.create("="), context.thisEntity[pk])));
1864
- }
1865
- return {
1866
- kind: "SelectQueryNode",
1867
- from: FromNode.create([
1868
- TableNode2.create(relationModel)
1869
- ]),
1870
- where: WhereNode.create(condition)
1871
- };
1872
- } else {
1873
- let condition;
1874
- if (ownedByModel) {
1875
- condition = conjunction(this.dialect, keyPairs.map(({ fk, pk }) => BinaryOperationNode2.create(ReferenceNode2.create(ColumnNode.create(fk), TableNode2.create(context.alias ?? fromModel)), OperatorNode2.create("="), ReferenceNode2.create(ColumnNode.create(pk), TableNode2.create(relationModel)))));
1876
- } else {
1877
- condition = conjunction(this.dialect, keyPairs.map(({ fk, pk }) => BinaryOperationNode2.create(ReferenceNode2.create(ColumnNode.create(pk), TableNode2.create(context.alias ?? fromModel)), OperatorNode2.create("="), ReferenceNode2.create(ColumnNode.create(fk), TableNode2.create(relationModel)))));
1878
- }
1879
- return {
1880
- kind: "SelectQueryNode",
1881
- from: FromNode.create([
1882
- TableNode2.create(relationModel)
1883
- ]),
1884
- where: WhereNode.create(condition)
1885
- };
1886
- }
1887
- }
1888
- createColumnRef(column, context) {
1889
- return ReferenceNode2.create(ColumnNode.create(column), TableNode2.create(context.alias ?? context.model));
1890
- }
1891
- isAuthCall(value) {
1892
- return ExpressionUtils.isCall(value) && value.function === "auth";
1893
- }
1894
- isAuthMember(expr2) {
1895
- return ExpressionUtils.isMember(expr2) && this.isAuthCall(expr2.receiver);
1896
- }
1897
- isNullNode(node) {
1898
- return ValueNode2.is(node) && node.value === null;
1899
- }
1900
- };
1901
- _ts_decorate([
1902
- expr("literal"),
1903
- _ts_metadata("design:type", Function),
1904
- _ts_metadata("design:paramtypes", [
1905
- typeof LiteralExpression === "undefined" ? Object : LiteralExpression
1906
- ]),
1907
- _ts_metadata("design:returntype", void 0)
1908
- ], ExpressionTransformer.prototype, "_literal", null);
1909
- _ts_decorate([
1910
- expr("array"),
1911
- _ts_metadata("design:type", Function),
1912
- _ts_metadata("design:paramtypes", [
1913
- typeof ArrayExpression === "undefined" ? Object : ArrayExpression,
1914
- typeof ExpressionTransformerContext === "undefined" ? Object : ExpressionTransformerContext
1915
- ]),
1916
- _ts_metadata("design:returntype", void 0)
1917
- ], ExpressionTransformer.prototype, "_array", null);
1918
- _ts_decorate([
1919
- expr("field"),
1920
- _ts_metadata("design:type", Function),
1921
- _ts_metadata("design:paramtypes", [
1922
- typeof FieldExpression === "undefined" ? Object : FieldExpression,
1923
- typeof ExpressionTransformerContext === "undefined" ? Object : ExpressionTransformerContext
1924
- ]),
1925
- _ts_metadata("design:returntype", void 0)
1926
- ], ExpressionTransformer.prototype, "_field", null);
1927
- _ts_decorate([
1928
- expr("null"),
1929
- _ts_metadata("design:type", Function),
1930
- _ts_metadata("design:paramtypes", []),
1931
- _ts_metadata("design:returntype", void 0)
1932
- ], ExpressionTransformer.prototype, "_null", null);
1933
- _ts_decorate([
1934
- expr("binary"),
1935
- _ts_metadata("design:type", Function),
1936
- _ts_metadata("design:paramtypes", [
1937
- typeof BinaryExpression === "undefined" ? Object : BinaryExpression,
1938
- typeof ExpressionTransformerContext === "undefined" ? Object : ExpressionTransformerContext
1939
- ]),
1940
- _ts_metadata("design:returntype", void 0)
1941
- ], ExpressionTransformer.prototype, "_binary", null);
1942
- _ts_decorate([
1943
- expr("unary"),
1944
- _ts_metadata("design:type", Function),
1945
- _ts_metadata("design:paramtypes", [
1946
- typeof UnaryExpression === "undefined" ? Object : UnaryExpression,
1947
- typeof ExpressionTransformerContext === "undefined" ? Object : ExpressionTransformerContext
1948
- ]),
1949
- _ts_metadata("design:returntype", void 0)
1950
- ], ExpressionTransformer.prototype, "_unary", null);
1951
- _ts_decorate([
1952
- expr("call"),
1953
- _ts_metadata("design:type", Function),
1954
- _ts_metadata("design:paramtypes", [
1955
- typeof CallExpression === "undefined" ? Object : CallExpression,
1956
- typeof ExpressionTransformerContext === "undefined" ? Object : ExpressionTransformerContext
1957
- ]),
1958
- _ts_metadata("design:returntype", void 0)
1959
- ], ExpressionTransformer.prototype, "_call", null);
1960
- _ts_decorate([
1961
- expr("member"),
1962
- _ts_metadata("design:type", Function),
1963
- _ts_metadata("design:paramtypes", [
1964
- typeof MemberExpression === "undefined" ? Object : MemberExpression,
1965
- typeof ExpressionTransformerContext === "undefined" ? Object : ExpressionTransformerContext
1966
- ]),
1967
- _ts_metadata("design:returntype", void 0)
1968
- ], ExpressionTransformer.prototype, "_member", null);
1969
-
1970
- // src/plugins/policy/policy-handler.ts
1971
- var PolicyHandler = class extends OperationNodeTransformer {
1972
- static {
1973
- __name(this, "PolicyHandler");
1974
- }
1975
- client;
1976
- dialect;
1977
- constructor(client) {
1978
- super(), this.client = client;
1979
- this.dialect = getCrudDialect(this.client.$schema, this.client.$options);
1980
- }
1981
- get kysely() {
1982
- return this.client.$qb;
1983
- }
1984
- async handle(node, proceed) {
1985
- if (!this.isCrudQueryNode(node)) {
1986
- throw new RejectedByPolicyError(void 0, "non-CRUD queries are not allowed");
1987
- }
1988
- if (!this.isMutationQueryNode(node)) {
1989
- return proceed(this.transformNode(node));
1990
- }
1991
- let mutationRequiresTransaction = false;
1992
- const mutationModel = this.getMutationModel(node);
1993
- if (InsertQueryNode.is(node)) {
1994
- const constCondition = this.tryGetConstantPolicy(mutationModel, "create");
1995
- if (constCondition === false) {
1996
- throw new RejectedByPolicyError(mutationModel);
1997
- } else if (constCondition === void 0) {
1998
- mutationRequiresTransaction = true;
1999
- }
2000
- }
2001
- if (!mutationRequiresTransaction && !node.returning) {
2002
- return proceed(this.transformNode(node));
2003
- }
2004
- if (InsertQueryNode.is(node)) {
2005
- await this.enforcePreCreatePolicy(node, proceed);
2006
- }
2007
- const transformedNode = this.transformNode(node);
2008
- const result = await proceed(transformedNode);
2009
- if (!this.onlyReturningId(node)) {
2010
- const readBackResult = await this.processReadBack(node, result, proceed);
2011
- if (readBackResult.rows.length !== result.rows.length) {
2012
- throw new RejectedByPolicyError(mutationModel, "result is not allowed to be read back");
2013
- }
2014
- return readBackResult;
2015
- } else {
2016
- return result;
2017
- }
2018
- }
2019
- onlyReturningId(node) {
2020
- if (!node.returning) {
2021
- return true;
2022
- }
2023
- const idFields = getIdFields(this.client.$schema, this.getMutationModel(node));
2024
- const collector = new ColumnCollector();
2025
- const selectedColumns = collector.collect(node.returning);
2026
- return selectedColumns.every((c) => idFields.includes(c));
2027
- }
2028
- async enforcePreCreatePolicy(node, proceed) {
2029
- if (!node.columns || !node.values) {
2030
- return;
2031
- }
2032
- const model = this.getMutationModel(node);
2033
- const fields = node.columns.map((c) => c.column.name);
2034
- const valueRows = this.unwrapCreateValueRows(node.values, model, fields);
2035
- for (const values of valueRows) {
2036
- await this.enforcePreCreatePolicyForOne(model, fields, values.map((v) => v.node), values.map((v) => v.raw), proceed);
2037
- }
2038
- }
2039
- async enforcePreCreatePolicyForOne(model, fields, values, valuesRaw, proceed) {
2040
- const thisEntity = {};
2041
- const thisEntityRaw = {};
2042
- for (let i = 0; i < fields.length; i++) {
2043
- thisEntity[fields[i]] = values[i];
2044
- thisEntityRaw[fields[i]] = valuesRaw[i];
2045
- }
2046
- const filter = this.buildPolicyFilter(model, void 0, "create", thisEntity, thisEntityRaw);
2047
- const preCreateCheck = {
2048
- kind: "SelectQueryNode",
2049
- selections: [
2050
- SelectionNode2.create(AliasNode3.create(filter, IdentifierNode2.create("$condition")))
2051
- ]
2052
- };
2053
- const result = await proceed(preCreateCheck);
2054
- if (!result.rows[0]?.$condition) {
2055
- throw new RejectedByPolicyError(model);
2056
- }
2057
- }
2058
- unwrapCreateValueRows(node, model, fields) {
2059
- if (ValuesNode.is(node)) {
2060
- return node.values.map((v) => this.unwrapCreateValueRow(v.values, model, fields));
2061
- } else if (PrimitiveValueListNode.is(node)) {
2062
- return [
2063
- this.unwrapCreateValueRow(node.values, model, fields)
2064
- ];
2065
- } else {
2066
- throw new InternalError(`Unexpected node kind: ${node.kind} for unwrapping create values`);
2067
- }
2068
- }
2069
- unwrapCreateValueRow(data, model, fields) {
2070
- invariant6(data.length === fields.length, "data length must match fields length");
2071
- const result = [];
2072
- for (let i = 0; i < data.length; i++) {
2073
- const item = data[i];
2074
- const fieldDef = requireField(this.client.$schema, model, fields[i]);
2075
- if (typeof item === "object" && item && "kind" in item) {
2076
- invariant6(item.kind === "ValueNode", "expecting a ValueNode");
2077
- result.push({
2078
- node: ValueNode3.create(this.dialect.transformPrimitive(item.value, fieldDef.type, !!fieldDef.array)),
2079
- raw: item.value
2080
- });
2081
- } else {
2082
- const value = this.dialect.transformPrimitive(item, fieldDef.type, !!fieldDef.array);
2083
- if (Array.isArray(value)) {
2084
- result.push({
2085
- node: RawNode.createWithSql(this.dialect.buildArrayLiteralSQL(value)),
2086
- raw: value
2087
- });
2088
- } else {
2089
- result.push({
2090
- node: ValueNode3.create(value),
2091
- raw: value
2092
- });
2093
- }
2094
- }
2095
- }
2096
- return result;
2097
- }
2098
- tryGetConstantPolicy(model, operation) {
2099
- const policies = this.getModelPolicies(model, operation);
2100
- if (!policies.some((p) => p.kind === "allow")) {
2101
- return false;
2102
- } else if (
2103
- // unconditional deny
2104
- policies.some((p) => p.kind === "deny" && this.isTrueExpr(p.condition))
2105
- ) {
2106
- return false;
2107
- } else if (
2108
- // unconditional allow
2109
- !policies.some((p) => p.kind === "deny") && policies.some((p) => p.kind === "allow" && this.isTrueExpr(p.condition))
2110
- ) {
2111
- return true;
2112
- } else {
2113
- return void 0;
2114
- }
2115
- }
2116
- isTrueExpr(expr2) {
2117
- return ExpressionUtils.isLiteral(expr2) && expr2.value === true;
2118
- }
2119
- async processReadBack(node, result, proceed) {
2120
- if (result.rows.length === 0) {
2121
- return result;
2122
- }
2123
- if (!this.isMutationQueryNode(node) || !node.returning) {
2124
- return result;
2125
- }
2126
- const table = this.getMutationModel(node);
2127
- if (!table) {
2128
- throw new InternalError(`Unable to get table name for query node: ${node}`);
2129
- }
2130
- const idConditions = this.buildIdConditions(table, result.rows);
2131
- const policyFilter = this.buildPolicyFilter(table, void 0, "read");
2132
- const select = {
2133
- kind: "SelectQueryNode",
2134
- from: FromNode2.create([
2135
- TableNode3.create(table)
2136
- ]),
2137
- where: WhereNode2.create(conjunction(this.dialect, [
2138
- idConditions,
2139
- policyFilter
2140
- ])),
2141
- selections: node.returning.selections
2142
- };
2143
- const selectResult = await proceed(select);
2144
- return selectResult;
2145
- }
2146
- buildIdConditions(table, rows) {
2147
- const idFields = getIdFields(this.client.$schema, table);
2148
- return disjunction(this.dialect, rows.map((row) => conjunction(this.dialect, idFields.map((field) => BinaryOperationNode3.create(ColumnNode2.create(field), OperatorNode3.create("="), ValueNode3.create(row[field]))))));
2149
- }
2150
- getMutationModel(node) {
2151
- const r = match7(node).when(InsertQueryNode.is, (node2) => getTableName(node2.into)).when(UpdateQueryNode.is, (node2) => getTableName(node2.table)).when(DeleteQueryNode.is, (node2) => {
2152
- if (node2.from.froms.length !== 1) {
2153
- throw new InternalError("Only one from table is supported for delete");
2154
- }
2155
- return getTableName(node2.from.froms[0]);
2156
- }).exhaustive();
2157
- if (!r) {
2158
- throw new InternalError(`Unable to get table name for query node: ${node}`);
2159
- }
2160
- return r;
2161
- }
2162
- isCrudQueryNode(node) {
2163
- return SelectQueryNode2.is(node) || InsertQueryNode.is(node) || UpdateQueryNode.is(node) || DeleteQueryNode.is(node);
2164
- }
2165
- isMutationQueryNode(node) {
2166
- return InsertQueryNode.is(node) || UpdateQueryNode.is(node) || DeleteQueryNode.is(node);
2167
- }
2168
- buildPolicyFilter(model, alias, operation, thisEntity, thisEntityRaw) {
2169
- const policies = this.getModelPolicies(model, operation);
2170
- if (policies.length === 0) {
2171
- return falseNode(this.dialect);
2172
- }
2173
- const allows = policies.filter((policy) => policy.kind === "allow").map((policy) => this.transformPolicyCondition(model, alias, operation, policy, thisEntity, thisEntityRaw));
2174
- const denies = policies.filter((policy) => policy.kind === "deny").map((policy) => this.transformPolicyCondition(model, alias, operation, policy, thisEntity, thisEntityRaw));
2175
- let combinedPolicy;
2176
- if (allows.length === 0) {
2177
- combinedPolicy = falseNode(this.dialect);
2178
- } else {
2179
- combinedPolicy = disjunction(this.dialect, allows);
2180
- if (denies.length !== 0) {
2181
- const combinedDenies = conjunction(this.dialect, denies.map((d) => buildIsFalse(d, this.dialect)));
2182
- combinedPolicy = conjunction(this.dialect, [
2183
- combinedPolicy,
2184
- combinedDenies
2185
- ]);
2186
- }
2187
- }
2188
- return combinedPolicy;
2189
- }
2190
- transformSelectQuery(node) {
2191
- let whereNode = node.where;
2192
- node.from?.froms.forEach((from) => {
2193
- const extractResult = this.extractTableName(from);
2194
- if (extractResult) {
2195
- const { model, alias } = extractResult;
2196
- const filter = this.buildPolicyFilter(model, alias, "read");
2197
- whereNode = WhereNode2.create(whereNode?.where ? conjunction(this.dialect, [
2198
- whereNode.where,
2199
- filter
2200
- ]) : filter);
2201
- }
2202
- });
2203
- const baseResult = super.transformSelectQuery({
2204
- ...node,
2205
- where: void 0
2206
- });
2207
- return {
2208
- ...baseResult,
2209
- where: whereNode
2210
- };
2211
- }
2212
- transformInsertQuery(node) {
2213
- const result = super.transformInsertQuery(node);
2214
- if (!node.returning) {
2215
- return result;
2216
- }
2217
- if (this.onlyReturningId(node)) {
2218
- return result;
2219
- } else {
2220
- const idFields = getIdFields(this.client.$schema, this.getMutationModel(node));
2221
- return {
2222
- ...result,
2223
- returning: ReturningNode.create(idFields.map((field) => SelectionNode2.create(ColumnNode2.create(field))))
2224
- };
2225
- }
2226
- }
2227
- transformUpdateQuery(node) {
2228
- const result = super.transformUpdateQuery(node);
2229
- const mutationModel = this.getMutationModel(node);
2230
- const filter = this.buildPolicyFilter(mutationModel, void 0, "update");
2231
- return {
2232
- ...result,
2233
- where: WhereNode2.create(result.where ? conjunction(this.dialect, [
2234
- result.where.where,
2235
- filter
2236
- ]) : filter)
2237
- };
2238
- }
2239
- transformDeleteQuery(node) {
2240
- const result = super.transformDeleteQuery(node);
2241
- const mutationModel = this.getMutationModel(node);
2242
- const filter = this.buildPolicyFilter(mutationModel, void 0, "delete");
2243
- return {
2244
- ...result,
2245
- where: WhereNode2.create(result.where ? conjunction(this.dialect, [
2246
- result.where.where,
2247
- filter
2248
- ]) : filter)
2249
- };
2250
- }
2251
- extractTableName(from) {
2252
- if (TableNode3.is(from)) {
2253
- return {
2254
- model: from.table.identifier.name
2255
- };
2256
- }
2257
- if (AliasNode3.is(from)) {
2258
- const inner = this.extractTableName(from.node);
2259
- if (!inner) {
2260
- return void 0;
2261
- }
2262
- return {
2263
- model: inner.model,
2264
- alias: IdentifierNode2.is(from.alias) ? from.alias.name : void 0
2265
- };
2266
- } else {
2267
- return void 0;
2268
- }
2269
- }
2270
- transformPolicyCondition(model, alias, operation, policy, thisEntity, thisEntityRaw) {
2271
- return new ExpressionTransformer(this.client.$schema, this.client.$options, this.client.$auth).transform(policy.condition, {
2272
- model,
2273
- alias,
2274
- operation,
2275
- thisEntity,
2276
- thisEntityRaw,
2277
- auth: this.client.$auth
2278
- });
2279
- }
2280
- getModelPolicies(modelName, operation) {
2281
- const modelDef = requireModel(this.client.$schema, modelName);
2282
- const result = [];
2283
- const extractOperations = /* @__PURE__ */ __name((expr2) => {
2284
- invariant6(ExpressionUtils.isLiteral(expr2), "expecting a literal");
2285
- invariant6(typeof expr2.value === "string", "expecting a string literal");
2286
- return expr2.value.split(",").filter((v) => !!v).map((v) => v.trim());
2287
- }, "extractOperations");
2288
- if (modelDef.attributes) {
2289
- result.push(...modelDef.attributes.filter((attr) => attr.name === "@@allow" || attr.name === "@@deny").map((attr) => ({
2290
- kind: attr.name === "@@allow" ? "allow" : "deny",
2291
- operations: extractOperations(attr.args[0].value),
2292
- condition: attr.args[1].value
2293
- })).filter((policy) => policy.operations.includes("all") || policy.operations.includes(operation)));
2294
- }
2295
- return result;
2296
- }
2297
- };
2298
-
2299
- // src/plugins/policy/plugin.ts
2300
- var PolicyPlugin = class {
2301
- static {
2302
- __name(this, "PolicyPlugin");
2303
- }
2304
- get id() {
2305
- return "policy";
2306
- }
2307
- get name() {
2308
- return "Access Policy";
2309
- }
2310
- get description() {
2311
- return "Enforces access policies defined in the schema.";
2312
- }
2313
- onKyselyQuery({
2314
- query,
2315
- client,
2316
- proceed
2317
- /*, transaction*/
2318
- }) {
2319
- const handler = new PolicyHandler(client);
2320
- return handler.handle(
2321
- query,
2322
- proceed
2323
- /*, transaction*/
2324
- );
2325
- }
2326
- };
2327
- export {
2328
- PolicyPlugin,
2329
- RejectedByPolicyError
2330
- };
2331
- //# sourceMappingURL=policy.js.map