@cedarjs/gqlorm 5.0.7-next.336 → 5.0.7-rc.3

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.
Files changed (37) hide show
  1. package/dist/cjs/generator/graphqlGenerator.d.ts +30 -0
  2. package/dist/cjs/generator/graphqlGenerator.d.ts.map +1 -0
  3. package/dist/cjs/generator/graphqlGenerator.js +430 -0
  4. package/dist/cjs/live/types.d.ts +262 -0
  5. package/dist/cjs/live/types.d.ts.map +1 -0
  6. package/dist/cjs/live/types.js +16 -0
  7. package/dist/cjs/package.json +1 -0
  8. package/dist/cjs/parser/queryParser.d.ts +27 -0
  9. package/dist/cjs/parser/queryParser.d.ts.map +1 -0
  10. package/dist/cjs/parser/queryParser.js +339 -0
  11. package/dist/cjs/queryBuilder.d.ts +114 -0
  12. package/dist/cjs/queryBuilder.d.ts.map +1 -0
  13. package/dist/cjs/queryBuilder.js +238 -0
  14. package/dist/cjs/react/useLiveQuery.d.ts +12 -0
  15. package/dist/cjs/react/useLiveQuery.d.ts.map +1 -0
  16. package/dist/cjs/react/useLiveQuery.js +62 -0
  17. package/dist/cjs/setup.d.ts +39 -0
  18. package/dist/cjs/setup.d.ts.map +1 -0
  19. package/dist/cjs/setup.js +31 -0
  20. package/dist/cjs/types/ast.d.ts +80 -0
  21. package/dist/cjs/types/ast.d.ts.map +1 -0
  22. package/dist/cjs/types/ast.js +16 -0
  23. package/dist/cjs/types/orm.d.ts +163 -0
  24. package/dist/cjs/types/orm.d.ts.map +1 -0
  25. package/dist/cjs/types/orm.js +16 -0
  26. package/dist/cjs/types/orm_for_testing.d.ts +44 -0
  27. package/dist/cjs/types/orm_for_testing.d.ts.map +1 -0
  28. package/dist/cjs/types/orm_for_testing.js +16 -0
  29. package/dist/cjs/types/schema.d.ts +4 -0
  30. package/dist/cjs/types/schema.d.ts.map +1 -0
  31. package/dist/cjs/types/schema.js +16 -0
  32. package/dist/cjs/types/typeUtils.d.ts +10 -0
  33. package/dist/cjs/types/typeUtils.d.ts.map +1 -0
  34. package/dist/cjs/types/typeUtils.js +65 -0
  35. package/dist/react/useLiveQuery.d.ts +2 -5
  36. package/dist/react/useLiveQuery.d.ts.map +1 -1
  37. package/package.json +67 -22
