@effect-gql/core 0.1.0 → 1.0.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 (164) hide show
  1. package/README.md +100 -0
  2. package/builder/index.cjs +1431 -0
  3. package/builder/index.cjs.map +1 -0
  4. package/builder/index.d.cts +259 -0
  5. package/{dist/builder/pipe-api.d.ts → builder/index.d.ts} +49 -21
  6. package/builder/index.js +1390 -0
  7. package/builder/index.js.map +1 -0
  8. package/index.cjs +3419 -0
  9. package/index.cjs.map +1 -0
  10. package/index.d.cts +523 -0
  11. package/index.d.ts +523 -0
  12. package/index.js +3242 -0
  13. package/index.js.map +1 -0
  14. package/package.json +19 -28
  15. package/schema-builder-Cvdq7Kz_.d.cts +963 -0
  16. package/schema-builder-Cvdq7Kz_.d.ts +963 -0
  17. package/server/index.cjs +1555 -0
  18. package/server/index.cjs.map +1 -0
  19. package/server/index.d.cts +680 -0
  20. package/server/index.d.ts +680 -0
  21. package/server/index.js +1524 -0
  22. package/server/index.js.map +1 -0
  23. package/dist/analyzer-extension.d.ts +0 -105
  24. package/dist/analyzer-extension.d.ts.map +0 -1
  25. package/dist/analyzer-extension.js +0 -137
  26. package/dist/analyzer-extension.js.map +0 -1
  27. package/dist/builder/execute.d.ts +0 -26
  28. package/dist/builder/execute.d.ts.map +0 -1
  29. package/dist/builder/execute.js +0 -104
  30. package/dist/builder/execute.js.map +0 -1
  31. package/dist/builder/field-builders.d.ts +0 -30
  32. package/dist/builder/field-builders.d.ts.map +0 -1
  33. package/dist/builder/field-builders.js +0 -200
  34. package/dist/builder/field-builders.js.map +0 -1
  35. package/dist/builder/index.d.ts +0 -7
  36. package/dist/builder/index.d.ts.map +0 -1
  37. package/dist/builder/index.js +0 -31
  38. package/dist/builder/index.js.map +0 -1
  39. package/dist/builder/pipe-api.d.ts.map +0 -1
  40. package/dist/builder/pipe-api.js +0 -151
  41. package/dist/builder/pipe-api.js.map +0 -1
  42. package/dist/builder/schema-builder.d.ts +0 -301
  43. package/dist/builder/schema-builder.d.ts.map +0 -1
  44. package/dist/builder/schema-builder.js +0 -566
  45. package/dist/builder/schema-builder.js.map +0 -1
  46. package/dist/builder/type-registry.d.ts +0 -80
  47. package/dist/builder/type-registry.d.ts.map +0 -1
  48. package/dist/builder/type-registry.js +0 -505
  49. package/dist/builder/type-registry.js.map +0 -1
  50. package/dist/builder/types.d.ts +0 -283
  51. package/dist/builder/types.d.ts.map +0 -1
  52. package/dist/builder/types.js +0 -3
  53. package/dist/builder/types.js.map +0 -1
  54. package/dist/cli/generate-schema.d.ts +0 -29
  55. package/dist/cli/generate-schema.d.ts.map +0 -1
  56. package/dist/cli/generate-schema.js +0 -233
  57. package/dist/cli/generate-schema.js.map +0 -1
  58. package/dist/cli/index.d.ts +0 -19
  59. package/dist/cli/index.d.ts.map +0 -1
  60. package/dist/cli/index.js +0 -24
  61. package/dist/cli/index.js.map +0 -1
  62. package/dist/context.d.ts +0 -18
  63. package/dist/context.d.ts.map +0 -1
  64. package/dist/context.js +0 -11
  65. package/dist/context.js.map +0 -1
  66. package/dist/error.d.ts +0 -45
  67. package/dist/error.d.ts.map +0 -1
  68. package/dist/error.js +0 -29
  69. package/dist/error.js.map +0 -1
  70. package/dist/extensions.d.ts +0 -130
  71. package/dist/extensions.d.ts.map +0 -1
  72. package/dist/extensions.js +0 -78
  73. package/dist/extensions.js.map +0 -1
  74. package/dist/index.d.ts +0 -12
  75. package/dist/index.d.ts.map +0 -1
  76. package/dist/index.js +0 -47
  77. package/dist/index.js.map +0 -1
  78. package/dist/loader.d.ts +0 -169
  79. package/dist/loader.d.ts.map +0 -1
  80. package/dist/loader.js +0 -237
  81. package/dist/loader.js.map +0 -1
  82. package/dist/resolver-context.d.ts +0 -154
  83. package/dist/resolver-context.d.ts.map +0 -1
  84. package/dist/resolver-context.js +0 -184
  85. package/dist/resolver-context.js.map +0 -1
  86. package/dist/schema-mapping.d.ts +0 -30
  87. package/dist/schema-mapping.d.ts.map +0 -1
  88. package/dist/schema-mapping.js +0 -280
  89. package/dist/schema-mapping.js.map +0 -1
  90. package/dist/server/cache-control.d.ts +0 -96
  91. package/dist/server/cache-control.d.ts.map +0 -1
  92. package/dist/server/cache-control.js +0 -308
  93. package/dist/server/cache-control.js.map +0 -1
  94. package/dist/server/complexity.d.ts +0 -165
  95. package/dist/server/complexity.d.ts.map +0 -1
  96. package/dist/server/complexity.js +0 -433
  97. package/dist/server/complexity.js.map +0 -1
  98. package/dist/server/config.d.ts +0 -66
  99. package/dist/server/config.d.ts.map +0 -1
  100. package/dist/server/config.js +0 -104
  101. package/dist/server/config.js.map +0 -1
  102. package/dist/server/graphiql.d.ts +0 -5
  103. package/dist/server/graphiql.d.ts.map +0 -1
  104. package/dist/server/graphiql.js +0 -43
  105. package/dist/server/graphiql.js.map +0 -1
  106. package/dist/server/index.d.ts +0 -18
  107. package/dist/server/index.d.ts.map +0 -1
  108. package/dist/server/index.js +0 -48
  109. package/dist/server/index.js.map +0 -1
  110. package/dist/server/router.d.ts +0 -79
  111. package/dist/server/router.d.ts.map +0 -1
  112. package/dist/server/router.js +0 -232
  113. package/dist/server/router.js.map +0 -1
  114. package/dist/server/schema-builder-extensions.d.ts +0 -42
  115. package/dist/server/schema-builder-extensions.d.ts.map +0 -1
  116. package/dist/server/schema-builder-extensions.js +0 -48
  117. package/dist/server/schema-builder-extensions.js.map +0 -1
  118. package/dist/server/sse-adapter.d.ts +0 -64
  119. package/dist/server/sse-adapter.d.ts.map +0 -1
  120. package/dist/server/sse-adapter.js +0 -227
  121. package/dist/server/sse-adapter.js.map +0 -1
  122. package/dist/server/sse-types.d.ts +0 -192
  123. package/dist/server/sse-types.d.ts.map +0 -1
  124. package/dist/server/sse-types.js +0 -63
  125. package/dist/server/sse-types.js.map +0 -1
  126. package/dist/server/ws-adapter.d.ts +0 -39
  127. package/dist/server/ws-adapter.d.ts.map +0 -1
  128. package/dist/server/ws-adapter.js +0 -247
  129. package/dist/server/ws-adapter.js.map +0 -1
  130. package/dist/server/ws-types.d.ts +0 -169
  131. package/dist/server/ws-types.d.ts.map +0 -1
  132. package/dist/server/ws-types.js +0 -11
  133. package/dist/server/ws-types.js.map +0 -1
  134. package/dist/server/ws-utils.d.ts +0 -42
  135. package/dist/server/ws-utils.d.ts.map +0 -1
  136. package/dist/server/ws-utils.js +0 -99
  137. package/dist/server/ws-utils.js.map +0 -1
  138. package/src/analyzer-extension.ts +0 -254
  139. package/src/builder/execute.ts +0 -153
  140. package/src/builder/field-builders.ts +0 -322
  141. package/src/builder/index.ts +0 -48
  142. package/src/builder/pipe-api.ts +0 -312
  143. package/src/builder/schema-builder.ts +0 -970
  144. package/src/builder/type-registry.ts +0 -670
  145. package/src/builder/types.ts +0 -305
  146. package/src/context.ts +0 -23
  147. package/src/error.ts +0 -32
  148. package/src/extensions.ts +0 -240
  149. package/src/index.ts +0 -32
  150. package/src/loader.ts +0 -363
  151. package/src/resolver-context.ts +0 -253
  152. package/src/schema-mapping.ts +0 -307
  153. package/src/server/cache-control.ts +0 -590
  154. package/src/server/complexity.ts +0 -774
  155. package/src/server/config.ts +0 -174
  156. package/src/server/graphiql.ts +0 -38
  157. package/src/server/index.ts +0 -96
  158. package/src/server/router.ts +0 -432
  159. package/src/server/schema-builder-extensions.ts +0 -51
  160. package/src/server/sse-adapter.ts +0 -327
  161. package/src/server/sse-types.ts +0 -234
  162. package/src/server/ws-adapter.ts +0 -355
  163. package/src/server/ws-types.ts +0 -192
  164. package/src/server/ws-utils.ts +0 -136
