@cosmneo/onion-lasagna 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/{chunk-XWKHOLIP.js → chunk-4HMXTGHK.js} +2 -2
  2. package/dist/chunk-4RFWJ5XZ.js +192 -0
  3. package/dist/chunk-4RFWJ5XZ.js.map +1 -0
  4. package/dist/{chunk-4BVOLXDJ.js → chunk-4YBAV6LZ.js} +2 -2
  5. package/dist/chunk-ANLXZHUS.js +230 -0
  6. package/dist/chunk-ANLXZHUS.js.map +1 -0
  7. package/dist/chunk-BG2FY27M.js +36 -0
  8. package/dist/chunk-BG2FY27M.js.map +1 -0
  9. package/dist/chunk-FEY2GSVT.js +1 -0
  10. package/dist/chunk-FEY2GSVT.js.map +1 -0
  11. package/dist/{chunk-2BVCU32G.js → chunk-HNEAH6OZ.js} +121 -2
  12. package/dist/chunk-HNEAH6OZ.js.map +1 -0
  13. package/dist/chunk-NQMFWI6Q.js +1 -0
  14. package/dist/chunk-NQMFWI6Q.js.map +1 -0
  15. package/dist/chunk-TZRBETT3.js +127 -0
  16. package/dist/chunk-TZRBETT3.js.map +1 -0
  17. package/dist/{chunk-MF2JDREK.js → chunk-UNVB4INM.js} +1 -1
  18. package/dist/{chunk-MF2JDREK.js.map → chunk-UNVB4INM.js.map} +1 -1
  19. package/dist/chunk-VBG3UYQR.js +119 -0
  20. package/dist/chunk-VBG3UYQR.js.map +1 -0
  21. package/dist/events/index.js +3 -4
  22. package/dist/events/server/index.js +3 -4
  23. package/dist/events/shared/index.js +2 -3
  24. package/dist/graphql/field/index.cjs +189 -0
  25. package/dist/graphql/field/index.cjs.map +1 -0
  26. package/dist/graphql/field/index.d.cts +214 -0
  27. package/dist/graphql/field/index.d.ts +214 -0
  28. package/dist/graphql/field/index.js +25 -0
  29. package/dist/graphql/field/index.js.map +1 -0
  30. package/dist/graphql/index.cjs +1148 -0
  31. package/dist/graphql/index.cjs.map +1 -0
  32. package/dist/graphql/index.d.cts +8 -0
  33. package/dist/graphql/index.d.ts +8 -0
  34. package/dist/graphql/index.js +49 -0
  35. package/dist/graphql/index.js.map +1 -0
  36. package/dist/graphql/sdl/index.cjs +241 -0
  37. package/dist/graphql/sdl/index.cjs.map +1 -0
  38. package/dist/graphql/sdl/index.d.cts +77 -0
  39. package/dist/graphql/sdl/index.d.ts +77 -0
  40. package/dist/graphql/sdl/index.js +8 -0
  41. package/dist/graphql/sdl/index.js.map +1 -0
  42. package/dist/graphql/server/index.cjs +505 -0
  43. package/dist/graphql/server/index.cjs.map +1 -0
  44. package/dist/graphql/server/index.d.cts +268 -0
  45. package/dist/graphql/server/index.d.ts +268 -0
  46. package/dist/graphql/server/index.js +15 -0
  47. package/dist/graphql/server/index.js.map +1 -0
  48. package/dist/graphql/shared/index.cjs +586 -0
  49. package/dist/graphql/shared/index.cjs.map +1 -0
  50. package/dist/graphql/shared/index.d.cts +82 -0
  51. package/dist/graphql/shared/index.d.ts +82 -0
  52. package/dist/graphql/shared/index.js +16 -0
  53. package/dist/graphql/shared/index.js.map +1 -0
  54. package/dist/http/index.cjs.map +1 -1
  55. package/dist/http/index.js +2 -3
  56. package/dist/http/route/index.cjs.map +1 -1
  57. package/dist/http/route/index.d.cts +4 -0
  58. package/dist/http/route/index.d.ts +4 -0
  59. package/dist/http/route/index.js +1 -1
  60. package/dist/http/shared/index.js +1 -2
  61. package/dist/index.cjs +672 -0
  62. package/dist/index.cjs.map +1 -1
  63. package/dist/index.d.cts +8 -0
  64. package/dist/index.d.ts +8 -0
  65. package/dist/index.js +43 -1
  66. package/dist/index.js.map +1 -1
  67. package/dist/schema-definition.type-C9PntBVc.d.cts +166 -0
  68. package/dist/schema-definition.type-CuhQLDr0.d.ts +166 -0
  69. package/package.json +31 -1
  70. package/dist/chunk-2BVCU32G.js.map +0 -1
  71. package/dist/chunk-H5TNDC5U.js +0 -138
  72. package/dist/chunk-H5TNDC5U.js.map +0 -1
  73. /package/dist/{chunk-XWKHOLIP.js.map → chunk-4HMXTGHK.js.map} +0 -0
  74. /package/dist/{chunk-4BVOLXDJ.js.map → chunk-4YBAV6LZ.js.map} +0 -0
