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