@@ -0,0 +1,1524 @@
1
+ import { Config, Option, Data, Context, Effect, Queue, Deferred, Stream, Ref, Runtime, Fiber } from 'effect';
2
+ import { HttpServerResponse, HttpServerRequest, HttpRouter } from '@effect/platform';
3
+ import { Kind, GraphQLObjectType, parse, specifiedRules, NoSchemaIntrospectionCustomRule, validate, subscribe, GraphQLError, GraphQLNonNull, GraphQLList, GraphQLSchema, GraphQLScalarType, GraphQLEnumType, execute } from 'graphql';
4
+ import { makeServer } from 'graphql-ws';
5
+
6
+ // src/server/config.ts
7
+ var defaultConfig = {
8
+ path: "/graphql",
9
+ graphiql: false,
10
+ complexity: void 0,
11
+ introspection: true,
12
+ cacheControl: void 0
13
+ };
14
+ var normalizeConfig = (input = {}) => {
15
+ const path = input.path ?? defaultConfig.path;
16
+ let graphiql = false;
17
+ if (input.graphiql === true) {
18
+ graphiql = { path: "/graphiql", endpoint: path };
19
+ } else if (input.graphiql && typeof input.graphiql === "object") {
20
+ graphiql = {
21
+ path: input.graphiql.path ?? "/graphiql",
22
+ endpoint: input.graphiql.endpoint ?? path
23
+ };
24
+ }
25
+ return {
26
+ path,
27
+ graphiql,
28
+ complexity: input.complexity,
29
+ introspection: input.introspection ?? true,
30
+ cacheControl: input.cacheControl
31
+ };
32
+ };
33
+ var GraphQLRouterConfigFromEnv = Config.all({
34
+ path: Config.string("GRAPHQL_PATH").pipe(Config.withDefault("/graphql")),
35
+ introspection: Config.boolean("GRAPHQL_INTROSPECTION").pipe(Config.withDefault(true)),
36
+ graphiqlEnabled: Config.boolean("GRAPHIQL_ENABLED").pipe(Config.withDefault(false)),
37
+ graphiqlPath: Config.string("GRAPHIQL_PATH").pipe(Config.withDefault("/graphiql")),
38
+ graphiqlEndpoint: Config.string("GRAPHIQL_ENDPOINT").pipe(Config.option),
39
+ maxDepth: Config.number("GRAPHQL_MAX_DEPTH").pipe(Config.option),
40
+ maxComplexity: Config.number("GRAPHQL_MAX_COMPLEXITY").pipe(Config.option),
41
+ maxAliases: Config.number("GRAPHQL_MAX_ALIASES").pipe(Config.option),
42
+ maxFields: Config.number("GRAPHQL_MAX_FIELDS").pipe(Config.option),
43
+ defaultFieldComplexity: Config.number("GRAPHQL_DEFAULT_FIELD_COMPLEXITY").pipe(
44
+ Config.withDefault(1)
45
+ ),
46
+ cacheControlEnabled: Config.boolean("GRAPHQL_CACHE_CONTROL_ENABLED").pipe(
47
+ Config.withDefault(false)
48
+ ),
49
+ cacheControlDefaultMaxAge: Config.number("GRAPHQL_CACHE_CONTROL_DEFAULT_MAX_AGE").pipe(
50
+ Config.withDefault(0)
51
+ ),
52
+ cacheControlDefaultScope: Config.string("GRAPHQL_CACHE_CONTROL_DEFAULT_SCOPE").pipe(
53
+ Config.withDefault("PUBLIC")
54
+ )
55
+ }).pipe(
56
+ Config.map(
57
+ ({
58
+ path,
59
+ introspection,
60
+ graphiqlEnabled,
61
+ graphiqlPath,
62
+ graphiqlEndpoint,
63
+ maxDepth,
64
+ maxComplexity,
65
+ maxAliases,
66
+ maxFields,
67
+ defaultFieldComplexity,
68
+ cacheControlEnabled,
69
+ cacheControlDefaultMaxAge,
70
+ cacheControlDefaultScope
71
+ }) => {
72
+ const hasComplexity = Option.isSome(maxDepth) || Option.isSome(maxComplexity) || Option.isSome(maxAliases) || Option.isSome(maxFields);
73
+ return {
74
+ path,
75
+ introspection,
76
+ graphiql: graphiqlEnabled ? {
77
+ path: graphiqlPath,
78
+ endpoint: Option.isSome(graphiqlEndpoint) ? graphiqlEndpoint.value : path
79
+ } : false,
80
+ complexity: hasComplexity ? {
81
+ maxDepth: Option.getOrUndefined(maxDepth),
82
+ maxComplexity: Option.getOrUndefined(maxComplexity),
83
+ maxAliases: Option.getOrUndefined(maxAliases),
84
+ maxFields: Option.getOrUndefined(maxFields),
85
+ defaultFieldComplexity
86
+ } : void 0,
87
+ cacheControl: cacheControlEnabled ? {
88
+ enabled: true,
89
+ defaultMaxAge: cacheControlDefaultMaxAge,
90
+ defaultScope: cacheControlDefaultScope === "PRIVATE" ? "PRIVATE" : "PUBLIC",
91
+ calculateHttpHeaders: true
92
+ } : void 0
93
+ };
94
+ }
95
+ )
96
+ );
97
+
98
+ // src/server/graphiql.ts
99
+ var graphiqlHtml = (endpoint) => `<!DOCTYPE html>
100
+ <html lang="en">
101
+ <head>
102
+ <meta charset="utf-8" />
103
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
104
+ <title>GraphiQL</title>
105
+ <link
106
+ rel="stylesheet"
107
+ href="https://unpkg.com/graphiql@3/graphiql.min.css"
108
+ />
109
+ </head>
110
+ <body style="margin: 0; overflow: hidden;">
111
+ <div id="graphiql" style="height: 100vh;"></div>
112
+ <script
113
+ crossorigin
114
+ src="https://unpkg.com/react@18/umd/react.production.min.js"
115
+ ></script>
116
+ <script
117
+ crossorigin
118
+ src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"
119
+ ></script>
120
+ <script
121
+ crossorigin
122
+ src="https://unpkg.com/graphiql@3/graphiql.min.js"
123
+ ></script>
124
+ <script>
125
+ const fetcher = GraphiQL.createFetcher({
126
+ url: ${JSON.stringify(endpoint)},
127
+ });
128
+ ReactDOM.createRoot(document.getElementById('graphiql')).render(
129
+ React.createElement(GraphiQL, { fetcher })
130
+ );
131
+ </script>
132
+ </body>
133
+ </html>`;
134
+ var ComplexityLimitExceededError = class extends Data.TaggedError("ComplexityLimitExceededError") {
135
+ };
136
+ var ComplexityAnalysisError = class extends Data.TaggedError("ComplexityAnalysisError") {
137
+ };
138
+ var defaultComplexityCalculator = (defaultCost = 1) => {
139
+ return (info) => Effect.try({
140
+ try: () => {
141
+ const fragments = /* @__PURE__ */ new Map();
142
+ for (const definition of info.document.definitions) {
143
+ if (definition.kind === Kind.FRAGMENT_DEFINITION) {
144
+ fragments.set(definition.name.value, definition);
145
+ }
146
+ }
147
+ const rootType = getRootType(info.schema, info.operation.operation);
148
+ if (!rootType) {
149
+ throw new Error(`No root type found for operation: ${info.operation.operation}`);
150
+ }
151
+ const result = analyzeSelectionSet(
152
+ info.operation.selectionSet,
153
+ rootType,
154
+ info.schema,
155
+ fragments,
156
+ info.fieldComplexities,
157
+ info.variables ?? {},
158
+ defaultCost,
159
+ 1,
160
+ // Starting depth
161
+ /* @__PURE__ */ new Set()
162
+ // Visited fragments to prevent infinite loops
163
+ );
164
+ return result;
165
+ },
166
+ catch: (error) => new ComplexityAnalysisError({
167
+ message: `Failed to analyze query complexity: ${error}`,
168
+ cause: error
169
+ })
170
+ });
171
+ };
172
+ function getRootType(schema, operation) {
173
+ switch (operation) {
174
+ case "query":
175
+ return schema.getQueryType() ?? null;
176
+ case "mutation":
177
+ return schema.getMutationType() ?? null;
178
+ case "subscription":
179
+ return schema.getSubscriptionType() ?? null;
180
+ }
181
+ }
182
+ function getNamedType(type) {
183
+ if (type instanceof GraphQLNonNull || type instanceof GraphQLList) {
184
+ return getNamedType(type.ofType);
185
+ }
186
+ if (type instanceof GraphQLObjectType) {
187
+ return type;
188
+ }
189
+ return null;
190
+ }
191
+ function accumulateResult(acc, result) {
192
+ acc.maxDepth = Math.max(acc.maxDepth, result.depth);
193
+ acc.complexity += result.complexity;
194
+ acc.fieldCount += result.fieldCount;
195
+ acc.aliasCount += result.aliasCount;
196
+ }
197
+ function analyzeSelectionSet(selectionSet, parentType, schema, fragments, fieldComplexities, variables, defaultCost, currentDepth, visitedFragments) {
198
+ const ctx = { schema, fragments, fieldComplexities, variables, defaultCost };
199
+ const acc = { maxDepth: currentDepth, complexity: 0, fieldCount: 0, aliasCount: 0 };
200
+ for (const selection of selectionSet.selections) {
201
+ const result = analyzeSelection(selection, parentType, ctx, currentDepth, visitedFragments);
202
+ accumulateResult(acc, result);
203
+ }
204
+ return {
205
+ depth: acc.maxDepth,
206
+ complexity: acc.complexity,
207
+ fieldCount: acc.fieldCount,
208
+ aliasCount: acc.aliasCount
209
+ };
210
+ }
211
+ function analyzeSelection(selection, parentType, ctx, currentDepth, visitedFragments) {
212
+ switch (selection.kind) {
213
+ case Kind.FIELD:
214
+ return analyzeField(selection, parentType, ctx, currentDepth, visitedFragments);
215
+ case Kind.FRAGMENT_SPREAD:
216
+ return analyzeFragmentSpread(selection, ctx, currentDepth, visitedFragments);
217
+ case Kind.INLINE_FRAGMENT:
218
+ return analyzeInlineFragment(selection, parentType, ctx, currentDepth, visitedFragments);
219
+ }
220
+ }
221
+ function analyzeField(field, parentType, ctx, currentDepth, visitedFragments) {
222
+ const fieldName = field.name.value;
223
+ const aliasCount = field.alias ? 1 : 0;
224
+ if (fieldName.startsWith("__")) {
225
+ return { depth: currentDepth, complexity: 0, fieldCount: 1, aliasCount };
226
+ }
227
+ const schemaField = parentType.getFields()[fieldName];
228
+ if (!schemaField) {
229
+ return { depth: currentDepth, complexity: ctx.defaultCost, fieldCount: 1, aliasCount };
230
+ }
231
+ const args = resolveFieldArguments(field, ctx.variables);
232
+ const complexityKey = `${parentType.name}.${fieldName}`;
233
+ const fieldComplexity = ctx.fieldComplexities.get(complexityKey);
234
+ const cost = fieldComplexity !== void 0 ? typeof fieldComplexity === "function" ? fieldComplexity(args) : fieldComplexity : ctx.defaultCost;
235
+ if (field.selectionSet) {
236
+ const fieldType = getNamedType(schemaField.type);
237
+ if (fieldType) {
238
+ const nestedResult = analyzeSelectionSet(
239
+ field.selectionSet,
240
+ fieldType,
241
+ ctx.schema,
242
+ ctx.fragments,
243
+ ctx.fieldComplexities,
244
+ ctx.variables,
245
+ ctx.defaultCost,
246
+ currentDepth + 1,
247
+ visitedFragments
248
+ );
249
+ return {
250
+ depth: nestedResult.depth,
251
+ complexity: cost + nestedResult.complexity,
252
+ fieldCount: 1 + nestedResult.fieldCount,
253
+ aliasCount: aliasCount + nestedResult.aliasCount
254
+ };
255
+ }
256
+ }
257
+ return { depth: currentDepth, complexity: cost, fieldCount: 1, aliasCount };
258
+ }
259
+ function analyzeFragmentSpread(spread, ctx, currentDepth, visitedFragments) {
260
+ const fragmentName = spread.name.value;
261
+ if (visitedFragments.has(fragmentName)) {
262
+ return { depth: currentDepth, complexity: 0, fieldCount: 0, aliasCount: 0 };
263
+ }
264
+ const fragment = ctx.fragments.get(fragmentName);
265
+ if (!fragment) {
266
+ return { depth: currentDepth, complexity: 0, fieldCount: 0, aliasCount: 0 };
267
+ }
268
+ const fragmentType = ctx.schema.getType(fragment.typeCondition.name.value);
269
+ if (!(fragmentType instanceof GraphQLObjectType)) {
270
+ return { depth: currentDepth, complexity: 0, fieldCount: 0, aliasCount: 0 };
271
+ }
272
+ const newVisited = new Set(visitedFragments);
273
+ newVisited.add(fragmentName);
274
+ return analyzeSelectionSet(
275
+ fragment.selectionSet,
276
+ fragmentType,
277
+ ctx.schema,
278
+ ctx.fragments,
279
+ ctx.fieldComplexities,
280
+ ctx.variables,
281
+ ctx.defaultCost,
282
+ currentDepth,
283
+ newVisited
284
+ );
285
+ }
286
+ function analyzeInlineFragment(fragment, parentType, ctx, currentDepth, visitedFragments) {
287
+ let targetType = parentType;
288
+ if (fragment.typeCondition) {
289
+ const conditionType = ctx.schema.getType(fragment.typeCondition.name.value);
290
+ if (conditionType instanceof GraphQLObjectType) {
291
+ targetType = conditionType;
292
+ }
293
+ }
294
+ return analyzeSelectionSet(
295
+ fragment.selectionSet,
296
+ targetType,
297
+ ctx.schema,
298
+ ctx.fragments,
299
+ ctx.fieldComplexities,
300
+ ctx.variables,
301
+ ctx.defaultCost,
302
+ currentDepth,
303
+ visitedFragments
304
+ );
305
+ }
306
+ function resolveFieldArguments(field, variables) {
307
+ const args = {};
308
+ if (!field.arguments) {
309
+ return args;
310
+ }
311
+ for (const arg of field.arguments) {
312
+ const value = arg.value;
313
+ switch (value.kind) {
314
+ case Kind.VARIABLE:
315
+ args[arg.name.value] = variables[value.name.value];
316
+ break;
317
+ case Kind.INT:
318
+ args[arg.name.value] = parseInt(value.value, 10);
319
+ break;
320
+ case Kind.FLOAT:
321
+ args[arg.name.value] = parseFloat(value.value);
322
+ break;
323
+ case Kind.STRING:
324
+ args[arg.name.value] = value.value;
325
+ break;
326
+ case Kind.BOOLEAN:
327
+ args[arg.name.value] = value.value;
328
+ break;
329
+ case Kind.NULL:
330
+ args[arg.name.value] = null;
331
+ break;
332
+ case Kind.ENUM:
333
+ args[arg.name.value] = value.value;
334
+ break;
335
+ case Kind.LIST:
336
+ args[arg.name.value] = [];
337
+ break;
338
+ case Kind.OBJECT:
339
+ args[arg.name.value] = {};
340
+ break;
341
+ }
342
+ }
343
+ return args;
344
+ }
345
+ var validateComplexity = (query, operationName, variables, schema, fieldComplexities, config) => Effect.gen(function* () {
346
+ const document = yield* Effect.try({
347
+ try: () => parse(query),
348
+ catch: (error) => new ComplexityAnalysisError({
349
+ message: `Failed to parse query: ${error}`,
350
+ cause: error
351
+ })
352
+ });
353
+ const operation = yield* Effect.try({
354
+ try: () => {
355
+ const operations = document.definitions.filter(
356
+ (d) => d.kind === Kind.OPERATION_DEFINITION
357
+ );
358
+ if (operations.length === 0) {
359
+ throw new Error("No operation found in query");
360
+ }
361
+ if (operationName) {
362
+ const op = operations.find((o) => o.name?.value === operationName);
363
+ if (!op) {
364
+ throw new Error(`Operation "${operationName}" not found`);
365
+ }
366
+ return op;
367
+ }
368
+ if (operations.length > 1) {
369
+ throw new Error("Multiple operations found - operationName required");
370
+ }
371
+ return operations[0];
372
+ },
373
+ catch: (error) => new ComplexityAnalysisError({
374
+ message: String(error),
375
+ cause: error
376
+ })
377
+ });
378
+ const calculator = config.calculator ?? defaultComplexityCalculator(config.defaultFieldComplexity ?? 1);
379
+ const result = yield* calculator({
380
+ document,
381
+ operation,
382
+ variables,
383
+ schema,
384
+ fieldComplexities
385
+ });
386
+ const checkLimit = (limitType, limit, actual) => Effect.gen(function* () {
387
+ if (limit !== void 0 && actual > limit) {
388
+ const exceededInfo = {
389
+ result,
390
+ exceededLimit: limitType,
391
+ limit,
392
+ actual,
393
+ query,
394
+ operationName
395
+ };
396
+ if (config.onExceeded) {
397
+ yield* config.onExceeded(exceededInfo);
398
+ }
399
+ yield* Effect.fail(
400
+ new ComplexityLimitExceededError({
401
+ message: `Query ${limitType} of ${actual} exceeds maximum allowed ${limitType} of ${limit}`,
402
+ limit,
403
+ actual,
404
+ limitType
405
+ })
406
+ );
407
+ }
408
+ });
409
+ yield* checkLimit("depth", config.maxDepth, result.depth);
410
+ yield* checkLimit("complexity", config.maxComplexity, result.complexity);
411
+ yield* checkLimit("aliases", config.maxAliases, result.aliasCount);
412
+ yield* checkLimit("fields", config.maxFields, result.fieldCount);
413
+ return result;
414
+ });
415
+ var ComplexityConfigFromEnv = Config.all({
416
+ maxDepth: Config.number("GRAPHQL_MAX_DEPTH").pipe(Config.option),
417
+ maxComplexity: Config.number("GRAPHQL_MAX_COMPLEXITY").pipe(Config.option),
418
+ maxAliases: Config.number("GRAPHQL_MAX_ALIASES").pipe(Config.option),
419
+ maxFields: Config.number("GRAPHQL_MAX_FIELDS").pipe(Config.option),
420
+ defaultFieldComplexity: Config.number("GRAPHQL_DEFAULT_FIELD_COMPLEXITY").pipe(
421
+ Config.withDefault(1)
422
+ )
423
+ }).pipe(
424
+ Config.map(({ maxDepth, maxComplexity, maxAliases, maxFields, defaultFieldComplexity }) => ({
425
+ maxDepth: Option.getOrUndefined(maxDepth),
426
+ maxComplexity: Option.getOrUndefined(maxComplexity),
427
+ maxAliases: Option.getOrUndefined(maxAliases),
428
+ maxFields: Option.getOrUndefined(maxFields),
429
+ defaultFieldComplexity
430
+ }))
431
+ );
432
+ var depthOnlyCalculator = (info) => Effect.try({
433
+ try: () => {
434
+ const fragments = /* @__PURE__ */ new Map();
435
+ for (const definition of info.document.definitions) {
436
+ if (definition.kind === Kind.FRAGMENT_DEFINITION) {
437
+ fragments.set(definition.name.value, definition);
438
+ }
439
+ }
440
+ const depth = calculateMaxDepth(info.operation.selectionSet, fragments, 1, /* @__PURE__ */ new Set());
441
+ return {
442
+ depth,
443
+ complexity: 0,
444
+ fieldCount: 0,
445
+ aliasCount: 0
446
+ };
447
+ },
448
+ catch: (error) => new ComplexityAnalysisError({
449
+ message: `Failed to analyze query depth: ${error}`,
450
+ cause: error
451
+ })
452
+ });
453
+ function calculateMaxDepth(selectionSet, fragments, currentDepth, visitedFragments) {
454
+ let maxDepth = currentDepth;
455
+ for (const selection of selectionSet.selections) {
456
+ switch (selection.kind) {
457
+ case Kind.FIELD:
458
+ if (selection.selectionSet) {
459
+ const nestedDepth = calculateMaxDepth(
460
+ selection.selectionSet,
461
+ fragments,
462
+ currentDepth + 1,
463
+ visitedFragments
464
+ );
465
+ maxDepth = Math.max(maxDepth, nestedDepth);
466
+ }
467
+ break;
468
+ case Kind.FRAGMENT_SPREAD: {
469
+ const fragmentName = selection.name.value;
470
+ if (!visitedFragments.has(fragmentName)) {
471
+ const fragment = fragments.get(fragmentName);
472
+ if (fragment) {
473
+ const newVisited = new Set(visitedFragments);
474
+ newVisited.add(fragmentName);
475
+ const fragmentDepth = calculateMaxDepth(
476
+ fragment.selectionSet,
477
+ fragments,
478
+ currentDepth,
479
+ newVisited
480
+ );
481
+ maxDepth = Math.max(maxDepth, fragmentDepth);
482
+ }
483
+ }
484
+ break;
485
+ }
486
+ case Kind.INLINE_FRAGMENT: {
487
+ const inlineDepth = calculateMaxDepth(
488
+ selection.selectionSet,
489
+ fragments,
490
+ currentDepth,
491
+ visitedFragments
492
+ );
493
+ maxDepth = Math.max(maxDepth, inlineDepth);
494
+ break;
495
+ }
496
+ }
497
+ }
498
+ return maxDepth;
499
+ }
500
+ var combineCalculators = (...calculators) => {
501
+ return (info) => Effect.gen(function* () {
502
+ let maxDepth = 0;
503
+ let maxComplexity = 0;
504
+ let maxFieldCount = 0;
505
+ let maxAliasCount = 0;
506
+ for (const calculator of calculators) {
507
+ const result = yield* calculator(info);
508
+ maxDepth = Math.max(maxDepth, result.depth);
509
+ maxComplexity = Math.max(maxComplexity, result.complexity);
510
+ maxFieldCount = Math.max(maxFieldCount, result.fieldCount);
511
+ maxAliasCount = Math.max(maxAliasCount, result.aliasCount);
512
+ }
513
+ return {
514
+ depth: maxDepth,
515
+ complexity: maxComplexity,
516
+ fieldCount: maxFieldCount,
517
+ aliasCount: maxAliasCount
518
+ };
519
+ });
520
+ };
521
+ var computeCachePolicy = (info) => Effect.sync(() => {
522
+ const fragments = /* @__PURE__ */ new Map();
523
+ for (const definition of info.document.definitions) {
524
+ if (definition.kind === Kind.FRAGMENT_DEFINITION) {
525
+ fragments.set(definition.name.value, definition);
526
+ }
527
+ }
528
+ const rootType = getRootType2(info.schema, info.operation.operation);
529
+ if (!rootType) {
530
+ return { maxAge: 0, scope: "PUBLIC" };
531
+ }
532
+ const defaultMaxAge = info.config.defaultMaxAge ?? 0;
533
+ const defaultScope = info.config.defaultScope ?? "PUBLIC";
534
+ const result = analyzeSelectionSet2(
535
+ info.operation.selectionSet,
536
+ rootType,
537
+ info.schema,
538
+ fragments,
539
+ info.cacheHints,
540
+ defaultMaxAge,
541
+ defaultScope,
542
+ void 0,
543
+ // No parent maxAge for root
544
+ /* @__PURE__ */ new Set()
545
+ );
546
+ return result;
547
+ });
548
+ var computeCachePolicyFromQuery = (query, operationName, schema, cacheHints, config = {}) => Effect.gen(function* () {
549
+ const document = yield* Effect.try({
550
+ try: () => parse(query),
551
+ catch: (error) => new Error(`Failed to parse query: ${error}`)
552
+ });
553
+ const operation = yield* Effect.try({
554
+ try: () => {
555
+ const operations = document.definitions.filter(
556
+ (d) => d.kind === Kind.OPERATION_DEFINITION
557
+ );
558
+ if (operations.length === 0) {
559
+ throw new Error("No operation found in query");
560
+ }
561
+ if (operationName) {
562
+ const op = operations.find((o) => o.name?.value === operationName);
563
+ if (!op) {
564
+ throw new Error(`Operation "${operationName}" not found`);
565
+ }
566
+ return op;
567
+ }
568
+ if (operations.length > 1) {
569
+ throw new Error("Multiple operations found - operationName required");
570
+ }
571
+ return operations[0];
572
+ },
573
+ catch: (error) => error
574
+ });
575
+ return yield* computeCachePolicy({
576
+ document,
577
+ operation,
578
+ schema,
579
+ cacheHints,
580
+ config
581
+ });
582
+ });
583
+ var toCacheControlHeader = (policy) => {
584
+ if (policy.maxAge === 0) {
585
+ return "no-store";
586
+ }
587
+ const directives = [];
588
+ directives.push(policy.scope === "PRIVATE" ? "private" : "public");
589
+ directives.push(`max-age=${policy.maxAge}`);
590
+ return directives.join(", ");
591
+ };
592
+ function getRootType2(schema, operation) {
593
+ switch (operation) {
594
+ case "query":
595
+ return schema.getQueryType() ?? null;
596
+ case "mutation":
597
+ return schema.getMutationType() ?? null;
598
+ case "subscription":
599
+ return schema.getSubscriptionType() ?? null;
600
+ }
601
+ }
602
+ function getNamedType2(type) {
603
+ if (type instanceof GraphQLNonNull || type instanceof GraphQLList) {
604
+ return getNamedType2(type.ofType);
605
+ }
606
+ if (type instanceof GraphQLObjectType || type instanceof GraphQLScalarType || type instanceof GraphQLEnumType) {
607
+ return type;
608
+ }
609
+ return null;
610
+ }
611
+ function isLeafType(type) {
612
+ const namedType = getNamedType2(type);
613
+ return namedType instanceof GraphQLScalarType || namedType instanceof GraphQLEnumType;
614
+ }
615
+ function aggregatePolicy(acc, policy) {
616
+ if (acc.minMaxAge === void 0) {
617
+ acc.minMaxAge = policy.maxAge;
618
+ } else {
619
+ acc.minMaxAge = Math.min(acc.minMaxAge, policy.maxAge);
620
+ }
621
+ if (policy.scope === "PRIVATE") {
622
+ acc.hasPrivate = true;
623
+ }
624
+ }
625
+ function analyzeFragmentSpread2(fragmentName, ctx, parentMaxAge, visitedFragments) {
626
+ if (visitedFragments.has(fragmentName)) {
627
+ return void 0;
628
+ }
629
+ const fragment = ctx.fragments.get(fragmentName);
630
+ if (!fragment) {
631
+ return void 0;
632
+ }
633
+ const fragmentType = ctx.schema.getType(fragment.typeCondition.name.value);
634
+ if (!(fragmentType instanceof GraphQLObjectType)) {
635
+ return void 0;
636
+ }
637
+ const newVisited = new Set(visitedFragments);
638
+ newVisited.add(fragmentName);
639
+ return analyzeSelectionSet2(fragment.selectionSet, fragmentType, ctx, parentMaxAge, newVisited);
640
+ }
641
+ function analyzeInlineFragment2(selection, parentType, ctx, parentMaxAge, visitedFragments) {
642
+ let targetType = parentType;
643
+ if (selection.typeCondition) {
644
+ const conditionType = ctx.schema.getType(selection.typeCondition.name.value);
645
+ if (conditionType instanceof GraphQLObjectType) {
646
+ targetType = conditionType;
647
+ }
648
+ }
649
+ return analyzeSelectionSet2(
650
+ selection.selectionSet,
651
+ targetType,
652
+ ctx,
653
+ parentMaxAge,
654
+ visitedFragments
655
+ );
656
+ }
657
+ function lookupEffectiveCacheHint(parentTypeName, fieldName, returnType, cacheHints) {
658
+ const fieldKey = `${parentTypeName}.${fieldName}`;
659
+ const fieldHint = cacheHints.get(fieldKey);
660
+ if (fieldHint) return fieldHint;
661
+ const namedType = getNamedType2(returnType);
662
+ return namedType ? cacheHints.get(namedType.name) : void 0;
663
+ }
664
+ function computeFieldMaxAge(hint, fieldType, parentMaxAge, defaultMaxAge) {
665
+ if (hint) {
666
+ if (hint.inheritMaxAge && parentMaxAge !== void 0) {
667
+ return parentMaxAge;
668
+ }
669
+ if (hint.maxAge !== void 0) {
670
+ return hint.maxAge;
671
+ }
672
+ }
673
+ if (isLeafType(fieldType) && parentMaxAge !== void 0) {
674
+ return parentMaxAge;
675
+ }
676
+ return defaultMaxAge;
677
+ }
678
+ function analyzeSelectionSet2(selectionSet, parentType, schemaOrCtx, fragmentsOrParentMaxAge, cacheHintsOrVisited, defaultMaxAge, defaultScope, parentMaxAge, visitedFragments) {
679
+ let ctx;
680
+ let actualParentMaxAge;
681
+ let actualVisitedFragments;
682
+ if (schemaOrCtx instanceof GraphQLSchema) {
683
+ ctx = {
684
+ schema: schemaOrCtx,
685
+ fragments: fragmentsOrParentMaxAge,
686
+ cacheHints: cacheHintsOrVisited,
687
+ defaultMaxAge,
688
+ defaultScope
689
+ };
690
+ actualParentMaxAge = parentMaxAge;
691
+ actualVisitedFragments = visitedFragments;
692
+ } else {
693
+ ctx = schemaOrCtx;
694
+ actualParentMaxAge = fragmentsOrParentMaxAge;
695
+ actualVisitedFragments = cacheHintsOrVisited;
696
+ }
697
+ const acc = { minMaxAge: void 0, hasPrivate: false };
698
+ for (const selection of selectionSet.selections) {
699
+ let fieldPolicy;
700
+ switch (selection.kind) {
701
+ case Kind.FIELD:
702
+ fieldPolicy = analyzeField2(
703
+ selection,
704
+ parentType,
705
+ ctx,
706
+ actualParentMaxAge,
707
+ actualVisitedFragments
708
+ );
709
+ break;
710
+ case Kind.FRAGMENT_SPREAD:
711
+ fieldPolicy = analyzeFragmentSpread2(
712
+ selection.name.value,
713
+ ctx,
714
+ actualParentMaxAge,
715
+ actualVisitedFragments
716
+ );
717
+ break;
718
+ case Kind.INLINE_FRAGMENT:
719
+ fieldPolicy = analyzeInlineFragment2(
720
+ selection,
721
+ parentType,
722
+ ctx,
723
+ actualParentMaxAge,
724
+ actualVisitedFragments
725
+ );
726
+ break;
727
+ }
728
+ if (fieldPolicy) {
729
+ aggregatePolicy(acc, fieldPolicy);
730
+ }
731
+ }
732
+ return {
733
+ maxAge: acc.minMaxAge ?? ctx.defaultMaxAge,
734
+ scope: acc.hasPrivate ? "PRIVATE" : ctx.defaultScope
735
+ };
736
+ }
737
+ function analyzeField2(field, parentType, ctx, parentMaxAge, visitedFragments) {
738
+ const fieldName = field.name.value;
739
+ if (fieldName.startsWith("__")) {
740
+ return { maxAge: Infinity, scope: "PUBLIC" };
741
+ }
742
+ const schemaField = parentType.getFields()[fieldName];
743
+ if (!schemaField) {
744
+ return { maxAge: ctx.defaultMaxAge, scope: ctx.defaultScope };
745
+ }
746
+ const effectiveHint = lookupEffectiveCacheHint(
747
+ parentType.name,
748
+ fieldName,
749
+ schemaField.type,
750
+ ctx.cacheHints
751
+ );
752
+ const fieldMaxAge = computeFieldMaxAge(
753
+ effectiveHint,
754
+ schemaField.type,
755
+ parentMaxAge,
756
+ ctx.defaultMaxAge
757
+ );
758
+ const fieldScope = effectiveHint?.scope ?? ctx.defaultScope;
759
+ const namedType = getNamedType2(schemaField.type);
760
+ if (field.selectionSet && namedType instanceof GraphQLObjectType) {
761
+ const nestedPolicy = analyzeSelectionSet2(
762
+ field.selectionSet,
763
+ namedType,
764
+ ctx,
765
+ fieldMaxAge,
766
+ visitedFragments
767
+ );
768
+ return {
769
+ maxAge: Math.min(fieldMaxAge, nestedPolicy.maxAge),
770
+ scope: fieldScope === "PRIVATE" || nestedPolicy.scope === "PRIVATE" ? "PRIVATE" : "PUBLIC"
771
+ };
772
+ }
773
+ return { maxAge: fieldMaxAge, scope: fieldScope };
774
+ }
775
+ var CacheControlConfigFromEnv = Config.all({
776
+ enabled: Config.boolean("GRAPHQL_CACHE_CONTROL_ENABLED").pipe(Config.withDefault(true)),
777
+ defaultMaxAge: Config.number("GRAPHQL_CACHE_CONTROL_DEFAULT_MAX_AGE").pipe(Config.withDefault(0)),
778
+ defaultScope: Config.string("GRAPHQL_CACHE_CONTROL_DEFAULT_SCOPE").pipe(
779
+ Config.withDefault("PUBLIC"),
780
+ Config.map((s) => s === "PRIVATE" ? "PRIVATE" : "PUBLIC")
781
+ ),
782
+ calculateHttpHeaders: Config.boolean("GRAPHQL_CACHE_CONTROL_HTTP_HEADERS").pipe(
783
+ Config.withDefault(true)
784
+ )
785
+ });
786
+ var ExtensionsService = Context.GenericTag(
787
+ "@effect-gql/ExtensionsService"
788
+ );
789
+ function deepMerge(target, source) {
790
+ const result = { ...target };
791
+ for (const key of Object.keys(source)) {
792
+ const sourceValue = source[key];
793
+ const targetValue = result[key];
794
+ if (typeof sourceValue === "object" && sourceValue !== null && !Array.isArray(sourceValue) && typeof targetValue === "object" && targetValue !== null && !Array.isArray(targetValue)) {
795
+ result[key] = deepMerge(
796
+ targetValue,
797
+ sourceValue
798
+ );
799
+ } else {
800
+ result[key] = sourceValue;
801
+ }
802
+ }
803
+ return result;
804
+ }
805
+ var makeExtensionsService = () => Effect.gen(function* () {
806
+ const ref = yield* Ref.make({});
807
+ return ExtensionsService.of({
808
+ set: (key, value) => Ref.update(ref, (current) => ({ ...current, [key]: value })),
809
+ merge: (key, value) => Ref.update(ref, (current) => {
810
+ const existing = current[key];
811
+ if (typeof existing === "object" && existing !== null && !Array.isArray(existing)) {
812
+ return {
813
+ ...current,
814
+ [key]: deepMerge(existing, value)
815
+ };
816
+ }
817
+ return { ...current, [key]: value };
818
+ }),
819
+ get: () => Ref.get(ref)
820
+ });
821
+ });
822
+ var runExtensionHooks = (extensions, hookName, getHookEffect) => Effect.forEach(
823
+ extensions.filter((ext) => ext[hookName] !== void 0),
824
+ (ext) => getHookEffect(ext).pipe(
825
+ Effect.catchAllCause(
826
+ (cause) => Effect.logWarning(`Extension "${ext.name}" ${String(hookName)} hook failed`, cause)
827
+ )
828
+ ),
829
+ { discard: true }
830
+ );
831
+ var runParseHooks = (extensions, source, document) => runExtensionHooks(extensions, "onParse", (ext) => ext.onParse(source, document));
832
+ var runValidateHooks = (extensions, document, errors) => runExtensionHooks(extensions, "onValidate", (ext) => ext.onValidate(document, errors));
833
+ var runExecuteStartHooks = (extensions, args) => runExtensionHooks(extensions, "onExecuteStart", (ext) => ext.onExecuteStart(args));
834
+ var runExecuteEndHooks = (extensions, result) => runExtensionHooks(extensions, "onExecuteEnd", (ext) => ext.onExecuteEnd(result));
835
+
836
+ // src/server/router.ts
837
+ var defaultErrorHandler = (cause) => (process.env.NODE_ENV !== "production" ? Effect.logError("GraphQL error", cause) : Effect.void).pipe(
838
+ Effect.andThen(
839
+ HttpServerResponse.json(
840
+ {
841
+ errors: [
842
+ {
843
+ message: "An error occurred processing your request"
844
+ }
845
+ ]
846
+ },
847
+ { status: 500 }
848
+ ).pipe(Effect.orDie)
849
+ )
850
+ );
851
+ var parseGraphQLQuery = (query, extensionsService) => Effect.gen(function* () {
852
+ try {
853
+ const document = parse(query);
854
+ return { ok: true, document };
855
+ } catch (parseError) {
856
+ const extensionData = yield* extensionsService.get();
857
+ const response = yield* HttpServerResponse.json({
858
+ errors: [{ message: String(parseError) }],
859
+ extensions: Object.keys(extensionData).length > 0 ? extensionData : void 0
860
+ }).pipe(Effect.orDie);
861
+ return { ok: false, response };
862
+ }
863
+ });
864
+ var runComplexityValidation = (body, schema, fieldComplexities, complexityConfig) => {
865
+ if (!complexityConfig) {
866
+ return Effect.void;
867
+ }
868
+ return validateComplexity(
869
+ body.query,
870
+ body.operationName,
871
+ body.variables,
872
+ schema,
873
+ fieldComplexities,
874
+ complexityConfig
875
+ ).pipe(
876
+ Effect.catchTag("ComplexityLimitExceededError", (error) => Effect.fail(error)),
877
+ Effect.catchTag(
878
+ "ComplexityAnalysisError",
879
+ (error) => Effect.logWarning("Complexity analysis failed", error)
880
+ )
881
+ );
882
+ };
883
+ var executeGraphQLQuery = (schema, document, variables, operationName, runtime) => Effect.gen(function* () {
884
+ const executeResult = yield* Effect.try({
885
+ try: () => execute({
886
+ schema,
887
+ document,
888
+ variableValues: variables,
889
+ operationName,
890
+ contextValue: { runtime }
891
+ }),
892
+ catch: (error) => new Error(String(error))
893
+ });
894
+ if (executeResult && typeof executeResult === "object" && "then" in executeResult) {
895
+ return yield* Effect.promise(
896
+ () => executeResult
897
+ );
898
+ }
899
+ return executeResult;
900
+ });
901
+ var computeCacheControlHeader = (document, operationName, schema, cacheHints, cacheControlConfig) => Effect.gen(function* () {
902
+ if (cacheControlConfig?.enabled === false || cacheControlConfig?.calculateHttpHeaders === false) {
903
+ return void 0;
904
+ }
905
+ const operations = document.definitions.filter(
906
+ (d) => d.kind === Kind.OPERATION_DEFINITION
907
+ );
908
+ const operation = operationName ? operations.find((o) => o.name?.value === operationName) : operations[0];
909
+ if (!operation || operation.operation === "mutation") {
910
+ return void 0;
911
+ }
912
+ const cachePolicy = yield* computeCachePolicy({
913
+ document,
914
+ operation,
915
+ schema,
916
+ cacheHints,
917
+ config: cacheControlConfig ?? {}
918
+ });
919
+ return toCacheControlHeader(cachePolicy);
920
+ });
921
+ var buildGraphQLResponse = (result, extensionData, cacheControlHeader) => {
922
+ const finalResult = Object.keys(extensionData).length > 0 ? {
923
+ ...result,
924
+ extensions: {
925
+ ...result.extensions,
926
+ ...extensionData
927
+ }
928
+ } : result;
929
+ const responseHeaders = cacheControlHeader ? { "cache-control": cacheControlHeader } : void 0;
930
+ return HttpServerResponse.json(finalResult, { headers: responseHeaders }).pipe(Effect.orDie);
931
+ };
932
+ var handleComplexityError = (error) => HttpServerResponse.json(
933
+ {
934
+ errors: [
935
+ {
936
+ message: error.message,
937
+ extensions: {
938
+ code: "COMPLEXITY_LIMIT_EXCEEDED",
939
+ limitType: error.limitType,
940
+ limit: error.limit,
941
+ actual: error.actual
942
+ }
943
+ }
944
+ ]
945
+ },
946
+ { status: 400 }
947
+ ).pipe(Effect.orDie);
948
+ var makeGraphQLRouter = (schema, layer, options = {}) => {
949
+ const resolvedConfig = normalizeConfig(options);
950
+ const fieldComplexities = options.fieldComplexities ?? /* @__PURE__ */ new Map();
951
+ const cacheHints = options.cacheHints ?? /* @__PURE__ */ new Map();
952
+ const extensions = options.extensions ?? [];
953
+ const errorHandler = options.errorHandler ?? defaultErrorHandler;
954
+ const graphqlHandler = Effect.gen(function* () {
955
+ const extensionsService = yield* makeExtensionsService();
956
+ const runtime = yield* Effect.runtime();
957
+ const request = yield* HttpServerRequest.HttpServerRequest;
958
+ const body = yield* request.json;
959
+ const parseResult = yield* parseGraphQLQuery(body.query, extensionsService);
960
+ if (!parseResult.ok) {
961
+ return parseResult.response;
962
+ }
963
+ const document = parseResult.document;
964
+ yield* runParseHooks(extensions, body.query, document).pipe(
965
+ Effect.provideService(ExtensionsService, extensionsService)
966
+ );
967
+ const validationRules = resolvedConfig.introspection ? void 0 : [...specifiedRules, NoSchemaIntrospectionCustomRule];
968
+ const validationErrors = validate(schema, document, validationRules);
969
+ yield* runValidateHooks(extensions, document, validationErrors).pipe(
970
+ Effect.provideService(ExtensionsService, extensionsService)
971
+ );
972
+ if (validationErrors.length > 0) {
973
+ const extensionData2 = yield* extensionsService.get();
974
+ return yield* HttpServerResponse.json(
975
+ {
976
+ errors: validationErrors.map((e) => ({
977
+ message: e.message,
978
+ locations: e.locations,
979
+ path: e.path
980
+ })),
981
+ extensions: Object.keys(extensionData2).length > 0 ? extensionData2 : void 0
982
+ },
983
+ { status: 400 }
984
+ );
985
+ }
986
+ yield* runComplexityValidation(body, schema, fieldComplexities, resolvedConfig.complexity);
987
+ yield* runExecuteStartHooks(extensions, {
988
+ source: body.query,
989
+ document,
990
+ variableValues: body.variables,
991
+ operationName: body.operationName,
992
+ schema,
993
+ fieldComplexities
994
+ }).pipe(Effect.provideService(ExtensionsService, extensionsService));
995
+ const result = yield* executeGraphQLQuery(
996
+ schema,
997
+ document,
998
+ body.variables,
999
+ body.operationName,
1000
+ runtime
1001
+ );
1002
+ yield* runExecuteEndHooks(extensions, result).pipe(
1003
+ Effect.provideService(ExtensionsService, extensionsService)
1004
+ );
1005
+ const extensionData = yield* extensionsService.get();
1006
+ const cacheControlHeader = yield* computeCacheControlHeader(
1007
+ document,
1008
+ body.operationName,
1009
+ schema,
1010
+ cacheHints,
1011
+ resolvedConfig.cacheControl
1012
+ );
1013
+ return yield* buildGraphQLResponse(result, extensionData, cacheControlHeader);
1014
+ }).pipe(
1015
+ Effect.provide(layer),
1016
+ Effect.catchAll((error) => {
1017
+ if (error instanceof ComplexityLimitExceededError) {
1018
+ return handleComplexityError(error);
1019
+ }
1020
+ return Effect.fail(error);
1021
+ }),
1022
+ Effect.catchAllCause(errorHandler)
1023
+ );
1024
+ let router = HttpRouter.empty.pipe(
1025
+ HttpRouter.post(resolvedConfig.path, graphqlHandler)
1026
+ );
1027
+ if (resolvedConfig.graphiql) {
1028
+ const { path, endpoint } = resolvedConfig.graphiql;
1029
+ router = router.pipe(
1030
+ HttpRouter.get(path, HttpServerResponse.html(graphiqlHtml(endpoint)))
1031
+ );
1032
+ }
1033
+ return router;
1034
+ };
1035
+
1036
+ // src/server/schema-builder-extensions.ts
1037
+ var toRouter = (builder, layer, options) => {
1038
+ const schema = builder.buildSchema();
1039
+ const fieldComplexities = builder.getFieldComplexities();
1040
+ const cacheHints = builder.getCacheHints();
1041
+ return makeGraphQLRouter(schema, layer, { ...options, fieldComplexities, cacheHints });
1042
+ };
1043
+ var WebSocketError = class extends Data.TaggedError("WebSocketError") {
1044
+ };
1045
+ var createConnectionContext = (extra) => ({
1046
+ runtime: extra.runtime,
1047
+ connectionParams: extra.connectionParams,
1048
+ socket: extra.socket
1049
+ });
1050
+ var makeOnConnectHandler = (options) => {
1051
+ if (!options?.onConnect) return void 0;
1052
+ return async (ctx) => {
1053
+ const extra = ctx.extra;
1054
+ try {
1055
+ const result = await Runtime.runPromise(extra.runtime)(
1056
+ options.onConnect(ctx.connectionParams ?? {})
1057
+ );
1058
+ if (typeof result === "object" && result !== null) {
1059
+ Object.assign(extra.connectionParams, result);
1060
+ }
1061
+ return result !== false;
1062
+ } catch {
1063
+ return false;
1064
+ }
1065
+ };
1066
+ };
1067
+ var makeOnDisconnectHandler = (options) => {
1068
+ if (!options?.onDisconnect) return void 0;
1069
+ return async (ctx) => {
1070
+ const extra = ctx.extra;
1071
+ await Runtime.runPromise(extra.runtime)(
1072
+ options.onDisconnect(createConnectionContext(extra))
1073
+ ).catch(() => {
1074
+ });
1075
+ };
1076
+ };
1077
+ var makeOnSubscribeHandler = (options, schema, complexityConfig, fieldComplexities) => {
1078
+ return async (ctx, id, payload) => {
1079
+ const extra = ctx.extra;
1080
+ const connectionCtx = createConnectionContext(extra);
1081
+ if (complexityConfig) {
1082
+ const validationEffect = validateComplexity(
1083
+ payload.query,
1084
+ payload.operationName ?? void 0,
1085
+ payload.variables ?? void 0,
1086
+ schema,
1087
+ fieldComplexities,
1088
+ complexityConfig
1089
+ ).pipe(
1090
+ Effect.catchAll((error) => {
1091
+ if (error._tag === "ComplexityLimitExceededError") {
1092
+ throw new GraphQLError(error.message, {
1093
+ extensions: {
1094
+ code: "COMPLEXITY_LIMIT_EXCEEDED",
1095
+ limitType: error.limitType,
1096
+ limit: error.limit,
1097
+ actual: error.actual
1098
+ }
1099
+ });
1100
+ }
1101
+ return Effect.logWarning("Complexity analysis failed for subscription", error);
1102
+ })
1103
+ );
1104
+ await Effect.runPromise(validationEffect);
1105
+ }
1106
+ if (options?.onSubscribe) {
1107
+ await Runtime.runPromise(extra.runtime)(
1108
+ options.onSubscribe(connectionCtx, {
1109
+ id,
1110
+ payload: {
1111
+ query: payload.query,
1112
+ variables: payload.variables ?? void 0,
1113
+ operationName: payload.operationName ?? void 0,
1114
+ extensions: payload.extensions ?? void 0
1115
+ }
1116
+ })
1117
+ );
1118
+ }
1119
+ };
1120
+ };
1121
+ var makeOnCompleteHandler = (options) => {
1122
+ if (!options?.onComplete) return void 0;
1123
+ return async (ctx, id, _payload) => {
1124
+ const extra = ctx.extra;
1125
+ await Runtime.runPromise(extra.runtime)(
1126
+ options.onComplete(createConnectionContext(extra), { id })
1127
+ ).catch(() => {
1128
+ });
1129
+ };
1130
+ };
1131
+ var makeOnErrorHandler = (options) => {
1132
+ if (!options?.onError) return void 0;
1133
+ return async (ctx, _id, _payload, errors) => {
1134
+ const extra = ctx.extra;
1135
+ await Runtime.runPromise(extra.runtime)(
1136
+ options.onError(createConnectionContext(extra), errors)
1137
+ ).catch(() => {
1138
+ });
1139
+ };
1140
+ };
1141
+ var createGraphqlWsSocketAdapter = (socket, runtime) => {
1142
+ let messageCallback = null;
1143
+ return {
1144
+ adapter: {
1145
+ protocol: socket.protocol,
1146
+ send: (data) => Runtime.runPromise(runtime)(
1147
+ socket.send(data).pipe(Effect.catchAll((error) => Effect.logError("WebSocket send error", error)))
1148
+ ),
1149
+ close: (code, reason) => {
1150
+ Runtime.runPromise(runtime)(socket.close(code, reason)).catch(() => {
1151
+ });
1152
+ },
1153
+ onMessage: (cb) => {
1154
+ messageCallback = cb;
1155
+ },
1156
+ onPong: (_payload) => {
1157
+ }
1158
+ },
1159
+ dispatchMessage: async (message) => {
1160
+ if (messageCallback) {
1161
+ await messageCallback(message);
1162
+ }
1163
+ }
1164
+ };
1165
+ };
1166
+ var runConnectionLifecycle = (socket, wsServer, extra) => Effect.gen(function* () {
1167
+ const messageQueue = yield* Queue.unbounded();
1168
+ const closedDeferred = yield* Deferred.make();
1169
+ const messageFiber = yield* Effect.fork(
1170
+ Stream.runForEach(socket.messages, (msg) => Queue.offer(messageQueue, msg)).pipe(
1171
+ Effect.catchAll((error) => Deferred.fail(closedDeferred, error))
1172
+ )
1173
+ );
1174
+ const closeFiber = yield* Effect.fork(
1175
+ socket.closed.pipe(
1176
+ Effect.tap((event) => Deferred.succeed(closedDeferred, event)),
1177
+ Effect.catchAll((error) => Deferred.fail(closedDeferred, error))
1178
+ )
1179
+ );
1180
+ const { adapter, dispatchMessage } = createGraphqlWsSocketAdapter(socket, extra.runtime);
1181
+ const closedHandler = wsServer.opened(adapter, extra);
1182
+ const processMessagesFiber = yield* Effect.fork(
1183
+ Effect.gen(function* () {
1184
+ while (true) {
1185
+ const message = yield* Queue.take(messageQueue);
1186
+ yield* Effect.tryPromise({
1187
+ try: () => dispatchMessage(message),
1188
+ catch: (error) => error
1189
+ }).pipe(Effect.catchAll(() => Effect.void));
1190
+ }
1191
+ })
1192
+ );
1193
+ yield* Deferred.await(closedDeferred).pipe(
1194
+ Effect.catchAll(() => Effect.succeed({ code: 1e3, reason: "Error" }))
1195
+ );
1196
+ closedHandler(1e3, "Connection closed");
1197
+ yield* Fiber.interrupt(messageFiber);
1198
+ yield* Fiber.interrupt(closeFiber);
1199
+ yield* Fiber.interrupt(processMessagesFiber);
1200
+ yield* Queue.shutdown(messageQueue);
1201
+ }).pipe(
1202
+ Effect.catchAllCause(() => Effect.void),
1203
+ Effect.scoped
1204
+ );
1205
+ var makeGraphQLWSHandler = (schema, layer, options) => {
1206
+ const complexityConfig = options?.complexity;
1207
+ const fieldComplexities = options?.fieldComplexities ?? /* @__PURE__ */ new Map();
1208
+ const serverOptions = {
1209
+ schema,
1210
+ context: async (ctx) => {
1211
+ const extra = ctx.extra;
1212
+ return {
1213
+ runtime: extra.runtime,
1214
+ ...extra.connectionParams
1215
+ };
1216
+ },
1217
+ subscribe: async (args) => subscribe(args),
1218
+ onConnect: makeOnConnectHandler(options),
1219
+ onDisconnect: makeOnDisconnectHandler(options),
1220
+ onSubscribe: makeOnSubscribeHandler(options, schema, complexityConfig, fieldComplexities),
1221
+ onComplete: makeOnCompleteHandler(options),
1222
+ onError: makeOnErrorHandler(options)
1223
+ };
1224
+ const wsServer = makeServer(serverOptions);
1225
+ return (socket) => Effect.gen(function* () {
1226
+ const runtime = yield* Effect.provide(Effect.runtime(), layer);
1227
+ const extra = {
1228
+ socket,
1229
+ runtime,
1230
+ connectionParams: {}
1231
+ };
1232
+ yield* runConnectionLifecycle(socket, wsServer, extra);
1233
+ }).pipe(
1234
+ Effect.catchAllCause(() => Effect.void),
1235
+ Effect.scoped
1236
+ );
1237
+ };
1238
+ var WS_CLOSED = 3;
1239
+ var toEffectWebSocketFromWs = (ws) => {
1240
+ const messagesEffect = Effect.gen(function* () {
1241
+ const queue = yield* Queue.unbounded();
1242
+ const closed = yield* Deferred.make();
1243
+ ws.on("message", (data) => {
1244
+ const message = data.toString();
1245
+ Effect.runPromise(Queue.offer(queue, message)).catch(() => {
1246
+ });
1247
+ });
1248
+ ws.on("error", (error) => {
1249
+ Effect.runPromise(Deferred.fail(closed, new WebSocketError({ cause: error }))).catch(() => {
1250
+ });
1251
+ });
1252
+ ws.on("close", (code, reason) => {
1253
+ Effect.runPromise(
1254
+ Queue.shutdown(queue).pipe(
1255
+ Effect.andThen(Deferred.succeed(closed, { code, reason: reason.toString() }))
1256
+ )
1257
+ ).catch(() => {
1258
+ });
1259
+ });
1260
+ return { queue, closed };
1261
+ });
1262
+ const messages = Stream.unwrap(
1263
+ messagesEffect.pipe(
1264
+ Effect.map(({ queue }) => Stream.fromQueue(queue).pipe(Stream.catchAll(() => Stream.empty)))
1265
+ )
1266
+ );
1267
+ return {
1268
+ protocol: ws.protocol || "graphql-transport-ws",
1269
+ send: (data) => Effect.async((resume) => {
1270
+ ws.send(data, (error) => {
1271
+ if (error) {
1272
+ resume(Effect.fail(new WebSocketError({ cause: error })));
1273
+ } else {
1274
+ resume(Effect.succeed(void 0));
1275
+ }
1276
+ });
1277
+ }),
1278
+ close: (code, reason) => Effect.sync(() => {
1279
+ ws.close(code ?? 1e3, reason ?? "");
1280
+ }),
1281
+ messages,
1282
+ closed: Effect.async((resume) => {
1283
+ if (ws.readyState === WS_CLOSED) {
1284
+ resume(Effect.succeed({ code: 1e3, reason: "" }));
1285
+ return;
1286
+ }
1287
+ const onClose = (code, reason) => {
1288
+ cleanup();
1289
+ resume(Effect.succeed({ code, reason: reason.toString() }));
1290
+ };
1291
+ const onError = (error) => {
1292
+ cleanup();
1293
+ resume(Effect.fail(new WebSocketError({ cause: error })));
1294
+ };
1295
+ const cleanup = () => {
1296
+ ws.removeListener("close", onClose);
1297
+ ws.removeListener("error", onError);
1298
+ };
1299
+ ws.on("close", onClose);
1300
+ ws.on("error", onError);
1301
+ return Effect.sync(cleanup);
1302
+ })
1303
+ };
1304
+ };
1305
+ var SSE_HEADERS = {
1306
+ "Content-Type": "text/event-stream",
1307
+ "Cache-Control": "no-cache",
1308
+ Connection: "keep-alive",
1309
+ "X-Accel-Buffering": "no"
1310
+ // Disable nginx buffering
1311
+ };
1312
+ var SSEError = class extends Data.TaggedError("SSEError") {
1313
+ };
1314
+ var formatNextEvent = (result) => ({
1315
+ event: "next",
1316
+ data: JSON.stringify(result)
1317
+ });
1318
+ var formatErrorEvent = (errors) => ({
1319
+ event: "error",
1320
+ data: JSON.stringify({ errors })
1321
+ });
1322
+ var formatCompleteEvent = () => ({
1323
+ event: "complete",
1324
+ data: ""
1325
+ });
1326
+ var formatSSEMessage = (event) => {
1327
+ const lines = [`event: ${event.event}`];
1328
+ if (event.data) {
1329
+ lines.push(`data: ${event.data}`);
1330
+ }
1331
+ lines.push("", "");
1332
+ return lines.join("\n");
1333
+ };
1334
+ var makeSSESubscriptionStream = (schema, layer, request, headers, options) => {
1335
+ const complexityConfig = options?.complexity;
1336
+ const fieldComplexities = options?.fieldComplexities ?? /* @__PURE__ */ new Map();
1337
+ return Stream.unwrap(
1338
+ Effect.gen(function* () {
1339
+ const runtime = yield* Effect.provide(Effect.runtime(), layer);
1340
+ let connectionContext = {};
1341
+ if (options?.onConnect) {
1342
+ try {
1343
+ connectionContext = yield* Effect.provide(options.onConnect(request, headers), layer);
1344
+ } catch {
1345
+ return Stream.make(
1346
+ formatErrorEvent([
1347
+ new GraphQLError("Subscription connection rejected", {
1348
+ extensions: { code: "CONNECTION_REJECTED" }
1349
+ })
1350
+ ]),
1351
+ formatCompleteEvent()
1352
+ );
1353
+ }
1354
+ }
1355
+ let document;
1356
+ try {
1357
+ document = parse(request.query);
1358
+ } catch (syntaxError) {
1359
+ return Stream.make(formatErrorEvent([syntaxError]), formatCompleteEvent());
1360
+ }
1361
+ const validationErrors = validate(schema, document);
1362
+ if (validationErrors.length > 0) {
1363
+ return Stream.make(formatErrorEvent(validationErrors), formatCompleteEvent());
1364
+ }
1365
+ const operations = document.definitions.filter(
1366
+ (d) => d.kind === Kind.OPERATION_DEFINITION
1367
+ );
1368
+ const operation = request.operationName ? operations.find((o) => o.name?.value === request.operationName) : operations[0];
1369
+ if (!operation) {
1370
+ return Stream.make(
1371
+ formatErrorEvent([new GraphQLError("No operation found in query")]),
1372
+ formatCompleteEvent()
1373
+ );
1374
+ }
1375
+ if (operation.operation !== "subscription") {
1376
+ return Stream.make(
1377
+ formatErrorEvent([
1378
+ new GraphQLError(
1379
+ `SSE endpoint only supports subscriptions, received: ${operation.operation}`,
1380
+ { extensions: { code: "OPERATION_NOT_SUPPORTED" } }
1381
+ )
1382
+ ]),
1383
+ formatCompleteEvent()
1384
+ );
1385
+ }
1386
+ if (complexityConfig) {
1387
+ const complexityResult = yield* validateComplexity(
1388
+ request.query,
1389
+ request.operationName,
1390
+ request.variables,
1391
+ schema,
1392
+ fieldComplexities,
1393
+ complexityConfig
1394
+ ).pipe(
1395
+ Effect.map(() => null),
1396
+ Effect.catchAll((error) => {
1397
+ if (error._tag === "ComplexityLimitExceededError") {
1398
+ return Effect.succeed(
1399
+ new GraphQLError(error.message, {
1400
+ extensions: {
1401
+ code: "COMPLEXITY_LIMIT_EXCEEDED",
1402
+ limitType: error.limitType,
1403
+ limit: error.limit,
1404
+ actual: error.actual
1405
+ }
1406
+ })
1407
+ );
1408
+ }
1409
+ return Effect.logWarning("Complexity analysis failed for SSE subscription", error).pipe(
1410
+ Effect.map(() => null)
1411
+ );
1412
+ })
1413
+ );
1414
+ if (complexityResult) {
1415
+ return Stream.make(formatErrorEvent([complexityResult]), formatCompleteEvent());
1416
+ }
1417
+ }
1418
+ const ctx = {
1419
+ runtime,
1420
+ request,
1421
+ connectionContext
1422
+ };
1423
+ if (options?.onSubscribe) {
1424
+ yield* Effect.provide(options.onSubscribe(ctx), layer).pipe(
1425
+ Effect.catchAll(() => Effect.void)
1426
+ );
1427
+ }
1428
+ const graphqlContext = {
1429
+ runtime,
1430
+ ...connectionContext
1431
+ };
1432
+ const subscriptionResult = yield* Effect.tryPromise({
1433
+ try: () => subscribe({
1434
+ schema,
1435
+ document,
1436
+ variableValues: request.variables,
1437
+ operationName: request.operationName ?? void 0,
1438
+ contextValue: graphqlContext
1439
+ }),
1440
+ catch: (error) => new SSEError({ cause: error })
1441
+ });
1442
+ if (!isAsyncIterable(subscriptionResult)) {
1443
+ const result = subscriptionResult;
1444
+ if (result.errors) {
1445
+ return Stream.make(formatErrorEvent(result.errors), formatCompleteEvent());
1446
+ }
1447
+ return Stream.make(formatNextEvent(result), formatCompleteEvent());
1448
+ }
1449
+ const asyncIterator = subscriptionResult[Symbol.asyncIterator]();
1450
+ const eventStream = Stream.async((emit) => {
1451
+ let done = false;
1452
+ const iterate = async () => {
1453
+ try {
1454
+ while (!done) {
1455
+ const result = await asyncIterator.next();
1456
+ if (result.done) {
1457
+ emit.end();
1458
+ break;
1459
+ }
1460
+ emit.single(formatNextEvent(result.value));
1461
+ }
1462
+ } catch (error) {
1463
+ if (!done) {
1464
+ emit.single(
1465
+ formatErrorEvent([
1466
+ error instanceof GraphQLError ? error : new GraphQLError(
1467
+ error instanceof Error ? error.message : "Subscription error",
1468
+ { extensions: { code: "SUBSCRIPTION_ERROR" } }
1469
+ )
1470
+ ])
1471
+ );
1472
+ emit.end();
1473
+ }
1474
+ }
1475
+ };
1476
+ iterate();
1477
+ return Effect.sync(() => {
1478
+ done = true;
1479
+ asyncIterator.return?.();
1480
+ });
1481
+ });
1482
+ return eventStream.pipe(
1483
+ Stream.onDone(
1484
+ () => Effect.gen(function* () {
1485
+ yield* Effect.sync(() => {
1486
+ });
1487
+ }).pipe(Effect.asVoid)
1488
+ ),
1489
+ Stream.concat(Stream.make(formatCompleteEvent())),
1490
+ Stream.onDone(() => {
1491
+ if (options?.onComplete) {
1492
+ return Effect.provide(options.onComplete(ctx), layer).pipe(
1493
+ Effect.catchAll(() => Effect.void)
1494
+ );
1495
+ }
1496
+ return Effect.void;
1497
+ })
1498
+ );
1499
+ }).pipe(
1500
+ Effect.catchAll(
1501
+ (error) => Effect.succeed(
1502
+ Stream.make(
1503
+ formatErrorEvent([
1504
+ new GraphQLError(error instanceof Error ? error.message : "Internal error", {
1505
+ extensions: { code: "INTERNAL_ERROR" }
1506
+ })
1507
+ ]),
1508
+ formatCompleteEvent()
1509
+ )
1510
+ )
1511
+ )
1512
+ )
1513
+ );
1514
+ };
1515
+ var makeGraphQLSSEHandler = (schema, layer, options) => {
1516
+ return (request, headers) => makeSSESubscriptionStream(schema, layer, request, headers, options);
1517
+ };
1518
+ function isAsyncIterable(value) {
1519
+ return typeof value === "object" && value !== null && Symbol.asyncIterator in value;
1520
+ }
1521
+
1522
+ export { CacheControlConfigFromEnv, ComplexityAnalysisError, ComplexityConfigFromEnv, ComplexityLimitExceededError, GraphQLRouterConfigFromEnv, SSEError, SSE_HEADERS, WS_CLOSED, WebSocketError, combineCalculators, computeCachePolicy, computeCachePolicyFromQuery, defaultComplexityCalculator, defaultConfig, defaultErrorHandler, depthOnlyCalculator, formatCompleteEvent, formatErrorEvent, formatNextEvent, formatSSEMessage, graphiqlHtml, makeGraphQLRouter, makeGraphQLSSEHandler, makeGraphQLWSHandler, makeSSESubscriptionStream, normalizeConfig, toCacheControlHeader, toEffectWebSocketFromWs, toRouter, validateComplexity };
1523
+ //# sourceMappingURL=index.js.map
1524
+ //# sourceMappingURL=index.js.map