@@ -0,0 +1,505 @@
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
+
20
+ // src/presentation/graphql/server/index.ts
21
+ var server_exports = {};
22
+ __export(server_exports, {
23
+ graphqlRoutes: () => graphqlRoutes,
24
+ isSimpleGraphQLHandlerConfig: () => isSimpleGraphQLHandlerConfig
25
+ });
26
+ module.exports = __toCommonJS(server_exports);
27
+
28
+ // src/presentation/graphql/field/types/schema-definition.type.ts
29
+ function isFieldDefinition(value) {
30
+ return typeof value === "object" && value !== null && "_isGraphQLField" in value && value._isGraphQLField === true;
31
+ }
32
+ function isSchemaDefinition(value) {
33
+ return typeof value === "object" && value !== null && "_isGraphQLSchema" in value && value._isGraphQLSchema === true;
34
+ }
35
+ function collectFields(config, basePath = "") {
36
+ const fields = [];
37
+ for (const [key, value] of Object.entries(config)) {
38
+ const fullKey = basePath ? `${basePath}.${key}` : key;
39
+ if (isFieldDefinition(value)) {
40
+ fields.push({ key: fullKey, field: value });
41
+ } else if (isSchemaDefinition(value)) {
42
+ fields.push(...collectFields(value.fields, fullKey));
43
+ } else if (typeof value === "object" && value !== null) {
44
+ fields.push(...collectFields(value, fullKey));
45
+ }
46
+ }
47
+ return fields;
48
+ }
49
+
50
+ // src/presentation/graphql/field/utils.ts
51
+ function generateFieldId(key) {
52
+ return key.split(".").map(
53
+ (segment, index) => index === 0 ? segment : segment.charAt(0).toUpperCase() + segment.slice(1)
54
+ ).join("");
55
+ }
56
+
57
+ // src/global/exceptions/coded-error.error.ts
58
+ var CodedError = class extends Error {
59
+ /** Machine-readable error code for programmatic handling. */
60
+ code;
61
+ /**
62
+ * Creates a new CodedError instance.
63
+ *
64
+ * @param options - Error configuration
65
+ * @param options.message - Human-readable error message
66
+ * @param options.code - Machine-readable error code from ErrorCodes registry or custom string
67
+ * @param options.cause - Optional underlying error that caused this error
68
+ */
69
+ constructor({
70
+ message,
71
+ code,
72
+ cause
73
+ }) {
74
+ super(message);
75
+ this.name = this.constructor.name;
76
+ this.code = code;
77
+ if (cause !== void 0) {
78
+ Object.defineProperty(this, "cause", {
79
+ value: cause,
80
+ writable: false,
81
+ enumerable: false,
82
+ configurable: true
83
+ });
84
+ }
85
+ }
86
+ /**
87
+ * Factory method to create a typed error from a caught error.
88
+ *
89
+ * Subclasses should override this to provide proper error transformation.
90
+ * Designed for use with {@link wrapErrorAsync} and {@link wrapError}.
91
+ *
92
+ * @param _cause - The original caught error
93
+ * @returns A new CodedError instance
94
+ * @throws {Error} If not overridden by subclass
95
+ *
96
+ * @example
97
+ * ```typescript
98
+ * class NotFoundError extends UseCaseError {
99
+ * static override fromError(cause: unknown): NotFoundError {
100
+ * return new NotFoundError({
101
+ * message: 'Resource not found',
102
+ * cause,
103
+ * });
104
+ * }
105
+ * }
106
+ * ```
107
+ */
108
+ static fromError(_cause) {
109
+ throw new Error(`${this.name}.fromError() must be implemented by subclass`);
110
+ }
111
+ };
112
+
113
+ // src/global/exceptions/error-codes.const.ts
114
+ var ErrorCodes = {
115
+ /**
116
+ * Domain layer error codes.
117
+ * Used for business rule violations and invariant failures.
118
+ */
119
+ Domain: {
120
+ /** Generic domain error */
121
+ DOMAIN_ERROR: "DOMAIN_ERROR",
122
+ /** Business invariant was violated */
123
+ INVARIANT_VIOLATION: "INVARIANT_VIOLATION",
124
+ /** Aggregate was partially loaded (missing required relations) */
125
+ PARTIAL_LOAD: "PARTIAL_LOAD"
126
+ },
127
+ /**
128
+ * Application layer (use case) error codes.
129
+ * Used for orchestration failures and business operation errors.
130
+ */
131
+ App: {
132
+ /** Generic use case error */
133
+ USE_CASE_ERROR: "USE_CASE_ERROR",
134
+ /** Requested resource was not found */
135
+ NOT_FOUND: "NOT_FOUND",
136
+ /** Resource state conflict (e.g., duplicate, already exists) */
137
+ CONFLICT: "CONFLICT",
138
+ /** Request is valid but cannot be processed due to business rules */
139
+ UNPROCESSABLE: "UNPROCESSABLE",
140
+ /** Authorization denied - user lacks permission for this operation */
141
+ FORBIDDEN: "FORBIDDEN",
142
+ /** Authentication required or invalid - user is not authenticated */
143
+ UNAUTHORIZED: "UNAUTHORIZED"
144
+ },
145
+ /**
146
+ * Infrastructure layer error codes.
147
+ * Used for data access, external services, and I/O failures.
148
+ */
149
+ Infra: {
150
+ /** Generic infrastructure error */
151
+ INFRA_ERROR: "INFRA_ERROR",
152
+ /** Database operation failed */
153
+ DB_ERROR: "DB_ERROR",
154
+ /** Network connectivity or communication error */
155
+ NETWORK_ERROR: "NETWORK_ERROR",
156
+ /** Operation timed out */
157
+ TIMEOUT_ERROR: "TIMEOUT_ERROR",
158
+ /** External/third-party service error */
159
+ EXTERNAL_SERVICE_ERROR: "EXTERNAL_SERVICE_ERROR"
160
+ },
161
+ /**
162
+ * Presentation layer error codes.
163
+ * Used for controller, request handling, and authorization errors.
164
+ */
165
+ Presentation: {
166
+ /** Generic controller error */
167
+ CONTROLLER_ERROR: "CONTROLLER_ERROR",
168
+ /** Request denied due to authorization failure */
169
+ ACCESS_DENIED: "ACCESS_DENIED",
170
+ /** Request validation failed (malformed input) */
171
+ INVALID_REQUEST: "INVALID_REQUEST"
172
+ },
173
+ /**
174
+ * Global/cross-cutting error codes.
175
+ * Used for validation and other cross-layer concerns.
176
+ */
177
+ Global: {
178
+ /** Object/schema validation failed */
179
+ OBJECT_VALIDATION_ERROR: "OBJECT_VALIDATION_ERROR"
180
+ }
181
+ };
182
+
183
+ // src/global/exceptions/object-validation.error.ts
184
+ var ObjectValidationError = class _ObjectValidationError extends CodedError {
185
+ /**
186
+ * Array of field-level validation errors.
187
+ *
188
+ * Each entry contains:
189
+ * - `field`: Dot-notation path to the invalid field (e.g., 'user.email')
190
+ * - `message`: Human-readable validation failure message
191
+ */
192
+ validationErrors;
193
+ /**
194
+ * Creates a new ObjectValidationError instance.
195
+ *
196
+ * @param options - Error configuration
197
+ * @param options.message - Human-readable summary message
198
+ * @param options.code - Machine-readable error code (default: 'OBJECT_VALIDATION_ERROR')
199
+ * @param options.cause - Optional underlying error from validation library
200
+ * @param options.validationErrors - Array of field-level validation errors
201
+ */
202
+ constructor({
203
+ message,
204
+ code = ErrorCodes.Global.OBJECT_VALIDATION_ERROR,
205
+ cause,
206
+ validationErrors
207
+ }) {
208
+ super({ message, code, cause });
209
+ this.validationErrors = validationErrors;
210
+ }
211
+ /**
212
+ * Creates an ObjectValidationError from a caught error.
213
+ *
214
+ * @param cause - The original caught error
215
+ * @returns A new ObjectValidationError instance with the cause attached
216
+ */
217
+ static fromError(cause) {
218
+ return new _ObjectValidationError({
219
+ message: cause instanceof Error ? cause.message : "Validation failed",
220
+ cause,
221
+ validationErrors: []
222
+ });
223
+ }
224
+ };
225
+
226
+ // src/app/exceptions/use-case.error.ts
227
+ var UseCaseError = class _UseCaseError extends CodedError {
228
+ /**
229
+ * Creates a new UseCaseError instance.
230
+ *
231
+ * @param options - Error configuration
232
+ * @param options.message - Human-readable error description
233
+ * @param options.code - Machine-readable error code (default: 'USE_CASE_ERROR')
234
+ * @param options.cause - Optional underlying error
235
+ */
236
+ constructor({
237
+ message,
238
+ code = ErrorCodes.App.USE_CASE_ERROR,
239
+ cause
240
+ }) {
241
+ super({ message, code, cause });
242
+ }
243
+ /**
244
+ * Creates a UseCaseError from a caught error.
245
+ *
246
+ * @param cause - The original caught error
247
+ * @returns A new UseCaseError instance with the cause attached
248
+ */
249
+ static fromError(cause) {
250
+ return new _UseCaseError({
251
+ message: cause instanceof Error ? cause.message : "Use case error",
252
+ cause
253
+ });
254
+ }
255
+ };
256
+
257
+ // src/app/exceptions/unauthorized.error.ts
258
+ var UnauthorizedError = class _UnauthorizedError extends UseCaseError {
259
+ /**
260
+ * Creates a new UnauthorizedError instance.
261
+ *
262
+ * @param options - Error configuration
263
+ * @param options.message - Description of why authentication failed
264
+ * @param options.code - Machine-readable error code (default: 'UNAUTHORIZED')
265
+ * @param options.cause - Optional underlying error
266
+ */
267
+ constructor({
268
+ message,
269
+ code = ErrorCodes.App.UNAUTHORIZED,
270
+ cause
271
+ }) {
272
+ super({ message, code, cause });
273
+ }
274
+ /**
275
+ * Creates an UnauthorizedError from a caught error.
276
+ *
277
+ * @param cause - The original caught error
278
+ * @returns A new UnauthorizedError instance with the cause attached
279
+ */
280
+ static fromError(cause) {
281
+ return new _UnauthorizedError({
282
+ message: cause instanceof Error ? cause.message : "Authentication required",
283
+ cause
284
+ });
285
+ }
286
+ };
287
+
288
+ // src/presentation/graphql/server/types.ts
289
+ function isSimpleGraphQLHandlerConfig(config) {
290
+ return "handler" in config && typeof config.handler === "function";
291
+ }
292
+
293
+ // src/presentation/graphql/server/create-graphql-routes.ts
294
+ function createGraphQLRoutesInternal(schema, handlers, options) {
295
+ const config = isSchemaDefinition(schema) ? schema.fields : schema;
296
+ const collectedFields = collectFields(config);
297
+ const result = [];
298
+ const resolvedOptions = {
299
+ ...options,
300
+ validateInput: options?.validateInput ?? true,
301
+ validateOutput: options?.validateOutput ?? true,
302
+ allowPartial: options?.allowPartial ?? false
303
+ };
304
+ for (const { key, field } of collectedFields) {
305
+ const handlerConfig = handlers[key];
306
+ if (!handlerConfig) {
307
+ if (resolvedOptions.allowPartial) {
308
+ continue;
309
+ }
310
+ throw new Error(
311
+ `Missing handler for field "${key}". All fields must have a handler configuration.`
312
+ );
313
+ }
314
+ result.push(createFieldHandler(key, field, handlerConfig, resolvedOptions));
315
+ }
316
+ return result;
317
+ }
318
+ function createFieldHandler(key, field, config, options) {
319
+ const middleware = config.middleware ?? [];
320
+ const globalMiddleware = options?.middleware ?? [];
321
+ const allMiddleware = [...globalMiddleware, ...middleware];
322
+ const shouldValidateInput = options.validateInput ?? true;
323
+ const shouldValidateOutput = options.validateOutput ?? true;
324
+ return {
325
+ key,
326
+ operation: field.operation,
327
+ metadata: {
328
+ fieldId: generateFieldId(key),
329
+ description: field.docs.description,
330
+ tags: field.docs.tags,
331
+ deprecated: field.docs.deprecated,
332
+ deprecationReason: field.docs.deprecationReason
333
+ },
334
+ handler: async (rawArgs, rawContext) => {
335
+ const context = options?.createContext ? options.createContext(rawContext) : rawContext ?? { requestId: generateRequestId() };
336
+ let validatedContext = context;
337
+ if (field.context) {
338
+ const contextResult = validateContextData(field, context);
339
+ if (!contextResult.success) {
340
+ throw new UnauthorizedError({
341
+ message: "Authentication required"
342
+ });
343
+ }
344
+ validatedContext = contextResult.data;
345
+ }
346
+ let validatedInput = rawArgs;
347
+ if (shouldValidateInput && field.input) {
348
+ const inputResult = validateInputData(field, rawArgs);
349
+ if (!inputResult.success) {
350
+ const errors = inputResult.errors ?? [];
351
+ throw new ObjectValidationError({
352
+ message: "Input validation failed",
353
+ validationErrors: errors.map((e) => ({
354
+ field: e.path.join("."),
355
+ message: e.message
356
+ }))
357
+ });
358
+ }
359
+ validatedInput = inputResult.data;
360
+ }
361
+ const validatedArgs = {
362
+ input: validatedInput,
363
+ raw: rawArgs
364
+ };
365
+ const executePipeline = async () => {
366
+ if (isSimpleGraphQLHandlerConfig(config)) {
367
+ return config.handler(
368
+ validatedArgs,
369
+ validatedContext
370
+ );
371
+ } else {
372
+ const { argsMapper, useCase, responseMapper } = config;
373
+ const input = argsMapper(
374
+ validatedArgs,
375
+ validatedContext
376
+ );
377
+ const output = await useCase.execute(input);
378
+ return responseMapper(output);
379
+ }
380
+ };
381
+ let result;
382
+ if (allMiddleware.length === 0) {
383
+ result = await executePipeline();
384
+ } else {
385
+ let index = 0;
386
+ let called = false;
387
+ const next = async () => {
388
+ if (index >= allMiddleware.length) {
389
+ if (called) throw new Error("next() called after pipeline already executed");
390
+ called = true;
391
+ return executePipeline();
392
+ }
393
+ const currentIndex = index++;
394
+ const mw = allMiddleware[currentIndex];
395
+ return mw(rawArgs, context, next);
396
+ };
397
+ result = await next();
398
+ }
399
+ if (shouldValidateOutput && field.output) {
400
+ const outputResult = validateOutputData(field, result);
401
+ if (!outputResult.success) {
402
+ const details = outputResult.errors?.map((e) => `${e.path.join(".")}: ${e.message}`).join("; ");
403
+ throw new ObjectValidationError({
404
+ message: `Output validation failed for field "${key}": ${details}`,
405
+ validationErrors: (outputResult.errors ?? []).map((e) => ({
406
+ field: e.path.join("."),
407
+ message: e.message
408
+ }))
409
+ });
410
+ }
411
+ }
412
+ return result;
413
+ }
414
+ };
415
+ }
416
+ function validateInputData(field, args) {
417
+ const schema = field.input;
418
+ if (!schema) return { success: true, data: args };
419
+ const result = schema.validate(args);
420
+ if (result.success) {
421
+ return { success: true, data: result.data };
422
+ }
423
+ const errors = result.issues.map((issue) => ({
424
+ ...issue,
425
+ path: ["input", ...issue.path]
426
+ }));
427
+ return { success: false, errors };
428
+ }
429
+ function validateOutputData(field, data) {
430
+ const schema = field.output;
431
+ if (!schema) return { success: true, data };
432
+ const result = schema.validate(data);
433
+ if (result.success) {
434
+ return { success: true, data: result.data };
435
+ }
436
+ const errors = result.issues.map((issue) => ({
437
+ ...issue,
438
+ path: ["output", ...issue.path]
439
+ }));
440
+ return { success: false, errors };
441
+ }
442
+ function validateContextData(field, context) {
443
+ const schema = field.context;
444
+ if (!schema) return { success: true, data: context };
445
+ const result = schema.validate(context);
446
+ if (result.success) {
447
+ return { success: true, data: result.data };
448
+ }
449
+ const errors = result.issues.map((issue) => ({
450
+ ...issue,
451
+ path: ["context", ...issue.path]
452
+ }));
453
+ return { success: false, errors };
454
+ }
455
+ function generateRequestId() {
456
+ return `gql_${crypto.randomUUID()}`;
457
+ }
458
+
459
+ // src/presentation/graphql/server/graphql-routes-builder.ts
460
+ var GraphQLRoutesBuilderImpl = class _GraphQLRoutesBuilderImpl {
461
+ schema;
462
+ handlers;
463
+ constructor(schema, handlers) {
464
+ this.schema = schema;
465
+ this.handlers = handlers ?? /* @__PURE__ */ new Map();
466
+ }
467
+ handle(key, handlerOrConfig) {
468
+ const config = typeof handlerOrConfig === "function" ? { handler: handlerOrConfig } : handlerOrConfig;
469
+ const newHandlers = new Map(this.handlers);
470
+ newHandlers.set(key, config);
471
+ return new _GraphQLRoutesBuilderImpl(
472
+ this.schema,
473
+ newHandlers
474
+ );
475
+ }
476
+ handleWithUseCase(key, config) {
477
+ const newHandlers = new Map(this.handlers);
478
+ newHandlers.set(
479
+ key,
480
+ config
481
+ );
482
+ return new _GraphQLRoutesBuilderImpl(
483
+ this.schema,
484
+ newHandlers
485
+ );
486
+ }
487
+ build(options) {
488
+ return createGraphQLRoutesInternal(this.schema, Object.fromEntries(this.handlers), options);
489
+ }
490
+ buildPartial(options) {
491
+ return createGraphQLRoutesInternal(this.schema, Object.fromEntries(this.handlers), {
492
+ ...options,
493
+ allowPartial: true
494
+ });
495
+ }
496
+ };
497
+ function graphqlRoutes(schema) {
498
+ return new GraphQLRoutesBuilderImpl(schema);
499
+ }
500
+ // Annotate the CommonJS export names for ESM import in node:
501
+ 0 && (module.exports = {
502
+ graphqlRoutes,
503
+ isSimpleGraphQLHandlerConfig
504
+ });
505
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/presentation/graphql/server/index.ts","../../../src/presentation/graphql/field/types/schema-definition.type.ts","../../../src/presentation/graphql/field/utils.ts","../../../src/global/exceptions/coded-error.error.ts","../../../src/global/exceptions/error-codes.const.ts","../../../src/global/exceptions/object-validation.error.ts","../../../src/app/exceptions/use-case.error.ts","../../../src/app/exceptions/unauthorized.error.ts","../../../src/presentation/graphql/server/types.ts","../../../src/presentation/graphql/server/create-graphql-routes.ts","../../../src/presentation/graphql/server/graphql-routes-builder.ts"],"sourcesContent":["export { graphqlRoutes } from './graphql-routes-builder';\nexport type {\n GraphQLRoutesBuilder,\n MissingHandlersError,\n BuilderGraphQLHandlerConfig,\n} from './graphql-routes-builder';\n\nexport type {\n ValidatedArgs,\n TypedGraphQLContext,\n GraphQLHandlerContext,\n GraphQLHandlerConfig,\n SimpleGraphQLHandlerFn,\n SimpleGraphQLSubscriptionFn,\n SimpleGraphQLHandlerConfig,\n AnyGraphQLHandlerConfig,\n GraphQLMiddlewareFunction,\n CreateGraphQLRoutesOptions,\n UnifiedGraphQLField,\n UseCasePort,\n} from './types';\n\nexport { isSimpleGraphQLHandlerConfig } from './types';\n","/**\n * @fileoverview GraphQL schema definition types for grouping fields.\n *\n * Mirrors the HTTP router definition pattern with hierarchical grouping,\n * dotted-key access, and deep merge support.\n *\n * @module graphql/field/types/schema-definition\n */\n\nimport type { GraphQLFieldDefinition, GraphQLOperationType } from './field-definition.type';\nimport type { SchemaAdapter } from '../../../http/schema/types';\n\n// ============================================================================\n// Schema Types\n// ============================================================================\n\n/**\n * A schema entry can be a field definition, a nested config, or a schema definition.\n */\nexport type GraphQLSchemaEntry =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | GraphQLFieldDefinition<GraphQLOperationType, any, any, any>\n | GraphQLSchemaConfig\n | GraphQLSchemaDefinition;\n\n/**\n * Configuration for a GraphQL schema (group of fields).\n */\nexport interface GraphQLSchemaConfig {\n readonly [key: string]: GraphQLSchemaEntry;\n}\n\n/**\n * Schema-level defaults applied to all child fields.\n */\nexport interface GraphQLSchemaDefaults {\n /** Default tags for all fields. Merged with field-specific tags. */\n readonly tags?: readonly string[];\n\n /** Default context schema. Applied to fields that don't define their own. */\n readonly context?: SchemaAdapter;\n}\n\n/**\n * A fully defined GraphQL schema.\n */\nexport interface GraphQLSchemaDefinition<T extends GraphQLSchemaConfig = GraphQLSchemaConfig> {\n /** The fields and nested groups in this schema. */\n readonly fields: T;\n\n /** Default values applied to all child fields. */\n readonly defaults?: GraphQLSchemaDefaults;\n\n /**\n * Marker to identify this as a GraphQL schema definition.\n * @internal\n */\n readonly _isGraphQLSchema: true;\n}\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\n/**\n * Checks if a value is a GraphQLFieldDefinition.\n */\nexport function isFieldDefinition(value: unknown): value is GraphQLFieldDefinition {\n return (\n typeof value === 'object' &&\n value !== null &&\n '_isGraphQLField' in value &&\n (value as GraphQLFieldDefinition)._isGraphQLField === true\n );\n}\n\n/**\n * Checks if a value is a GraphQLSchemaDefinition.\n */\nexport function isSchemaDefinition(value: unknown): value is GraphQLSchemaDefinition {\n return (\n typeof value === 'object' &&\n value !== null &&\n '_isGraphQLSchema' in value &&\n (value as GraphQLSchemaDefinition)._isGraphQLSchema === true\n );\n}\n\n// ============================================================================\n// Utility Types\n// ============================================================================\n\n/**\n * Flattens a schema into a map of dotted keys to field definitions.\n */\nexport type FlattenSchema<\n T extends GraphQLSchemaConfig,\n Prefix extends string = '',\n> = T extends GraphQLSchemaConfig\n ? {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [K in keyof T]: T[K] extends GraphQLFieldDefinition<any, any, any, any>\n ? { [P in `${Prefix}${K & string}`]: T[K] }\n : T[K] extends GraphQLSchemaConfig\n ? FlattenSchema<T[K], `${Prefix}${K & string}.`>\n : never;\n }[keyof T] extends infer U\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n U extends Record<string, GraphQLFieldDefinition<any, any, any, any>>\n ? U\n : never\n : never\n : never;\n\n/**\n * Gets all field keys from a schema.\n */\nexport type SchemaKeys<\n T extends GraphQLSchemaConfig,\n Prefix extends string = '',\n> = T extends GraphQLSchemaConfig\n ? {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [K in keyof T]: T[K] extends GraphQLFieldDefinition<any, any, any, any>\n ? `${Prefix}${K & string}`\n : T[K] extends GraphQLSchemaConfig\n ? SchemaKeys<T[K], `${Prefix}${K & string}.`>\n : never;\n }[keyof T]\n : never;\n\n/**\n * Gets a field by its dotted key path.\n */\nexport type GetField<\n T extends GraphQLSchemaConfig,\n K extends string,\n> = K extends `${infer Head}.${infer Tail}`\n ? Head extends keyof T\n ? T[Head] extends GraphQLSchemaConfig\n ? GetField<T[Head], Tail>\n : never\n : never\n : K extends keyof T\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n T[K] extends GraphQLFieldDefinition<any, any, any, any>\n ? T[K]\n : never\n : never;\n\n// ============================================================================\n// Deep Merge Types\n// ============================================================================\n\n/**\n * Deep-merges two schema configs at the type level.\n */\nexport type DeepMergeSchemas<A extends GraphQLSchemaConfig, B extends GraphQLSchemaConfig> = {\n readonly [K in keyof A | keyof B]: K extends keyof A\n ? K extends keyof B\n ? A[K] extends GraphQLSchemaConfig\n ? B[K] extends GraphQLSchemaConfig\n ? DeepMergeSchemas<A[K], B[K]>\n : B[K]\n : B[K]\n : A[K]\n : K extends keyof B\n ? B[K]\n : never;\n};\n\n/**\n * Recursively deep-merges N schema configs left-to-right.\n */\nexport type DeepMergeSchemasAll<T extends readonly GraphQLSchemaConfig[]> = T extends readonly [\n infer Only extends GraphQLSchemaConfig,\n]\n ? Only\n : T extends readonly [\n infer First extends GraphQLSchemaConfig,\n infer Second extends GraphQLSchemaConfig,\n ...infer Rest extends readonly GraphQLSchemaConfig[],\n ]\n ? DeepMergeSchemasAll<[DeepMergeSchemas<First, Second>, ...Rest]>\n : GraphQLSchemaConfig;\n\n// ============================================================================\n// Runtime Utilities\n// ============================================================================\n\n/**\n * Collects all fields from a schema into a flat array.\n */\nexport function collectFields(\n config: GraphQLSchemaConfig,\n basePath = '',\n): { key: string; field: GraphQLFieldDefinition }[] {\n const fields: { key: string; field: GraphQLFieldDefinition }[] = [];\n\n for (const [key, value] of Object.entries(config)) {\n const fullKey = basePath ? `${basePath}.${key}` : key;\n\n if (isFieldDefinition(value)) {\n fields.push({ key: fullKey, field: value });\n } else if (isSchemaDefinition(value)) {\n fields.push(...collectFields(value.fields, fullKey));\n } else if (typeof value === 'object' && value !== null) {\n fields.push(...collectFields(value as GraphQLSchemaConfig, fullKey));\n }\n }\n\n return fields;\n}\n","/**\n * @fileoverview GraphQL field utility functions.\n *\n * @module graphql/field/utils\n */\n\n/**\n * Generates a field ID from a schema key path.\n *\n * This is the **single source of truth** for the naming convention used across:\n * - SDL generation (`type Query { usersGet(...) }`)\n * - Yoga resolver map keys\n * - Client query string field names\n *\n * Converts dotted key paths to camelCase:\n * - `\"users.get\"` → `\"usersGet\"`\n * - `\"projects.members.list\"` → `\"projectsMembersList\"`\n * - `\"getUser\"` → `\"getUser\"` (single segment unchanged)\n *\n * @param key - The dotted schema key path\n * @returns A camelCase field ID string\n */\nexport function generateFieldId(key: string): string {\n return key\n .split('.')\n .map((segment, index) =>\n index === 0 ? segment : segment.charAt(0).toUpperCase() + segment.slice(1),\n )\n .join('');\n}\n","import type { ErrorCode } from './error-codes.const';\n\n/**\n * Base error class for all application errors with a machine-readable code.\n *\n * Abstract class that extends the native `Error` with:\n * - A `code` property for programmatic error handling\n * - Optional `cause` for error chaining (ES2022 compatible)\n * - A `fromError` static factory pattern for error transformation\n *\n * **Why abstract:** Prevents non-declarative error usage. All errors must\n * be explicitly defined as subclasses to ensure consistent error taxonomy.\n *\n * @example Subclass implementation\n * ```typescript\n * class DbError extends InfraError {\n * static override fromError(cause: unknown): DbError {\n * return new DbError({\n * message: cause instanceof Error ? cause.message : 'Database error',\n * cause,\n * });\n * }\n * }\n * ```\n *\n * @example Usage with wrapErrorAsync\n * ```typescript\n * await wrapErrorAsync(\n * () => this.db.query(...),\n * DbError.fromError,\n * );\n * ```\n */\nexport abstract class CodedError extends Error {\n /** Machine-readable error code for programmatic handling. */\n public readonly code: ErrorCode | string;\n\n /**\n * Creates a new CodedError instance.\n *\n * @param options - Error configuration\n * @param options.message - Human-readable error message\n * @param options.code - Machine-readable error code from ErrorCodes registry or custom string\n * @param options.cause - Optional underlying error that caused this error\n */\n constructor({\n message,\n code,\n cause,\n }: {\n message: string;\n code: ErrorCode | string;\n cause?: unknown;\n }) {\n super(message);\n this.name = this.constructor.name;\n this.code = code;\n if (cause !== undefined) {\n Object.defineProperty(this, 'cause', {\n value: cause,\n writable: false,\n enumerable: false,\n configurable: true,\n });\n }\n }\n\n /**\n * Factory method to create a typed error from a caught error.\n *\n * Subclasses should override this to provide proper error transformation.\n * Designed for use with {@link wrapErrorAsync} and {@link wrapError}.\n *\n * @param _cause - The original caught error\n * @returns A new CodedError instance\n * @throws {Error} If not overridden by subclass\n *\n * @example\n * ```typescript\n * class NotFoundError extends UseCaseError {\n * static override fromError(cause: unknown): NotFoundError {\n * return new NotFoundError({\n * message: 'Resource not found',\n * cause,\n * });\n * }\n * }\n * ```\n */\n static fromError(_cause: unknown): CodedError {\n throw new Error(`${this.name}.fromError() must be implemented by subclass`);\n }\n}\n","/**\n * Centralized registry of all error codes used across the application.\n *\n * Error codes are grouped by architectural layer to maintain clear boundaries\n * and make it easy to identify where an error originated.\n *\n * @example Using error codes in custom errors\n * ```typescript\n * import { ErrorCodes } from '@cosmneo/onion-lasagna/global';\n *\n * throw new NotFoundError({\n * message: 'User not found',\n * code: ErrorCodes.App.NOT_FOUND,\n * });\n * ```\n *\n * @example Checking error codes programmatically\n * ```typescript\n * if (error.code === ErrorCodes.App.NOT_FOUND) {\n * // Handle not found case\n * }\n * ```\n */\nexport const ErrorCodes = {\n /**\n * Domain layer error codes.\n * Used for business rule violations and invariant failures.\n */\n Domain: {\n /** Generic domain error */\n DOMAIN_ERROR: 'DOMAIN_ERROR',\n /** Business invariant was violated */\n INVARIANT_VIOLATION: 'INVARIANT_VIOLATION',\n /** Aggregate was partially loaded (missing required relations) */\n PARTIAL_LOAD: 'PARTIAL_LOAD',\n },\n\n /**\n * Application layer (use case) error codes.\n * Used for orchestration failures and business operation errors.\n */\n App: {\n /** Generic use case error */\n USE_CASE_ERROR: 'USE_CASE_ERROR',\n /** Requested resource was not found */\n NOT_FOUND: 'NOT_FOUND',\n /** Resource state conflict (e.g., duplicate, already exists) */\n CONFLICT: 'CONFLICT',\n /** Request is valid but cannot be processed due to business rules */\n UNPROCESSABLE: 'UNPROCESSABLE',\n /** Authorization denied - user lacks permission for this operation */\n FORBIDDEN: 'FORBIDDEN',\n /** Authentication required or invalid - user is not authenticated */\n UNAUTHORIZED: 'UNAUTHORIZED',\n },\n\n /**\n * Infrastructure layer error codes.\n * Used for data access, external services, and I/O failures.\n */\n Infra: {\n /** Generic infrastructure error */\n INFRA_ERROR: 'INFRA_ERROR',\n /** Database operation failed */\n DB_ERROR: 'DB_ERROR',\n /** Network connectivity or communication error */\n NETWORK_ERROR: 'NETWORK_ERROR',\n /** Operation timed out */\n TIMEOUT_ERROR: 'TIMEOUT_ERROR',\n /** External/third-party service error */\n EXTERNAL_SERVICE_ERROR: 'EXTERNAL_SERVICE_ERROR',\n },\n\n /**\n * Presentation layer error codes.\n * Used for controller, request handling, and authorization errors.\n */\n Presentation: {\n /** Generic controller error */\n CONTROLLER_ERROR: 'CONTROLLER_ERROR',\n /** Request denied due to authorization failure */\n ACCESS_DENIED: 'ACCESS_DENIED',\n /** Request validation failed (malformed input) */\n INVALID_REQUEST: 'INVALID_REQUEST',\n },\n\n /**\n * Global/cross-cutting error codes.\n * Used for validation and other cross-layer concerns.\n */\n Global: {\n /** Object/schema validation failed */\n OBJECT_VALIDATION_ERROR: 'OBJECT_VALIDATION_ERROR',\n },\n} as const;\n\n/**\n * Type representing all possible domain error codes.\n */\nexport type DomainErrorCode = (typeof ErrorCodes.Domain)[keyof typeof ErrorCodes.Domain];\n\n/**\n * Type representing all possible application error codes.\n */\nexport type AppErrorCode = (typeof ErrorCodes.App)[keyof typeof ErrorCodes.App];\n\n/**\n * Type representing all possible infrastructure error codes.\n */\nexport type InfraErrorCode = (typeof ErrorCodes.Infra)[keyof typeof ErrorCodes.Infra];\n\n/**\n * Type representing all possible presentation error codes.\n */\nexport type PresentationErrorCode =\n (typeof ErrorCodes.Presentation)[keyof typeof ErrorCodes.Presentation];\n\n/**\n * Type representing all possible global error codes.\n */\nexport type GlobalErrorCode = (typeof ErrorCodes.Global)[keyof typeof ErrorCodes.Global];\n\n/**\n * Union type of all error codes across all layers.\n *\n * Use this when you need to accept any valid error code.\n *\n * @example\n * ```typescript\n * function logError(code: ErrorCode, message: string) {\n * console.error(`[${code}] ${message}`);\n * }\n * ```\n */\nexport type ErrorCode =\n | DomainErrorCode\n | AppErrorCode\n | InfraErrorCode\n | PresentationErrorCode\n | GlobalErrorCode;\n","import { CodedError } from './coded-error.error';\nimport { ErrorCodes, type GlobalErrorCode } from './error-codes.const';\nimport type { ValidationError } from '../interfaces/types/validation-error.type';\n\n/**\n * Error thrown when object validation fails.\n *\n * Contains structured validation errors with field paths and messages,\n * making it easy to report specific validation failures to clients.\n * Thrown by all validator implementations (Zod, ArkType, TypeBox, Valibot).\n *\n * **Flow:**\n * 1. Validator throws `ObjectValidationError` with field-level errors\n * 2. Controller catches and converts to {@link InvalidRequestError}\n * 3. HTTP layer maps to 400 Bad Request with error details\n *\n * @example\n * ```typescript\n * try {\n * const dto = CreateUserDto.create(invalidData);\n * } catch (error) {\n * if (error instanceof ObjectValidationError) {\n * console.log(error.validationErrors);\n * // [\n * // { field: 'email', message: 'Invalid email format' },\n * // { field: 'age', message: 'Must be a positive number' }\n * // ]\n * }\n * }\n * ```\n */\nexport class ObjectValidationError extends CodedError {\n /**\n * Array of field-level validation errors.\n *\n * Each entry contains:\n * - `field`: Dot-notation path to the invalid field (e.g., 'user.email')\n * - `message`: Human-readable validation failure message\n */\n validationErrors: ValidationError[];\n\n /**\n * Creates a new ObjectValidationError instance.\n *\n * @param options - Error configuration\n * @param options.message - Human-readable summary message\n * @param options.code - Machine-readable error code (default: 'OBJECT_VALIDATION_ERROR')\n * @param options.cause - Optional underlying error from validation library\n * @param options.validationErrors - Array of field-level validation errors\n */\n constructor({\n message,\n code = ErrorCodes.Global.OBJECT_VALIDATION_ERROR,\n cause,\n validationErrors,\n }: {\n message: string;\n code?: GlobalErrorCode | string;\n cause?: unknown;\n validationErrors: ValidationError[];\n }) {\n super({ message, code, cause });\n this.validationErrors = validationErrors;\n }\n\n /**\n * Creates an ObjectValidationError from a caught error.\n *\n * @param cause - The original caught error\n * @returns A new ObjectValidationError instance with the cause attached\n */\n static override fromError(cause: unknown): ObjectValidationError {\n return new ObjectValidationError({\n message: cause instanceof Error ? cause.message : 'Validation failed',\n cause,\n validationErrors: [],\n });\n }\n}\n","import { CodedError } from '../../global/exceptions/coded-error.error';\nimport { ErrorCodes, type AppErrorCode } from '../../global/exceptions/error-codes.const';\n\n/**\n * Base error class for application layer (use case) failures.\n *\n * Use case errors represent failures in the application's business logic\n * orchestration, such as resource conflicts, missing entities, or\n * unprocessable requests. They bridge domain errors to the presentation layer.\n *\n * **When to throw:**\n * - Resource not found (e.g., \"User with ID X not found\")\n * - Conflict states (e.g., \"Email already registered\")\n * - Unprocessable business operations\n *\n * **Child classes:**\n * - {@link ConflictError} - Resource state conflicts (HTTP 409)\n * - {@link NotFoundError} - Resource not found (HTTP 404)\n * - {@link UnprocessableError} - Valid but unprocessable request (HTTP 422)\n *\n * @example\n * ```typescript\n * const user = await this.userRepo.findById(id);\n * if (!user) {\n * throw new NotFoundError({\n * message: `User with ID ${id} not found`,\n * code: 'USER_NOT_FOUND',\n * });\n * }\n * ```\n */\nexport class UseCaseError extends CodedError {\n /**\n * Creates a new UseCaseError instance.\n *\n * @param options - Error configuration\n * @param options.message - Human-readable error description\n * @param options.code - Machine-readable error code (default: 'USE_CASE_ERROR')\n * @param options.cause - Optional underlying error\n */\n constructor({\n message,\n code = ErrorCodes.App.USE_CASE_ERROR,\n cause,\n }: {\n message: string;\n code?: AppErrorCode | string;\n cause?: unknown;\n }) {\n super({ message, code, cause });\n }\n\n /**\n * Creates a UseCaseError from a caught error.\n *\n * @param cause - The original caught error\n * @returns A new UseCaseError instance with the cause attached\n */\n static override fromError(cause: unknown): UseCaseError {\n return new UseCaseError({\n message: cause instanceof Error ? cause.message : 'Use case error',\n cause,\n });\n }\n}\n","import { ErrorCodes, type AppErrorCode } from '../../global/exceptions/error-codes.const';\nimport { UseCaseError } from './use-case.error';\n\n/**\n * Error thrown when authentication is required or invalid.\n *\n * Indicates that the user is not authenticated or their authentication\n * credentials are invalid/expired. This is different from `ForbiddenError`\n * which is for authenticated users who lack permission.\n *\n * **When to throw:**\n * - User is not logged in but authentication is required\n * - Authentication token is missing, invalid, or expired\n * - Session has been invalidated\n * - API key is invalid or revoked\n *\n * **Difference from ForbiddenError:**\n * - `UnauthorizedError` (401) = Not authenticated (who are you?)\n * - `ForbiddenError` (403) = Authenticated but not authorized (you can't do this)\n *\n * @example Missing authentication\n * ```typescript\n * protected async authorize(input: Input): Promise<AuthContext> {\n * if (!input.userId) {\n * throw new UnauthorizedError({ message: 'Authentication required' });\n * }\n *\n * const user = await this.userRepo.findById(input.userId);\n * if (!user) {\n * throw new UnauthorizedError({ message: 'Invalid user credentials' });\n * }\n *\n * return { user };\n * }\n * ```\n *\n * @example Token validation\n * ```typescript\n * if (!token || isTokenExpired(token)) {\n * throw new UnauthorizedError({\n * message: 'Session expired, please log in again',\n * code: 'SESSION_EXPIRED',\n * });\n * }\n * ```\n *\n * @extends UseCaseError\n */\nexport class UnauthorizedError extends UseCaseError {\n /**\n * Creates a new UnauthorizedError instance.\n *\n * @param options - Error configuration\n * @param options.message - Description of why authentication failed\n * @param options.code - Machine-readable error code (default: 'UNAUTHORIZED')\n * @param options.cause - Optional underlying error\n */\n constructor({\n message,\n code = ErrorCodes.App.UNAUTHORIZED,\n cause,\n }: {\n message: string;\n code?: AppErrorCode | string;\n cause?: unknown;\n }) {\n super({ message, code, cause });\n }\n\n /**\n * Creates an UnauthorizedError from a caught error.\n *\n * @param cause - The original caught error\n * @returns A new UnauthorizedError instance with the cause attached\n */\n static override fromError(cause: unknown): UnauthorizedError {\n return new UnauthorizedError({\n message: cause instanceof Error ? cause.message : 'Authentication required',\n cause,\n });\n }\n}\n","/**\n * @fileoverview Server types for the GraphQL field system.\n *\n * @module graphql/server/types\n */\n\nimport type { GraphQLFieldDefinition, GraphQLOperationType } from '../field/types';\n\n// Re-export UseCasePort from HTTP — same interface, no duplication\nexport type { UseCasePort } from '../../http/server/types';\n\n// ============================================================================\n// Validated Args\n// ============================================================================\n\n/**\n * Validated arguments with typed data.\n * This is what handlers receive after input validation passes.\n */\nexport interface ValidatedArgs<TField extends GraphQLFieldDefinition> {\n /** Validated input arguments. */\n readonly input: TField['_types']['input'];\n\n /** Raw unvalidated arguments for advanced use cases. */\n readonly raw: unknown;\n}\n\n/**\n * Typed GraphQL context based on field definition.\n * If the field defines a context schema, this will be the validated type.\n * Otherwise, it falls back to the generic GraphQLHandlerContext.\n */\nexport type TypedGraphQLContext<TField extends GraphQLFieldDefinition> =\n TField['_types']['context'] extends undefined\n ? GraphQLHandlerContext\n : TField['_types']['context'];\n\n// ============================================================================\n// Handler Context\n// ============================================================================\n\n/**\n * Context passed to GraphQL handlers.\n * Can be extended with custom context via graphqlRoutes options.\n */\nexport interface GraphQLHandlerContext {\n /** Request ID for tracing. */\n readonly requestId?: string;\n\n /** Additional context data. */\n readonly [key: string]: unknown;\n}\n\n// ============================================================================\n// Handler Types\n// ============================================================================\n\n/**\n * Handler configuration using the use case pattern.\n *\n * @typeParam TField - The field definition type\n * @typeParam TInput - Use case input type\n * @typeParam TOutput - Use case output type\n */\nexport interface GraphQLHandlerConfig<\n TField extends GraphQLFieldDefinition,\n TInput = void,\n TOutput = void,\n> {\n /**\n * Maps the validated args to use case input.\n * Both `args` and `ctx` are fully typed based on field schemas.\n */\n readonly argsMapper: (args: ValidatedArgs<TField>, ctx: TypedGraphQLContext<TField>) => TInput;\n\n /** The use case to execute. */\n readonly useCase: { execute(input?: TInput): Promise<TOutput> };\n\n /**\n * Maps the use case output to the GraphQL response.\n */\n readonly responseMapper: (output: TOutput) => TField['_types']['output'];\n\n /** Middleware to run before the handler. */\n readonly middleware?: readonly GraphQLMiddlewareFunction[];\n}\n\n/**\n * Simple handler function that directly returns the output.\n * Use this for query and mutation fields.\n */\nexport type SimpleGraphQLHandlerFn<TField extends GraphQLFieldDefinition> = (\n args: ValidatedArgs<TField>,\n ctx: TypedGraphQLContext<TField>,\n) => Promise<TField['_types']['output']> | TField['_types']['output'];\n\n/**\n * Subscription handler function that returns an async iterable.\n * Each yielded value is sent to the subscriber.\n */\nexport type SimpleGraphQLSubscriptionFn<TField extends GraphQLFieldDefinition> = (\n args: ValidatedArgs<TField>,\n ctx: TypedGraphQLContext<TField>,\n) => AsyncIterable<TField['_types']['output']>;\n\n/**\n * Configuration for a simple handler (no use case).\n */\nexport interface SimpleGraphQLHandlerConfig<TField extends GraphQLFieldDefinition> {\n readonly handler: SimpleGraphQLHandlerFn<TField>;\n readonly middleware?: readonly GraphQLMiddlewareFunction[];\n}\n\n/**\n * Union of all handler config types.\n * Used internally to store handlers in the builder.\n */\nexport type AnyGraphQLHandlerConfig<\n TField extends GraphQLFieldDefinition,\n TInput = unknown,\n TOutput = unknown,\n> = GraphQLHandlerConfig<TField, TInput, TOutput> | SimpleGraphQLHandlerConfig<TField>;\n\n/**\n * Type guard to check if config is a simple GraphQL handler.\n */\nexport function isSimpleGraphQLHandlerConfig(\n config: AnyGraphQLHandlerConfig<GraphQLFieldDefinition, unknown, unknown>,\n): config is SimpleGraphQLHandlerConfig<GraphQLFieldDefinition> {\n return 'handler' in config && typeof config.handler === 'function';\n}\n\n/**\n * GraphQL middleware function type.\n */\nexport type GraphQLMiddlewareFunction = (\n args: unknown,\n context: GraphQLHandlerContext,\n next: () => Promise<unknown>,\n) => Promise<unknown>;\n\n// ============================================================================\n// Server Configuration\n// ============================================================================\n\n/**\n * Options for creating GraphQL routes.\n */\nexport interface CreateGraphQLRoutesOptions {\n /** Global middleware to run before all handlers. */\n readonly middleware?: readonly GraphQLMiddlewareFunction[];\n\n /**\n * Whether to validate incoming args against field schemas.\n * When enabled, invalid args throw ObjectValidationError.\n * @default true\n */\n readonly validateInput?: boolean;\n\n /**\n * Whether to validate outgoing results against field schemas.\n * When enabled, invalid results log a warning.\n * @default true\n */\n readonly validateOutput?: boolean;\n\n /**\n * Context factory to create handler context.\n */\n readonly createContext?: (rawContext: unknown) => GraphQLHandlerContext;\n\n /**\n * Allow partial handler configuration (not all fields need handlers).\n * When true, missing handlers are silently skipped.\n * When false (default), missing handlers throw an error.\n * @default false\n * @internal Used by builder pattern's buildPartial()\n */\n readonly allowPartial?: boolean;\n}\n\n// ============================================================================\n// Unified GraphQL Field (for framework adapters)\n// ============================================================================\n\n/**\n * GraphQL field input compatible with framework adapters.\n * This is the output of graphqlRoutes().build().\n */\nexport interface UnifiedGraphQLField {\n /** Schema key path (e.g., 'users.get'). */\n readonly key: string;\n\n /** GraphQL operation type. */\n readonly operation: GraphQLOperationType;\n\n /** Handler function. */\n readonly handler: (args: unknown, context: unknown) => Promise<unknown>;\n\n /** Field metadata for documentation. */\n readonly metadata: {\n readonly fieldId?: string;\n readonly description?: string;\n readonly tags?: readonly string[];\n readonly deprecated?: boolean;\n readonly deprecationReason?: string;\n };\n}\n","/**\n * @fileoverview Internal implementation for creating GraphQL routes with auto-validation.\n *\n * Generates GraphQL field handlers from a schema definition.\n * Each handler automatically validates incoming args and outgoing results\n * against the field's schemas.\n *\n * @module graphql/server/create-graphql-routes\n * @internal\n */\n\nimport type { SchemaAdapter, ValidationIssue } from '../../http/schema/types';\nimport type {\n GraphQLSchemaConfig,\n GraphQLSchemaDefinition,\n GraphQLFieldDefinition,\n} from '../field/types';\nimport { isSchemaDefinition, collectFields } from '../field/types';\nimport { generateFieldId } from '../field/utils';\nimport { mapErrorToGraphQLError } from '../shared/error-mapping';\nimport type {\n AnyGraphQLHandlerConfig,\n CreateGraphQLRoutesOptions,\n GraphQLHandlerContext,\n UnifiedGraphQLField,\n ValidatedArgs,\n} from './types';\nimport { isSimpleGraphQLHandlerConfig } from './types';\nimport { ObjectValidationError } from '../../../global/exceptions/object-validation.error';\nimport { UnauthorizedError } from '../../../app/exceptions/unauthorized.error';\n\n/**\n * Internal implementation for creating GraphQL routes.\n * Used by the builder pattern (graphqlRoutes).\n *\n * @internal\n */\nexport function createGraphQLRoutesInternal<T extends GraphQLSchemaConfig>(\n schema: T | GraphQLSchemaDefinition<T>,\n handlers: Record<string, AnyGraphQLHandlerConfig<GraphQLFieldDefinition, unknown, unknown>>,\n options?: CreateGraphQLRoutesOptions,\n): UnifiedGraphQLField[] {\n const config = isSchemaDefinition(schema) ? schema.fields : schema;\n const collectedFields = collectFields(config);\n\n const result: UnifiedGraphQLField[] = [];\n\n const resolvedOptions: CreateGraphQLRoutesOptions = {\n ...options,\n validateInput: options?.validateInput ?? true,\n validateOutput: options?.validateOutput ?? true,\n allowPartial: options?.allowPartial ?? false,\n };\n\n for (const { key, field } of collectedFields) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const handlerConfig = handlers[key] as\n | AnyGraphQLHandlerConfig<GraphQLFieldDefinition, any, any>\n | undefined;\n\n if (!handlerConfig) {\n if (resolvedOptions.allowPartial) {\n continue;\n }\n throw new Error(\n `Missing handler for field \"${key}\". All fields must have a handler configuration.`,\n );\n }\n\n result.push(createFieldHandler(key, field, handlerConfig, resolvedOptions));\n }\n\n return result;\n}\n\n/**\n * Creates a single field handler with validation and error mapping.\n */\nfunction createFieldHandler(\n key: string,\n field: GraphQLFieldDefinition,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n config: AnyGraphQLHandlerConfig<GraphQLFieldDefinition, any, any>,\n options: CreateGraphQLRoutesOptions,\n): UnifiedGraphQLField {\n const middleware = config.middleware ?? [];\n const globalMiddleware = options?.middleware ?? [];\n const allMiddleware = [...globalMiddleware, ...middleware];\n const shouldValidateInput = options.validateInput ?? true;\n const shouldValidateOutput = options.validateOutput ?? true;\n\n return {\n key,\n operation: field.operation,\n metadata: {\n fieldId: generateFieldId(key),\n description: field.docs.description,\n tags: field.docs.tags as string[],\n deprecated: field.docs.deprecated,\n deprecationReason: field.docs.deprecationReason,\n },\n handler: async (rawArgs: unknown, rawContext: unknown): Promise<unknown> => {\n // Create context\n const context: GraphQLHandlerContext = options?.createContext\n ? options.createContext(rawContext)\n : ((rawContext as GraphQLHandlerContext) ?? { requestId: generateRequestId() });\n\n // Validate context (if schema defined)\n // Context validation failures → UnauthorizedError (401 semantics).\n // Error message is generic to prevent leaking context schema details\n // (field names, types, constraints) to unauthenticated clients.\n let validatedContext: unknown = context;\n if (field.context) {\n const contextResult = validateContextData(field, context);\n if (!contextResult.success) {\n throw new UnauthorizedError({\n message: 'Authentication required',\n });\n }\n validatedContext = contextResult.data;\n }\n\n // Validate input args (if enabled and schema defined)\n let validatedInput: unknown = rawArgs;\n if (shouldValidateInput && field.input) {\n const inputResult = validateInputData(field, rawArgs);\n if (!inputResult.success) {\n const errors = inputResult.errors ?? [];\n throw new ObjectValidationError({\n message: 'Input validation failed',\n validationErrors: errors.map((e) => ({\n field: e.path.join('.'),\n message: e.message,\n })),\n });\n }\n validatedInput = inputResult.data;\n }\n\n const validatedArgs: ValidatedArgsInternal = {\n input: validatedInput,\n raw: rawArgs,\n };\n\n // Execute the pipeline\n const executePipeline = async (): Promise<unknown> => {\n if (isSimpleGraphQLHandlerConfig(config)) {\n return config.handler(\n validatedArgs as unknown as ValidatedArgs<GraphQLFieldDefinition>,\n validatedContext as GraphQLHandlerContext,\n );\n } else {\n const { argsMapper, useCase, responseMapper } = config;\n\n const input = argsMapper(\n validatedArgs as unknown as ValidatedArgs<GraphQLFieldDefinition>,\n validatedContext as GraphQLHandlerContext,\n );\n\n const output = await useCase.execute(input);\n\n return responseMapper(output);\n }\n };\n\n let result: unknown;\n\n if (allMiddleware.length === 0) {\n result = await executePipeline();\n } else {\n // Build middleware chain with re-entrancy guard\n let index = 0;\n let called = false;\n const next = async (): Promise<unknown> => {\n if (index >= allMiddleware.length) {\n if (called) throw new Error('next() called after pipeline already executed');\n called = true;\n return executePipeline();\n }\n const currentIndex = index++;\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- index bounds checked above\n const mw = allMiddleware[currentIndex]!;\n return mw(rawArgs, context, next);\n };\n\n result = await next();\n }\n\n // Validate output (if enabled and schema defined)\n if (shouldValidateOutput && field.output) {\n const outputResult = validateOutputData(field, result);\n if (!outputResult.success) {\n const details = outputResult.errors\n ?.map((e) => `${e.path.join('.')}: ${e.message}`)\n .join('; ');\n throw new ObjectValidationError({\n message: `Output validation failed for field \"${key}\": ${details}`,\n validationErrors: (outputResult.errors ?? []).map((e) => ({\n field: e.path.join('.'),\n message: e.message,\n })),\n });\n }\n }\n\n return result;\n },\n };\n}\n\n// ============================================================================\n// Validation Helpers\n// ============================================================================\n\ninterface ValidationResultInternal {\n success: boolean;\n errors?: ValidationIssue[];\n data?: unknown;\n}\n\n/**\n * Validates input args against the field's input schema.\n */\nfunction validateInputData(field: GraphQLFieldDefinition, args: unknown): ValidationResultInternal {\n const schema = field.input as SchemaAdapter | undefined;\n if (!schema) return { success: true, data: args };\n\n const result = schema.validate(args);\n if (result.success) {\n return { success: true, data: result.data };\n }\n\n const errors = result.issues.map((issue) => ({\n ...issue,\n path: ['input', ...issue.path],\n }));\n\n return { success: false, errors };\n}\n\n/**\n * Validates output data against the field's output schema.\n */\nfunction validateOutputData(\n field: GraphQLFieldDefinition,\n data: unknown,\n): ValidationResultInternal {\n const schema = field.output as SchemaAdapter | undefined;\n if (!schema) return { success: true, data };\n\n const result = schema.validate(data);\n if (result.success) {\n return { success: true, data: result.data };\n }\n\n const errors = result.issues.map((issue) => ({\n ...issue,\n path: ['output', ...issue.path],\n }));\n\n return { success: false, errors };\n}\n\n/**\n * Validates context data against the field's context schema.\n */\nfunction validateContextData(\n field: GraphQLFieldDefinition,\n context: GraphQLHandlerContext,\n): ValidationResultInternal {\n const schema = field.context as SchemaAdapter | undefined;\n if (!schema) return { success: true, data: context };\n\n const result = schema.validate(context);\n if (result.success) {\n return { success: true, data: result.data };\n }\n\n const errors = result.issues.map((issue) => ({\n ...issue,\n path: ['context', ...issue.path],\n }));\n\n return { success: false, errors };\n}\n\n/**\n * Internal validated args type with unknown fields.\n * Used inside createFieldHandler where specific types are erased.\n */\ninterface ValidatedArgsInternal {\n readonly input: unknown;\n readonly raw: unknown;\n}\n\n/**\n * Generates a unique request ID.\n */\nfunction generateRequestId(): string {\n return `gql_${crypto.randomUUID()}`;\n}\n","/**\n * @fileoverview Builder pattern for creating type-safe GraphQL routes.\n *\n * The `graphqlRoutes` function returns a builder that provides 100% type inference\n * for all handler parameters — no manual type annotations required.\n *\n * @module graphql/server/graphql-routes-builder\n */\n\nimport type {\n GraphQLSchemaConfig,\n GraphQLSchemaDefinition,\n GetField,\n SchemaKeys,\n GraphQLFieldDefinition,\n} from '../field/types';\nimport type {\n AnyGraphQLHandlerConfig,\n CreateGraphQLRoutesOptions,\n GraphQLHandlerConfig,\n GraphQLMiddlewareFunction,\n SimpleGraphQLHandlerConfig,\n SimpleGraphQLHandlerFn,\n TypedGraphQLContext,\n UnifiedGraphQLField,\n ValidatedArgs,\n} from './types';\nimport { createGraphQLRoutesInternal } from './create-graphql-routes';\n\n// ============================================================================\n// Builder Types\n// ============================================================================\n\n/**\n * Error type displayed when attempting to build() with missing handlers.\n * The `___missingFields` property shows which fields are missing.\n */\nexport interface MissingHandlersError<TMissing extends string> {\n /**\n * This error indicates that not all GraphQL fields have handlers.\n * Use buildPartial() to build with only the defined handlers,\n * or add handlers for the missing fields.\n */\n (options?: never): never;\n /** Fields that are missing handlers. */\n readonly ___missingFields: TMissing;\n}\n\n/**\n * Handler configuration for the builder pattern.\n */\nexport interface BuilderGraphQLHandlerConfig<\n TField extends GraphQLFieldDefinition,\n TInput,\n TOutput,\n> {\n /**\n * Maps the validated args to use case input.\n * Both `args` and `ctx` are fully typed based on field schemas.\n */\n readonly argsMapper: (args: ValidatedArgs<TField>, ctx: TypedGraphQLContext<TField>) => TInput;\n\n /** The use case to execute. */\n readonly useCase: { execute(input?: TInput): Promise<TOutput> };\n\n /**\n * Maps the use case output to the GraphQL response.\n */\n readonly responseMapper: (output: TOutput) => TField['_types']['output'];\n\n /** Middleware to run before the handler. */\n readonly middleware?: readonly GraphQLMiddlewareFunction[];\n}\n\n/**\n * Builder interface for creating type-safe GraphQL routes.\n *\n * Each `.handle()` call captures the specific field type and provides\n * full type inference for argsMapper, useCase, and responseMapper.\n *\n * @typeParam T - The schema configuration type\n * @typeParam THandled - Union of field keys that have handlers (accumulates)\n *\n * @example\n * ```typescript\n * const fields = graphqlRoutes(projectSchema)\n * .handleWithUseCase('projects.create', {\n * argsMapper: (args, ctx) => ({\n * name: args.input.name,\n * createdBy: ctx.userId,\n * }),\n * useCase: createProjectUseCase,\n * responseMapper: (output) => ({ projectId: output.projectId }),\n * })\n * .handle('projects.list', async (args) => {\n * return allProjects;\n * })\n * .build();\n * ```\n */\nexport interface GraphQLRoutesBuilder<\n T extends GraphQLSchemaConfig,\n THandled extends string = never,\n> {\n /**\n * Register a simple handler for a field.\n * The handler receives validated args and context, returns output directly.\n */\n handle<K extends Exclude<SchemaKeys<T>, THandled>>(\n key: K,\n handlerOrConfig:\n | SimpleGraphQLHandlerFn<GetField<T, K>>\n | SimpleGraphQLHandlerConfig<GetField<T, K>>,\n ): GraphQLRoutesBuilder<T, THandled | K>;\n\n /**\n * Register a handler using the use case pattern.\n * Follows: argsMapper → useCase.execute() → responseMapper\n */\n handleWithUseCase<K extends Exclude<SchemaKeys<T>, THandled>, TInput, TOutput>(\n key: K,\n config: BuilderGraphQLHandlerConfig<GetField<T, K>, TInput, TOutput>,\n ): GraphQLRoutesBuilder<T, THandled | K>;\n\n /**\n * Build the fields array for framework adapter registration.\n *\n * This method is only available when ALL fields have handlers.\n * If some fields are missing handlers, use `buildPartial()` instead.\n */\n build: [Exclude<SchemaKeys<T>, THandled>] extends [never]\n ? (options?: CreateGraphQLRoutesOptions) => UnifiedGraphQLField[]\n : MissingHandlersError<Exclude<SchemaKeys<T>, THandled>>;\n\n /**\n * Build fields for only the defined handlers.\n * No compile-time enforcement of completeness.\n */\n buildPartial(options?: CreateGraphQLRoutesOptions): UnifiedGraphQLField[];\n}\n\n// ============================================================================\n// Builder Implementation\n// ============================================================================\n\n/**\n * Internal builder implementation.\n *\n * Uses an immutable pattern where each handle() call returns a new\n * builder instance with the updated handlers map.\n */\nclass GraphQLRoutesBuilderImpl<T extends GraphQLSchemaConfig, THandled extends string = never> {\n private readonly schema: T | GraphQLSchemaDefinition<T>;\n private readonly handlers: Map<\n string,\n AnyGraphQLHandlerConfig<GraphQLFieldDefinition, unknown, unknown>\n >;\n\n constructor(\n schema: T | GraphQLSchemaDefinition<T>,\n handlers?: Map<string, AnyGraphQLHandlerConfig<GraphQLFieldDefinition, unknown, unknown>>,\n ) {\n this.schema = schema;\n this.handlers = handlers ?? new Map();\n }\n\n handle<K extends Exclude<SchemaKeys<T>, THandled>>(\n key: K,\n handlerOrConfig:\n | SimpleGraphQLHandlerFn<GetField<T, K>>\n | SimpleGraphQLHandlerConfig<GetField<T, K>>,\n ): GraphQLRoutesBuilder<T, THandled | K> {\n // Cast through unknown is safe: type erasure in the builder requires this cast\n // The type system tracks the specific field types through the interface\n const config: SimpleGraphQLHandlerConfig<GraphQLFieldDefinition> =\n typeof handlerOrConfig === 'function'\n ? { handler: handlerOrConfig as unknown as SimpleGraphQLHandlerFn<GraphQLFieldDefinition> }\n : (handlerOrConfig as unknown as SimpleGraphQLHandlerConfig<GraphQLFieldDefinition>);\n\n const newHandlers = new Map(this.handlers);\n newHandlers.set(key as string, config);\n\n return new GraphQLRoutesBuilderImpl<T, THandled | K>(\n this.schema,\n newHandlers,\n ) as unknown as GraphQLRoutesBuilder<T, THandled | K>;\n }\n\n handleWithUseCase<K extends Exclude<SchemaKeys<T>, THandled>, TInput, TOutput>(\n key: K,\n config: BuilderGraphQLHandlerConfig<GetField<T, K>, TInput, TOutput>,\n ): GraphQLRoutesBuilder<T, THandled | K> {\n const newHandlers = new Map(this.handlers);\n // Cast through unknown is safe: the type system tracks THandled | K through the interface\n newHandlers.set(\n key as string,\n config as unknown as GraphQLHandlerConfig<GraphQLFieldDefinition, unknown, unknown>,\n );\n\n return new GraphQLRoutesBuilderImpl<T, THandled | K>(\n this.schema,\n newHandlers,\n ) as unknown as GraphQLRoutesBuilder<T, THandled | K>;\n }\n\n build(options?: CreateGraphQLRoutesOptions): UnifiedGraphQLField[] {\n return createGraphQLRoutesInternal(this.schema, Object.fromEntries(this.handlers), options);\n }\n\n buildPartial(options?: CreateGraphQLRoutesOptions): UnifiedGraphQLField[] {\n return createGraphQLRoutesInternal(this.schema, Object.fromEntries(this.handlers), {\n ...options,\n allowPartial: true,\n });\n }\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Creates a type-safe GraphQL routes builder for a schema.\n *\n * The builder pattern provides 100% type inference for all handler parameters:\n * - `args.input` is typed from the field's input schema\n * - `ctx` is typed from the field's context schema (or GraphQLHandlerContext)\n * - `output` in responseMapper is typed from the use case\n *\n * @param schema - GraphQL schema definition or schema config\n * @returns Builder for registering handlers\n *\n * @example Basic usage\n * ```typescript\n * import { graphqlRoutes } from '@cosmneo/onion-lasagna/graphql/server';\n * import { projectSchema } from './schema';\n *\n * const fields = graphqlRoutes(projectSchema)\n * .handleWithUseCase('projects.create', {\n * argsMapper: (args, ctx) => ({\n * name: args.input.name,\n * createdBy: ctx.userId,\n * }),\n * useCase: createProjectUseCase,\n * responseMapper: (output) => ({ projectId: output.projectId }),\n * })\n * .handle('projects.list', async () => allProjects)\n * .build();\n * ```\n */\nexport function graphqlRoutes<T extends GraphQLSchemaConfig>(\n schema: T | GraphQLSchemaDefinition<T>,\n): GraphQLRoutesBuilder<T, never> {\n return new GraphQLRoutesBuilderImpl(schema) as unknown as GraphQLRoutesBuilder<T, never>;\n}\n"],"mappings":";;;;;;;;;;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