@@ -0,0 +1,30 @@
1
+ /**
2
+ * GraphQL query generator that converts AST to GraphQL query strings
3
+ * Transforms our internal AST representation into valid GraphQL queries
4
+ */
5
+ import type { QueryAST } from '../types/ast.js';
6
+ import { type ModelSchema } from '../types/schema.js';
7
+ export declare class GraphQLGenerateError extends Error {
8
+ context?: any | undefined;
9
+ constructor(message: string, context?: any | undefined);
10
+ }
11
+ export interface GraphQLQuery {
12
+ query: string;
13
+ variables?: Record<string, any>;
14
+ }
15
+ export declare class GraphQLGenerator {
16
+ #private;
17
+ constructor(schema?: ModelSchema);
18
+ /**
19
+ * Update the model schema used for automatic field selection.
20
+ * Pass `undefined` to revert to the id-only fallback.
21
+ * Safe to call multiple times — last call wins.
22
+ */
23
+ setSchema(schema: ModelSchema | undefined): void;
24
+ /**
25
+ * Generate GraphQL query from AST
26
+ */
27
+ generate(ast: QueryAST): GraphQLQuery;
28
+ }
29
+ export declare const graphqlGenerator: GraphQLGenerator;
30
+ //# sourceMappingURL=graphqlGenerator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graphqlGenerator.d.ts","sourceRoot":"","sources":["../../../src/generator/graphqlGenerator.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAOV,QAAQ,EAKT,MAAM,iBAAiB,CAAA;AACxB,OAAO,EAAE,KAAK,WAAW,EAAE,MAAM,oBAAoB,CAAA;AAOrD,qBAAa,oBAAqB,SAAQ,KAAK;IAGpC,OAAO,CAAC,EAAE,GAAG;gBADpB,OAAO,EAAE,MAAM,EACR,OAAO,CAAC,EAAE,GAAG,YAAA;CAKvB;AAED,MAAM,WAAW,YAAY;IAC3B,KAAK,EAAE,MAAM,CAAA;IACb,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;CAChC;AAED,qBAAa,gBAAgB;;gBASf,MAAM,CAAC,EAAE,WAAW;IAIhC;;;;OAIG;IACH,SAAS,CAAC,MAAM,EAAE,WAAW,GAAG,SAAS,GAAG,IAAI;IAIhD;;OAEG;IACH,QAAQ,CAAC,GAAG,EAAE,QAAQ,GAAG,YAAY;CAodtC;AAGD,eAAO,MAAM,gBAAgB,kBAAyB,CAAA"}
@@ -0,0 +1,430 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var graphqlGenerator_exports = {};
20
+ __export(graphqlGenerator_exports, {
21
+ GraphQLGenerateError: () => GraphQLGenerateError,
22
+ GraphQLGenerator: () => GraphQLGenerator,
23
+ graphqlGenerator: () => graphqlGenerator
24
+ });
25
+ module.exports = __toCommonJS(graphqlGenerator_exports);
26
+ var import_typeUtils = require("../types/typeUtils.js");
27
+ class GraphQLGenerateError extends Error {
28
+ constructor(message, context) {
29
+ super(message);
30
+ this.context = context;
31
+ this.name = "GraphQLGenerateError";
32
+ }
33
+ context;
34
+ }
35
+ class GraphQLGenerator {
36
+ #variableCounter = 0;
37
+ #variables = {};
38
+ // Track field names for each variable
39
+ #variableFields = /* @__PURE__ */ new Map();
40
+ // Track current operation for context-aware type generation
41
+ #operation;
42
+ #schema;
43
+ constructor(schema) {
44
+ this.#schema = schema;
45
+ }
46
+ /**
47
+ * Update the model schema used for automatic field selection.
48
+ * Pass `undefined` to revert to the id-only fallback.
49
+ * Safe to call multiple times — last call wins.
50
+ */
51
+ setSchema(schema) {
52
+ this.#schema = schema;
53
+ }
54
+ /**
55
+ * Generate GraphQL query from AST
56
+ */
57
+ generate(ast) {
58
+ this.#resetState();
59
+ this.#operation = ast.operation;
60
+ const operationName = this.#generateOperationName(ast);
61
+ const queryBody = this.#generateQueryBody(ast);
62
+ let query = `query ${operationName}`;
63
+ const hasVariables = Object.keys(this.#variables).length > 0;
64
+ if (hasVariables) {
65
+ const variableDefinitions = this.#generateVariableDefinitions();
66
+ query += `(${variableDefinitions})`;
67
+ }
68
+ if (ast.isLive) {
69
+ query += " @live";
70
+ }
71
+ query += ` {
72
+ ${queryBody}
73
+ }`;
74
+ const result = { query };
75
+ if (hasVariables) {
76
+ result.variables = structuredClone(this.#variables);
77
+ }
78
+ return result;
79
+ }
80
+ /**
81
+ * Reset internal state for new query generation
82
+ */
83
+ #resetState() {
84
+ this.#variableCounter = 0;
85
+ this.#variables = {};
86
+ this.#variableFields.clear();
87
+ this.#operation = void 0;
88
+ }
89
+ /**
90
+ * Generate operation name
91
+ */
92
+ #generateOperationName(ast) {
93
+ const { model, operation } = ast;
94
+ return `${operation}${this.#capitalize(model)}`;
95
+ }
96
+ /**
97
+ * Generate main query body
98
+ */
99
+ #generateQueryBody(ast) {
100
+ const { model, operation, args } = ast;
101
+ const fieldName = this.#getGraphQLFieldName(model, operation);
102
+ let query = ` ${fieldName}`;
103
+ if (args) {
104
+ const argsString = this.#generateArguments(args, operation);
105
+ if (argsString) {
106
+ query += `(${argsString})`;
107
+ }
108
+ }
109
+ const fields = this.#generateFieldSelection(args, model);
110
+ query += ` {
111
+ ${fields}
112
+ }`;
113
+ return query;
114
+ }
115
+ /**
116
+ * Convert operation to GraphQL field name
117
+ */
118
+ #getGraphQLFieldName(model, operation) {
119
+ switch (operation) {
120
+ case "findMany":
121
+ return `${model}s`;
122
+ case "findUnique":
123
+ case "findUniqueOrThrow":
124
+ return model;
125
+ case "findFirst":
126
+ case "findFirstOrThrow":
127
+ return model;
128
+ default:
129
+ throw new GraphQLGenerateError(`Unsupported operation: ${operation}`);
130
+ }
131
+ }
132
+ /**
133
+ * Generate GraphQL arguments from query args
134
+ */
135
+ #generateArguments(args, operation) {
136
+ const argParts = [];
137
+ if (args?.where) {
138
+ const isFindUnique = operation === "findUnique" || operation === "findUniqueOrThrow";
139
+ const simpleUniqueArg = isFindUnique ? this.#extractSimpleUniqueArgument(args.where) : null;
140
+ if (simpleUniqueArg) {
141
+ argParts.push(simpleUniqueArg);
142
+ } else {
143
+ const whereArg = this.#generateWhereArgument(args.where);
144
+ if (whereArg && whereArg !== "{}") {
145
+ argParts.push(`where: ${whereArg}`);
146
+ }
147
+ }
148
+ }
149
+ if (args?.orderBy) {
150
+ const orderByArg = this.#generateOrderByArgument(args.orderBy);
151
+ argParts.push(`orderBy: ${orderByArg}`);
152
+ }
153
+ if (typeof args?.take === "number") {
154
+ argParts.push(`first: ${args.take}`);
155
+ }
156
+ if (typeof args?.skip === "number") {
157
+ argParts.push(`skip: ${args.skip}`);
158
+ }
159
+ return argParts.join(", ");
160
+ }
161
+ /**
162
+ * Extract simple unique argument for findUnique operations
163
+ * Returns direct argument format (e.g., "id: $var0") if the where clause
164
+ * contains a single simple field equality, otherwise returns null
165
+ */
166
+ #extractSimpleUniqueArgument(where) {
167
+ if (where.conditions.length !== 1) {
168
+ return null;
169
+ }
170
+ const condition = where.conditions[0];
171
+ if (!(0, import_typeUtils.isFieldCondition)(condition) || condition.operator !== "equals") {
172
+ return null;
173
+ }
174
+ const variableName = this.#addVariable(condition.value, condition.field);
175
+ return `${condition.field}: $${variableName}`;
176
+ }
177
+ /**
178
+ * Generate variable definitions for GraphQL query
179
+ */
180
+ #generateVariableDefinitions() {
181
+ return Object.entries(this.#variables).map(([name, value]) => {
182
+ const fieldName = this.#variableFields.get(name);
183
+ const baseType = this.#getGraphQLType(value, fieldName);
184
+ const isFindUnique = this.#operation === "findUnique" || this.#operation === "findUniqueOrThrow";
185
+ const isIdField = fieldName === "id" || fieldName?.endsWith("Id");
186
+ if (isFindUnique && isIdField && !baseType.includes("!")) {
187
+ return `$${name}: ${baseType}!`;
188
+ }
189
+ return `$${name}: ${baseType}`;
190
+ }).join(", ");
191
+ }
192
+ /**
193
+ * Generate WHERE argument
194
+ */
195
+ #generateWhereArgument(where) {
196
+ const conditions = where.conditions.map(
197
+ (condition) => this.#generateCondition(condition)
198
+ );
199
+ if (conditions.length === 0) {
200
+ return "{}";
201
+ }
202
+ if (conditions.length === 1) {
203
+ return conditions[0];
204
+ }
205
+ return `{ AND: [${conditions.join(", ")}] }`;
206
+ }
207
+ /**
208
+ * Generate individual where condition
209
+ */
210
+ #generateCondition(condition) {
211
+ if ((0, import_typeUtils.isFieldCondition)(condition)) {
212
+ return this.#generateFieldCondition(condition);
213
+ } else if ((0, import_typeUtils.isLogicalCondition)(condition)) {
214
+ return this.#generateLogicalCondition(condition);
215
+ } else if ((0, import_typeUtils.isRelationCondition)(condition)) {
216
+ return this.#generateRelationCondition(condition);
217
+ }
218
+ throw new GraphQLGenerateError("Unknown condition type", { condition });
219
+ }
220
+ /**
221
+ * Generate field condition
222
+ */
223
+ #generateFieldCondition(condition) {
224
+ const { field, operator, value } = condition;
225
+ if (operator === "equals") {
226
+ const variableName2 = this.#addVariable(value, field);
227
+ return `{ ${field}: $${variableName2} }`;
228
+ }
229
+ const operatorMap = {
230
+ equals: "equals",
231
+ not: "not",
232
+ in: "in",
233
+ notIn: "notIn",
234
+ lt: "lt",
235
+ lte: "lte",
236
+ gt: "gt",
237
+ gte: "gte",
238
+ contains: "contains",
239
+ startsWith: "startsWith",
240
+ endsWith: "endsWith",
241
+ isNull: "isNull",
242
+ isNotNull: "isNotNull"
243
+ };
244
+ const gqlOperator = operatorMap[operator];
245
+ if (!gqlOperator) {
246
+ throw new GraphQLGenerateError(`Unsupported operator: ${operator}`);
247
+ }
248
+ if (operator === "isNull" || operator === "isNotNull") {
249
+ return `{ ${field}: { ${gqlOperator}: ${operator === "isNull"} } }`;
250
+ }
251
+ const variableName = this.#addVariable(value, field);
252
+ return `{ ${field}: { ${gqlOperator}: $${variableName} } }`;
253
+ }
254
+ /**
255
+ * Generate logical condition
256
+ */
257
+ #generateLogicalCondition(condition) {
258
+ const { operator, conditions } = condition;
259
+ const conditionStrings = conditions.map(
260
+ (cond) => this.#generateCondition(cond)
261
+ );
262
+ if (operator === "NOT") {
263
+ if (conditionStrings.length !== 1) {
264
+ throw new GraphQLGenerateError(
265
+ "NOT operator must have exactly one condition"
266
+ );
267
+ }
268
+ return `{ NOT: ${conditionStrings[0]} }`;
269
+ }
270
+ return `{ ${operator}: [${conditionStrings.join(", ")}] }`;
271
+ }
272
+ /**
273
+ * Generate relation condition
274
+ */
275
+ #generateRelationCondition(condition) {
276
+ const { relation, condition: nestedCondition } = condition;
277
+ const whereArg = this.#generateWhereArgument(nestedCondition);
278
+ return `{ ${relation}: ${whereArg} }`;
279
+ }
280
+ /**
281
+ * Generate ORDER BY argument
282
+ */
283
+ #generateOrderByArgument(orderBy) {
284
+ const fields = orderBy.fields.map((field) => {
285
+ const direction = field.direction.toUpperCase();
286
+ return `{ ${field.field}: ${direction} }`;
287
+ });
288
+ if (fields.length === 1) {
289
+ return fields[0];
290
+ }
291
+ return `[${fields.join(", ")}]`;
292
+ }
293
+ /**
294
+ * Generate field selection
295
+ */
296
+ #generateFieldSelection(args, model) {
297
+ if (args?.select) {
298
+ return this.#generateSelectFields(args.select);
299
+ }
300
+ if (args?.include) {
301
+ return this.#generateIncludeFields(args.include);
302
+ }
303
+ if (model && this.#schema && this.#schema[model]) {
304
+ const fields = this.#schema[model];
305
+ return fields.map((field) => ` ${field}`).join("\n");
306
+ }
307
+ return " id";
308
+ }
309
+ /**
310
+ * Generate fields from SELECT clause
311
+ */
312
+ #generateSelectFields(select) {
313
+ const fieldStrings = [];
314
+ for (const fieldSelection of select.fields) {
315
+ if (!fieldSelection.selected) {
316
+ continue;
317
+ }
318
+ if (fieldSelection.nested) {
319
+ const nestedFields = fieldSelection.nested.type === "Select" ? this.#generateSelectFields(fieldSelection.nested) : this.#generateIncludeFields(fieldSelection.nested);
320
+ const indentedFields = this.#indent(nestedFields, 2);
321
+ fieldStrings.push(
322
+ ` ${fieldSelection.field} {
323
+ ${indentedFields}
324
+ }`
325
+ );
326
+ } else {
327
+ fieldStrings.push(` ${fieldSelection.field}`);
328
+ }
329
+ }
330
+ return fieldStrings.join("\n");
331
+ }
332
+ /**
333
+ * Generate fields from INCLUDE clause
334
+ */
335
+ #generateIncludeFields(include) {
336
+ const fieldStrings = [];
337
+ fieldStrings.push(" id");
338
+ for (const relationInclusion of include.relations) {
339
+ if (!relationInclusion.included) {
340
+ continue;
341
+ }
342
+ let relationQuery = ` ${relationInclusion.relation}`;
343
+ if (relationInclusion.args) {
344
+ const argsString = this.#generateArguments(relationInclusion.args);
345
+ if (argsString) {
346
+ relationQuery += `(${argsString})`;
347
+ }
348
+ }
349
+ let nestedFields;
350
+ if (relationInclusion.nested) {
351
+ nestedFields = this.#generateIncludeFields(relationInclusion.nested);
352
+ } else if (relationInclusion.args?.select) {
353
+ nestedFields = this.#generateSelectFields(relationInclusion.args.select);
354
+ } else {
355
+ nestedFields = " id";
356
+ }
357
+ relationQuery += ` {
358
+ ${this.#indent(nestedFields, 2)}
359
+ }`;
360
+ fieldStrings.push(relationQuery);
361
+ }
362
+ return fieldStrings.join("\n");
363
+ }
364
+ /**
365
+ * Add variable and return variable name
366
+ */
367
+ #addVariable(value, fieldName) {
368
+ const variableName = `var${this.#variableCounter++}`;
369
+ this.#variables[variableName] = value;
370
+ if (fieldName) {
371
+ this.#variableFields.set(variableName, fieldName);
372
+ }
373
+ return variableName;
374
+ }
375
+ /**
376
+ * Get GraphQL type for a value
377
+ */
378
+ #getGraphQLType(value, fieldName) {
379
+ const isIdField = fieldName && /^(id|.*Id|.*ID)$/.test(fieldName);
380
+ if (value === void 0 || value === null) {
381
+ return isIdField ? "ID" : "String";
382
+ }
383
+ if (typeof value === "string") {
384
+ return isIdField ? "ID" : "String";
385
+ }
386
+ if (typeof value === "number") {
387
+ if (isIdField) {
388
+ return "ID";
389
+ }
390
+ return Number.isInteger(value) ? "Int" : "Float";
391
+ }
392
+ if (typeof value === "boolean") {
393
+ return "Boolean";
394
+ }
395
+ if (value instanceof Date) {
396
+ return "DateTime";
397
+ }
398
+ if (Array.isArray(value)) {
399
+ if (value.length === 0) {
400
+ return "[String]";
401
+ }
402
+ const itemType = this.#getGraphQLType(value[0], fieldName);
403
+ if (isIdField && (itemType === "ID" || itemType === "String")) {
404
+ return `[ID!]`;
405
+ }
406
+ return `[${itemType}]`;
407
+ }
408
+ return "String";
409
+ }
410
+ /**
411
+ * Capitalize first letter of string
412
+ */
413
+ #capitalize(str) {
414
+ return str.charAt(0).toUpperCase() + str.slice(1);
415
+ }
416
+ /**
417
+ * Indent text by specified number of levels
418
+ */
419
+ #indent(text, levels) {
420
+ const indentation = " ".repeat(levels);
421
+ return text.split("\n").map((line) => line.trim() ? `${indentation}${line}` : line).join("\n");
422
+ }
423
+ }
424
+ const graphqlGenerator = new GraphQLGenerator();
425
+ // Annotate the CommonJS export names for ESM import in node:
426
+ 0 && (module.exports = {
427
+ GraphQLGenerateError,
428
+ GraphQLGenerator,
429
+ graphqlGenerator
430
+ });