@macss/modular-api 0.4.5 → 0.4.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +70 -8
- package/dist/core/body_parser_error_handler.d.ts +15 -0
- package/dist/core/body_parser_error_handler.js +35 -0
- package/dist/core/logger/logger.d.ts +1 -0
- package/dist/core/logger/logger.js +1 -0
- package/dist/core/logger/logging_middleware.js +11 -0
- package/dist/core/modular_api.d.ts +17 -0
- package/dist/core/modular_api.js +107 -43
- package/dist/core/official_plugins.d.ts +35 -0
- package/dist/core/official_plugins.js +213 -0
- package/dist/core/plugin.d.ts +163 -0
- package/dist/core/plugin.js +304 -0
- package/dist/core/request_pipeline_audit.d.ts +15 -0
- package/dist/core/request_pipeline_audit.js +29 -0
- package/dist/core/schema/field.d.ts +2 -1
- package/dist/core/schema/field.js +4 -0
- package/dist/core/unhandled_request_error_handler.d.ts +2 -0
- package/dist/core/unhandled_request_error_handler.js +17 -0
- package/dist/core/usecase.js +1 -0
- package/dist/core/usecase_handler.js +3 -2
- package/dist/graphql/catalog/graphql_catalog_builder.d.ts +149 -0
- package/dist/graphql/catalog/graphql_catalog_builder.js +564 -0
- package/dist/graphql/metadata/graphql_metadata_parser.d.ts +53 -0
- package/dist/graphql/metadata/graphql_metadata_parser.js +373 -0
- package/dist/graphql/read/sql_read_contract.d.ts +155 -0
- package/dist/graphql/read/sql_read_contract.js +194 -0
- package/dist/graphql/read/sqlserver_read_compiler.d.ts +58 -0
- package/dist/graphql/read/sqlserver_read_compiler.js +279 -0
- package/dist/graphql/runtime/graphql_artifacts.d.ts +43 -0
- package/dist/graphql/runtime/graphql_artifacts.js +512 -0
- package/dist/graphql/runtime/graphql_runtime_options.d.ts +52 -0
- package/dist/graphql/runtime/graphql_runtime_options.js +60 -0
- package/dist/graphql/runtime/graphql_runtime_plugin.d.ts +18 -0
- package/dist/graphql/runtime/graphql_runtime_plugin.js +946 -0
- package/dist/graphql/schema/graphql_schema_sdl_generator.d.ts +17 -0
- package/dist/graphql/schema/graphql_schema_sdl_generator.js +221 -0
- package/dist/graphql/sqlserver/physical_model.d.ts +28 -0
- package/dist/graphql/sqlserver/physical_model.js +8 -0
- package/dist/graphql/sqlserver/sql_server_connection_settings.d.ts +15 -0
- package/dist/graphql/sqlserver/sql_server_connection_settings.js +28 -0
- package/dist/graphql/sqlserver/sql_server_metadata_reader.d.ts +39 -0
- package/dist/graphql/sqlserver/sql_server_metadata_reader.js +294 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +58 -1
- package/dist/openapi/swagger_docs.d.ts +11 -6
- package/dist/openapi/swagger_docs.js +16 -193
- package/package.json +9 -6
- package/dist/core/usecase_test_handler.d.ts +0 -27
- package/dist/core/usecase_test_handler.js +0 -60
|
@@ -0,0 +1,946 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.GraphqlRuntimePlugin = void 0;
|
|
4
|
+
const graphql_1 = require("graphql");
|
|
5
|
+
const health_check_1 = require("../../core/health/health_check");
|
|
6
|
+
const graphql_catalog_builder_1 = require("../catalog/graphql_catalog_builder");
|
|
7
|
+
const sql_read_contract_1 = require("../read/sql_read_contract");
|
|
8
|
+
const sqlserver_read_compiler_1 = require("../read/sqlserver_read_compiler");
|
|
9
|
+
const graphql_runtime_options_1 = require("./graphql_runtime_options");
|
|
10
|
+
const graphql_artifacts_1 = require("./graphql_artifacts");
|
|
11
|
+
const OFFICIAL_PLUGIN_HOST_RANGE = '>=0.1.0 <0.2.0';
|
|
12
|
+
const GRAPHQL_JSON_CONTENT_TYPE = 'application/json; charset=utf-8';
|
|
13
|
+
const GRAPHQL_TOTAL_COUNT_THUNK_KEY = Symbol('graphql.totalCountThunk');
|
|
14
|
+
class GraphqlRuntimePlugin {
|
|
15
|
+
options;
|
|
16
|
+
healthService;
|
|
17
|
+
manifest = {
|
|
18
|
+
id: 'modular_api.graphql',
|
|
19
|
+
displayName: 'GraphQL Plugin',
|
|
20
|
+
version: '0.1.0',
|
|
21
|
+
hostApiVersion: OFFICIAL_PLUGIN_HOST_RANGE,
|
|
22
|
+
};
|
|
23
|
+
state = { status: 'disabled' };
|
|
24
|
+
constructor(options, healthService) {
|
|
25
|
+
this.options = options;
|
|
26
|
+
this.healthService = healthService;
|
|
27
|
+
}
|
|
28
|
+
setup(host) {
|
|
29
|
+
this.healthService.addHealthCheck(new GraphqlRuntimeHealthCheck(() => this.state.status));
|
|
30
|
+
if (!this.options) {
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
host.registerRoute({
|
|
34
|
+
id: 'graphql.endpoint',
|
|
35
|
+
method: 'POST',
|
|
36
|
+
path: '/graphql',
|
|
37
|
+
visibility: 'transport',
|
|
38
|
+
handler: async (context) => this.handleRequest(context),
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
async validate(host) {
|
|
42
|
+
if (!this.options) {
|
|
43
|
+
return [];
|
|
44
|
+
}
|
|
45
|
+
if (this.options.maxDepth < 1) {
|
|
46
|
+
return [
|
|
47
|
+
this.validationFailure('graphql.maxDepth', 'GraphQL maxDepth must be greater than or equal to 1.'),
|
|
48
|
+
];
|
|
49
|
+
}
|
|
50
|
+
if (this.options.maxComplexity < 1) {
|
|
51
|
+
return [
|
|
52
|
+
this.validationFailure('graphql.maxComplexity', 'GraphQL maxComplexity must be greater than or equal to 1.'),
|
|
53
|
+
];
|
|
54
|
+
}
|
|
55
|
+
if (this.options.defaultLimit < 0) {
|
|
56
|
+
return [
|
|
57
|
+
this.validationFailure('graphql.defaultLimit', 'GraphQL defaultLimit must be non-negative.'),
|
|
58
|
+
];
|
|
59
|
+
}
|
|
60
|
+
if (this.options.maxLimit < 1) {
|
|
61
|
+
return [this.validationFailure('graphql.maxLimit', 'GraphQL maxLimit must be greater than zero.')];
|
|
62
|
+
}
|
|
63
|
+
if (this.options.defaultLimit > this.options.maxLimit) {
|
|
64
|
+
return [
|
|
65
|
+
this.validationFailure('graphql.defaultLimit', 'GraphQL defaultLimit cannot exceed maxLimit.'),
|
|
66
|
+
];
|
|
67
|
+
}
|
|
68
|
+
const executor = this.resolveExecutor(host);
|
|
69
|
+
if ('validationFailure' in executor) {
|
|
70
|
+
return [executor.validationFailure];
|
|
71
|
+
}
|
|
72
|
+
try {
|
|
73
|
+
const catalog = await (0, graphql_artifacts_1.resolveCatalogFromArtifactsOrSource)({ graphql: this.options });
|
|
74
|
+
const sdl = this.options.sdlFactory(catalog);
|
|
75
|
+
validateGeneratedSdl(sdl);
|
|
76
|
+
const schema = (0, graphql_1.buildSchema)(sdl);
|
|
77
|
+
const dispatcher = new sqlserver_read_compiler_1.SqlCatalogReadDispatcher({
|
|
78
|
+
compiler: new sqlserver_read_compiler_1.SqlServerReadCompiler(),
|
|
79
|
+
executor: executor.value,
|
|
80
|
+
});
|
|
81
|
+
this.state.status = 'ready';
|
|
82
|
+
this.state.ready = {
|
|
83
|
+
catalog,
|
|
84
|
+
executor: executor.value,
|
|
85
|
+
sdl,
|
|
86
|
+
schema,
|
|
87
|
+
dispatcher,
|
|
88
|
+
resolvers: buildResolverRegistry({ catalog, dispatcher, options: this.options }),
|
|
89
|
+
};
|
|
90
|
+
return [];
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
if (error instanceof graphql_artifacts_1.GraphqlArtifactLoadError) {
|
|
94
|
+
return [
|
|
95
|
+
this.validationFailure('graphql.artifacts', `GraphQL artifact loading failed: ${error.message}`),
|
|
96
|
+
];
|
|
97
|
+
}
|
|
98
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
99
|
+
const resourceId = message.startsWith('GraphQL schema generation failed:') ? 'graphql.schema' : 'graphql.catalog';
|
|
100
|
+
return [
|
|
101
|
+
this.validationFailure(resourceId, resourceId === 'graphql.schema' ? message : `GraphQL catalog construction failed: ${message}`),
|
|
102
|
+
];
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
async shutdown() {
|
|
106
|
+
this.state.status = 'disabled';
|
|
107
|
+
const ownedExecutor = this.options?.executor;
|
|
108
|
+
if (ownedExecutor) {
|
|
109
|
+
await ownedExecutor.close();
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
resolveExecutor(host) {
|
|
113
|
+
if (!this.options) {
|
|
114
|
+
return {
|
|
115
|
+
validationFailure: this.validationFailure(graphql_runtime_options_1.graphqlDefaultReadExecutorCapabilityId, 'GraphQL runtime is not configured.'),
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
if (this.options.executor) {
|
|
119
|
+
return { value: this.options.executor };
|
|
120
|
+
}
|
|
121
|
+
const capabilityId = this.options.executionCapabilityId ?? graphql_runtime_options_1.graphqlDefaultReadExecutorCapabilityId;
|
|
122
|
+
const capability = host.resolveCapability(capabilityId);
|
|
123
|
+
if (!capability) {
|
|
124
|
+
return {
|
|
125
|
+
validationFailure: this.validationFailure(capabilityId, `Missing GraphQL read executor capability: ${capabilityId}`),
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
if (!isReadExecutor(capability.value)) {
|
|
129
|
+
return {
|
|
130
|
+
validationFailure: this.validationFailure(capabilityId, `Capability ${capabilityId} does not expose a ReadExecutor.`),
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
return { value: capability.value };
|
|
134
|
+
}
|
|
135
|
+
validationFailure(resourceId, message) {
|
|
136
|
+
return {
|
|
137
|
+
code: 'PLUGIN_VALIDATION_FAILED',
|
|
138
|
+
message,
|
|
139
|
+
pluginId: this.manifest.id,
|
|
140
|
+
resourceId,
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
async handleRequest(context) {
|
|
144
|
+
const readyState = this.state.ready;
|
|
145
|
+
if (!this.options || !readyState) {
|
|
146
|
+
return {
|
|
147
|
+
status: 503,
|
|
148
|
+
contentType: GRAPHQL_JSON_CONTENT_TYPE,
|
|
149
|
+
body: { errors: [{ message: 'GraphQL runtime is not initialized.' }] },
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
await this.emitEvent(context, new graphql_runtime_options_1.GraphqlRequestEvent({
|
|
153
|
+
phase: graphql_runtime_options_1.GraphqlRequestPhase.Started,
|
|
154
|
+
requestId: context.requestId,
|
|
155
|
+
method: context.method,
|
|
156
|
+
path: context.path,
|
|
157
|
+
}));
|
|
158
|
+
try {
|
|
159
|
+
const response = await this.executeRequest(context, readyState);
|
|
160
|
+
await this.emitEvent(context, new graphql_runtime_options_1.GraphqlRequestEvent({
|
|
161
|
+
phase: graphql_runtime_options_1.GraphqlRequestPhase.Completed,
|
|
162
|
+
requestId: context.requestId,
|
|
163
|
+
method: context.method,
|
|
164
|
+
path: context.path,
|
|
165
|
+
statusCode: response.status,
|
|
166
|
+
}));
|
|
167
|
+
return response;
|
|
168
|
+
}
|
|
169
|
+
catch (error) {
|
|
170
|
+
await this.emitEvent(context, new graphql_runtime_options_1.GraphqlRequestEvent({
|
|
171
|
+
phase: graphql_runtime_options_1.GraphqlRequestPhase.Completed,
|
|
172
|
+
requestId: context.requestId,
|
|
173
|
+
method: context.method,
|
|
174
|
+
path: context.path,
|
|
175
|
+
statusCode: 500,
|
|
176
|
+
}));
|
|
177
|
+
throw error;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
async emitEvent(context, event) {
|
|
181
|
+
const sink = this.options?.onEvent;
|
|
182
|
+
if (!sink) {
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
try {
|
|
186
|
+
await sink(event);
|
|
187
|
+
}
|
|
188
|
+
catch (error) {
|
|
189
|
+
context.logger?.warning('graphql telemetry hook failed', {
|
|
190
|
+
request_id: context.requestId,
|
|
191
|
+
path: context.path,
|
|
192
|
+
error: error instanceof Error ? error.message : String(error),
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
async executeRequest(context, readyState) {
|
|
197
|
+
const query = readQuery(context);
|
|
198
|
+
if (!query) {
|
|
199
|
+
return {
|
|
200
|
+
status: 400,
|
|
201
|
+
contentType: GRAPHQL_JSON_CONTENT_TYPE,
|
|
202
|
+
body: { errors: [{ message: 'GraphQL request body must include a query string.' }] },
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
let document;
|
|
206
|
+
try {
|
|
207
|
+
document = (0, graphql_1.parse)(query);
|
|
208
|
+
}
|
|
209
|
+
catch (error) {
|
|
210
|
+
return graphqlOkResponse({ errors: [formatGraphqlError(error)] });
|
|
211
|
+
}
|
|
212
|
+
const maxDepth = computeDocumentDepth(document);
|
|
213
|
+
if (maxDepth > this.options.maxDepth) {
|
|
214
|
+
return graphqlOkResponse({
|
|
215
|
+
errors: [
|
|
216
|
+
validationError(`Maximum operation depth of ${this.options.maxDepth} reached. Operation depth: ${maxDepth}.`, 'queryDepthComplexity'),
|
|
217
|
+
],
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
const validationErrors = (0, graphql_1.validate)(readyState.schema, document, this.options.introspectionEnabled ? graphql_1.specifiedRules : [...graphql_1.specifiedRules, graphql_1.NoSchemaIntrospectionCustomRule]);
|
|
221
|
+
if (validationErrors.length > 0) {
|
|
222
|
+
return graphqlOkResponse({ errors: validationErrors.map((error) => formatGraphqlError(error)) });
|
|
223
|
+
}
|
|
224
|
+
const complexity = computeDocumentComplexity(document);
|
|
225
|
+
if (complexity > this.options.maxComplexity) {
|
|
226
|
+
return graphqlOkResponse({
|
|
227
|
+
errors: [
|
|
228
|
+
validationError(`Maximum operation complexity of ${this.options.maxComplexity} reached. Operation complexity: ${complexity}.`, 'queryComplexity'),
|
|
229
|
+
],
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
const result = await (0, graphql_1.execute)({
|
|
233
|
+
schema: readyState.schema,
|
|
234
|
+
document,
|
|
235
|
+
operationName: readOperationName(context.body),
|
|
236
|
+
variableValues: readVariables(context.body),
|
|
237
|
+
rootValue: {},
|
|
238
|
+
contextValue: {
|
|
239
|
+
request: context,
|
|
240
|
+
readyState,
|
|
241
|
+
relationLoaders: new Map(),
|
|
242
|
+
},
|
|
243
|
+
fieldResolver: createFieldResolver(),
|
|
244
|
+
});
|
|
245
|
+
return graphqlOkResponse({
|
|
246
|
+
data: result.data,
|
|
247
|
+
errors: result.errors?.map((error) => formatGraphqlError(error)),
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
exports.GraphqlRuntimePlugin = GraphqlRuntimePlugin;
|
|
252
|
+
class GraphqlRuntimeHealthCheck extends health_check_1.HealthCheck {
|
|
253
|
+
statusReader;
|
|
254
|
+
name = 'graphql';
|
|
255
|
+
constructor(statusReader) {
|
|
256
|
+
super();
|
|
257
|
+
this.statusReader = statusReader;
|
|
258
|
+
}
|
|
259
|
+
async check() {
|
|
260
|
+
const status = this.statusReader();
|
|
261
|
+
return new health_check_1.HealthCheckResult('pass', {
|
|
262
|
+
output: status === 'disabled' ? 'disabled' : 'ready',
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
class RelationBatchLoader {
|
|
267
|
+
options;
|
|
268
|
+
cache = new Map();
|
|
269
|
+
queue = new Map();
|
|
270
|
+
keys = new Map();
|
|
271
|
+
flushScheduled = false;
|
|
272
|
+
constructor(options) {
|
|
273
|
+
this.options = options;
|
|
274
|
+
}
|
|
275
|
+
load(key) {
|
|
276
|
+
const cached = this.cache.get(key.cacheKey);
|
|
277
|
+
if (cached) {
|
|
278
|
+
return cached;
|
|
279
|
+
}
|
|
280
|
+
const promise = new Promise((resolve, reject) => {
|
|
281
|
+
const existing = this.queue.get(key.cacheKey);
|
|
282
|
+
const request = { key, resolve, reject };
|
|
283
|
+
if (existing) {
|
|
284
|
+
existing.push(request);
|
|
285
|
+
}
|
|
286
|
+
else {
|
|
287
|
+
this.queue.set(key.cacheKey, [request]);
|
|
288
|
+
this.keys.set(key.cacheKey, key);
|
|
289
|
+
}
|
|
290
|
+
if (!this.flushScheduled) {
|
|
291
|
+
this.flushScheduled = true;
|
|
292
|
+
queueMicrotask(() => {
|
|
293
|
+
void this.flush();
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
});
|
|
297
|
+
this.cache.set(key.cacheKey, promise);
|
|
298
|
+
return promise;
|
|
299
|
+
}
|
|
300
|
+
async flush() {
|
|
301
|
+
const entries = [...this.queue.entries()];
|
|
302
|
+
const keys = [...this.keys.values()];
|
|
303
|
+
this.queue.clear();
|
|
304
|
+
this.keys.clear();
|
|
305
|
+
this.flushScheduled = false;
|
|
306
|
+
try {
|
|
307
|
+
const rowSet = await this.options.dispatcher.readRelationBatch({
|
|
308
|
+
catalog: this.options.catalog,
|
|
309
|
+
selection: new sql_read_contract_1.SqlRelationBatchSelection({
|
|
310
|
+
sourceObjectId: this.options.sourceObject.id,
|
|
311
|
+
relationName: this.options.relation.name,
|
|
312
|
+
projectedFields: this.options.projectedFields,
|
|
313
|
+
parentKeys: keys.map((key) => key.values),
|
|
314
|
+
}),
|
|
315
|
+
context: buildExecutionContext(this.options.requestContext),
|
|
316
|
+
});
|
|
317
|
+
const groupedRows = groupRelationRows({
|
|
318
|
+
rowSet,
|
|
319
|
+
targetObject: this.options.targetObject,
|
|
320
|
+
relation: this.options.relation,
|
|
321
|
+
});
|
|
322
|
+
for (const [cacheKey, requests] of entries) {
|
|
323
|
+
const rows = groupedRows.get(cacheKey) ?? [];
|
|
324
|
+
this.cache.set(cacheKey, Promise.resolve(rows));
|
|
325
|
+
for (const request of requests) {
|
|
326
|
+
request.resolve(rows);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
catch (error) {
|
|
331
|
+
for (const [cacheKey, requests] of entries) {
|
|
332
|
+
this.cache.delete(cacheKey);
|
|
333
|
+
for (const request of requests) {
|
|
334
|
+
request.reject(error);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
function buildResolverRegistry(options) {
|
|
341
|
+
const resolvers = new Map();
|
|
342
|
+
for (const object of options.catalog.objects) {
|
|
343
|
+
if (object.graphql.itemField) {
|
|
344
|
+
resolvers.set(`Query.${object.graphql.itemField}`, async (_source, args, context, info) => resolveItem({
|
|
345
|
+
args,
|
|
346
|
+
context,
|
|
347
|
+
info,
|
|
348
|
+
catalog: options.catalog,
|
|
349
|
+
object,
|
|
350
|
+
dispatcher: options.dispatcher,
|
|
351
|
+
}));
|
|
352
|
+
}
|
|
353
|
+
resolvers.set(`Query.${object.graphql.collectionField}`, async (_source, args, context, info) => resolveCollection({
|
|
354
|
+
args,
|
|
355
|
+
context,
|
|
356
|
+
info,
|
|
357
|
+
catalog: options.catalog,
|
|
358
|
+
object,
|
|
359
|
+
dispatcher: options.dispatcher,
|
|
360
|
+
runtimeOptions: options.options,
|
|
361
|
+
}));
|
|
362
|
+
for (const relation of object.relations) {
|
|
363
|
+
resolvers.set(`${object.graphql.typeName}.${relation.name}`, async (source, _args, context, info) => resolveRelation({
|
|
364
|
+
source,
|
|
365
|
+
context,
|
|
366
|
+
info,
|
|
367
|
+
catalog: options.catalog,
|
|
368
|
+
sourceObject: object,
|
|
369
|
+
relation,
|
|
370
|
+
dispatcher: options.dispatcher,
|
|
371
|
+
}));
|
|
372
|
+
}
|
|
373
|
+
resolvers.set(`${object.graphql.typeName}List.totalCount`, async (source) => {
|
|
374
|
+
if (!source || typeof source !== 'object') {
|
|
375
|
+
return 0;
|
|
376
|
+
}
|
|
377
|
+
const thunk = source[GRAPHQL_TOTAL_COUNT_THUNK_KEY];
|
|
378
|
+
if (typeof thunk === 'function') {
|
|
379
|
+
return thunk();
|
|
380
|
+
}
|
|
381
|
+
return 0;
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
return resolvers;
|
|
385
|
+
}
|
|
386
|
+
function createFieldResolver() {
|
|
387
|
+
return async (source, args, context, info) => {
|
|
388
|
+
const resolver = context.readyState.resolvers.get(`${info.parentType.name}.${info.fieldName}`);
|
|
389
|
+
if (resolver) {
|
|
390
|
+
return resolver(source, args, context, info);
|
|
391
|
+
}
|
|
392
|
+
return (0, graphql_1.defaultFieldResolver)(source, args, context, info);
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
async function resolveItem(options) {
|
|
396
|
+
if (!isPlainObject(options.args.key)) {
|
|
397
|
+
throw graphqlValidationError('graphql.key', 'GraphQL item queries require a key input object.');
|
|
398
|
+
}
|
|
399
|
+
const rowSet = await options.dispatcher.readItem({
|
|
400
|
+
catalog: options.catalog,
|
|
401
|
+
selection: new sql_read_contract_1.SqlItemSelection({
|
|
402
|
+
objectId: options.object.id,
|
|
403
|
+
projectedFields: projectedFieldsForObject({
|
|
404
|
+
object: options.object,
|
|
405
|
+
fieldNodes: options.info.fieldNodes,
|
|
406
|
+
fragments: options.info.fragments,
|
|
407
|
+
}),
|
|
408
|
+
key: { ...options.args.key },
|
|
409
|
+
}),
|
|
410
|
+
context: buildExecutionContext(options.context.request),
|
|
411
|
+
});
|
|
412
|
+
return rowSet.rows[0] ?? null;
|
|
413
|
+
}
|
|
414
|
+
async function resolveCollection(options) {
|
|
415
|
+
const envelopeFields = collectSelectedFieldNodes(options.info.fieldNodes, options.info.fragments);
|
|
416
|
+
const itemFieldNodes = envelopeFields.get('items') ?? [];
|
|
417
|
+
const wantsTotalCount = envelopeFields.has('totalCount');
|
|
418
|
+
const filter = parseFilter(options.object, options.args.filter);
|
|
419
|
+
const orderBy = parseOrderBy(options.object, options.args.orderBy);
|
|
420
|
+
const page = parsePage(options.object, options.args.page, options.runtimeOptions);
|
|
421
|
+
let items = [];
|
|
422
|
+
if (itemFieldNodes.length > 0 && page.limit > 0) {
|
|
423
|
+
const rowSet = await options.dispatcher.readCollection({
|
|
424
|
+
catalog: options.catalog,
|
|
425
|
+
selection: new sql_read_contract_1.SqlCollectionSelection({
|
|
426
|
+
objectId: options.object.id,
|
|
427
|
+
projectedFields: projectedFieldsForObject({
|
|
428
|
+
object: options.object,
|
|
429
|
+
fieldNodes: itemFieldNodes,
|
|
430
|
+
fragments: options.info.fragments,
|
|
431
|
+
}),
|
|
432
|
+
filter,
|
|
433
|
+
orderBy,
|
|
434
|
+
page,
|
|
435
|
+
}),
|
|
436
|
+
context: buildExecutionContext(options.context.request),
|
|
437
|
+
});
|
|
438
|
+
items = rowSet.rows;
|
|
439
|
+
}
|
|
440
|
+
const envelope = { items };
|
|
441
|
+
if (wantsTotalCount) {
|
|
442
|
+
envelope[GRAPHQL_TOTAL_COUNT_THUNK_KEY] = async () => {
|
|
443
|
+
const rowSet = await options.dispatcher.readCount({
|
|
444
|
+
catalog: options.catalog,
|
|
445
|
+
selection: new sql_read_contract_1.SqlCountSelection({
|
|
446
|
+
objectId: options.object.id,
|
|
447
|
+
filter,
|
|
448
|
+
}),
|
|
449
|
+
context: buildExecutionContext(options.context.request),
|
|
450
|
+
});
|
|
451
|
+
return extractTotalCount(rowSet);
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
return envelope;
|
|
455
|
+
}
|
|
456
|
+
async function resolveRelation(options) {
|
|
457
|
+
if (!isPlainObject(options.source)) {
|
|
458
|
+
return options.relation.cardinality === graphql_catalog_builder_1.GraphqlCatalogRelationCardinality.Many ? [] : null;
|
|
459
|
+
}
|
|
460
|
+
const targetObject = objectById(options.catalog, options.relation.target);
|
|
461
|
+
const requiredPublicFields = options.relation.targetFields.map((column) => fieldByColumn(targetObject, column).publicName);
|
|
462
|
+
const projectedFields = projectedFieldsForObject({
|
|
463
|
+
object: targetObject,
|
|
464
|
+
fieldNodes: options.info.fieldNodes,
|
|
465
|
+
fragments: options.info.fragments,
|
|
466
|
+
requiredPublicFields,
|
|
467
|
+
});
|
|
468
|
+
const parentValues = relationParentValues({
|
|
469
|
+
sourceObject: options.sourceObject,
|
|
470
|
+
relation: options.relation,
|
|
471
|
+
parent: options.source,
|
|
472
|
+
});
|
|
473
|
+
const loader = relationLoader({
|
|
474
|
+
executionContext: options.context,
|
|
475
|
+
catalog: options.catalog,
|
|
476
|
+
sourceObject: options.sourceObject,
|
|
477
|
+
targetObject,
|
|
478
|
+
relation: options.relation,
|
|
479
|
+
projectedFields,
|
|
480
|
+
dispatcher: options.dispatcher,
|
|
481
|
+
});
|
|
482
|
+
const rows = await loader.load({
|
|
483
|
+
cacheKey: relationKeyFromValues(parentValues),
|
|
484
|
+
values: parentValues,
|
|
485
|
+
});
|
|
486
|
+
if (options.relation.cardinality === graphql_catalog_builder_1.GraphqlCatalogRelationCardinality.Many) {
|
|
487
|
+
return rows;
|
|
488
|
+
}
|
|
489
|
+
return rows[0] ?? null;
|
|
490
|
+
}
|
|
491
|
+
function relationLoader(options) {
|
|
492
|
+
const loaderId = [options.sourceObject.id, options.relation.name, options.projectedFields.join(',')].join('|');
|
|
493
|
+
const existing = options.executionContext.relationLoaders.get(loaderId);
|
|
494
|
+
if (existing) {
|
|
495
|
+
return existing;
|
|
496
|
+
}
|
|
497
|
+
const loader = new RelationBatchLoader({
|
|
498
|
+
catalog: options.catalog,
|
|
499
|
+
sourceObject: options.sourceObject,
|
|
500
|
+
targetObject: options.targetObject,
|
|
501
|
+
relation: options.relation,
|
|
502
|
+
projectedFields: options.projectedFields,
|
|
503
|
+
dispatcher: options.dispatcher,
|
|
504
|
+
requestContext: options.executionContext.request,
|
|
505
|
+
});
|
|
506
|
+
options.executionContext.relationLoaders.set(loaderId, loader);
|
|
507
|
+
return loader;
|
|
508
|
+
}
|
|
509
|
+
function projectedFieldsForObject(options) {
|
|
510
|
+
const projected = new Set(options.requiredPublicFields ?? []);
|
|
511
|
+
for (const column of options.object.identity.fields) {
|
|
512
|
+
projected.add(fieldByColumn(options.object, column).publicName);
|
|
513
|
+
}
|
|
514
|
+
const selected = collectSelectedFieldNodes(options.fieldNodes, options.fragments);
|
|
515
|
+
for (const field of options.object.fields) {
|
|
516
|
+
if (selected.has(field.publicName)) {
|
|
517
|
+
projected.add(field.publicName);
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
for (const relation of options.object.relations) {
|
|
521
|
+
if (!selected.has(relation.name)) {
|
|
522
|
+
continue;
|
|
523
|
+
}
|
|
524
|
+
for (const column of relation.sourceFields) {
|
|
525
|
+
projected.add(fieldByColumn(options.object, column).publicName);
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
return options.object.fields
|
|
529
|
+
.filter((field) => projected.has(field.publicName))
|
|
530
|
+
.map((field) => field.publicName);
|
|
531
|
+
}
|
|
532
|
+
function collectSelectedFieldNodes(fieldNodes, fragments) {
|
|
533
|
+
const collected = new Map();
|
|
534
|
+
const visitedFragments = new Set();
|
|
535
|
+
for (const fieldNode of fieldNodes) {
|
|
536
|
+
collectSelectionSet(fieldNode.selectionSet, fragments, collected, visitedFragments);
|
|
537
|
+
}
|
|
538
|
+
return collected;
|
|
539
|
+
}
|
|
540
|
+
function collectSelectionSet(selectionSet, fragments, collected, visitedFragments) {
|
|
541
|
+
if (!selectionSet) {
|
|
542
|
+
return;
|
|
543
|
+
}
|
|
544
|
+
for (const selection of selectionSet.selections) {
|
|
545
|
+
switch (selection.kind) {
|
|
546
|
+
case graphql_1.Kind.FIELD: {
|
|
547
|
+
const existing = collected.get(selection.name.value);
|
|
548
|
+
if (existing) {
|
|
549
|
+
existing.push(selection);
|
|
550
|
+
}
|
|
551
|
+
else {
|
|
552
|
+
collected.set(selection.name.value, [selection]);
|
|
553
|
+
}
|
|
554
|
+
break;
|
|
555
|
+
}
|
|
556
|
+
case graphql_1.Kind.INLINE_FRAGMENT:
|
|
557
|
+
collectSelectionSet(selection.selectionSet, fragments, collected, visitedFragments);
|
|
558
|
+
break;
|
|
559
|
+
case graphql_1.Kind.FRAGMENT_SPREAD: {
|
|
560
|
+
if (visitedFragments.has(selection.name.value)) {
|
|
561
|
+
break;
|
|
562
|
+
}
|
|
563
|
+
visitedFragments.add(selection.name.value);
|
|
564
|
+
collectSelectionSet(fragments[selection.name.value]?.selectionSet, fragments, collected, visitedFragments);
|
|
565
|
+
break;
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
function parseFilter(object, raw) {
|
|
571
|
+
if (raw == null) {
|
|
572
|
+
return undefined;
|
|
573
|
+
}
|
|
574
|
+
if (!isPlainObject(raw)) {
|
|
575
|
+
throw graphqlValidationError('graphql.filter', 'GraphQL filter input must be an object.');
|
|
576
|
+
}
|
|
577
|
+
const nodes = [];
|
|
578
|
+
for (const [key, value] of Object.entries(raw)) {
|
|
579
|
+
switch (key) {
|
|
580
|
+
case 'and': {
|
|
581
|
+
const children = Array.isArray(value)
|
|
582
|
+
? value.map((child) => parseFilter(object, child)).filter((child) => !!child)
|
|
583
|
+
: [];
|
|
584
|
+
if (children.length > 0) {
|
|
585
|
+
nodes.push(sql_read_contract_1.SqlFilterGroup.and(children));
|
|
586
|
+
}
|
|
587
|
+
break;
|
|
588
|
+
}
|
|
589
|
+
case 'or': {
|
|
590
|
+
const children = Array.isArray(value)
|
|
591
|
+
? value.map((child) => parseFilter(object, child)).filter((child) => !!child)
|
|
592
|
+
: [];
|
|
593
|
+
if (children.length > 0) {
|
|
594
|
+
nodes.push(sql_read_contract_1.SqlFilterGroup.or(children));
|
|
595
|
+
}
|
|
596
|
+
break;
|
|
597
|
+
}
|
|
598
|
+
case 'not': {
|
|
599
|
+
const child = parseFilter(object, value);
|
|
600
|
+
if (child) {
|
|
601
|
+
nodes.push(sql_read_contract_1.SqlFilterGroup.not(child));
|
|
602
|
+
}
|
|
603
|
+
break;
|
|
604
|
+
}
|
|
605
|
+
default: {
|
|
606
|
+
const field = fieldByPublicName(object, key);
|
|
607
|
+
if (!field.filterable) {
|
|
608
|
+
throw graphqlValidationError('graphql.filter', `Field ${field.publicName} is not filterable.`);
|
|
609
|
+
}
|
|
610
|
+
if (!isPlainObject(value)) {
|
|
611
|
+
throw graphqlValidationError('graphql.filter', `Filter operators for ${field.publicName} must be an object.`);
|
|
612
|
+
}
|
|
613
|
+
const conditions = Object.entries(value).map(([operatorName, operatorValue]) => new sql_read_contract_1.SqlFilterCondition({
|
|
614
|
+
field: field.publicName,
|
|
615
|
+
operator: parseFilterOperator(operatorName),
|
|
616
|
+
value: operatorValue,
|
|
617
|
+
}));
|
|
618
|
+
if (conditions.length === 1) {
|
|
619
|
+
nodes.push(conditions[0]);
|
|
620
|
+
}
|
|
621
|
+
else if (conditions.length > 1) {
|
|
622
|
+
nodes.push(sql_read_contract_1.SqlFilterGroup.and(conditions));
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
if (nodes.length === 0) {
|
|
628
|
+
return undefined;
|
|
629
|
+
}
|
|
630
|
+
return nodes.length === 1 ? nodes[0] : sql_read_contract_1.SqlFilterGroup.and(nodes);
|
|
631
|
+
}
|
|
632
|
+
function parseFilterOperator(name) {
|
|
633
|
+
switch (name) {
|
|
634
|
+
case 'eq':
|
|
635
|
+
return sql_read_contract_1.SqlFilterOperator.Eq;
|
|
636
|
+
case 'ne':
|
|
637
|
+
return sql_read_contract_1.SqlFilterOperator.Ne;
|
|
638
|
+
case 'in':
|
|
639
|
+
return sql_read_contract_1.SqlFilterOperator.InList;
|
|
640
|
+
case 'lt':
|
|
641
|
+
return sql_read_contract_1.SqlFilterOperator.Lt;
|
|
642
|
+
case 'lte':
|
|
643
|
+
return sql_read_contract_1.SqlFilterOperator.Lte;
|
|
644
|
+
case 'gt':
|
|
645
|
+
return sql_read_contract_1.SqlFilterOperator.Gt;
|
|
646
|
+
case 'gte':
|
|
647
|
+
return sql_read_contract_1.SqlFilterOperator.Gte;
|
|
648
|
+
case 'isNull':
|
|
649
|
+
return sql_read_contract_1.SqlFilterOperator.IsNull;
|
|
650
|
+
case 'contains':
|
|
651
|
+
return sql_read_contract_1.SqlFilterOperator.Contains;
|
|
652
|
+
case 'startsWith':
|
|
653
|
+
return sql_read_contract_1.SqlFilterOperator.StartsWith;
|
|
654
|
+
case 'endsWith':
|
|
655
|
+
return sql_read_contract_1.SqlFilterOperator.EndsWith;
|
|
656
|
+
default:
|
|
657
|
+
throw graphqlValidationError('graphql.filter', `Unsupported filter operator ${name}.`);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
function parseOrderBy(object, raw) {
|
|
661
|
+
if (raw == null) {
|
|
662
|
+
return [];
|
|
663
|
+
}
|
|
664
|
+
if (!Array.isArray(raw)) {
|
|
665
|
+
throw graphqlValidationError('graphql.orderBy', 'GraphQL orderBy input must be a list.');
|
|
666
|
+
}
|
|
667
|
+
return raw.map((entry) => {
|
|
668
|
+
if (!isPlainObject(entry)) {
|
|
669
|
+
throw graphqlValidationError('graphql.orderBy', 'Each orderBy entry must be an object.');
|
|
670
|
+
}
|
|
671
|
+
const fieldName = entry.field;
|
|
672
|
+
const direction = entry.direction;
|
|
673
|
+
if (typeof fieldName !== 'string' || typeof direction !== 'string') {
|
|
674
|
+
throw graphqlValidationError('graphql.orderBy', 'Each orderBy entry must define field and direction.');
|
|
675
|
+
}
|
|
676
|
+
const field = fieldByPublicName(object, fieldName);
|
|
677
|
+
if (!field.sortable) {
|
|
678
|
+
throw graphqlValidationError('graphql.orderBy', `Field ${field.publicName} is not sortable.`);
|
|
679
|
+
}
|
|
680
|
+
return new sql_read_contract_1.SqlOrderByClause({
|
|
681
|
+
field: field.publicName,
|
|
682
|
+
direction: direction === 'DESC' ? sql_read_contract_1.SqlSortDirection.Desc : sql_read_contract_1.SqlSortDirection.Asc,
|
|
683
|
+
});
|
|
684
|
+
});
|
|
685
|
+
}
|
|
686
|
+
function parsePage(object, raw, options) {
|
|
687
|
+
const effectiveMax = Math.min(object.capabilities.pagination.maxLimit, options.maxLimit);
|
|
688
|
+
const effectiveDefault = Math.min(object.capabilities.pagination.defaultLimit, options.defaultLimit, effectiveMax);
|
|
689
|
+
if (raw == null) {
|
|
690
|
+
return new sql_read_contract_1.SqlPage({ limit: effectiveDefault, offset: 0 });
|
|
691
|
+
}
|
|
692
|
+
if (!isPlainObject(raw)) {
|
|
693
|
+
throw graphqlValidationError('graphql.page', 'GraphQL page input must be an object.');
|
|
694
|
+
}
|
|
695
|
+
const limit = typeof raw.limit === 'number' ? raw.limit : effectiveDefault;
|
|
696
|
+
const offset = typeof raw.offset === 'number' ? raw.offset : 0;
|
|
697
|
+
if (limit < 0 || offset < 0) {
|
|
698
|
+
throw graphqlValidationError('graphql.page', 'GraphQL page limit and offset must be non-negative.');
|
|
699
|
+
}
|
|
700
|
+
if (limit > effectiveMax) {
|
|
701
|
+
throw graphqlValidationError('graphql.page', `Requested page limit ${limit} exceeds the effective max limit ${effectiveMax}.`);
|
|
702
|
+
}
|
|
703
|
+
return new sql_read_contract_1.SqlPage({ limit, offset });
|
|
704
|
+
}
|
|
705
|
+
function buildExecutionContext(context) {
|
|
706
|
+
return new sql_read_contract_1.ReadExecutionContext({
|
|
707
|
+
requestId: headerValue(context, 'x-request-id') ?? context.requestId,
|
|
708
|
+
tenantId: headerValue(context, 'x-tenant-id'),
|
|
709
|
+
principal: headerValue(context, 'x-principal'),
|
|
710
|
+
telemetry: context.logger,
|
|
711
|
+
});
|
|
712
|
+
}
|
|
713
|
+
function headerValue(context, name) {
|
|
714
|
+
const raw = Object.entries(context.headers).find(([key]) => key.toLowerCase() === name)?.[1];
|
|
715
|
+
if (typeof raw === 'string') {
|
|
716
|
+
return raw;
|
|
717
|
+
}
|
|
718
|
+
return Array.isArray(raw) ? raw[0] : undefined;
|
|
719
|
+
}
|
|
720
|
+
function groupRelationRows(options) {
|
|
721
|
+
const grouped = new Map();
|
|
722
|
+
for (const row of options.rowSet.rows) {
|
|
723
|
+
const key = relationKeyFromValues(Object.fromEntries(options.relation.targetFields.map((column) => {
|
|
724
|
+
const field = fieldByColumn(options.targetObject, column);
|
|
725
|
+
return [field.publicName, row[field.publicName]];
|
|
726
|
+
})));
|
|
727
|
+
const existing = grouped.get(key);
|
|
728
|
+
if (existing) {
|
|
729
|
+
grouped.set(key, [...existing, row]);
|
|
730
|
+
}
|
|
731
|
+
else {
|
|
732
|
+
grouped.set(key, [row]);
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
return grouped;
|
|
736
|
+
}
|
|
737
|
+
function relationParentValues(options) {
|
|
738
|
+
const values = {};
|
|
739
|
+
for (const column of options.relation.sourceFields) {
|
|
740
|
+
const publicName = fieldByColumn(options.sourceObject, column).publicName;
|
|
741
|
+
values[publicName] = options.parent[publicName];
|
|
742
|
+
}
|
|
743
|
+
return values;
|
|
744
|
+
}
|
|
745
|
+
function relationKeyFromValues(values) {
|
|
746
|
+
return JSON.stringify(Object.keys(values)
|
|
747
|
+
.sort((left, right) => left.localeCompare(right))
|
|
748
|
+
.map((key) => [key, values[key] ?? null]));
|
|
749
|
+
}
|
|
750
|
+
function extractTotalCount(rowSet) {
|
|
751
|
+
if (rowSet.rows.length === 0) {
|
|
752
|
+
return 0;
|
|
753
|
+
}
|
|
754
|
+
const value = rowSet.rows[0]?.totalCount;
|
|
755
|
+
if (typeof value === 'number') {
|
|
756
|
+
return value;
|
|
757
|
+
}
|
|
758
|
+
throw new Error(`Expected totalCount to be numeric, got ${String(value)}.`);
|
|
759
|
+
}
|
|
760
|
+
function fieldByColumn(object, column) {
|
|
761
|
+
const field = object.fields.find((candidate) => candidate.column === column);
|
|
762
|
+
if (!field) {
|
|
763
|
+
throw new Error(`Unknown source column ${column} for ${object.id}.`);
|
|
764
|
+
}
|
|
765
|
+
return field;
|
|
766
|
+
}
|
|
767
|
+
function fieldByPublicName(object, publicName) {
|
|
768
|
+
const field = object.fields.find((candidate) => candidate.publicName === publicName);
|
|
769
|
+
if (!field) {
|
|
770
|
+
throw new Error(`Unknown public field ${publicName} for ${object.id}.`);
|
|
771
|
+
}
|
|
772
|
+
return field;
|
|
773
|
+
}
|
|
774
|
+
function objectById(catalog, objectId) {
|
|
775
|
+
const object = catalog.objects.find((candidate) => candidate.id === objectId);
|
|
776
|
+
if (!object) {
|
|
777
|
+
throw new Error(`Unknown catalog object ${objectId}.`);
|
|
778
|
+
}
|
|
779
|
+
return object;
|
|
780
|
+
}
|
|
781
|
+
function readQuery(context) {
|
|
782
|
+
if (isPlainObject(context.body) && typeof context.body.query === 'string') {
|
|
783
|
+
return context.body.query;
|
|
784
|
+
}
|
|
785
|
+
const query = context.query.query;
|
|
786
|
+
return typeof query === 'string' ? query : undefined;
|
|
787
|
+
}
|
|
788
|
+
function readOperationName(body) {
|
|
789
|
+
return isPlainObject(body) && typeof body.operationName === 'string' ? body.operationName : undefined;
|
|
790
|
+
}
|
|
791
|
+
function readVariables(body) {
|
|
792
|
+
return isPlainObject(body) && isPlainObject(body.variables) ? { ...body.variables } : undefined;
|
|
793
|
+
}
|
|
794
|
+
function computeDocumentDepth(document) {
|
|
795
|
+
const fragments = collectFragments(document);
|
|
796
|
+
const visitedFragments = new Set();
|
|
797
|
+
let maxDepth = 0;
|
|
798
|
+
for (const definition of document.definitions) {
|
|
799
|
+
if (definition.kind !== graphql_1.Kind.OPERATION_DEFINITION) {
|
|
800
|
+
continue;
|
|
801
|
+
}
|
|
802
|
+
maxDepth = Math.max(maxDepth, selectionSetDepth(definition.selectionSet, fragments, visitedFragments, 0));
|
|
803
|
+
}
|
|
804
|
+
return maxDepth;
|
|
805
|
+
}
|
|
806
|
+
function selectionSetDepth(selectionSet, fragments, visitedFragments, currentDepth) {
|
|
807
|
+
let maxDepth = currentDepth;
|
|
808
|
+
for (const selection of selectionSet.selections) {
|
|
809
|
+
switch (selection.kind) {
|
|
810
|
+
case graphql_1.Kind.FIELD: {
|
|
811
|
+
const nextDepth = currentDepth + 1;
|
|
812
|
+
maxDepth = Math.max(maxDepth, nextDepth);
|
|
813
|
+
if (selection.selectionSet) {
|
|
814
|
+
maxDepth = Math.max(maxDepth, selectionSetDepth(selection.selectionSet, fragments, visitedFragments, nextDepth));
|
|
815
|
+
}
|
|
816
|
+
break;
|
|
817
|
+
}
|
|
818
|
+
case graphql_1.Kind.INLINE_FRAGMENT:
|
|
819
|
+
maxDepth = Math.max(maxDepth, selectionSetDepth(selection.selectionSet, fragments, visitedFragments, currentDepth));
|
|
820
|
+
break;
|
|
821
|
+
case graphql_1.Kind.FRAGMENT_SPREAD: {
|
|
822
|
+
if (visitedFragments.has(selection.name.value)) {
|
|
823
|
+
break;
|
|
824
|
+
}
|
|
825
|
+
visitedFragments.add(selection.name.value);
|
|
826
|
+
const fragment = fragments[selection.name.value];
|
|
827
|
+
if (fragment) {
|
|
828
|
+
maxDepth = Math.max(maxDepth, selectionSetDepth(fragment.selectionSet, fragments, visitedFragments, currentDepth));
|
|
829
|
+
}
|
|
830
|
+
break;
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
return maxDepth;
|
|
835
|
+
}
|
|
836
|
+
function computeDocumentComplexity(document) {
|
|
837
|
+
const fragments = collectFragments(document);
|
|
838
|
+
const visitedFragments = new Set();
|
|
839
|
+
let complexity = 0;
|
|
840
|
+
for (const definition of document.definitions) {
|
|
841
|
+
if (definition.kind !== graphql_1.Kind.OPERATION_DEFINITION) {
|
|
842
|
+
continue;
|
|
843
|
+
}
|
|
844
|
+
complexity += selectionSetComplexity(definition.selectionSet, fragments, visitedFragments, 1);
|
|
845
|
+
}
|
|
846
|
+
return complexity;
|
|
847
|
+
}
|
|
848
|
+
function selectionSetComplexity(selectionSet, fragments, visitedFragments, currentDepth) {
|
|
849
|
+
let complexity = 0;
|
|
850
|
+
for (const selection of selectionSet.selections) {
|
|
851
|
+
switch (selection.kind) {
|
|
852
|
+
case graphql_1.Kind.FIELD:
|
|
853
|
+
complexity += currentDepth;
|
|
854
|
+
if (selection.selectionSet) {
|
|
855
|
+
complexity += selectionSetComplexity(selection.selectionSet, fragments, visitedFragments, currentDepth + 1);
|
|
856
|
+
}
|
|
857
|
+
break;
|
|
858
|
+
case graphql_1.Kind.INLINE_FRAGMENT:
|
|
859
|
+
complexity += selectionSetComplexity(selection.selectionSet, fragments, visitedFragments, currentDepth);
|
|
860
|
+
break;
|
|
861
|
+
case graphql_1.Kind.FRAGMENT_SPREAD: {
|
|
862
|
+
if (visitedFragments.has(selection.name.value)) {
|
|
863
|
+
break;
|
|
864
|
+
}
|
|
865
|
+
visitedFragments.add(selection.name.value);
|
|
866
|
+
const fragment = fragments[selection.name.value];
|
|
867
|
+
if (fragment) {
|
|
868
|
+
complexity += selectionSetComplexity(fragment.selectionSet, fragments, visitedFragments, currentDepth);
|
|
869
|
+
}
|
|
870
|
+
break;
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
return complexity;
|
|
875
|
+
}
|
|
876
|
+
function collectFragments(document) {
|
|
877
|
+
const fragments = {};
|
|
878
|
+
for (const definition of document.definitions) {
|
|
879
|
+
if (definition.kind === graphql_1.Kind.FRAGMENT_DEFINITION) {
|
|
880
|
+
fragments[definition.name.value] = definition;
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
return fragments;
|
|
884
|
+
}
|
|
885
|
+
function graphqlOkResponse(body) {
|
|
886
|
+
return {
|
|
887
|
+
status: 200,
|
|
888
|
+
contentType: GRAPHQL_JSON_CONTENT_TYPE,
|
|
889
|
+
body,
|
|
890
|
+
};
|
|
891
|
+
}
|
|
892
|
+
function validationError(message, code) {
|
|
893
|
+
return {
|
|
894
|
+
message,
|
|
895
|
+
extensions: {
|
|
896
|
+
validationError: {
|
|
897
|
+
code,
|
|
898
|
+
},
|
|
899
|
+
},
|
|
900
|
+
};
|
|
901
|
+
}
|
|
902
|
+
function formatGraphqlError(error) {
|
|
903
|
+
if (error instanceof graphql_1.GraphQLError) {
|
|
904
|
+
const formatted = error.toJSON();
|
|
905
|
+
return {
|
|
906
|
+
...formatted,
|
|
907
|
+
...(formatted.extensions ? { extensions: { ...formatted.extensions } } : {}),
|
|
908
|
+
};
|
|
909
|
+
}
|
|
910
|
+
if (error instanceof Error) {
|
|
911
|
+
return { message: error.message };
|
|
912
|
+
}
|
|
913
|
+
return { message: String(error) };
|
|
914
|
+
}
|
|
915
|
+
function graphqlValidationError(code, message) {
|
|
916
|
+
return new graphql_1.GraphQLError(message, { extensions: { code } });
|
|
917
|
+
}
|
|
918
|
+
function validateGeneratedSdl(sdl) {
|
|
919
|
+
if (!sdl.trim()) {
|
|
920
|
+
throw new Error('GraphQL schema generation failed: Generated SDL must not be empty.');
|
|
921
|
+
}
|
|
922
|
+
if (!/type\s+Query\s*\{/.test(sdl)) {
|
|
923
|
+
throw new Error('GraphQL schema generation failed: Generated SDL must declare a Query root type.');
|
|
924
|
+
}
|
|
925
|
+
let depth = 0;
|
|
926
|
+
for (const char of sdl) {
|
|
927
|
+
if (char === '{') {
|
|
928
|
+
depth += 1;
|
|
929
|
+
}
|
|
930
|
+
else if (char === '}') {
|
|
931
|
+
depth -= 1;
|
|
932
|
+
if (depth < 0) {
|
|
933
|
+
throw new Error('GraphQL schema generation failed: Generated SDL has unmatched closing brace.');
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
if (depth !== 0) {
|
|
938
|
+
throw new Error('GraphQL schema generation failed: Generated SDL has unmatched opening brace.');
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
function isReadExecutor(value) {
|
|
942
|
+
return !!value && typeof value === 'object' && typeof value.execute === 'function';
|
|
943
|
+
}
|
|
944
|
+
function isPlainObject(value) {
|
|
945
|
+
return !!value && typeof value === 'object' && !Array.isArray(value);
|
|
946
|
+
}
|