@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
package/index.js ADDED
@@ -0,0 +1,3242 @@
1
+ import { GraphQLDirective, GraphQLEnumType, GraphQLInputObjectType, GraphQLInterfaceType, GraphQLObjectType, GraphQLUnionType, GraphQLSchema, GraphQLNonNull, GraphQLString, GraphQLFloat, GraphQLBoolean, GraphQLInt, GraphQLList, parse, GraphQLError, validate, execute as execute$1, Kind, specifiedRules, NoSchemaIntrospectionCustomRule, subscribe, GraphQLScalarType } from 'graphql';
2
+ export { DirectiveLocation, GraphQLBoolean, GraphQLEnumType, GraphQLFloat, GraphQLID, GraphQLInputObjectType, GraphQLInt, GraphQLInterfaceType, GraphQLList, GraphQLNonNull, GraphQLObjectType, GraphQLScalarType, GraphQLSchema, GraphQLString, GraphQLUnionType, Kind, graphql, lexicographicSortSchema, printSchema } from 'graphql';
3
+ import { Pipeable, Context, Data, Layer, Effect, Ref, HashMap, Config, Option, Runtime, Queue, Stream, Fiber, Deferred } from 'effect';
4
+ import * as S2 from 'effect/Schema';
5
+ import * as AST from 'effect/SchemaAST';
6
+ import DataLoader from 'dataloader';
7
+ import { HttpServerResponse, HttpServerRequest, HttpRouter } from '@effect/platform';
8
+ import { makeServer } from 'graphql-ws';
9
+
10
+ // src/builder/index.ts
11
+ var isIntegerType = (ast) => {
12
+ if (ast._tag === "Refinement") {
13
+ const refinement = ast;
14
+ const annotations = refinement.annotations;
15
+ if (annotations) {
16
+ const identifier = AST.getIdentifierAnnotation(refinement);
17
+ if (identifier._tag === "Some" && identifier.value === "Int") {
18
+ return true;
19
+ }
20
+ }
21
+ return isIntegerType(refinement.from);
22
+ }
23
+ return false;
24
+ };
25
+ var toGraphQLType = (schema) => {
26
+ const ast = schema.ast;
27
+ if (ast._tag === "StringKeyword") return GraphQLString;
28
+ if (ast._tag === "NumberKeyword") return GraphQLFloat;
29
+ if (ast._tag === "BooleanKeyword") return GraphQLBoolean;
30
+ if (ast._tag === "Refinement") {
31
+ if (isIntegerType(ast)) {
32
+ return GraphQLInt;
33
+ }
34
+ return toGraphQLType(S2.make(ast.from));
35
+ }
36
+ if (ast._tag === "Literal") {
37
+ if (typeof ast.literal === "string") return GraphQLString;
38
+ if (typeof ast.literal === "number") {
39
+ return Number.isInteger(ast.literal) ? GraphQLInt : GraphQLFloat;
40
+ }
41
+ if (typeof ast.literal === "boolean") return GraphQLBoolean;
42
+ }
43
+ if (ast._tag === "TupleType") {
44
+ const elements = ast.elements;
45
+ if (elements.length > 0) {
46
+ const elementSchema = S2.make(elements[0].type);
47
+ return new GraphQLList(toGraphQLType(elementSchema));
48
+ }
49
+ }
50
+ if (ast._tag === "TypeLiteral") {
51
+ const fields = {};
52
+ for (const field2 of ast.propertySignatures) {
53
+ const fieldName = String(field2.name);
54
+ const fieldSchema = S2.make(field2.type);
55
+ let fieldType = toGraphQLType(fieldSchema);
56
+ if (!field2.isOptional) {
57
+ fieldType = new GraphQLNonNull(fieldType);
58
+ }
59
+ fields[fieldName] = { type: fieldType };
60
+ }
61
+ const typeName = schema.annotations?.identifier || `Object_${Math.random().toString(36).slice(2, 11)}`;
62
+ return new GraphQLObjectType({
63
+ name: typeName,
64
+ fields
65
+ });
66
+ }
67
+ if (ast._tag === "Transformation") {
68
+ return toGraphQLType(S2.make(ast.to));
69
+ }
70
+ if (ast._tag === "Union") {
71
+ const types = ast.types;
72
+ if (types.length > 0) {
73
+ return toGraphQLType(S2.make(types[0]));
74
+ }
75
+ }
76
+ if (ast._tag === "Suspend") {
77
+ const innerAst = ast.f();
78
+ return toGraphQLType(S2.make(innerAst));
79
+ }
80
+ return GraphQLString;
81
+ };
82
+ var toGraphQLInputType = (schema) => {
83
+ const ast = schema.ast;
84
+ if (ast._tag === "StringKeyword") return GraphQLString;
85
+ if (ast._tag === "NumberKeyword") return GraphQLFloat;
86
+ if (ast._tag === "BooleanKeyword") return GraphQLBoolean;
87
+ if (ast._tag === "Refinement") {
88
+ if (isIntegerType(ast)) {
89
+ return GraphQLInt;
90
+ }
91
+ return toGraphQLInputType(S2.make(ast.from));
92
+ }
93
+ if (ast._tag === "Literal") {
94
+ if (typeof ast.literal === "string") return GraphQLString;
95
+ if (typeof ast.literal === "number") {
96
+ return Number.isInteger(ast.literal) ? GraphQLInt : GraphQLFloat;
97
+ }
98
+ if (typeof ast.literal === "boolean") return GraphQLBoolean;
99
+ }
100
+ if (ast._tag === "TupleType") {
101
+ const elements = ast.elements;
102
+ if (elements.length > 0) {
103
+ const elementSchema = S2.make(elements[0].type);
104
+ return new GraphQLList(toGraphQLInputType(elementSchema));
105
+ }
106
+ }
107
+ if (ast._tag === "TypeLiteral") {
108
+ const fields = {};
109
+ for (const field2 of ast.propertySignatures) {
110
+ const fieldName = String(field2.name);
111
+ const fieldSchema = S2.make(field2.type);
112
+ let fieldType = toGraphQLInputType(fieldSchema);
113
+ if (!field2.isOptional) {
114
+ fieldType = new GraphQLNonNull(fieldType);
115
+ }
116
+ fields[fieldName] = { type: fieldType };
117
+ }
118
+ const typeName = schema.annotations?.identifier || `Input_${Math.random().toString(36).slice(2, 11)}`;
119
+ return new GraphQLInputObjectType({
120
+ name: typeName,
121
+ fields
122
+ });
123
+ }
124
+ if (ast._tag === "Transformation") {
125
+ return toGraphQLInputType(S2.make(ast.from));
126
+ }
127
+ if (ast._tag === "Union") {
128
+ const types = ast.types;
129
+ if (types.length > 0) {
130
+ return toGraphQLInputType(S2.make(types[0]));
131
+ }
132
+ }
133
+ if (ast._tag === "Suspend") {
134
+ const innerAst = ast.f();
135
+ return toGraphQLInputType(S2.make(innerAst));
136
+ }
137
+ return GraphQLString;
138
+ };
139
+ var toGraphQLObjectType = (name, schema, additionalFields) => {
140
+ const ast = schema.ast;
141
+ if (ast._tag === "TypeLiteral") {
142
+ const fields = {};
143
+ for (const field2 of ast.propertySignatures) {
144
+ const fieldName = String(field2.name);
145
+ const fieldSchema = S2.make(field2.type);
146
+ let fieldType = toGraphQLType(fieldSchema);
147
+ if (!field2.isOptional) {
148
+ fieldType = new GraphQLNonNull(fieldType);
149
+ }
150
+ fields[fieldName] = { type: fieldType };
151
+ }
152
+ if (additionalFields) {
153
+ for (const [fieldName, fieldConfig] of Object.entries(additionalFields)) {
154
+ fields[fieldName] = {
155
+ type: fieldConfig.type,
156
+ args: fieldConfig.args,
157
+ description: fieldConfig.description,
158
+ // Note: resolve will be set later when runtime is available
159
+ resolve: fieldConfig.resolve
160
+ };
161
+ }
162
+ }
163
+ return new GraphQLObjectType({
164
+ name,
165
+ fields
166
+ });
167
+ }
168
+ throw new Error(`Schema must be an object type to convert to GraphQLObjectType`);
169
+ };
170
+ var toGraphQLArgs = (schema) => {
171
+ const ast = schema.ast;
172
+ if (ast._tag === "TypeLiteral") {
173
+ const args = {};
174
+ for (const field2 of ast.propertySignatures) {
175
+ const fieldName = String(field2.name);
176
+ const fieldSchema = S2.make(field2.type);
177
+ let fieldType = toGraphQLInputType(fieldSchema);
178
+ if (!field2.isOptional) {
179
+ fieldType = new GraphQLNonNull(fieldType);
180
+ }
181
+ args[fieldName] = { type: fieldType };
182
+ }
183
+ return args;
184
+ }
185
+ throw new Error(`Schema must be an object type to convert to GraphQL arguments`);
186
+ };
187
+
188
+ // src/builder/type-registry.ts
189
+ function getSchemaName(schema) {
190
+ const ast = schema.ast;
191
+ if (ast._tag === "Transformation") {
192
+ const identifier = AST.getIdentifierAnnotation(ast.to);
193
+ if (identifier._tag === "Some") {
194
+ return identifier.value;
195
+ }
196
+ }
197
+ if (ast._tag === "TypeLiteral") {
198
+ const tagProp = ast.propertySignatures.find((p) => String(p.name) === "_tag");
199
+ if (tagProp && tagProp.type._tag === "Literal" && typeof tagProp.type.literal === "string") {
200
+ return tagProp.type.literal;
201
+ }
202
+ }
203
+ return void 0;
204
+ }
205
+ function buildReverseLookups(ctx) {
206
+ if (!ctx.schemaToTypeName) {
207
+ ctx.schemaToTypeName = /* @__PURE__ */ new Map();
208
+ ctx.astToTypeName = /* @__PURE__ */ new Map();
209
+ for (const [typeName, typeReg] of ctx.types) {
210
+ ctx.schemaToTypeName.set(typeReg.schema, typeName);
211
+ ctx.astToTypeName.set(typeReg.schema.ast, typeName);
212
+ }
213
+ }
214
+ if (!ctx.schemaToInterfaceName) {
215
+ ctx.schemaToInterfaceName = /* @__PURE__ */ new Map();
216
+ ctx.astToInterfaceName = /* @__PURE__ */ new Map();
217
+ for (const [interfaceName, interfaceReg] of ctx.interfaces) {
218
+ ctx.schemaToInterfaceName.set(interfaceReg.schema, interfaceName);
219
+ ctx.astToInterfaceName.set(interfaceReg.schema.ast, interfaceName);
220
+ }
221
+ }
222
+ if (!ctx.schemaToInputName) {
223
+ ctx.schemaToInputName = /* @__PURE__ */ new Map();
224
+ ctx.astToInputName = /* @__PURE__ */ new Map();
225
+ for (const [inputName, inputReg] of ctx.inputs) {
226
+ ctx.schemaToInputName.set(inputReg.schema, inputName);
227
+ ctx.astToInputName.set(inputReg.schema.ast, inputName);
228
+ }
229
+ }
230
+ if (!ctx.enumSortedValues) {
231
+ ctx.enumSortedValues = /* @__PURE__ */ new Map();
232
+ ctx.literalToEnumName = /* @__PURE__ */ new Map();
233
+ for (const [enumName, enumReg] of ctx.enums) {
234
+ ctx.enumSortedValues.set(enumName, [...enumReg.values].sort());
235
+ for (const value of enumReg.values) {
236
+ ctx.literalToEnumName.set(value, enumName);
237
+ }
238
+ }
239
+ }
240
+ if (!ctx.unionSortedTypes) {
241
+ ctx.unionSortedTypes = /* @__PURE__ */ new Map();
242
+ for (const [unionName, unionReg] of ctx.unions) {
243
+ ctx.unionSortedTypes.set(unionName, [...unionReg.types].sort());
244
+ }
245
+ }
246
+ }
247
+ var nonNullCache = /* @__PURE__ */ new WeakMap();
248
+ function getNonNull(type) {
249
+ let cached = nonNullCache.get(type);
250
+ if (!cached) {
251
+ cached = new GraphQLNonNull(type);
252
+ nonNullCache.set(type, cached);
253
+ }
254
+ return cached;
255
+ }
256
+ function toGraphQLTypeWithRegistry(schema, ctx) {
257
+ buildReverseLookups(ctx);
258
+ const ast = schema.ast;
259
+ const registeredType = findRegisteredType(schema, ast, ctx);
260
+ if (registeredType) return registeredType;
261
+ const registeredInterface = findRegisteredInterface(schema, ast, ctx);
262
+ if (registeredInterface) return registeredInterface;
263
+ if (ast._tag === "Transformation") {
264
+ return handleTransformationAST(ast, ctx);
265
+ }
266
+ if (ast._tag === "Union") {
267
+ return handleUnionAST(ast, ctx);
268
+ }
269
+ if (ast._tag === "Literal") {
270
+ const enumType2 = findEnumForLiteral(ast, ctx);
271
+ if (enumType2) return enumType2;
272
+ }
273
+ if (ast._tag === "TupleType") {
274
+ return handleTupleTypeAST(ast, ctx);
275
+ }
276
+ if (ast._tag === "Suspend") {
277
+ const innerAst = ast.f();
278
+ return toGraphQLTypeWithRegistry(S2.make(innerAst), ctx);
279
+ }
280
+ return toGraphQLType(schema);
281
+ }
282
+ function findRegisteredType(schema, ast, ctx) {
283
+ const typeName = ctx.schemaToTypeName?.get(schema) ?? ctx.astToTypeName?.get(ast);
284
+ if (typeName) {
285
+ return ctx.typeRegistry.get(typeName);
286
+ }
287
+ return void 0;
288
+ }
289
+ function findRegisteredInterface(schema, ast, ctx) {
290
+ const interfaceName = ctx.schemaToInterfaceName?.get(schema) ?? ctx.astToInterfaceName?.get(ast);
291
+ if (interfaceName) {
292
+ return ctx.interfaceRegistry.get(interfaceName);
293
+ }
294
+ return void 0;
295
+ }
296
+ function handleTransformationAST(ast, ctx) {
297
+ const toAst = ast.to;
298
+ if (toAst._tag === "TupleType") {
299
+ if (toAst.rest && toAst.rest.length > 0) {
300
+ const elementSchema = S2.make(toAst.rest[0].type);
301
+ const elementType = toGraphQLTypeWithRegistry(elementSchema, ctx);
302
+ return new GraphQLList(elementType);
303
+ } else if (toAst.elements.length > 0) {
304
+ const elementSchema = S2.make(toAst.elements[0].type);
305
+ const elementType = toGraphQLTypeWithRegistry(elementSchema, ctx);
306
+ return new GraphQLList(elementType);
307
+ }
308
+ }
309
+ return toGraphQLTypeWithRegistry(S2.make(ast.to), ctx);
310
+ }
311
+ function handleUnionAST(ast, ctx) {
312
+ const allLiterals = ast.types.every((t) => t._tag === "Literal");
313
+ if (allLiterals) {
314
+ const enumType2 = findEnumForLiteralUnion(ast.types, ctx);
315
+ if (enumType2) return enumType2;
316
+ } else {
317
+ const unionType2 = findRegisteredUnion(ast.types, ctx);
318
+ if (unionType2) return unionType2;
319
+ }
320
+ if (ast.types.length > 0) {
321
+ return toGraphQLTypeWithRegistry(S2.make(ast.types[0]), ctx);
322
+ }
323
+ return toGraphQLType(S2.make(ast));
324
+ }
325
+ function findEnumForLiteralUnion(types, ctx) {
326
+ const literalValues = types.map((t) => String(t.literal)).sort();
327
+ for (const [enumName] of ctx.enums) {
328
+ const enumValues = ctx.enumSortedValues?.get(enumName);
329
+ if (enumValues && literalValues.length === enumValues.length && literalValues.every((v, i) => v === enumValues[i])) {
330
+ return ctx.enumRegistry.get(enumName);
331
+ }
332
+ }
333
+ return void 0;
334
+ }
335
+ function findRegisteredUnion(types, ctx) {
336
+ const memberTags = [];
337
+ for (const memberAst of types) {
338
+ if (memberAst._tag === "TypeLiteral") {
339
+ const tagProp = memberAst.propertySignatures.find((p) => String(p.name) === "_tag");
340
+ if (tagProp && tagProp.type._tag === "Literal") {
341
+ memberTags.push(String(tagProp.type.literal));
342
+ }
343
+ }
344
+ }
345
+ if (memberTags.length === types.length) {
346
+ const sortedTags = memberTags.sort();
347
+ for (const [unionName] of ctx.unions) {
348
+ const unionTypes = ctx.unionSortedTypes?.get(unionName);
349
+ if (unionTypes && sortedTags.length === unionTypes.length && sortedTags.every((tag, i) => tag === unionTypes[i])) {
350
+ return ctx.unionRegistry.get(unionName);
351
+ }
352
+ }
353
+ }
354
+ return void 0;
355
+ }
356
+ function findEnumForLiteral(ast, ctx) {
357
+ const literalValue = String(ast.literal);
358
+ const enumName = ctx.literalToEnumName?.get(literalValue);
359
+ if (enumName) {
360
+ return ctx.enumRegistry.get(enumName);
361
+ }
362
+ return void 0;
363
+ }
364
+ function handleTupleTypeAST(ast, ctx) {
365
+ if (ast.rest && ast.rest.length > 0) {
366
+ const elementSchema = S2.make(ast.rest[0].type);
367
+ const elementType = toGraphQLTypeWithRegistry(elementSchema, ctx);
368
+ return new GraphQLList(elementType);
369
+ } else if (ast.elements && ast.elements.length > 0) {
370
+ const elementSchema = S2.make(ast.elements[0].type);
371
+ const elementType = toGraphQLTypeWithRegistry(elementSchema, ctx);
372
+ return new GraphQLList(elementType);
373
+ }
374
+ return toGraphQLType(S2.make(ast));
375
+ }
376
+ function schemaToFields(schema, ctx) {
377
+ let ast = schema.ast;
378
+ if (ast._tag === "Transformation") {
379
+ ast = ast.to;
380
+ }
381
+ if (ast._tag === "Declaration") {
382
+ const typeParams = ast.typeParameters;
383
+ if (typeParams && typeParams.length > 0 && typeParams[0]._tag === "TypeLiteral") {
384
+ ast = typeParams[0];
385
+ }
386
+ }
387
+ if (ast._tag === "TypeLiteral") {
388
+ const fields = {};
389
+ for (const field2 of ast.propertySignatures) {
390
+ const fieldName = String(field2.name);
391
+ const fieldSchema = S2.make(field2.type);
392
+ let fieldType = toGraphQLTypeWithRegistry(fieldSchema, ctx);
393
+ if (!field2.isOptional) {
394
+ fieldType = getNonNull(fieldType);
395
+ }
396
+ fields[fieldName] = { type: fieldType };
397
+ }
398
+ return fields;
399
+ }
400
+ return {};
401
+ }
402
+ function schemaToInputFields(schema, enumRegistry, inputRegistry, inputs, enums, cache) {
403
+ const ast = schema.ast;
404
+ if (ast._tag === "TypeLiteral") {
405
+ const fields = {};
406
+ for (const field2 of ast.propertySignatures) {
407
+ const fieldName = String(field2.name);
408
+ const fieldSchema = S2.make(field2.type);
409
+ let fieldType = toGraphQLInputTypeWithRegistry(
410
+ fieldSchema,
411
+ enumRegistry,
412
+ inputRegistry,
413
+ inputs,
414
+ enums,
415
+ cache
416
+ );
417
+ if (!field2.isOptional) {
418
+ fieldType = getNonNull(fieldType);
419
+ }
420
+ fields[fieldName] = { type: fieldType };
421
+ }
422
+ return fields;
423
+ }
424
+ return {};
425
+ }
426
+ function buildInputTypeLookupCache(inputs, enums) {
427
+ const cache = {
428
+ schemaToInputName: /* @__PURE__ */ new Map(),
429
+ astToInputName: /* @__PURE__ */ new Map(),
430
+ literalToEnumName: /* @__PURE__ */ new Map(),
431
+ enumSortedValues: /* @__PURE__ */ new Map()
432
+ };
433
+ for (const [inputName, inputReg] of inputs) {
434
+ cache.schemaToInputName.set(inputReg.schema, inputName);
435
+ cache.astToInputName.set(inputReg.schema.ast, inputName);
436
+ }
437
+ for (const [enumName, enumReg] of enums) {
438
+ cache.enumSortedValues.set(enumName, [...enumReg.values].sort());
439
+ for (const value of enumReg.values) {
440
+ cache.literalToEnumName.set(value, enumName);
441
+ }
442
+ }
443
+ return cache;
444
+ }
445
+ function toGraphQLInputTypeWithRegistry(schema, enumRegistry, inputRegistry, inputs, enums, cache) {
446
+ const ast = schema.ast;
447
+ if (ast._tag === "Transformation") {
448
+ const toAst = ast.to;
449
+ return toGraphQLInputTypeWithRegistry(
450
+ S2.make(toAst),
451
+ enumRegistry,
452
+ inputRegistry,
453
+ inputs,
454
+ enums,
455
+ cache
456
+ );
457
+ }
458
+ if (cache?.schemaToInputName || cache?.astToInputName) {
459
+ const inputName = cache.schemaToInputName?.get(schema) ?? cache.astToInputName?.get(ast);
460
+ if (inputName) {
461
+ const result = inputRegistry.get(inputName);
462
+ if (result) return result;
463
+ }
464
+ } else {
465
+ for (const [inputName, inputReg] of inputs) {
466
+ if (inputReg.schema.ast === ast || inputReg.schema === schema) {
467
+ const result = inputRegistry.get(inputName);
468
+ if (result) return result;
469
+ }
470
+ }
471
+ }
472
+ if (ast._tag === "Union") {
473
+ const unionAst = ast;
474
+ const nonUndefinedTypes = unionAst.types.filter((t) => t._tag !== "UndefinedKeyword");
475
+ if (nonUndefinedTypes.length === 1 && nonUndefinedTypes[0]._tag === "Union") {
476
+ return toGraphQLInputTypeWithRegistry(
477
+ S2.make(nonUndefinedTypes[0]),
478
+ enumRegistry,
479
+ inputRegistry,
480
+ inputs,
481
+ enums,
482
+ cache
483
+ );
484
+ }
485
+ if (nonUndefinedTypes.length === 1 && nonUndefinedTypes[0]._tag === "TypeLiteral") {
486
+ return toGraphQLInputTypeWithRegistry(
487
+ S2.make(nonUndefinedTypes[0]),
488
+ enumRegistry,
489
+ inputRegistry,
490
+ inputs,
491
+ enums,
492
+ cache
493
+ );
494
+ }
495
+ const allLiterals = unionAst.types.every((t) => t._tag === "Literal");
496
+ if (allLiterals) {
497
+ const literalValues = unionAst.types.map((t) => String(t.literal)).sort();
498
+ for (const [enumName] of enums) {
499
+ const enumValues = cache?.enumSortedValues?.get(enumName) ?? [...enums.get(enumName).values].sort();
500
+ if (literalValues.length === enumValues.length && literalValues.every((v, i) => v === enumValues[i])) {
501
+ const result = enumRegistry.get(enumName);
502
+ if (result) return result;
503
+ }
504
+ }
505
+ }
506
+ }
507
+ if (ast._tag === "Literal") {
508
+ const literalValue = String(ast.literal);
509
+ if (cache?.literalToEnumName) {
510
+ const enumName = cache.literalToEnumName.get(literalValue);
511
+ if (enumName) {
512
+ const result = enumRegistry.get(enumName);
513
+ if (result) return result;
514
+ }
515
+ } else {
516
+ for (const [enumName, enumReg] of enums) {
517
+ if (enumReg.values.includes(literalValue)) {
518
+ const result = enumRegistry.get(enumName);
519
+ if (result) return result;
520
+ }
521
+ }
522
+ }
523
+ }
524
+ if (ast._tag === "Suspend") {
525
+ const innerAst = ast.f();
526
+ return toGraphQLInputTypeWithRegistry(
527
+ S2.make(innerAst),
528
+ enumRegistry,
529
+ inputRegistry,
530
+ inputs,
531
+ enums,
532
+ cache
533
+ );
534
+ }
535
+ return toGraphQLInputType(schema);
536
+ }
537
+ function toGraphQLArgsWithRegistry(schema, enumRegistry, inputRegistry, inputs, enums, cache) {
538
+ const ast = schema.ast;
539
+ if (ast._tag === "TypeLiteral") {
540
+ const args = {};
541
+ for (const field2 of ast.propertySignatures) {
542
+ const fieldName = String(field2.name);
543
+ const fieldSchema = S2.make(field2.type);
544
+ let fieldType = toGraphQLInputTypeWithRegistry(
545
+ fieldSchema,
546
+ enumRegistry,
547
+ inputRegistry,
548
+ inputs,
549
+ enums,
550
+ cache
551
+ );
552
+ if (!field2.isOptional) {
553
+ fieldType = getNonNull(fieldType);
554
+ }
555
+ args[fieldName] = { type: fieldType };
556
+ }
557
+ return args;
558
+ }
559
+ return toGraphQLArgs(schema);
560
+ }
561
+ function applyDirectives(effect, directives, directiveRegistrations) {
562
+ if (!directives) return effect;
563
+ let wrapped = effect;
564
+ for (const directiveApp of directives) {
565
+ const directiveReg = directiveRegistrations.get(directiveApp.name);
566
+ if (directiveReg?.apply) {
567
+ wrapped = directiveReg.apply(directiveApp.args ?? {})(wrapped);
568
+ }
569
+ }
570
+ return wrapped;
571
+ }
572
+ function applyMiddleware(effect, context, middlewares) {
573
+ if (middlewares.length === 0) return effect;
574
+ let wrapped = effect;
575
+ for (let i = middlewares.length - 1; i >= 0; i--) {
576
+ const middleware2 = middlewares[i];
577
+ if (middleware2.match && !middleware2.match(context.info)) {
578
+ continue;
579
+ }
580
+ wrapped = middleware2.apply(wrapped, context);
581
+ }
582
+ return wrapped;
583
+ }
584
+ function buildField(config, ctx) {
585
+ const fieldConfig = {
586
+ type: toGraphQLTypeWithRegistry(config.type, ctx),
587
+ resolve: async (_parent, args, context, info) => {
588
+ let effect = applyDirectives(
589
+ config.resolve(args),
590
+ config.directives,
591
+ ctx.directiveRegistrations
592
+ );
593
+ const middlewareContext = { parent: _parent, args, info };
594
+ effect = applyMiddleware(effect, middlewareContext, ctx.middlewares);
595
+ return await Runtime.runPromise(context.runtime)(effect);
596
+ }
597
+ };
598
+ if (config.args) {
599
+ fieldConfig.args = toGraphQLArgsWithRegistry(
600
+ config.args,
601
+ ctx.enumRegistry,
602
+ ctx.inputRegistry,
603
+ ctx.inputs,
604
+ ctx.enums,
605
+ ctx.inputTypeLookupCache
606
+ );
607
+ }
608
+ if (config.description) {
609
+ fieldConfig.description = config.description;
610
+ }
611
+ return fieldConfig;
612
+ }
613
+ function buildObjectField(config, ctx) {
614
+ const fieldConfig = {
615
+ type: toGraphQLTypeWithRegistry(config.type, ctx),
616
+ resolve: async (parent, args, context, info) => {
617
+ let effect = applyDirectives(
618
+ config.resolve(parent, args),
619
+ config.directives,
620
+ ctx.directiveRegistrations
621
+ );
622
+ const middlewareContext = { parent, args, info };
623
+ effect = applyMiddleware(effect, middlewareContext, ctx.middlewares);
624
+ return await Runtime.runPromise(context.runtime)(effect);
625
+ }
626
+ };
627
+ if (config.args) {
628
+ fieldConfig.args = toGraphQLArgsWithRegistry(
629
+ config.args,
630
+ ctx.enumRegistry,
631
+ ctx.inputRegistry,
632
+ ctx.inputs,
633
+ ctx.enums,
634
+ ctx.inputTypeLookupCache
635
+ );
636
+ }
637
+ if (config.description) {
638
+ fieldConfig.description = config.description;
639
+ }
640
+ return fieldConfig;
641
+ }
642
+ function buildSubscriptionField(config, ctx) {
643
+ const fieldConfig = {
644
+ type: toGraphQLTypeWithRegistry(config.type, ctx),
645
+ // The subscribe function returns an AsyncIterator
646
+ subscribe: async (_parent, args, context, info) => {
647
+ let subscribeEffect = config.subscribe(args);
648
+ subscribeEffect = applyDirectives(
649
+ subscribeEffect,
650
+ config.directives,
651
+ ctx.directiveRegistrations
652
+ );
653
+ const middlewareContext = { parent: _parent, args, info };
654
+ subscribeEffect = applyMiddleware(subscribeEffect, middlewareContext, ctx.middlewares);
655
+ const stream = await Runtime.runPromise(context.runtime)(subscribeEffect);
656
+ return streamToAsyncIterator(stream, context.runtime);
657
+ },
658
+ // The resolve function transforms each yielded value
659
+ // If no custom resolve is provided, return the payload directly
660
+ resolve: config.resolve ? async (value, args, context, info) => {
661
+ let effect = config.resolve(value, args);
662
+ const middlewareContext = { parent: value, args, info };
663
+ effect = applyMiddleware(effect, middlewareContext, ctx.middlewares);
664
+ return await Runtime.runPromise(context.runtime)(effect);
665
+ } : (value) => value
666
+ };
667
+ if (config.args) {
668
+ fieldConfig.args = toGraphQLArgsWithRegistry(
669
+ config.args,
670
+ ctx.enumRegistry,
671
+ ctx.inputRegistry,
672
+ ctx.inputs,
673
+ ctx.enums,
674
+ ctx.inputTypeLookupCache
675
+ );
676
+ }
677
+ if (config.description) {
678
+ fieldConfig.description = config.description;
679
+ }
680
+ return fieldConfig;
681
+ }
682
+ function streamToAsyncIterator(stream, runtime) {
683
+ let queue;
684
+ let fiber;
685
+ let initialized = false;
686
+ let done = false;
687
+ const initialize = async () => {
688
+ if (initialized) return;
689
+ initialized = true;
690
+ queue = await Runtime.runPromise(runtime)(Queue.unbounded());
691
+ fiber = Runtime.runFork(runtime)(
692
+ Effect.ensuring(
693
+ Stream.runForEach(stream, (value) => Queue.offer(queue, Option.some(value))),
694
+ // Signal completion by pushing None
695
+ Queue.offer(queue, Option.none())
696
+ )
697
+ );
698
+ };
699
+ return {
700
+ [Symbol.asyncIterator]() {
701
+ return this;
702
+ },
703
+ async next() {
704
+ await initialize();
705
+ if (done) {
706
+ return { done: true, value: void 0 };
707
+ }
708
+ try {
709
+ const optionValue = await Runtime.runPromise(runtime)(Queue.take(queue));
710
+ if (Option.isNone(optionValue)) {
711
+ done = true;
712
+ return { done: true, value: void 0 };
713
+ }
714
+ return { done: false, value: optionValue.value };
715
+ } catch (error) {
716
+ done = true;
717
+ throw error;
718
+ }
719
+ },
720
+ async return() {
721
+ done = true;
722
+ if (initialized) {
723
+ try {
724
+ await Runtime.runPromise(runtime)(
725
+ Fiber.interrupt(fiber)
726
+ );
727
+ await Runtime.runPromise(runtime)(Queue.shutdown(queue));
728
+ } catch {
729
+ }
730
+ }
731
+ return { done: true, value: void 0 };
732
+ }
733
+ };
734
+ }
735
+
736
+ // src/builder/schema-builder.ts
737
+ function updateState(state, key, value) {
738
+ return { ...state, [key]: value };
739
+ }
740
+ var GraphQLSchemaBuilder = class _GraphQLSchemaBuilder {
741
+ constructor(state) {
742
+ this.state = state;
743
+ }
744
+ pipe() {
745
+ return Pipeable.pipeArguments(this, arguments);
746
+ }
747
+ /**
748
+ * Create an empty schema builder
749
+ */
750
+ static empty = new _GraphQLSchemaBuilder({
751
+ types: /* @__PURE__ */ new Map(),
752
+ interfaces: /* @__PURE__ */ new Map(),
753
+ enums: /* @__PURE__ */ new Map(),
754
+ unions: /* @__PURE__ */ new Map(),
755
+ inputs: /* @__PURE__ */ new Map(),
756
+ directives: /* @__PURE__ */ new Map(),
757
+ middlewares: [],
758
+ extensions: [],
759
+ queries: /* @__PURE__ */ new Map(),
760
+ mutations: /* @__PURE__ */ new Map(),
761
+ subscriptions: /* @__PURE__ */ new Map(),
762
+ objectFields: /* @__PURE__ */ new Map()
763
+ });
764
+ /**
765
+ * Create a new builder with updated state
766
+ */
767
+ with(newState) {
768
+ return new _GraphQLSchemaBuilder(newState);
769
+ }
770
+ // ============================================================================
771
+ // Registration Methods
772
+ // ============================================================================
773
+ /**
774
+ * Add a query field
775
+ */
776
+ query(name, config) {
777
+ const newQueries = new Map(this.state.queries);
778
+ newQueries.set(name, config);
779
+ return this.with(updateState(this.state, "queries", newQueries));
780
+ }
781
+ /**
782
+ * Add a mutation field
783
+ */
784
+ mutation(name, config) {
785
+ const newMutations = new Map(this.state.mutations);
786
+ newMutations.set(name, config);
787
+ return this.with(updateState(this.state, "mutations", newMutations));
788
+ }
789
+ /**
790
+ * Add a subscription field
791
+ *
792
+ * Subscriptions return a Stream that yields values over time.
793
+ * The subscribe function returns an Effect that produces a Stream.
794
+ *
795
+ * @example
796
+ * ```typescript
797
+ * builder.subscription("userCreated", {
798
+ * type: User,
799
+ * subscribe: Effect.gen(function*() {
800
+ * const pubsub = yield* PubSubService
801
+ * return pubsub.subscribe("USER_CREATED")
802
+ * }),
803
+ * })
804
+ * ```
805
+ */
806
+ subscription(name, config) {
807
+ const newSubscriptions = new Map(this.state.subscriptions);
808
+ newSubscriptions.set(name, config);
809
+ return this.with(updateState(this.state, "subscriptions", newSubscriptions));
810
+ }
811
+ /**
812
+ * Register an object type from a schema
813
+ */
814
+ objectType(config) {
815
+ const { schema, implements: implementsInterfaces, directives, cacheControl, fields } = config;
816
+ const name = config.name ?? getSchemaName(schema);
817
+ if (!name) {
818
+ throw new Error(
819
+ "objectType requires a name. Either provide one explicitly or use a TaggedStruct/TaggedClass/Schema.Class"
820
+ );
821
+ }
822
+ const newTypes = new Map(this.state.types);
823
+ newTypes.set(name, { name, schema, implements: implementsInterfaces, directives, cacheControl });
824
+ let newObjectFields = this.state.objectFields;
825
+ if (fields) {
826
+ newObjectFields = new Map(this.state.objectFields);
827
+ const typeFields = /* @__PURE__ */ new Map();
828
+ for (const [fieldName, fieldConfig] of Object.entries(fields)) {
829
+ typeFields.set(fieldName, fieldConfig);
830
+ }
831
+ newObjectFields.set(name, typeFields);
832
+ }
833
+ return this.with({
834
+ ...this.state,
835
+ types: newTypes,
836
+ objectFields: newObjectFields
837
+ });
838
+ }
839
+ /**
840
+ * Register an interface type from a schema
841
+ */
842
+ interfaceType(config) {
843
+ const { schema, resolveType, directives } = config;
844
+ const name = config.name ?? getSchemaName(schema);
845
+ if (!name) {
846
+ throw new Error(
847
+ "interfaceType requires a name. Either provide one explicitly or use a TaggedStruct/TaggedClass/Schema.Class"
848
+ );
849
+ }
850
+ const newInterfaces = new Map(this.state.interfaces);
851
+ newInterfaces.set(name, {
852
+ name,
853
+ schema,
854
+ resolveType: resolveType ?? ((value) => value._tag),
855
+ directives
856
+ });
857
+ return this.with(updateState(this.state, "interfaces", newInterfaces));
858
+ }
859
+ /**
860
+ * Register an enum type
861
+ */
862
+ enumType(config) {
863
+ const { name, values, description, directives } = config;
864
+ const newEnums = new Map(this.state.enums);
865
+ newEnums.set(name, { name, values, description, directives });
866
+ return this.with(updateState(this.state, "enums", newEnums));
867
+ }
868
+ /**
869
+ * Register a union type
870
+ */
871
+ unionType(config) {
872
+ const { name, types, resolveType, directives } = config;
873
+ const newUnions = new Map(this.state.unions);
874
+ newUnions.set(name, {
875
+ name,
876
+ types,
877
+ resolveType: resolveType ?? ((value) => value._tag),
878
+ directives
879
+ });
880
+ return this.with(updateState(this.state, "unions", newUnions));
881
+ }
882
+ /**
883
+ * Register an input type
884
+ */
885
+ inputType(config) {
886
+ const { schema, description, directives } = config;
887
+ const name = config.name ?? getSchemaName(schema);
888
+ if (!name) {
889
+ throw new Error(
890
+ "inputType requires a name. Either provide one explicitly or use a TaggedStruct/TaggedClass/Schema.Class"
891
+ );
892
+ }
893
+ const newInputs = new Map(this.state.inputs);
894
+ newInputs.set(name, { name, schema, description, directives });
895
+ return this.with(updateState(this.state, "inputs", newInputs));
896
+ }
897
+ /**
898
+ * Register a directive
899
+ */
900
+ directive(config) {
901
+ const newDirectives = new Map(this.state.directives);
902
+ newDirectives.set(config.name, config);
903
+ return this.with(updateState(this.state, "directives", newDirectives));
904
+ }
905
+ /**
906
+ * Register a middleware
907
+ *
908
+ * Middleware wraps all resolvers (or those matching a pattern) and executes
909
+ * in an "onion" model - first registered middleware is the outermost layer.
910
+ *
911
+ * @param config.name - Middleware name (for debugging/logging)
912
+ * @param config.description - Optional description
913
+ * @param config.match - Optional predicate to filter which fields this applies to
914
+ * @param config.apply - Function that transforms the resolver Effect
915
+ *
916
+ * @example
917
+ * ```typescript
918
+ * builder.middleware({
919
+ * name: "logging",
920
+ * apply: (effect, ctx) => Effect.gen(function*() {
921
+ * yield* Effect.logInfo(`Resolving ${ctx.info.fieldName}`)
922
+ * const start = Date.now()
923
+ * const result = yield* effect
924
+ * yield* Effect.logInfo(`Resolved in ${Date.now() - start}ms`)
925
+ * return result
926
+ * })
927
+ * })
928
+ * ```
929
+ */
930
+ middleware(config) {
931
+ const newMiddlewares = [...this.state.middlewares, config];
932
+ return this.with({ ...this.state, middlewares: newMiddlewares });
933
+ }
934
+ /**
935
+ * Register an extension
936
+ *
937
+ * Extensions provide lifecycle hooks that run at each phase of request processing
938
+ * (parse, validate, execute) and can contribute data to the response's extensions field.
939
+ *
940
+ * @param config.name - Extension name (for debugging/logging)
941
+ * @param config.description - Optional description
942
+ * @param config.onParse - Called after query parsing
943
+ * @param config.onValidate - Called after validation
944
+ * @param config.onExecuteStart - Called before execution begins
945
+ * @param config.onExecuteEnd - Called after execution completes
946
+ *
947
+ * @example
948
+ * ```typescript
949
+ * builder.extension({
950
+ * name: "tracing",
951
+ * onExecuteStart: () => Effect.gen(function*() {
952
+ * const ext = yield* ExtensionsService
953
+ * yield* ext.set("tracing", { startTime: Date.now() })
954
+ * }),
955
+ * onExecuteEnd: () => Effect.gen(function*() {
956
+ * const ext = yield* ExtensionsService
957
+ * yield* ext.merge("tracing", { endTime: Date.now() })
958
+ * }),
959
+ * })
960
+ * ```
961
+ */
962
+ extension(config) {
963
+ const newExtensions = [...this.state.extensions, config];
964
+ return this.with({ ...this.state, extensions: newExtensions });
965
+ }
966
+ /**
967
+ * Get the registered extensions for use by the execution layer
968
+ */
969
+ getExtensions() {
970
+ return this.state.extensions;
971
+ }
972
+ /**
973
+ * Add a computed/relational field to an object type
974
+ */
975
+ field(typeName, fieldName, config) {
976
+ const newObjectFields = new Map(this.state.objectFields);
977
+ const typeFields = newObjectFields.get(typeName) || /* @__PURE__ */ new Map();
978
+ typeFields.set(fieldName, config);
979
+ newObjectFields.set(typeName, typeFields);
980
+ return this.with(updateState(this.state, "objectFields", newObjectFields));
981
+ }
982
+ // ============================================================================
983
+ // Schema Building
984
+ // ============================================================================
985
+ /**
986
+ * Get the field complexity map for use in complexity validation.
987
+ * Maps "TypeName.fieldName" to the complexity value or function.
988
+ */
989
+ getFieldComplexities() {
990
+ const complexities = /* @__PURE__ */ new Map();
991
+ for (const [name, config] of this.state.queries) {
992
+ if (config.complexity !== void 0) {
993
+ complexities.set(`Query.${name}`, config.complexity);
994
+ }
995
+ }
996
+ for (const [name, config] of this.state.mutations) {
997
+ if (config.complexity !== void 0) {
998
+ complexities.set(`Mutation.${name}`, config.complexity);
999
+ }
1000
+ }
1001
+ for (const [name, config] of this.state.subscriptions) {
1002
+ if (config.complexity !== void 0) {
1003
+ complexities.set(`Subscription.${name}`, config.complexity);
1004
+ }
1005
+ }
1006
+ for (const [typeName, fields] of this.state.objectFields) {
1007
+ for (const [fieldName, config] of fields) {
1008
+ if (config.complexity !== void 0) {
1009
+ complexities.set(`${typeName}.${fieldName}`, config.complexity);
1010
+ }
1011
+ }
1012
+ }
1013
+ return complexities;
1014
+ }
1015
+ /**
1016
+ * Get the cache hint map for use in cache control calculation.
1017
+ * Maps "TypeName.fieldName" to the cache hint for field-level hints,
1018
+ * or "TypeName" to the cache hint for type-level hints.
1019
+ */
1020
+ getCacheHints() {
1021
+ const hints = /* @__PURE__ */ new Map();
1022
+ for (const [typeName, typeReg] of this.state.types) {
1023
+ if (typeReg.cacheControl !== void 0) {
1024
+ hints.set(typeName, typeReg.cacheControl);
1025
+ }
1026
+ }
1027
+ for (const [name, config] of this.state.queries) {
1028
+ if (config.cacheControl !== void 0) {
1029
+ hints.set(`Query.${name}`, config.cacheControl);
1030
+ }
1031
+ }
1032
+ for (const [name, config] of this.state.subscriptions) {
1033
+ if (config.cacheControl !== void 0) {
1034
+ hints.set(`Subscription.${name}`, config.cacheControl);
1035
+ }
1036
+ }
1037
+ for (const [typeName, fields] of this.state.objectFields) {
1038
+ for (const [fieldName, config] of fields) {
1039
+ if (config.cacheControl !== void 0) {
1040
+ hints.set(`${typeName}.${fieldName}`, config.cacheControl);
1041
+ }
1042
+ }
1043
+ }
1044
+ return hints;
1045
+ }
1046
+ /**
1047
+ * Build the GraphQL schema (no services required)
1048
+ */
1049
+ buildSchema() {
1050
+ const directiveRegistry = this.buildDirectiveRegistry();
1051
+ const enumRegistry = this.buildEnumRegistry();
1052
+ const inputRegistry = this.buildInputRegistry(enumRegistry);
1053
+ const interfaceRegistry = this.buildInterfaceRegistry(enumRegistry);
1054
+ const { typeRegistry, unionRegistry } = this.buildTypeAndUnionRegistries(
1055
+ enumRegistry,
1056
+ interfaceRegistry
1057
+ );
1058
+ const fieldCtx = this.createFieldBuilderContext(
1059
+ typeRegistry,
1060
+ interfaceRegistry,
1061
+ enumRegistry,
1062
+ unionRegistry,
1063
+ inputRegistry
1064
+ );
1065
+ const queryFields = this.buildQueryFields(fieldCtx);
1066
+ const mutationFields = this.buildMutationFields(fieldCtx);
1067
+ const subscriptionFields = this.buildSubscriptionFields(fieldCtx);
1068
+ return this.assembleSchema({
1069
+ directiveRegistry,
1070
+ enumRegistry,
1071
+ inputRegistry,
1072
+ interfaceRegistry,
1073
+ typeRegistry,
1074
+ unionRegistry,
1075
+ queryFields,
1076
+ mutationFields,
1077
+ subscriptionFields
1078
+ });
1079
+ }
1080
+ buildDirectiveRegistry() {
1081
+ const registry = /* @__PURE__ */ new Map();
1082
+ const cache = buildInputTypeLookupCache(this.state.inputs, this.state.enums);
1083
+ for (const [name, reg] of this.state.directives) {
1084
+ const graphqlDirective = new GraphQLDirective({
1085
+ name,
1086
+ description: reg.description,
1087
+ locations: [...reg.locations],
1088
+ args: reg.args ? toGraphQLArgsWithRegistry(
1089
+ reg.args,
1090
+ /* @__PURE__ */ new Map(),
1091
+ /* @__PURE__ */ new Map(),
1092
+ this.state.inputs,
1093
+ this.state.enums,
1094
+ cache
1095
+ ) : void 0
1096
+ });
1097
+ registry.set(name, graphqlDirective);
1098
+ }
1099
+ return registry;
1100
+ }
1101
+ buildEnumRegistry() {
1102
+ const registry = /* @__PURE__ */ new Map();
1103
+ for (const [name, reg] of this.state.enums) {
1104
+ const enumValues = {};
1105
+ for (const value of reg.values) {
1106
+ enumValues[value] = { value };
1107
+ }
1108
+ registry.set(
1109
+ name,
1110
+ new GraphQLEnumType({
1111
+ name,
1112
+ values: enumValues,
1113
+ description: reg.description,
1114
+ extensions: reg.directives ? { directives: reg.directives } : void 0
1115
+ })
1116
+ );
1117
+ }
1118
+ return registry;
1119
+ }
1120
+ buildInputRegistry(enumRegistry) {
1121
+ const registry = /* @__PURE__ */ new Map();
1122
+ const cache = buildInputTypeLookupCache(this.state.inputs, this.state.enums);
1123
+ for (const [name, reg] of this.state.inputs) {
1124
+ const inputType2 = new GraphQLInputObjectType({
1125
+ name,
1126
+ description: reg.description,
1127
+ fields: () => schemaToInputFields(
1128
+ reg.schema,
1129
+ enumRegistry,
1130
+ registry,
1131
+ this.state.inputs,
1132
+ this.state.enums,
1133
+ cache
1134
+ ),
1135
+ extensions: reg.directives ? { directives: reg.directives } : void 0
1136
+ });
1137
+ registry.set(name, inputType2);
1138
+ }
1139
+ return registry;
1140
+ }
1141
+ buildInterfaceRegistry(enumRegistry) {
1142
+ const registry = /* @__PURE__ */ new Map();
1143
+ const typeRegistry = /* @__PURE__ */ new Map();
1144
+ const unionRegistry = /* @__PURE__ */ new Map();
1145
+ const sharedCtx = {
1146
+ types: this.state.types,
1147
+ interfaces: this.state.interfaces,
1148
+ enums: this.state.enums,
1149
+ unions: this.state.unions,
1150
+ inputs: this.state.inputs,
1151
+ typeRegistry,
1152
+ interfaceRegistry: registry,
1153
+ enumRegistry,
1154
+ unionRegistry};
1155
+ buildReverseLookups(sharedCtx);
1156
+ for (const [name, reg] of this.state.interfaces) {
1157
+ const interfaceType2 = new GraphQLInterfaceType({
1158
+ name,
1159
+ fields: () => schemaToFields(reg.schema, sharedCtx),
1160
+ resolveType: reg.resolveType,
1161
+ extensions: reg.directives ? { directives: reg.directives } : void 0
1162
+ });
1163
+ registry.set(name, interfaceType2);
1164
+ }
1165
+ return registry;
1166
+ }
1167
+ buildTypeAndUnionRegistries(enumRegistry, interfaceRegistry) {
1168
+ const typeRegistry = /* @__PURE__ */ new Map();
1169
+ const unionRegistry = /* @__PURE__ */ new Map();
1170
+ const sharedCtx = {
1171
+ types: this.state.types,
1172
+ interfaces: this.state.interfaces,
1173
+ enums: this.state.enums,
1174
+ unions: this.state.unions,
1175
+ inputs: this.state.inputs,
1176
+ typeRegistry,
1177
+ interfaceRegistry,
1178
+ enumRegistry,
1179
+ unionRegistry};
1180
+ buildReverseLookups(sharedCtx);
1181
+ const sharedFieldCtx = this.createFieldBuilderContext(
1182
+ typeRegistry,
1183
+ interfaceRegistry,
1184
+ enumRegistry,
1185
+ unionRegistry,
1186
+ /* @__PURE__ */ new Map()
1187
+ );
1188
+ for (const [typeName, typeReg] of this.state.types) {
1189
+ const implementedInterfaces = typeReg.implements?.map((name) => interfaceRegistry.get(name)).filter(Boolean) ?? [];
1190
+ const graphqlType = new GraphQLObjectType({
1191
+ name: typeName,
1192
+ fields: () => {
1193
+ const baseFields = schemaToFields(typeReg.schema, sharedCtx);
1194
+ const additionalFields = this.state.objectFields.get(typeName);
1195
+ if (additionalFields) {
1196
+ for (const [fieldName, fieldConfig] of additionalFields) {
1197
+ baseFields[fieldName] = buildObjectField(fieldConfig, sharedFieldCtx);
1198
+ }
1199
+ }
1200
+ return baseFields;
1201
+ },
1202
+ interfaces: implementedInterfaces.length > 0 ? implementedInterfaces : void 0,
1203
+ extensions: typeReg.directives ? { directives: typeReg.directives } : void 0
1204
+ });
1205
+ typeRegistry.set(typeName, graphqlType);
1206
+ }
1207
+ for (const [name, reg] of this.state.unions) {
1208
+ const unionType2 = new GraphQLUnionType({
1209
+ name,
1210
+ types: () => reg.types.map((typeName) => typeRegistry.get(typeName)).filter(Boolean),
1211
+ resolveType: reg.resolveType,
1212
+ extensions: reg.directives ? { directives: reg.directives } : void 0
1213
+ });
1214
+ unionRegistry.set(name, unionType2);
1215
+ }
1216
+ return { typeRegistry, unionRegistry };
1217
+ }
1218
+ createFieldBuilderContext(typeRegistry, interfaceRegistry, enumRegistry, unionRegistry, inputRegistry) {
1219
+ const inputTypeLookupCache = buildInputTypeLookupCache(this.state.inputs, this.state.enums);
1220
+ return {
1221
+ types: this.state.types,
1222
+ interfaces: this.state.interfaces,
1223
+ enums: this.state.enums,
1224
+ unions: this.state.unions,
1225
+ inputs: this.state.inputs,
1226
+ typeRegistry,
1227
+ interfaceRegistry,
1228
+ enumRegistry,
1229
+ unionRegistry,
1230
+ inputRegistry,
1231
+ directiveRegistrations: this.state.directives,
1232
+ middlewares: this.state.middlewares,
1233
+ inputTypeLookupCache
1234
+ };
1235
+ }
1236
+ buildQueryFields(ctx) {
1237
+ const fields = {};
1238
+ for (const [name, config] of this.state.queries) {
1239
+ fields[name] = buildField(config, ctx);
1240
+ }
1241
+ return fields;
1242
+ }
1243
+ buildMutationFields(ctx) {
1244
+ const fields = {};
1245
+ for (const [name, config] of this.state.mutations) {
1246
+ fields[name] = buildField(config, ctx);
1247
+ }
1248
+ return fields;
1249
+ }
1250
+ buildSubscriptionFields(ctx) {
1251
+ const fields = {};
1252
+ for (const [name, config] of this.state.subscriptions) {
1253
+ fields[name] = buildSubscriptionField(config, ctx);
1254
+ }
1255
+ return fields;
1256
+ }
1257
+ assembleSchema(registries) {
1258
+ const schemaConfig = {
1259
+ types: [
1260
+ ...Array.from(registries.enumRegistry.values()),
1261
+ ...Array.from(registries.inputRegistry.values()),
1262
+ ...Array.from(registries.interfaceRegistry.values()),
1263
+ ...Array.from(registries.typeRegistry.values()),
1264
+ ...Array.from(registries.unionRegistry.values())
1265
+ ],
1266
+ directives: registries.directiveRegistry.size > 0 ? [...Array.from(registries.directiveRegistry.values())] : void 0
1267
+ };
1268
+ if (Object.keys(registries.queryFields).length > 0) {
1269
+ schemaConfig.query = new GraphQLObjectType({
1270
+ name: "Query",
1271
+ fields: registries.queryFields
1272
+ });
1273
+ }
1274
+ if (Object.keys(registries.mutationFields).length > 0) {
1275
+ schemaConfig.mutation = new GraphQLObjectType({
1276
+ name: "Mutation",
1277
+ fields: registries.mutationFields
1278
+ });
1279
+ }
1280
+ if (Object.keys(registries.subscriptionFields).length > 0) {
1281
+ schemaConfig.subscription = new GraphQLObjectType({
1282
+ name: "Subscription",
1283
+ fields: registries.subscriptionFields
1284
+ });
1285
+ }
1286
+ return new GraphQLSchema(schemaConfig);
1287
+ }
1288
+ };
1289
+
1290
+ // src/builder/pipe-api.ts
1291
+ var objectType = (config) => (builder) => builder.objectType(config);
1292
+ var interfaceType = (config) => (builder) => builder.interfaceType(config);
1293
+ var enumType = (config) => (builder) => builder.enumType(config);
1294
+ var unionType = (config) => (builder) => builder.unionType(config);
1295
+ var inputType = (config) => (builder) => builder.inputType(config);
1296
+ var directive = (config) => (builder) => builder.directive(config);
1297
+ var middleware = (config) => (builder) => builder.middleware(config);
1298
+ var extension = (config) => (builder) => builder.extension(config);
1299
+ var query = (name, config) => (builder) => builder.query(name, config);
1300
+ var mutation = (name, config) => (builder) => builder.mutation(name, config);
1301
+ var subscription = (name, config) => (builder) => builder.subscription(name, config);
1302
+ var field = (typeName, fieldName, config) => (builder) => builder.field(typeName, fieldName, config);
1303
+ var compose = (...operations) => (builder) => operations.reduce((b, op) => op(b), builder);
1304
+ var ExtensionsService = Context.GenericTag(
1305
+ "@effect-gql/ExtensionsService"
1306
+ );
1307
+ function deepMerge(target, source) {
1308
+ const result = { ...target };
1309
+ for (const key of Object.keys(source)) {
1310
+ const sourceValue = source[key];
1311
+ const targetValue = result[key];
1312
+ if (typeof sourceValue === "object" && sourceValue !== null && !Array.isArray(sourceValue) && typeof targetValue === "object" && targetValue !== null && !Array.isArray(targetValue)) {
1313
+ result[key] = deepMerge(
1314
+ targetValue,
1315
+ sourceValue
1316
+ );
1317
+ } else {
1318
+ result[key] = sourceValue;
1319
+ }
1320
+ }
1321
+ return result;
1322
+ }
1323
+ var makeExtensionsService = () => Effect.gen(function* () {
1324
+ const ref = yield* Ref.make({});
1325
+ return ExtensionsService.of({
1326
+ set: (key, value) => Ref.update(ref, (current) => ({ ...current, [key]: value })),
1327
+ merge: (key, value) => Ref.update(ref, (current) => {
1328
+ const existing = current[key];
1329
+ if (typeof existing === "object" && existing !== null && !Array.isArray(existing)) {
1330
+ return {
1331
+ ...current,
1332
+ [key]: deepMerge(existing, value)
1333
+ };
1334
+ }
1335
+ return { ...current, [key]: value };
1336
+ }),
1337
+ get: () => Ref.get(ref)
1338
+ });
1339
+ });
1340
+ var runExtensionHooks = (extensions, hookName, getHookEffect) => Effect.forEach(
1341
+ extensions.filter((ext) => ext[hookName] !== void 0),
1342
+ (ext) => getHookEffect(ext).pipe(
1343
+ Effect.catchAllCause(
1344
+ (cause) => Effect.logWarning(`Extension "${ext.name}" ${String(hookName)} hook failed`, cause)
1345
+ )
1346
+ ),
1347
+ { discard: true }
1348
+ );
1349
+ var runParseHooks = (extensions, source, document) => runExtensionHooks(extensions, "onParse", (ext) => ext.onParse(source, document));
1350
+ var runValidateHooks = (extensions, document, errors) => runExtensionHooks(extensions, "onValidate", (ext) => ext.onValidate(document, errors));
1351
+ var runExecuteStartHooks = (extensions, args) => runExtensionHooks(extensions, "onExecuteStart", (ext) => ext.onExecuteStart(args));
1352
+ var runExecuteEndHooks = (extensions, result) => runExtensionHooks(extensions, "onExecuteEnd", (ext) => ext.onExecuteEnd(result));
1353
+
1354
+ // src/builder/execute.ts
1355
+ var execute = (schema, layer, extensions = [], fieldComplexities = /* @__PURE__ */ new Map()) => (source, variableValues, operationName) => Effect.gen(function* () {
1356
+ const extensionsService = yield* makeExtensionsService();
1357
+ const runtime = yield* Effect.runtime();
1358
+ let document;
1359
+ try {
1360
+ document = parse(source);
1361
+ } catch (parseError) {
1362
+ const extensionData2 = yield* extensionsService.get();
1363
+ return {
1364
+ errors: [
1365
+ parseError instanceof GraphQLError ? parseError : new GraphQLError(String(parseError))
1366
+ ],
1367
+ extensions: Object.keys(extensionData2).length > 0 ? extensionData2 : void 0
1368
+ };
1369
+ }
1370
+ yield* runParseHooks(extensions, source, document).pipe(
1371
+ Effect.provideService(ExtensionsService, extensionsService)
1372
+ );
1373
+ const validationErrors = validate(schema, document);
1374
+ yield* runValidateHooks(extensions, document, validationErrors).pipe(
1375
+ Effect.provideService(ExtensionsService, extensionsService)
1376
+ );
1377
+ if (validationErrors.length > 0) {
1378
+ const extensionData2 = yield* extensionsService.get();
1379
+ return {
1380
+ errors: validationErrors,
1381
+ extensions: Object.keys(extensionData2).length > 0 ? extensionData2 : void 0
1382
+ };
1383
+ }
1384
+ const executionArgs = {
1385
+ source,
1386
+ document,
1387
+ variableValues,
1388
+ operationName,
1389
+ schema,
1390
+ fieldComplexities
1391
+ };
1392
+ yield* runExecuteStartHooks(extensions, executionArgs).pipe(
1393
+ Effect.provideService(ExtensionsService, extensionsService)
1394
+ );
1395
+ const executeResult = yield* Effect.try({
1396
+ try: () => execute$1({
1397
+ schema,
1398
+ document,
1399
+ variableValues,
1400
+ operationName,
1401
+ contextValue: { runtime }
1402
+ }),
1403
+ catch: (error) => new Error(String(error))
1404
+ });
1405
+ const resolvedResult = executeResult && typeof executeResult === "object" && "then" in executeResult ? yield* Effect.promise(() => executeResult) : executeResult;
1406
+ yield* runExecuteEndHooks(extensions, resolvedResult).pipe(
1407
+ Effect.provideService(ExtensionsService, extensionsService)
1408
+ );
1409
+ const extensionData = yield* extensionsService.get();
1410
+ if (Object.keys(extensionData).length > 0) {
1411
+ return {
1412
+ ...resolvedResult,
1413
+ extensions: {
1414
+ ...resolvedResult.extensions,
1415
+ ...extensionData
1416
+ }
1417
+ };
1418
+ }
1419
+ return resolvedResult;
1420
+ }).pipe(Effect.provide(layer));
1421
+ var GraphQLError2 = class extends Data.TaggedError("GraphQLError") {
1422
+ };
1423
+ var ValidationError = class extends Data.TaggedError("ValidationError") {
1424
+ };
1425
+ var AuthorizationError = class extends Data.TaggedError("AuthorizationError") {
1426
+ };
1427
+ var NotFoundError = class extends Data.TaggedError("NotFoundError") {
1428
+ };
1429
+ var GraphQLRequestContext = Context.GenericTag("GraphQLRequestContext");
1430
+ var makeRequestContextLayer = (context) => Layer.succeed(GraphQLRequestContext, context);
1431
+ function single(config) {
1432
+ return {
1433
+ _tag: "single",
1434
+ batch: config.batch,
1435
+ key: config.key
1436
+ };
1437
+ }
1438
+ function grouped(config) {
1439
+ return {
1440
+ _tag: "grouped",
1441
+ batch: config.batch,
1442
+ groupBy: config.groupBy
1443
+ };
1444
+ }
1445
+ var LoaderRegistry = class {
1446
+ constructor(definitions) {
1447
+ this.definitions = definitions;
1448
+ this.Service = Context.GenericTag(
1449
+ `DataLoaders(${Object.keys(definitions).join(", ")})`
1450
+ );
1451
+ }
1452
+ _tag = "LoaderRegistry";
1453
+ /**
1454
+ * The Effect service tag for this loader registry
1455
+ */
1456
+ Service;
1457
+ /**
1458
+ * Create a Layer that provides fresh DataLoader instances.
1459
+ * Call this once per request to get request-scoped loaders.
1460
+ */
1461
+ toLayer() {
1462
+ const self = this;
1463
+ return Layer.effect(
1464
+ this.Service,
1465
+ Effect.gen(function* () {
1466
+ const instances = {};
1467
+ for (const [name, def] of Object.entries(self.definitions)) {
1468
+ instances[name] = yield* createDataLoader(def);
1469
+ }
1470
+ return instances;
1471
+ })
1472
+ );
1473
+ }
1474
+ /**
1475
+ * Helper to use loaders in a resolver with a callback.
1476
+ */
1477
+ use(fn) {
1478
+ const self = this;
1479
+ return Effect.gen(function* () {
1480
+ const loaders = yield* self.Service;
1481
+ return yield* Effect.promise(() => fn(loaders));
1482
+ });
1483
+ }
1484
+ /**
1485
+ * Load a single value by key.
1486
+ * This is the most common operation in resolvers.
1487
+ */
1488
+ load(name, key) {
1489
+ const self = this;
1490
+ return Effect.gen(function* () {
1491
+ const loaders = yield* self.Service;
1492
+ const loader = loaders[name];
1493
+ return yield* Effect.promise(() => loader.load(key));
1494
+ });
1495
+ }
1496
+ /**
1497
+ * Load multiple values by keys.
1498
+ * All keys are batched into a single request.
1499
+ */
1500
+ loadMany(name, keys) {
1501
+ const self = this;
1502
+ return Effect.gen(function* () {
1503
+ const loaders = yield* self.Service;
1504
+ const loader = loaders[name];
1505
+ const results = yield* Effect.promise(() => loader.loadMany(keys));
1506
+ for (const result of results) {
1507
+ if (result instanceof Error) {
1508
+ return yield* Effect.fail(result);
1509
+ }
1510
+ }
1511
+ return results;
1512
+ });
1513
+ }
1514
+ };
1515
+ function createDataLoader(def) {
1516
+ return Effect.gen(function* () {
1517
+ const context = yield* Effect.context();
1518
+ if (def._tag === "single") {
1519
+ const loader = new DataLoader(async (keys) => {
1520
+ const items = await Effect.runPromise(def.batch(keys).pipe(Effect.provide(context)));
1521
+ return keys.map((key) => {
1522
+ const item = items.find((i) => def.key(i) === key);
1523
+ if (!item) return new Error(`Not found: ${key}`);
1524
+ return item;
1525
+ });
1526
+ });
1527
+ return loader;
1528
+ } else {
1529
+ const loader = new DataLoader(async (keys) => {
1530
+ const items = await Effect.runPromise(def.batch(keys).pipe(Effect.provide(context)));
1531
+ const map = /* @__PURE__ */ new Map();
1532
+ for (const item of items) {
1533
+ const key = def.groupBy(item);
1534
+ let arr = map.get(key);
1535
+ if (!arr) {
1536
+ arr = [];
1537
+ map.set(key, arr);
1538
+ }
1539
+ arr.push(item);
1540
+ }
1541
+ return keys.map((key) => map.get(key) ?? []);
1542
+ });
1543
+ return loader;
1544
+ }
1545
+ });
1546
+ }
1547
+ function define(definitions) {
1548
+ return new LoaderRegistry(definitions);
1549
+ }
1550
+ function mapByKey(keys, items, keyFn) {
1551
+ const map = /* @__PURE__ */ new Map();
1552
+ for (const item of items) {
1553
+ map.set(keyFn(item), item);
1554
+ }
1555
+ return keys.map((key) => map.get(key) ?? new Error(`Not found: ${key}`));
1556
+ }
1557
+ function groupByKey(keys, items, keyFn) {
1558
+ const map = /* @__PURE__ */ new Map();
1559
+ for (const key of keys) {
1560
+ map.set(key, []);
1561
+ }
1562
+ for (const item of items) {
1563
+ const key = keyFn(item);
1564
+ const arr = map.get(key);
1565
+ if (arr) arr.push(item);
1566
+ }
1567
+ return map;
1568
+ }
1569
+ var Loader = {
1570
+ define,
1571
+ single,
1572
+ grouped,
1573
+ mapByKey,
1574
+ groupByKey
1575
+ };
1576
+ var MissingResolverContextError = class extends Error {
1577
+ constructor(contextName) {
1578
+ super(
1579
+ `Resolver context "${contextName}" was not provided. Ensure a parent resolver or directive provides this context.`
1580
+ );
1581
+ this.contextName = contextName;
1582
+ this.name = "MissingResolverContextError";
1583
+ }
1584
+ _tag = "MissingResolverContextError";
1585
+ };
1586
+ var ResolverContextStore = Context.GenericTag(
1587
+ "effect-gql/ResolverContextStore"
1588
+ );
1589
+ var makeStoreLayer = () => Effect.map(
1590
+ Ref.make(HashMap.empty()),
1591
+ (ref) => Layer.succeed(ResolverContextStore, { ref })
1592
+ );
1593
+ var storeLayer = Layer.effect(
1594
+ ResolverContextStore,
1595
+ Effect.map(Ref.make(HashMap.empty()), (ref) => ({ ref }))
1596
+ );
1597
+ var make3 = (name) => ({
1598
+ _tag: "ResolverContextSlot",
1599
+ name,
1600
+ _A: void 0
1601
+ });
1602
+ var get = (slot) => Effect.flatMap(
1603
+ ResolverContextStore,
1604
+ (store) => Effect.flatMap(Ref.get(store.ref), (map) => {
1605
+ const value = HashMap.get(map, slot.name);
1606
+ return Option.match(value, {
1607
+ onNone: () => Effect.fail(new MissingResolverContextError(slot.name)),
1608
+ onSome: (v) => Effect.succeed(v)
1609
+ });
1610
+ })
1611
+ );
1612
+ var getOption = (slot) => Effect.flatMap(
1613
+ ResolverContextStore,
1614
+ (store) => Effect.map(Ref.get(store.ref), (map) => HashMap.get(map, slot.name))
1615
+ );
1616
+ var set = (slot, value) => Effect.flatMap(
1617
+ ResolverContextStore,
1618
+ (store) => Ref.update(store.ref, (map) => HashMap.set(map, slot.name, value))
1619
+ );
1620
+ var setMany = (values) => Effect.flatMap(
1621
+ ResolverContextStore,
1622
+ (store) => Ref.update(store.ref, (map) => {
1623
+ let result = map;
1624
+ for (const [slot, value] of values) {
1625
+ result = HashMap.set(result, slot.name, value);
1626
+ }
1627
+ return result;
1628
+ })
1629
+ );
1630
+ var has = (slot) => Effect.flatMap(
1631
+ ResolverContextStore,
1632
+ (store) => Effect.map(Ref.get(store.ref), (map) => HashMap.has(map, slot.name))
1633
+ );
1634
+ var getOrElse = (slot, orElse) => Effect.flatMap(
1635
+ ResolverContextStore,
1636
+ (store) => Effect.map(
1637
+ Ref.get(store.ref),
1638
+ (map) => Option.getOrElse(HashMap.get(map, slot.name), orElse)
1639
+ )
1640
+ );
1641
+ var scoped = (slot, value) => (effect) => Effect.flatMap(
1642
+ ResolverContextStore,
1643
+ (store) => Effect.acquireUseRelease(
1644
+ // Acquire: save current value and set new one
1645
+ Effect.flatMap(Ref.get(store.ref), (map) => {
1646
+ const previous = HashMap.get(map, slot.name);
1647
+ return Effect.as(Ref.set(store.ref, HashMap.set(map, slot.name, value)), previous);
1648
+ }),
1649
+ // Use: run the effect
1650
+ () => effect,
1651
+ // Release: restore previous value
1652
+ (previous) => Ref.update(
1653
+ store.ref,
1654
+ (map) => Option.match(previous, {
1655
+ onNone: () => HashMap.remove(map, slot.name),
1656
+ onSome: (v) => HashMap.set(map, slot.name, v)
1657
+ })
1658
+ )
1659
+ )
1660
+ );
1661
+ var ResolverContext = {
1662
+ make: make3,
1663
+ get,
1664
+ getOption,
1665
+ set,
1666
+ setMany,
1667
+ has,
1668
+ getOrElse,
1669
+ scoped,
1670
+ storeLayer,
1671
+ makeStoreLayer,
1672
+ Store: ResolverContextStore,
1673
+ MissingResolverContextError
1674
+ };
1675
+ var defaultConfig = {
1676
+ path: "/graphql",
1677
+ graphiql: false,
1678
+ complexity: void 0,
1679
+ introspection: true,
1680
+ cacheControl: void 0
1681
+ };
1682
+ var normalizeConfig = (input = {}) => {
1683
+ const path = input.path ?? defaultConfig.path;
1684
+ let graphiql = false;
1685
+ if (input.graphiql === true) {
1686
+ graphiql = { path: "/graphiql", endpoint: path };
1687
+ } else if (input.graphiql && typeof input.graphiql === "object") {
1688
+ graphiql = {
1689
+ path: input.graphiql.path ?? "/graphiql",
1690
+ endpoint: input.graphiql.endpoint ?? path
1691
+ };
1692
+ }
1693
+ return {
1694
+ path,
1695
+ graphiql,
1696
+ complexity: input.complexity,
1697
+ introspection: input.introspection ?? true,
1698
+ cacheControl: input.cacheControl
1699
+ };
1700
+ };
1701
+ var GraphQLRouterConfigFromEnv = Config.all({
1702
+ path: Config.string("GRAPHQL_PATH").pipe(Config.withDefault("/graphql")),
1703
+ introspection: Config.boolean("GRAPHQL_INTROSPECTION").pipe(Config.withDefault(true)),
1704
+ graphiqlEnabled: Config.boolean("GRAPHIQL_ENABLED").pipe(Config.withDefault(false)),
1705
+ graphiqlPath: Config.string("GRAPHIQL_PATH").pipe(Config.withDefault("/graphiql")),
1706
+ graphiqlEndpoint: Config.string("GRAPHIQL_ENDPOINT").pipe(Config.option),
1707
+ maxDepth: Config.number("GRAPHQL_MAX_DEPTH").pipe(Config.option),
1708
+ maxComplexity: Config.number("GRAPHQL_MAX_COMPLEXITY").pipe(Config.option),
1709
+ maxAliases: Config.number("GRAPHQL_MAX_ALIASES").pipe(Config.option),
1710
+ maxFields: Config.number("GRAPHQL_MAX_FIELDS").pipe(Config.option),
1711
+ defaultFieldComplexity: Config.number("GRAPHQL_DEFAULT_FIELD_COMPLEXITY").pipe(
1712
+ Config.withDefault(1)
1713
+ ),
1714
+ cacheControlEnabled: Config.boolean("GRAPHQL_CACHE_CONTROL_ENABLED").pipe(
1715
+ Config.withDefault(false)
1716
+ ),
1717
+ cacheControlDefaultMaxAge: Config.number("GRAPHQL_CACHE_CONTROL_DEFAULT_MAX_AGE").pipe(
1718
+ Config.withDefault(0)
1719
+ ),
1720
+ cacheControlDefaultScope: Config.string("GRAPHQL_CACHE_CONTROL_DEFAULT_SCOPE").pipe(
1721
+ Config.withDefault("PUBLIC")
1722
+ )
1723
+ }).pipe(
1724
+ Config.map(
1725
+ ({
1726
+ path,
1727
+ introspection,
1728
+ graphiqlEnabled,
1729
+ graphiqlPath,
1730
+ graphiqlEndpoint,
1731
+ maxDepth,
1732
+ maxComplexity,
1733
+ maxAliases,
1734
+ maxFields,
1735
+ defaultFieldComplexity,
1736
+ cacheControlEnabled,
1737
+ cacheControlDefaultMaxAge,
1738
+ cacheControlDefaultScope
1739
+ }) => {
1740
+ const hasComplexity = Option.isSome(maxDepth) || Option.isSome(maxComplexity) || Option.isSome(maxAliases) || Option.isSome(maxFields);
1741
+ return {
1742
+ path,
1743
+ introspection,
1744
+ graphiql: graphiqlEnabled ? {
1745
+ path: graphiqlPath,
1746
+ endpoint: Option.isSome(graphiqlEndpoint) ? graphiqlEndpoint.value : path
1747
+ } : false,
1748
+ complexity: hasComplexity ? {
1749
+ maxDepth: Option.getOrUndefined(maxDepth),
1750
+ maxComplexity: Option.getOrUndefined(maxComplexity),
1751
+ maxAliases: Option.getOrUndefined(maxAliases),
1752
+ maxFields: Option.getOrUndefined(maxFields),
1753
+ defaultFieldComplexity
1754
+ } : void 0,
1755
+ cacheControl: cacheControlEnabled ? {
1756
+ enabled: true,
1757
+ defaultMaxAge: cacheControlDefaultMaxAge,
1758
+ defaultScope: cacheControlDefaultScope === "PRIVATE" ? "PRIVATE" : "PUBLIC",
1759
+ calculateHttpHeaders: true
1760
+ } : void 0
1761
+ };
1762
+ }
1763
+ )
1764
+ );
1765
+
1766
+ // src/server/graphiql.ts
1767
+ var graphiqlHtml = (endpoint) => `<!DOCTYPE html>
1768
+ <html lang="en">
1769
+ <head>
1770
+ <meta charset="utf-8" />
1771
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
1772
+ <title>GraphiQL</title>
1773
+ <link
1774
+ rel="stylesheet"
1775
+ href="https://unpkg.com/graphiql@3/graphiql.min.css"
1776
+ />
1777
+ </head>
1778
+ <body style="margin: 0; overflow: hidden;">
1779
+ <div id="graphiql" style="height: 100vh;"></div>
1780
+ <script
1781
+ crossorigin
1782
+ src="https://unpkg.com/react@18/umd/react.production.min.js"
1783
+ ></script>
1784
+ <script
1785
+ crossorigin
1786
+ src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"
1787
+ ></script>
1788
+ <script
1789
+ crossorigin
1790
+ src="https://unpkg.com/graphiql@3/graphiql.min.js"
1791
+ ></script>
1792
+ <script>
1793
+ const fetcher = GraphiQL.createFetcher({
1794
+ url: ${JSON.stringify(endpoint)},
1795
+ });
1796
+ ReactDOM.createRoot(document.getElementById('graphiql')).render(
1797
+ React.createElement(GraphiQL, { fetcher })
1798
+ );
1799
+ </script>
1800
+ </body>
1801
+ </html>`;
1802
+ var ComplexityLimitExceededError = class extends Data.TaggedError("ComplexityLimitExceededError") {
1803
+ };
1804
+ var ComplexityAnalysisError = class extends Data.TaggedError("ComplexityAnalysisError") {
1805
+ };
1806
+ var defaultComplexityCalculator = (defaultCost = 1) => {
1807
+ return (info) => Effect.try({
1808
+ try: () => {
1809
+ const fragments = /* @__PURE__ */ new Map();
1810
+ for (const definition of info.document.definitions) {
1811
+ if (definition.kind === Kind.FRAGMENT_DEFINITION) {
1812
+ fragments.set(definition.name.value, definition);
1813
+ }
1814
+ }
1815
+ const rootType = getRootType(info.schema, info.operation.operation);
1816
+ if (!rootType) {
1817
+ throw new Error(`No root type found for operation: ${info.operation.operation}`);
1818
+ }
1819
+ const result = analyzeSelectionSet(
1820
+ info.operation.selectionSet,
1821
+ rootType,
1822
+ info.schema,
1823
+ fragments,
1824
+ info.fieldComplexities,
1825
+ info.variables ?? {},
1826
+ defaultCost,
1827
+ 1,
1828
+ // Starting depth
1829
+ /* @__PURE__ */ new Set()
1830
+ // Visited fragments to prevent infinite loops
1831
+ );
1832
+ return result;
1833
+ },
1834
+ catch: (error) => new ComplexityAnalysisError({
1835
+ message: `Failed to analyze query complexity: ${error}`,
1836
+ cause: error
1837
+ })
1838
+ });
1839
+ };
1840
+ function getRootType(schema, operation) {
1841
+ switch (operation) {
1842
+ case "query":
1843
+ return schema.getQueryType() ?? null;
1844
+ case "mutation":
1845
+ return schema.getMutationType() ?? null;
1846
+ case "subscription":
1847
+ return schema.getSubscriptionType() ?? null;
1848
+ }
1849
+ }
1850
+ function getNamedType(type) {
1851
+ if (type instanceof GraphQLNonNull || type instanceof GraphQLList) {
1852
+ return getNamedType(type.ofType);
1853
+ }
1854
+ if (type instanceof GraphQLObjectType) {
1855
+ return type;
1856
+ }
1857
+ return null;
1858
+ }
1859
+ function accumulateResult(acc, result) {
1860
+ acc.maxDepth = Math.max(acc.maxDepth, result.depth);
1861
+ acc.complexity += result.complexity;
1862
+ acc.fieldCount += result.fieldCount;
1863
+ acc.aliasCount += result.aliasCount;
1864
+ }
1865
+ function analyzeSelectionSet(selectionSet, parentType, schema, fragments, fieldComplexities, variables, defaultCost, currentDepth, visitedFragments) {
1866
+ const ctx = { schema, fragments, fieldComplexities, variables, defaultCost };
1867
+ const acc = { maxDepth: currentDepth, complexity: 0, fieldCount: 0, aliasCount: 0 };
1868
+ for (const selection of selectionSet.selections) {
1869
+ const result = analyzeSelection(selection, parentType, ctx, currentDepth, visitedFragments);
1870
+ accumulateResult(acc, result);
1871
+ }
1872
+ return {
1873
+ depth: acc.maxDepth,
1874
+ complexity: acc.complexity,
1875
+ fieldCount: acc.fieldCount,
1876
+ aliasCount: acc.aliasCount
1877
+ };
1878
+ }
1879
+ function analyzeSelection(selection, parentType, ctx, currentDepth, visitedFragments) {
1880
+ switch (selection.kind) {
1881
+ case Kind.FIELD:
1882
+ return analyzeField(selection, parentType, ctx, currentDepth, visitedFragments);
1883
+ case Kind.FRAGMENT_SPREAD:
1884
+ return analyzeFragmentSpread(selection, ctx, currentDepth, visitedFragments);
1885
+ case Kind.INLINE_FRAGMENT:
1886
+ return analyzeInlineFragment(selection, parentType, ctx, currentDepth, visitedFragments);
1887
+ }
1888
+ }
1889
+ function analyzeField(field2, parentType, ctx, currentDepth, visitedFragments) {
1890
+ const fieldName = field2.name.value;
1891
+ const aliasCount = field2.alias ? 1 : 0;
1892
+ if (fieldName.startsWith("__")) {
1893
+ return { depth: currentDepth, complexity: 0, fieldCount: 1, aliasCount };
1894
+ }
1895
+ const schemaField = parentType.getFields()[fieldName];
1896
+ if (!schemaField) {
1897
+ return { depth: currentDepth, complexity: ctx.defaultCost, fieldCount: 1, aliasCount };
1898
+ }
1899
+ const args = resolveFieldArguments(field2, ctx.variables);
1900
+ const complexityKey = `${parentType.name}.${fieldName}`;
1901
+ const fieldComplexity = ctx.fieldComplexities.get(complexityKey);
1902
+ const cost = fieldComplexity !== void 0 ? typeof fieldComplexity === "function" ? fieldComplexity(args) : fieldComplexity : ctx.defaultCost;
1903
+ if (field2.selectionSet) {
1904
+ const fieldType = getNamedType(schemaField.type);
1905
+ if (fieldType) {
1906
+ const nestedResult = analyzeSelectionSet(
1907
+ field2.selectionSet,
1908
+ fieldType,
1909
+ ctx.schema,
1910
+ ctx.fragments,
1911
+ ctx.fieldComplexities,
1912
+ ctx.variables,
1913
+ ctx.defaultCost,
1914
+ currentDepth + 1,
1915
+ visitedFragments
1916
+ );
1917
+ return {
1918
+ depth: nestedResult.depth,
1919
+ complexity: cost + nestedResult.complexity,
1920
+ fieldCount: 1 + nestedResult.fieldCount,
1921
+ aliasCount: aliasCount + nestedResult.aliasCount
1922
+ };
1923
+ }
1924
+ }
1925
+ return { depth: currentDepth, complexity: cost, fieldCount: 1, aliasCount };
1926
+ }
1927
+ function analyzeFragmentSpread(spread, ctx, currentDepth, visitedFragments) {
1928
+ const fragmentName = spread.name.value;
1929
+ if (visitedFragments.has(fragmentName)) {
1930
+ return { depth: currentDepth, complexity: 0, fieldCount: 0, aliasCount: 0 };
1931
+ }
1932
+ const fragment = ctx.fragments.get(fragmentName);
1933
+ if (!fragment) {
1934
+ return { depth: currentDepth, complexity: 0, fieldCount: 0, aliasCount: 0 };
1935
+ }
1936
+ const fragmentType = ctx.schema.getType(fragment.typeCondition.name.value);
1937
+ if (!(fragmentType instanceof GraphQLObjectType)) {
1938
+ return { depth: currentDepth, complexity: 0, fieldCount: 0, aliasCount: 0 };
1939
+ }
1940
+ const newVisited = new Set(visitedFragments);
1941
+ newVisited.add(fragmentName);
1942
+ return analyzeSelectionSet(
1943
+ fragment.selectionSet,
1944
+ fragmentType,
1945
+ ctx.schema,
1946
+ ctx.fragments,
1947
+ ctx.fieldComplexities,
1948
+ ctx.variables,
1949
+ ctx.defaultCost,
1950
+ currentDepth,
1951
+ newVisited
1952
+ );
1953
+ }
1954
+ function analyzeInlineFragment(fragment, parentType, ctx, currentDepth, visitedFragments) {
1955
+ let targetType = parentType;
1956
+ if (fragment.typeCondition) {
1957
+ const conditionType = ctx.schema.getType(fragment.typeCondition.name.value);
1958
+ if (conditionType instanceof GraphQLObjectType) {
1959
+ targetType = conditionType;
1960
+ }
1961
+ }
1962
+ return analyzeSelectionSet(
1963
+ fragment.selectionSet,
1964
+ targetType,
1965
+ ctx.schema,
1966
+ ctx.fragments,
1967
+ ctx.fieldComplexities,
1968
+ ctx.variables,
1969
+ ctx.defaultCost,
1970
+ currentDepth,
1971
+ visitedFragments
1972
+ );
1973
+ }
1974
+ function resolveFieldArguments(field2, variables) {
1975
+ const args = {};
1976
+ if (!field2.arguments) {
1977
+ return args;
1978
+ }
1979
+ for (const arg of field2.arguments) {
1980
+ const value = arg.value;
1981
+ switch (value.kind) {
1982
+ case Kind.VARIABLE:
1983
+ args[arg.name.value] = variables[value.name.value];
1984
+ break;
1985
+ case Kind.INT:
1986
+ args[arg.name.value] = parseInt(value.value, 10);
1987
+ break;
1988
+ case Kind.FLOAT:
1989
+ args[arg.name.value] = parseFloat(value.value);
1990
+ break;
1991
+ case Kind.STRING:
1992
+ args[arg.name.value] = value.value;
1993
+ break;
1994
+ case Kind.BOOLEAN:
1995
+ args[arg.name.value] = value.value;
1996
+ break;
1997
+ case Kind.NULL:
1998
+ args[arg.name.value] = null;
1999
+ break;
2000
+ case Kind.ENUM:
2001
+ args[arg.name.value] = value.value;
2002
+ break;
2003
+ case Kind.LIST:
2004
+ args[arg.name.value] = [];
2005
+ break;
2006
+ case Kind.OBJECT:
2007
+ args[arg.name.value] = {};
2008
+ break;
2009
+ }
2010
+ }
2011
+ return args;
2012
+ }
2013
+ var validateComplexity = (query2, operationName, variables, schema, fieldComplexities, config) => Effect.gen(function* () {
2014
+ const document = yield* Effect.try({
2015
+ try: () => parse(query2),
2016
+ catch: (error) => new ComplexityAnalysisError({
2017
+ message: `Failed to parse query: ${error}`,
2018
+ cause: error
2019
+ })
2020
+ });
2021
+ const operation = yield* Effect.try({
2022
+ try: () => {
2023
+ const operations = document.definitions.filter(
2024
+ (d) => d.kind === Kind.OPERATION_DEFINITION
2025
+ );
2026
+ if (operations.length === 0) {
2027
+ throw new Error("No operation found in query");
2028
+ }
2029
+ if (operationName) {
2030
+ const op = operations.find((o) => o.name?.value === operationName);
2031
+ if (!op) {
2032
+ throw new Error(`Operation "${operationName}" not found`);
2033
+ }
2034
+ return op;
2035
+ }
2036
+ if (operations.length > 1) {
2037
+ throw new Error("Multiple operations found - operationName required");
2038
+ }
2039
+ return operations[0];
2040
+ },
2041
+ catch: (error) => new ComplexityAnalysisError({
2042
+ message: String(error),
2043
+ cause: error
2044
+ })
2045
+ });
2046
+ const calculator = config.calculator ?? defaultComplexityCalculator(config.defaultFieldComplexity ?? 1);
2047
+ const result = yield* calculator({
2048
+ document,
2049
+ operation,
2050
+ variables,
2051
+ schema,
2052
+ fieldComplexities
2053
+ });
2054
+ const checkLimit = (limitType, limit, actual) => Effect.gen(function* () {
2055
+ if (limit !== void 0 && actual > limit) {
2056
+ const exceededInfo = {
2057
+ result,
2058
+ exceededLimit: limitType,
2059
+ limit,
2060
+ actual,
2061
+ query: query2,
2062
+ operationName
2063
+ };
2064
+ if (config.onExceeded) {
2065
+ yield* config.onExceeded(exceededInfo);
2066
+ }
2067
+ yield* Effect.fail(
2068
+ new ComplexityLimitExceededError({
2069
+ message: `Query ${limitType} of ${actual} exceeds maximum allowed ${limitType} of ${limit}`,
2070
+ limit,
2071
+ actual,
2072
+ limitType
2073
+ })
2074
+ );
2075
+ }
2076
+ });
2077
+ yield* checkLimit("depth", config.maxDepth, result.depth);
2078
+ yield* checkLimit("complexity", config.maxComplexity, result.complexity);
2079
+ yield* checkLimit("aliases", config.maxAliases, result.aliasCount);
2080
+ yield* checkLimit("fields", config.maxFields, result.fieldCount);
2081
+ return result;
2082
+ });
2083
+ var ComplexityConfigFromEnv = Config.all({
2084
+ maxDepth: Config.number("GRAPHQL_MAX_DEPTH").pipe(Config.option),
2085
+ maxComplexity: Config.number("GRAPHQL_MAX_COMPLEXITY").pipe(Config.option),
2086
+ maxAliases: Config.number("GRAPHQL_MAX_ALIASES").pipe(Config.option),
2087
+ maxFields: Config.number("GRAPHQL_MAX_FIELDS").pipe(Config.option),
2088
+ defaultFieldComplexity: Config.number("GRAPHQL_DEFAULT_FIELD_COMPLEXITY").pipe(
2089
+ Config.withDefault(1)
2090
+ )
2091
+ }).pipe(
2092
+ Config.map(({ maxDepth, maxComplexity, maxAliases, maxFields, defaultFieldComplexity }) => ({
2093
+ maxDepth: Option.getOrUndefined(maxDepth),
2094
+ maxComplexity: Option.getOrUndefined(maxComplexity),
2095
+ maxAliases: Option.getOrUndefined(maxAliases),
2096
+ maxFields: Option.getOrUndefined(maxFields),
2097
+ defaultFieldComplexity
2098
+ }))
2099
+ );
2100
+ var depthOnlyCalculator = (info) => Effect.try({
2101
+ try: () => {
2102
+ const fragments = /* @__PURE__ */ new Map();
2103
+ for (const definition of info.document.definitions) {
2104
+ if (definition.kind === Kind.FRAGMENT_DEFINITION) {
2105
+ fragments.set(definition.name.value, definition);
2106
+ }
2107
+ }
2108
+ const depth = calculateMaxDepth(info.operation.selectionSet, fragments, 1, /* @__PURE__ */ new Set());
2109
+ return {
2110
+ depth,
2111
+ complexity: 0,
2112
+ fieldCount: 0,
2113
+ aliasCount: 0
2114
+ };
2115
+ },
2116
+ catch: (error) => new ComplexityAnalysisError({
2117
+ message: `Failed to analyze query depth: ${error}`,
2118
+ cause: error
2119
+ })
2120
+ });
2121
+ function calculateMaxDepth(selectionSet, fragments, currentDepth, visitedFragments) {
2122
+ let maxDepth = currentDepth;
2123
+ for (const selection of selectionSet.selections) {
2124
+ switch (selection.kind) {
2125
+ case Kind.FIELD:
2126
+ if (selection.selectionSet) {
2127
+ const nestedDepth = calculateMaxDepth(
2128
+ selection.selectionSet,
2129
+ fragments,
2130
+ currentDepth + 1,
2131
+ visitedFragments
2132
+ );
2133
+ maxDepth = Math.max(maxDepth, nestedDepth);
2134
+ }
2135
+ break;
2136
+ case Kind.FRAGMENT_SPREAD: {
2137
+ const fragmentName = selection.name.value;
2138
+ if (!visitedFragments.has(fragmentName)) {
2139
+ const fragment = fragments.get(fragmentName);
2140
+ if (fragment) {
2141
+ const newVisited = new Set(visitedFragments);
2142
+ newVisited.add(fragmentName);
2143
+ const fragmentDepth = calculateMaxDepth(
2144
+ fragment.selectionSet,
2145
+ fragments,
2146
+ currentDepth,
2147
+ newVisited
2148
+ );
2149
+ maxDepth = Math.max(maxDepth, fragmentDepth);
2150
+ }
2151
+ }
2152
+ break;
2153
+ }
2154
+ case Kind.INLINE_FRAGMENT: {
2155
+ const inlineDepth = calculateMaxDepth(
2156
+ selection.selectionSet,
2157
+ fragments,
2158
+ currentDepth,
2159
+ visitedFragments
2160
+ );
2161
+ maxDepth = Math.max(maxDepth, inlineDepth);
2162
+ break;
2163
+ }
2164
+ }
2165
+ }
2166
+ return maxDepth;
2167
+ }
2168
+ var combineCalculators = (...calculators) => {
2169
+ return (info) => Effect.gen(function* () {
2170
+ let maxDepth = 0;
2171
+ let maxComplexity = 0;
2172
+ let maxFieldCount = 0;
2173
+ let maxAliasCount = 0;
2174
+ for (const calculator of calculators) {
2175
+ const result = yield* calculator(info);
2176
+ maxDepth = Math.max(maxDepth, result.depth);
2177
+ maxComplexity = Math.max(maxComplexity, result.complexity);
2178
+ maxFieldCount = Math.max(maxFieldCount, result.fieldCount);
2179
+ maxAliasCount = Math.max(maxAliasCount, result.aliasCount);
2180
+ }
2181
+ return {
2182
+ depth: maxDepth,
2183
+ complexity: maxComplexity,
2184
+ fieldCount: maxFieldCount,
2185
+ aliasCount: maxAliasCount
2186
+ };
2187
+ });
2188
+ };
2189
+ var computeCachePolicy = (info) => Effect.sync(() => {
2190
+ const fragments = /* @__PURE__ */ new Map();
2191
+ for (const definition of info.document.definitions) {
2192
+ if (definition.kind === Kind.FRAGMENT_DEFINITION) {
2193
+ fragments.set(definition.name.value, definition);
2194
+ }
2195
+ }
2196
+ const rootType = getRootType2(info.schema, info.operation.operation);
2197
+ if (!rootType) {
2198
+ return { maxAge: 0, scope: "PUBLIC" };
2199
+ }
2200
+ const defaultMaxAge = info.config.defaultMaxAge ?? 0;
2201
+ const defaultScope = info.config.defaultScope ?? "PUBLIC";
2202
+ const result = analyzeSelectionSet2(
2203
+ info.operation.selectionSet,
2204
+ rootType,
2205
+ info.schema,
2206
+ fragments,
2207
+ info.cacheHints,
2208
+ defaultMaxAge,
2209
+ defaultScope,
2210
+ void 0,
2211
+ // No parent maxAge for root
2212
+ /* @__PURE__ */ new Set()
2213
+ );
2214
+ return result;
2215
+ });
2216
+ var computeCachePolicyFromQuery = (query2, operationName, schema, cacheHints, config = {}) => Effect.gen(function* () {
2217
+ const document = yield* Effect.try({
2218
+ try: () => parse(query2),
2219
+ catch: (error) => new Error(`Failed to parse query: ${error}`)
2220
+ });
2221
+ const operation = yield* Effect.try({
2222
+ try: () => {
2223
+ const operations = document.definitions.filter(
2224
+ (d) => d.kind === Kind.OPERATION_DEFINITION
2225
+ );
2226
+ if (operations.length === 0) {
2227
+ throw new Error("No operation found in query");
2228
+ }
2229
+ if (operationName) {
2230
+ const op = operations.find((o) => o.name?.value === operationName);
2231
+ if (!op) {
2232
+ throw new Error(`Operation "${operationName}" not found`);
2233
+ }
2234
+ return op;
2235
+ }
2236
+ if (operations.length > 1) {
2237
+ throw new Error("Multiple operations found - operationName required");
2238
+ }
2239
+ return operations[0];
2240
+ },
2241
+ catch: (error) => error
2242
+ });
2243
+ return yield* computeCachePolicy({
2244
+ document,
2245
+ operation,
2246
+ schema,
2247
+ cacheHints,
2248
+ config
2249
+ });
2250
+ });
2251
+ var toCacheControlHeader = (policy) => {
2252
+ if (policy.maxAge === 0) {
2253
+ return "no-store";
2254
+ }
2255
+ const directives = [];
2256
+ directives.push(policy.scope === "PRIVATE" ? "private" : "public");
2257
+ directives.push(`max-age=${policy.maxAge}`);
2258
+ return directives.join(", ");
2259
+ };
2260
+ function getRootType2(schema, operation) {
2261
+ switch (operation) {
2262
+ case "query":
2263
+ return schema.getQueryType() ?? null;
2264
+ case "mutation":
2265
+ return schema.getMutationType() ?? null;
2266
+ case "subscription":
2267
+ return schema.getSubscriptionType() ?? null;
2268
+ }
2269
+ }
2270
+ function getNamedType2(type) {
2271
+ if (type instanceof GraphQLNonNull || type instanceof GraphQLList) {
2272
+ return getNamedType2(type.ofType);
2273
+ }
2274
+ if (type instanceof GraphQLObjectType || type instanceof GraphQLScalarType || type instanceof GraphQLEnumType) {
2275
+ return type;
2276
+ }
2277
+ return null;
2278
+ }
2279
+ function isLeafType(type) {
2280
+ const namedType = getNamedType2(type);
2281
+ return namedType instanceof GraphQLScalarType || namedType instanceof GraphQLEnumType;
2282
+ }
2283
+ function aggregatePolicy(acc, policy) {
2284
+ if (acc.minMaxAge === void 0) {
2285
+ acc.minMaxAge = policy.maxAge;
2286
+ } else {
2287
+ acc.minMaxAge = Math.min(acc.minMaxAge, policy.maxAge);
2288
+ }
2289
+ if (policy.scope === "PRIVATE") {
2290
+ acc.hasPrivate = true;
2291
+ }
2292
+ }
2293
+ function analyzeFragmentSpread2(fragmentName, ctx, parentMaxAge, visitedFragments) {
2294
+ if (visitedFragments.has(fragmentName)) {
2295
+ return void 0;
2296
+ }
2297
+ const fragment = ctx.fragments.get(fragmentName);
2298
+ if (!fragment) {
2299
+ return void 0;
2300
+ }
2301
+ const fragmentType = ctx.schema.getType(fragment.typeCondition.name.value);
2302
+ if (!(fragmentType instanceof GraphQLObjectType)) {
2303
+ return void 0;
2304
+ }
2305
+ const newVisited = new Set(visitedFragments);
2306
+ newVisited.add(fragmentName);
2307
+ return analyzeSelectionSet2(fragment.selectionSet, fragmentType, ctx, parentMaxAge, newVisited);
2308
+ }
2309
+ function analyzeInlineFragment2(selection, parentType, ctx, parentMaxAge, visitedFragments) {
2310
+ let targetType = parentType;
2311
+ if (selection.typeCondition) {
2312
+ const conditionType = ctx.schema.getType(selection.typeCondition.name.value);
2313
+ if (conditionType instanceof GraphQLObjectType) {
2314
+ targetType = conditionType;
2315
+ }
2316
+ }
2317
+ return analyzeSelectionSet2(
2318
+ selection.selectionSet,
2319
+ targetType,
2320
+ ctx,
2321
+ parentMaxAge,
2322
+ visitedFragments
2323
+ );
2324
+ }
2325
+ function lookupEffectiveCacheHint(parentTypeName, fieldName, returnType, cacheHints) {
2326
+ const fieldKey = `${parentTypeName}.${fieldName}`;
2327
+ const fieldHint = cacheHints.get(fieldKey);
2328
+ if (fieldHint) return fieldHint;
2329
+ const namedType = getNamedType2(returnType);
2330
+ return namedType ? cacheHints.get(namedType.name) : void 0;
2331
+ }
2332
+ function computeFieldMaxAge(hint, fieldType, parentMaxAge, defaultMaxAge) {
2333
+ if (hint) {
2334
+ if (hint.inheritMaxAge && parentMaxAge !== void 0) {
2335
+ return parentMaxAge;
2336
+ }
2337
+ if (hint.maxAge !== void 0) {
2338
+ return hint.maxAge;
2339
+ }
2340
+ }
2341
+ if (isLeafType(fieldType) && parentMaxAge !== void 0) {
2342
+ return parentMaxAge;
2343
+ }
2344
+ return defaultMaxAge;
2345
+ }
2346
+ function analyzeSelectionSet2(selectionSet, parentType, schemaOrCtx, fragmentsOrParentMaxAge, cacheHintsOrVisited, defaultMaxAge, defaultScope, parentMaxAge, visitedFragments) {
2347
+ let ctx;
2348
+ let actualParentMaxAge;
2349
+ let actualVisitedFragments;
2350
+ if (schemaOrCtx instanceof GraphQLSchema) {
2351
+ ctx = {
2352
+ schema: schemaOrCtx,
2353
+ fragments: fragmentsOrParentMaxAge,
2354
+ cacheHints: cacheHintsOrVisited,
2355
+ defaultMaxAge,
2356
+ defaultScope
2357
+ };
2358
+ actualParentMaxAge = parentMaxAge;
2359
+ actualVisitedFragments = visitedFragments;
2360
+ } else {
2361
+ ctx = schemaOrCtx;
2362
+ actualParentMaxAge = fragmentsOrParentMaxAge;
2363
+ actualVisitedFragments = cacheHintsOrVisited;
2364
+ }
2365
+ const acc = { minMaxAge: void 0, hasPrivate: false };
2366
+ for (const selection of selectionSet.selections) {
2367
+ let fieldPolicy;
2368
+ switch (selection.kind) {
2369
+ case Kind.FIELD:
2370
+ fieldPolicy = analyzeField2(
2371
+ selection,
2372
+ parentType,
2373
+ ctx,
2374
+ actualParentMaxAge,
2375
+ actualVisitedFragments
2376
+ );
2377
+ break;
2378
+ case Kind.FRAGMENT_SPREAD:
2379
+ fieldPolicy = analyzeFragmentSpread2(
2380
+ selection.name.value,
2381
+ ctx,
2382
+ actualParentMaxAge,
2383
+ actualVisitedFragments
2384
+ );
2385
+ break;
2386
+ case Kind.INLINE_FRAGMENT:
2387
+ fieldPolicy = analyzeInlineFragment2(
2388
+ selection,
2389
+ parentType,
2390
+ ctx,
2391
+ actualParentMaxAge,
2392
+ actualVisitedFragments
2393
+ );
2394
+ break;
2395
+ }
2396
+ if (fieldPolicy) {
2397
+ aggregatePolicy(acc, fieldPolicy);
2398
+ }
2399
+ }
2400
+ return {
2401
+ maxAge: acc.minMaxAge ?? ctx.defaultMaxAge,
2402
+ scope: acc.hasPrivate ? "PRIVATE" : ctx.defaultScope
2403
+ };
2404
+ }
2405
+ function analyzeField2(field2, parentType, ctx, parentMaxAge, visitedFragments) {
2406
+ const fieldName = field2.name.value;
2407
+ if (fieldName.startsWith("__")) {
2408
+ return { maxAge: Infinity, scope: "PUBLIC" };
2409
+ }
2410
+ const schemaField = parentType.getFields()[fieldName];
2411
+ if (!schemaField) {
2412
+ return { maxAge: ctx.defaultMaxAge, scope: ctx.defaultScope };
2413
+ }
2414
+ const effectiveHint = lookupEffectiveCacheHint(
2415
+ parentType.name,
2416
+ fieldName,
2417
+ schemaField.type,
2418
+ ctx.cacheHints
2419
+ );
2420
+ const fieldMaxAge = computeFieldMaxAge(
2421
+ effectiveHint,
2422
+ schemaField.type,
2423
+ parentMaxAge,
2424
+ ctx.defaultMaxAge
2425
+ );
2426
+ const fieldScope = effectiveHint?.scope ?? ctx.defaultScope;
2427
+ const namedType = getNamedType2(schemaField.type);
2428
+ if (field2.selectionSet && namedType instanceof GraphQLObjectType) {
2429
+ const nestedPolicy = analyzeSelectionSet2(
2430
+ field2.selectionSet,
2431
+ namedType,
2432
+ ctx,
2433
+ fieldMaxAge,
2434
+ visitedFragments
2435
+ );
2436
+ return {
2437
+ maxAge: Math.min(fieldMaxAge, nestedPolicy.maxAge),
2438
+ scope: fieldScope === "PRIVATE" || nestedPolicy.scope === "PRIVATE" ? "PRIVATE" : "PUBLIC"
2439
+ };
2440
+ }
2441
+ return { maxAge: fieldMaxAge, scope: fieldScope };
2442
+ }
2443
+ var CacheControlConfigFromEnv = Config.all({
2444
+ enabled: Config.boolean("GRAPHQL_CACHE_CONTROL_ENABLED").pipe(Config.withDefault(true)),
2445
+ defaultMaxAge: Config.number("GRAPHQL_CACHE_CONTROL_DEFAULT_MAX_AGE").pipe(Config.withDefault(0)),
2446
+ defaultScope: Config.string("GRAPHQL_CACHE_CONTROL_DEFAULT_SCOPE").pipe(
2447
+ Config.withDefault("PUBLIC"),
2448
+ Config.map((s) => s === "PRIVATE" ? "PRIVATE" : "PUBLIC")
2449
+ ),
2450
+ calculateHttpHeaders: Config.boolean("GRAPHQL_CACHE_CONTROL_HTTP_HEADERS").pipe(
2451
+ Config.withDefault(true)
2452
+ )
2453
+ });
2454
+
2455
+ // src/server/router.ts
2456
+ var defaultErrorHandler = (cause) => (process.env.NODE_ENV !== "production" ? Effect.logError("GraphQL error", cause) : Effect.void).pipe(
2457
+ Effect.andThen(
2458
+ HttpServerResponse.json(
2459
+ {
2460
+ errors: [
2461
+ {
2462
+ message: "An error occurred processing your request"
2463
+ }
2464
+ ]
2465
+ },
2466
+ { status: 500 }
2467
+ ).pipe(Effect.orDie)
2468
+ )
2469
+ );
2470
+ var parseGraphQLQuery = (query2, extensionsService) => Effect.gen(function* () {
2471
+ try {
2472
+ const document = parse(query2);
2473
+ return { ok: true, document };
2474
+ } catch (parseError) {
2475
+ const extensionData = yield* extensionsService.get();
2476
+ const response = yield* HttpServerResponse.json({
2477
+ errors: [{ message: String(parseError) }],
2478
+ extensions: Object.keys(extensionData).length > 0 ? extensionData : void 0
2479
+ }).pipe(Effect.orDie);
2480
+ return { ok: false, response };
2481
+ }
2482
+ });
2483
+ var runComplexityValidation = (body, schema, fieldComplexities, complexityConfig) => {
2484
+ if (!complexityConfig) {
2485
+ return Effect.void;
2486
+ }
2487
+ return validateComplexity(
2488
+ body.query,
2489
+ body.operationName,
2490
+ body.variables,
2491
+ schema,
2492
+ fieldComplexities,
2493
+ complexityConfig
2494
+ ).pipe(
2495
+ Effect.catchTag("ComplexityLimitExceededError", (error) => Effect.fail(error)),
2496
+ Effect.catchTag(
2497
+ "ComplexityAnalysisError",
2498
+ (error) => Effect.logWarning("Complexity analysis failed", error)
2499
+ )
2500
+ );
2501
+ };
2502
+ var executeGraphQLQuery = (schema, document, variables, operationName, runtime) => Effect.gen(function* () {
2503
+ const executeResult = yield* Effect.try({
2504
+ try: () => execute$1({
2505
+ schema,
2506
+ document,
2507
+ variableValues: variables,
2508
+ operationName,
2509
+ contextValue: { runtime }
2510
+ }),
2511
+ catch: (error) => new Error(String(error))
2512
+ });
2513
+ if (executeResult && typeof executeResult === "object" && "then" in executeResult) {
2514
+ return yield* Effect.promise(
2515
+ () => executeResult
2516
+ );
2517
+ }
2518
+ return executeResult;
2519
+ });
2520
+ var computeCacheControlHeader = (document, operationName, schema, cacheHints, cacheControlConfig) => Effect.gen(function* () {
2521
+ if (cacheControlConfig?.enabled === false || cacheControlConfig?.calculateHttpHeaders === false) {
2522
+ return void 0;
2523
+ }
2524
+ const operations = document.definitions.filter(
2525
+ (d) => d.kind === Kind.OPERATION_DEFINITION
2526
+ );
2527
+ const operation = operationName ? operations.find((o) => o.name?.value === operationName) : operations[0];
2528
+ if (!operation || operation.operation === "mutation") {
2529
+ return void 0;
2530
+ }
2531
+ const cachePolicy = yield* computeCachePolicy({
2532
+ document,
2533
+ operation,
2534
+ schema,
2535
+ cacheHints,
2536
+ config: cacheControlConfig ?? {}
2537
+ });
2538
+ return toCacheControlHeader(cachePolicy);
2539
+ });
2540
+ var buildGraphQLResponse = (result, extensionData, cacheControlHeader) => {
2541
+ const finalResult = Object.keys(extensionData).length > 0 ? {
2542
+ ...result,
2543
+ extensions: {
2544
+ ...result.extensions,
2545
+ ...extensionData
2546
+ }
2547
+ } : result;
2548
+ const responseHeaders = cacheControlHeader ? { "cache-control": cacheControlHeader } : void 0;
2549
+ return HttpServerResponse.json(finalResult, { headers: responseHeaders }).pipe(Effect.orDie);
2550
+ };
2551
+ var handleComplexityError = (error) => HttpServerResponse.json(
2552
+ {
2553
+ errors: [
2554
+ {
2555
+ message: error.message,
2556
+ extensions: {
2557
+ code: "COMPLEXITY_LIMIT_EXCEEDED",
2558
+ limitType: error.limitType,
2559
+ limit: error.limit,
2560
+ actual: error.actual
2561
+ }
2562
+ }
2563
+ ]
2564
+ },
2565
+ { status: 400 }
2566
+ ).pipe(Effect.orDie);
2567
+ var makeGraphQLRouter = (schema, layer, options = {}) => {
2568
+ const resolvedConfig = normalizeConfig(options);
2569
+ const fieldComplexities = options.fieldComplexities ?? /* @__PURE__ */ new Map();
2570
+ const cacheHints = options.cacheHints ?? /* @__PURE__ */ new Map();
2571
+ const extensions = options.extensions ?? [];
2572
+ const errorHandler = options.errorHandler ?? defaultErrorHandler;
2573
+ const graphqlHandler = Effect.gen(function* () {
2574
+ const extensionsService = yield* makeExtensionsService();
2575
+ const runtime = yield* Effect.runtime();
2576
+ const request = yield* HttpServerRequest.HttpServerRequest;
2577
+ const body = yield* request.json;
2578
+ const parseResult = yield* parseGraphQLQuery(body.query, extensionsService);
2579
+ if (!parseResult.ok) {
2580
+ return parseResult.response;
2581
+ }
2582
+ const document = parseResult.document;
2583
+ yield* runParseHooks(extensions, body.query, document).pipe(
2584
+ Effect.provideService(ExtensionsService, extensionsService)
2585
+ );
2586
+ const validationRules = resolvedConfig.introspection ? void 0 : [...specifiedRules, NoSchemaIntrospectionCustomRule];
2587
+ const validationErrors = validate(schema, document, validationRules);
2588
+ yield* runValidateHooks(extensions, document, validationErrors).pipe(
2589
+ Effect.provideService(ExtensionsService, extensionsService)
2590
+ );
2591
+ if (validationErrors.length > 0) {
2592
+ const extensionData2 = yield* extensionsService.get();
2593
+ return yield* HttpServerResponse.json(
2594
+ {
2595
+ errors: validationErrors.map((e) => ({
2596
+ message: e.message,
2597
+ locations: e.locations,
2598
+ path: e.path
2599
+ })),
2600
+ extensions: Object.keys(extensionData2).length > 0 ? extensionData2 : void 0
2601
+ },
2602
+ { status: 400 }
2603
+ );
2604
+ }
2605
+ yield* runComplexityValidation(body, schema, fieldComplexities, resolvedConfig.complexity);
2606
+ yield* runExecuteStartHooks(extensions, {
2607
+ source: body.query,
2608
+ document,
2609
+ variableValues: body.variables,
2610
+ operationName: body.operationName,
2611
+ schema,
2612
+ fieldComplexities
2613
+ }).pipe(Effect.provideService(ExtensionsService, extensionsService));
2614
+ const result = yield* executeGraphQLQuery(
2615
+ schema,
2616
+ document,
2617
+ body.variables,
2618
+ body.operationName,
2619
+ runtime
2620
+ );
2621
+ yield* runExecuteEndHooks(extensions, result).pipe(
2622
+ Effect.provideService(ExtensionsService, extensionsService)
2623
+ );
2624
+ const extensionData = yield* extensionsService.get();
2625
+ const cacheControlHeader = yield* computeCacheControlHeader(
2626
+ document,
2627
+ body.operationName,
2628
+ schema,
2629
+ cacheHints,
2630
+ resolvedConfig.cacheControl
2631
+ );
2632
+ return yield* buildGraphQLResponse(result, extensionData, cacheControlHeader);
2633
+ }).pipe(
2634
+ Effect.provide(layer),
2635
+ Effect.catchAll((error) => {
2636
+ if (error instanceof ComplexityLimitExceededError) {
2637
+ return handleComplexityError(error);
2638
+ }
2639
+ return Effect.fail(error);
2640
+ }),
2641
+ Effect.catchAllCause(errorHandler)
2642
+ );
2643
+ let router = HttpRouter.empty.pipe(
2644
+ HttpRouter.post(resolvedConfig.path, graphqlHandler)
2645
+ );
2646
+ if (resolvedConfig.graphiql) {
2647
+ const { path, endpoint } = resolvedConfig.graphiql;
2648
+ router = router.pipe(
2649
+ HttpRouter.get(path, HttpServerResponse.html(graphiqlHtml(endpoint)))
2650
+ );
2651
+ }
2652
+ return router;
2653
+ };
2654
+
2655
+ // src/server/schema-builder-extensions.ts
2656
+ var toRouter = (builder, layer, options) => {
2657
+ const schema = builder.buildSchema();
2658
+ const fieldComplexities = builder.getFieldComplexities();
2659
+ const cacheHints = builder.getCacheHints();
2660
+ return makeGraphQLRouter(schema, layer, { ...options, fieldComplexities, cacheHints });
2661
+ };
2662
+ var WebSocketError = class extends Data.TaggedError("WebSocketError") {
2663
+ };
2664
+ var createConnectionContext = (extra) => ({
2665
+ runtime: extra.runtime,
2666
+ connectionParams: extra.connectionParams,
2667
+ socket: extra.socket
2668
+ });
2669
+ var makeOnConnectHandler = (options) => {
2670
+ if (!options?.onConnect) return void 0;
2671
+ return async (ctx) => {
2672
+ const extra = ctx.extra;
2673
+ try {
2674
+ const result = await Runtime.runPromise(extra.runtime)(
2675
+ options.onConnect(ctx.connectionParams ?? {})
2676
+ );
2677
+ if (typeof result === "object" && result !== null) {
2678
+ Object.assign(extra.connectionParams, result);
2679
+ }
2680
+ return result !== false;
2681
+ } catch {
2682
+ return false;
2683
+ }
2684
+ };
2685
+ };
2686
+ var makeOnDisconnectHandler = (options) => {
2687
+ if (!options?.onDisconnect) return void 0;
2688
+ return async (ctx) => {
2689
+ const extra = ctx.extra;
2690
+ await Runtime.runPromise(extra.runtime)(
2691
+ options.onDisconnect(createConnectionContext(extra))
2692
+ ).catch(() => {
2693
+ });
2694
+ };
2695
+ };
2696
+ var makeOnSubscribeHandler = (options, schema, complexityConfig, fieldComplexities) => {
2697
+ return async (ctx, id, payload) => {
2698
+ const extra = ctx.extra;
2699
+ const connectionCtx = createConnectionContext(extra);
2700
+ if (complexityConfig) {
2701
+ const validationEffect = validateComplexity(
2702
+ payload.query,
2703
+ payload.operationName ?? void 0,
2704
+ payload.variables ?? void 0,
2705
+ schema,
2706
+ fieldComplexities,
2707
+ complexityConfig
2708
+ ).pipe(
2709
+ Effect.catchAll((error) => {
2710
+ if (error._tag === "ComplexityLimitExceededError") {
2711
+ throw new GraphQLError(error.message, {
2712
+ extensions: {
2713
+ code: "COMPLEXITY_LIMIT_EXCEEDED",
2714
+ limitType: error.limitType,
2715
+ limit: error.limit,
2716
+ actual: error.actual
2717
+ }
2718
+ });
2719
+ }
2720
+ return Effect.logWarning("Complexity analysis failed for subscription", error);
2721
+ })
2722
+ );
2723
+ await Effect.runPromise(validationEffect);
2724
+ }
2725
+ if (options?.onSubscribe) {
2726
+ await Runtime.runPromise(extra.runtime)(
2727
+ options.onSubscribe(connectionCtx, {
2728
+ id,
2729
+ payload: {
2730
+ query: payload.query,
2731
+ variables: payload.variables ?? void 0,
2732
+ operationName: payload.operationName ?? void 0,
2733
+ extensions: payload.extensions ?? void 0
2734
+ }
2735
+ })
2736
+ );
2737
+ }
2738
+ };
2739
+ };
2740
+ var makeOnCompleteHandler = (options) => {
2741
+ if (!options?.onComplete) return void 0;
2742
+ return async (ctx, id, _payload) => {
2743
+ const extra = ctx.extra;
2744
+ await Runtime.runPromise(extra.runtime)(
2745
+ options.onComplete(createConnectionContext(extra), { id })
2746
+ ).catch(() => {
2747
+ });
2748
+ };
2749
+ };
2750
+ var makeOnErrorHandler = (options) => {
2751
+ if (!options?.onError) return void 0;
2752
+ return async (ctx, _id, _payload, errors) => {
2753
+ const extra = ctx.extra;
2754
+ await Runtime.runPromise(extra.runtime)(
2755
+ options.onError(createConnectionContext(extra), errors)
2756
+ ).catch(() => {
2757
+ });
2758
+ };
2759
+ };
2760
+ var createGraphqlWsSocketAdapter = (socket, runtime) => {
2761
+ let messageCallback = null;
2762
+ return {
2763
+ adapter: {
2764
+ protocol: socket.protocol,
2765
+ send: (data) => Runtime.runPromise(runtime)(
2766
+ socket.send(data).pipe(Effect.catchAll((error) => Effect.logError("WebSocket send error", error)))
2767
+ ),
2768
+ close: (code, reason) => {
2769
+ Runtime.runPromise(runtime)(socket.close(code, reason)).catch(() => {
2770
+ });
2771
+ },
2772
+ onMessage: (cb) => {
2773
+ messageCallback = cb;
2774
+ },
2775
+ onPong: (_payload) => {
2776
+ }
2777
+ },
2778
+ dispatchMessage: async (message) => {
2779
+ if (messageCallback) {
2780
+ await messageCallback(message);
2781
+ }
2782
+ }
2783
+ };
2784
+ };
2785
+ var runConnectionLifecycle = (socket, wsServer, extra) => Effect.gen(function* () {
2786
+ const messageQueue = yield* Queue.unbounded();
2787
+ const closedDeferred = yield* Deferred.make();
2788
+ const messageFiber = yield* Effect.fork(
2789
+ Stream.runForEach(socket.messages, (msg) => Queue.offer(messageQueue, msg)).pipe(
2790
+ Effect.catchAll((error) => Deferred.fail(closedDeferred, error))
2791
+ )
2792
+ );
2793
+ const closeFiber = yield* Effect.fork(
2794
+ socket.closed.pipe(
2795
+ Effect.tap((event) => Deferred.succeed(closedDeferred, event)),
2796
+ Effect.catchAll((error) => Deferred.fail(closedDeferred, error))
2797
+ )
2798
+ );
2799
+ const { adapter, dispatchMessage } = createGraphqlWsSocketAdapter(socket, extra.runtime);
2800
+ const closedHandler = wsServer.opened(adapter, extra);
2801
+ const processMessagesFiber = yield* Effect.fork(
2802
+ Effect.gen(function* () {
2803
+ while (true) {
2804
+ const message = yield* Queue.take(messageQueue);
2805
+ yield* Effect.tryPromise({
2806
+ try: () => dispatchMessage(message),
2807
+ catch: (error) => error
2808
+ }).pipe(Effect.catchAll(() => Effect.void));
2809
+ }
2810
+ })
2811
+ );
2812
+ yield* Deferred.await(closedDeferred).pipe(
2813
+ Effect.catchAll(() => Effect.succeed({ code: 1e3, reason: "Error" }))
2814
+ );
2815
+ closedHandler(1e3, "Connection closed");
2816
+ yield* Fiber.interrupt(messageFiber);
2817
+ yield* Fiber.interrupt(closeFiber);
2818
+ yield* Fiber.interrupt(processMessagesFiber);
2819
+ yield* Queue.shutdown(messageQueue);
2820
+ }).pipe(
2821
+ Effect.catchAllCause(() => Effect.void),
2822
+ Effect.scoped
2823
+ );
2824
+ var makeGraphQLWSHandler = (schema, layer, options) => {
2825
+ const complexityConfig = options?.complexity;
2826
+ const fieldComplexities = options?.fieldComplexities ?? /* @__PURE__ */ new Map();
2827
+ const serverOptions = {
2828
+ schema,
2829
+ context: async (ctx) => {
2830
+ const extra = ctx.extra;
2831
+ return {
2832
+ runtime: extra.runtime,
2833
+ ...extra.connectionParams
2834
+ };
2835
+ },
2836
+ subscribe: async (args) => subscribe(args),
2837
+ onConnect: makeOnConnectHandler(options),
2838
+ onDisconnect: makeOnDisconnectHandler(options),
2839
+ onSubscribe: makeOnSubscribeHandler(options, schema, complexityConfig, fieldComplexities),
2840
+ onComplete: makeOnCompleteHandler(options),
2841
+ onError: makeOnErrorHandler(options)
2842
+ };
2843
+ const wsServer = makeServer(serverOptions);
2844
+ return (socket) => Effect.gen(function* () {
2845
+ const runtime = yield* Effect.provide(Effect.runtime(), layer);
2846
+ const extra = {
2847
+ socket,
2848
+ runtime,
2849
+ connectionParams: {}
2850
+ };
2851
+ yield* runConnectionLifecycle(socket, wsServer, extra);
2852
+ }).pipe(
2853
+ Effect.catchAllCause(() => Effect.void),
2854
+ Effect.scoped
2855
+ );
2856
+ };
2857
+ var WS_CLOSED = 3;
2858
+ var toEffectWebSocketFromWs = (ws) => {
2859
+ const messagesEffect = Effect.gen(function* () {
2860
+ const queue = yield* Queue.unbounded();
2861
+ const closed = yield* Deferred.make();
2862
+ ws.on("message", (data) => {
2863
+ const message = data.toString();
2864
+ Effect.runPromise(Queue.offer(queue, message)).catch(() => {
2865
+ });
2866
+ });
2867
+ ws.on("error", (error) => {
2868
+ Effect.runPromise(Deferred.fail(closed, new WebSocketError({ cause: error }))).catch(() => {
2869
+ });
2870
+ });
2871
+ ws.on("close", (code, reason) => {
2872
+ Effect.runPromise(
2873
+ Queue.shutdown(queue).pipe(
2874
+ Effect.andThen(Deferred.succeed(closed, { code, reason: reason.toString() }))
2875
+ )
2876
+ ).catch(() => {
2877
+ });
2878
+ });
2879
+ return { queue, closed };
2880
+ });
2881
+ const messages = Stream.unwrap(
2882
+ messagesEffect.pipe(
2883
+ Effect.map(({ queue }) => Stream.fromQueue(queue).pipe(Stream.catchAll(() => Stream.empty)))
2884
+ )
2885
+ );
2886
+ return {
2887
+ protocol: ws.protocol || "graphql-transport-ws",
2888
+ send: (data) => Effect.async((resume) => {
2889
+ ws.send(data, (error) => {
2890
+ if (error) {
2891
+ resume(Effect.fail(new WebSocketError({ cause: error })));
2892
+ } else {
2893
+ resume(Effect.succeed(void 0));
2894
+ }
2895
+ });
2896
+ }),
2897
+ close: (code, reason) => Effect.sync(() => {
2898
+ ws.close(code ?? 1e3, reason ?? "");
2899
+ }),
2900
+ messages,
2901
+ closed: Effect.async((resume) => {
2902
+ if (ws.readyState === WS_CLOSED) {
2903
+ resume(Effect.succeed({ code: 1e3, reason: "" }));
2904
+ return;
2905
+ }
2906
+ const onClose = (code, reason) => {
2907
+ cleanup();
2908
+ resume(Effect.succeed({ code, reason: reason.toString() }));
2909
+ };
2910
+ const onError = (error) => {
2911
+ cleanup();
2912
+ resume(Effect.fail(new WebSocketError({ cause: error })));
2913
+ };
2914
+ const cleanup = () => {
2915
+ ws.removeListener("close", onClose);
2916
+ ws.removeListener("error", onError);
2917
+ };
2918
+ ws.on("close", onClose);
2919
+ ws.on("error", onError);
2920
+ return Effect.sync(cleanup);
2921
+ })
2922
+ };
2923
+ };
2924
+ var SSE_HEADERS = {
2925
+ "Content-Type": "text/event-stream",
2926
+ "Cache-Control": "no-cache",
2927
+ Connection: "keep-alive",
2928
+ "X-Accel-Buffering": "no"
2929
+ // Disable nginx buffering
2930
+ };
2931
+ var SSEError = class extends Data.TaggedError("SSEError") {
2932
+ };
2933
+ var formatNextEvent = (result) => ({
2934
+ event: "next",
2935
+ data: JSON.stringify(result)
2936
+ });
2937
+ var formatErrorEvent = (errors) => ({
2938
+ event: "error",
2939
+ data: JSON.stringify({ errors })
2940
+ });
2941
+ var formatCompleteEvent = () => ({
2942
+ event: "complete",
2943
+ data: ""
2944
+ });
2945
+ var formatSSEMessage = (event) => {
2946
+ const lines = [`event: ${event.event}`];
2947
+ if (event.data) {
2948
+ lines.push(`data: ${event.data}`);
2949
+ }
2950
+ lines.push("", "");
2951
+ return lines.join("\n");
2952
+ };
2953
+ var makeSSESubscriptionStream = (schema, layer, request, headers, options) => {
2954
+ const complexityConfig = options?.complexity;
2955
+ const fieldComplexities = options?.fieldComplexities ?? /* @__PURE__ */ new Map();
2956
+ return Stream.unwrap(
2957
+ Effect.gen(function* () {
2958
+ const runtime = yield* Effect.provide(Effect.runtime(), layer);
2959
+ let connectionContext = {};
2960
+ if (options?.onConnect) {
2961
+ try {
2962
+ connectionContext = yield* Effect.provide(options.onConnect(request, headers), layer);
2963
+ } catch {
2964
+ return Stream.make(
2965
+ formatErrorEvent([
2966
+ new GraphQLError("Subscription connection rejected", {
2967
+ extensions: { code: "CONNECTION_REJECTED" }
2968
+ })
2969
+ ]),
2970
+ formatCompleteEvent()
2971
+ );
2972
+ }
2973
+ }
2974
+ let document;
2975
+ try {
2976
+ document = parse(request.query);
2977
+ } catch (syntaxError) {
2978
+ return Stream.make(formatErrorEvent([syntaxError]), formatCompleteEvent());
2979
+ }
2980
+ const validationErrors = validate(schema, document);
2981
+ if (validationErrors.length > 0) {
2982
+ return Stream.make(formatErrorEvent(validationErrors), formatCompleteEvent());
2983
+ }
2984
+ const operations = document.definitions.filter(
2985
+ (d) => d.kind === Kind.OPERATION_DEFINITION
2986
+ );
2987
+ const operation = request.operationName ? operations.find((o) => o.name?.value === request.operationName) : operations[0];
2988
+ if (!operation) {
2989
+ return Stream.make(
2990
+ formatErrorEvent([new GraphQLError("No operation found in query")]),
2991
+ formatCompleteEvent()
2992
+ );
2993
+ }
2994
+ if (operation.operation !== "subscription") {
2995
+ return Stream.make(
2996
+ formatErrorEvent([
2997
+ new GraphQLError(
2998
+ `SSE endpoint only supports subscriptions, received: ${operation.operation}`,
2999
+ { extensions: { code: "OPERATION_NOT_SUPPORTED" } }
3000
+ )
3001
+ ]),
3002
+ formatCompleteEvent()
3003
+ );
3004
+ }
3005
+ if (complexityConfig) {
3006
+ const complexityResult = yield* validateComplexity(
3007
+ request.query,
3008
+ request.operationName,
3009
+ request.variables,
3010
+ schema,
3011
+ fieldComplexities,
3012
+ complexityConfig
3013
+ ).pipe(
3014
+ Effect.map(() => null),
3015
+ Effect.catchAll((error) => {
3016
+ if (error._tag === "ComplexityLimitExceededError") {
3017
+ return Effect.succeed(
3018
+ new GraphQLError(error.message, {
3019
+ extensions: {
3020
+ code: "COMPLEXITY_LIMIT_EXCEEDED",
3021
+ limitType: error.limitType,
3022
+ limit: error.limit,
3023
+ actual: error.actual
3024
+ }
3025
+ })
3026
+ );
3027
+ }
3028
+ return Effect.logWarning("Complexity analysis failed for SSE subscription", error).pipe(
3029
+ Effect.map(() => null)
3030
+ );
3031
+ })
3032
+ );
3033
+ if (complexityResult) {
3034
+ return Stream.make(formatErrorEvent([complexityResult]), formatCompleteEvent());
3035
+ }
3036
+ }
3037
+ const ctx = {
3038
+ runtime,
3039
+ request,
3040
+ connectionContext
3041
+ };
3042
+ if (options?.onSubscribe) {
3043
+ yield* Effect.provide(options.onSubscribe(ctx), layer).pipe(
3044
+ Effect.catchAll(() => Effect.void)
3045
+ );
3046
+ }
3047
+ const graphqlContext = {
3048
+ runtime,
3049
+ ...connectionContext
3050
+ };
3051
+ const subscriptionResult = yield* Effect.tryPromise({
3052
+ try: () => subscribe({
3053
+ schema,
3054
+ document,
3055
+ variableValues: request.variables,
3056
+ operationName: request.operationName ?? void 0,
3057
+ contextValue: graphqlContext
3058
+ }),
3059
+ catch: (error) => new SSEError({ cause: error })
3060
+ });
3061
+ if (!isAsyncIterable(subscriptionResult)) {
3062
+ const result = subscriptionResult;
3063
+ if (result.errors) {
3064
+ return Stream.make(formatErrorEvent(result.errors), formatCompleteEvent());
3065
+ }
3066
+ return Stream.make(formatNextEvent(result), formatCompleteEvent());
3067
+ }
3068
+ const asyncIterator = subscriptionResult[Symbol.asyncIterator]();
3069
+ const eventStream = Stream.async((emit) => {
3070
+ let done = false;
3071
+ const iterate = async () => {
3072
+ try {
3073
+ while (!done) {
3074
+ const result = await asyncIterator.next();
3075
+ if (result.done) {
3076
+ emit.end();
3077
+ break;
3078
+ }
3079
+ emit.single(formatNextEvent(result.value));
3080
+ }
3081
+ } catch (error) {
3082
+ if (!done) {
3083
+ emit.single(
3084
+ formatErrorEvent([
3085
+ error instanceof GraphQLError ? error : new GraphQLError(
3086
+ error instanceof Error ? error.message : "Subscription error",
3087
+ { extensions: { code: "SUBSCRIPTION_ERROR" } }
3088
+ )
3089
+ ])
3090
+ );
3091
+ emit.end();
3092
+ }
3093
+ }
3094
+ };
3095
+ iterate();
3096
+ return Effect.sync(() => {
3097
+ done = true;
3098
+ asyncIterator.return?.();
3099
+ });
3100
+ });
3101
+ return eventStream.pipe(
3102
+ Stream.onDone(
3103
+ () => Effect.gen(function* () {
3104
+ yield* Effect.sync(() => {
3105
+ });
3106
+ }).pipe(Effect.asVoid)
3107
+ ),
3108
+ Stream.concat(Stream.make(formatCompleteEvent())),
3109
+ Stream.onDone(() => {
3110
+ if (options?.onComplete) {
3111
+ return Effect.provide(options.onComplete(ctx), layer).pipe(
3112
+ Effect.catchAll(() => Effect.void)
3113
+ );
3114
+ }
3115
+ return Effect.void;
3116
+ })
3117
+ );
3118
+ }).pipe(
3119
+ Effect.catchAll(
3120
+ (error) => Effect.succeed(
3121
+ Stream.make(
3122
+ formatErrorEvent([
3123
+ new GraphQLError(error instanceof Error ? error.message : "Internal error", {
3124
+ extensions: { code: "INTERNAL_ERROR" }
3125
+ })
3126
+ ]),
3127
+ formatCompleteEvent()
3128
+ )
3129
+ )
3130
+ )
3131
+ )
3132
+ );
3133
+ };
3134
+ var makeGraphQLSSEHandler = (schema, layer, options) => {
3135
+ return (request, headers) => makeSSESubscriptionStream(schema, layer, request, headers, options);
3136
+ };
3137
+ function isAsyncIterable(value) {
3138
+ return typeof value === "object" && value !== null && Symbol.asyncIterator in value;
3139
+ }
3140
+ var createAnalyzerExtension = (config = {}) => {
3141
+ const {
3142
+ includeComplexity = true,
3143
+ includeDepth = true,
3144
+ includeFieldCount = false,
3145
+ includeAliasCount = false,
3146
+ key = "analyzer",
3147
+ thresholds,
3148
+ defaultFieldComplexity = 1,
3149
+ fieldComplexities: configFieldComplexities
3150
+ } = config;
3151
+ return {
3152
+ name: "analyzer",
3153
+ description: "Reports query complexity metrics in response extensions",
3154
+ onExecuteStart: (args) => Effect.gen(function* () {
3155
+ const ext = yield* ExtensionsService;
3156
+ const operation = findOperation(args);
3157
+ if (!operation) {
3158
+ return;
3159
+ }
3160
+ const fieldComplexities = configFieldComplexities ?? args.fieldComplexities;
3161
+ const calculator = defaultComplexityCalculator(defaultFieldComplexity);
3162
+ const result = yield* calculator({
3163
+ document: args.document,
3164
+ operation,
3165
+ variables: args.variableValues,
3166
+ schema: args.schema,
3167
+ fieldComplexities
3168
+ }).pipe(
3169
+ Effect.catchAll(
3170
+ (error) => Effect.logWarning("Analyzer extension: complexity calculation failed", error).pipe(
3171
+ Effect.as(null)
3172
+ )
3173
+ )
3174
+ );
3175
+ if (!result) {
3176
+ return;
3177
+ }
3178
+ yield* checkThresholds(result, thresholds);
3179
+ const output = {};
3180
+ if (includeComplexity) {
3181
+ output.complexity = result.complexity;
3182
+ }
3183
+ if (includeDepth) {
3184
+ output.depth = result.depth;
3185
+ }
3186
+ if (includeFieldCount) {
3187
+ output.fieldCount = result.fieldCount;
3188
+ }
3189
+ if (includeAliasCount) {
3190
+ output.aliasCount = result.aliasCount;
3191
+ }
3192
+ yield* ext.set(key, output);
3193
+ })
3194
+ };
3195
+ };
3196
+ function findOperation(args) {
3197
+ const operations = args.document.definitions.filter(
3198
+ (d) => d.kind === Kind.OPERATION_DEFINITION
3199
+ );
3200
+ if (operations.length === 0) {
3201
+ return null;
3202
+ }
3203
+ if (args.operationName) {
3204
+ return operations.find((o) => o.name?.value === args.operationName) ?? null;
3205
+ }
3206
+ return operations[0];
3207
+ }
3208
+ function checkThresholds(result, thresholds) {
3209
+ if (!thresholds) {
3210
+ return Effect.void;
3211
+ }
3212
+ const warnings = [];
3213
+ if (thresholds.depth !== void 0 && result.depth > thresholds.depth) {
3214
+ warnings.push(`Query depth ${result.depth} exceeds threshold ${thresholds.depth}`);
3215
+ }
3216
+ if (thresholds.complexity !== void 0 && result.complexity > thresholds.complexity) {
3217
+ warnings.push(
3218
+ `Query complexity ${result.complexity} exceeds threshold ${thresholds.complexity}`
3219
+ );
3220
+ }
3221
+ if (thresholds.fieldCount !== void 0 && result.fieldCount > thresholds.fieldCount) {
3222
+ warnings.push(
3223
+ `Query field count ${result.fieldCount} exceeds threshold ${thresholds.fieldCount}`
3224
+ );
3225
+ }
3226
+ if (thresholds.aliasCount !== void 0 && result.aliasCount > thresholds.aliasCount) {
3227
+ warnings.push(
3228
+ `Query alias count ${result.aliasCount} exceeds threshold ${thresholds.aliasCount}`
3229
+ );
3230
+ }
3231
+ if (warnings.length > 0) {
3232
+ return Effect.logWarning("Analyzer extension: thresholds exceeded", {
3233
+ warnings,
3234
+ result
3235
+ });
3236
+ }
3237
+ return Effect.void;
3238
+ }
3239
+
3240
+ export { AuthorizationError, CacheControlConfigFromEnv, ComplexityAnalysisError, ComplexityConfigFromEnv, ComplexityLimitExceededError, ExtensionsService, GraphQLError2 as GraphQLError, GraphQLRequestContext, GraphQLRouterConfigFromEnv, GraphQLSchemaBuilder, Loader, MissingResolverContextError, NotFoundError, ResolverContext, ResolverContextStore, SSEError, SSE_HEADERS, ValidationError, WS_CLOSED, WebSocketError, combineCalculators, compose, computeCachePolicy, computeCachePolicyFromQuery, createAnalyzerExtension, defaultComplexityCalculator, defaultConfig, defaultErrorHandler, depthOnlyCalculator, directive, enumType, execute, extension, field, formatCompleteEvent, formatErrorEvent, formatNextEvent, formatSSEMessage, get, getOption, getOrElse, getSchemaName, graphiqlHtml, has, inputType, interfaceType, make3 as make, makeExtensionsService, makeGraphQLRouter, makeGraphQLSSEHandler, makeGraphQLWSHandler, makeRequestContextLayer, makeSSESubscriptionStream, makeStoreLayer, middleware, mutation, normalizeConfig, objectType, query, runExecuteEndHooks, runExecuteStartHooks, runParseHooks, runValidateHooks, scoped, set, setMany, storeLayer, subscription, toCacheControlHeader, toEffectWebSocketFromWs, toGraphQLArgs, toGraphQLInputType, toGraphQLObjectType, toGraphQLType, toRouter, unionType, validateComplexity };
3241
+ //# sourceMappingURL=index.js.map
3242
+ //# sourceMappingURL=index.js.map