@tangen/graphql 0.0.0-stage → 0.1.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1277 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __returnValue = (v) => v;
3
+ function __exportSetter(name, newValue) {
4
+ this[name] = __returnValue.bind(null, newValue);
5
+ }
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, {
9
+ get: all[name],
10
+ enumerable: true,
11
+ configurable: true,
12
+ set: __exportSetter.bind(all, name)
13
+ });
14
+ };
15
+
16
+ // src/index.ts
17
+ import {
18
+ parse as parse4,
19
+ validate as validate2,
20
+ execute,
21
+ getOperationAST as getOperationAST2,
22
+ GraphQLError as GraphQLError5,
23
+ GraphQLSchema as GraphQLSchema2,
24
+ GraphQLObjectType as GraphQLObjectType3,
25
+ GraphQLString as GraphQLString3,
26
+ NoSchemaIntrospectionCustomRule,
27
+ specifiedRules as specifiedRules2
28
+ } from "graphql";
29
+
30
+ // src/depth-limit.ts
31
+ import { GraphQLError, Kind, parse } from "graphql";
32
+ function depthOf(set, fragments, seen) {
33
+ let max = 0;
34
+ for (const selection of set.selections) {
35
+ if (selection.kind === Kind.FIELD) {
36
+ if (selection.name.value.startsWith("__"))
37
+ continue;
38
+ const inner = selection.selectionSet ? depthOf(selection.selectionSet, fragments, seen) : 0;
39
+ max = Math.max(max, 1 + inner);
40
+ } else if (selection.kind === Kind.INLINE_FRAGMENT) {
41
+ max = Math.max(max, depthOf(selection.selectionSet, fragments, seen));
42
+ } else if (selection.kind === Kind.FRAGMENT_SPREAD) {
43
+ const name = selection.name.value;
44
+ if (seen.has(name))
45
+ continue;
46
+ const fragment = fragments.get(name);
47
+ if (!fragment)
48
+ continue;
49
+ max = Math.max(max, depthOf(fragment.selectionSet, fragments, new Set([...seen, name])));
50
+ }
51
+ }
52
+ return max;
53
+ }
54
+ function createMaxDepthRule(maxDepth) {
55
+ return (context) => {
56
+ const fragments = new Map;
57
+ for (const definition of context.getDocument().definitions) {
58
+ if (definition.kind === Kind.FRAGMENT_DEFINITION)
59
+ fragments.set(definition.name.value, definition);
60
+ }
61
+ return {
62
+ OperationDefinition(node) {
63
+ if (!Number.isFinite(maxDepth) || maxDepth < 1)
64
+ return false;
65
+ const depth = depthOf(node.selectionSet, fragments, new Set);
66
+ if (depth > maxDepth) {
67
+ context.reportError(new GraphQLError(`Query is too deep: ${depth} levels of nesting exceeds the maximum of ${maxDepth}.`, { nodes: [node] }));
68
+ }
69
+ return false;
70
+ }
71
+ };
72
+ };
73
+ }
74
+ function measureQueryDepth(source) {
75
+ let document;
76
+ try {
77
+ document = typeof source === "string" ? parse(source) : source;
78
+ } catch {
79
+ return null;
80
+ }
81
+ const fragments = new Map;
82
+ for (const definition of document.definitions) {
83
+ if (definition.kind === Kind.FRAGMENT_DEFINITION)
84
+ fragments.set(definition.name.value, definition);
85
+ }
86
+ let max = 0;
87
+ for (const definition of document.definitions) {
88
+ if (definition.kind !== Kind.OPERATION_DEFINITION)
89
+ continue;
90
+ max = Math.max(max, depthOf(definition.selectionSet, fragments, new Set));
91
+ }
92
+ return max;
93
+ }
94
+
95
+ // src/config.ts
96
+ var DISABLED = { enabled: false, graphiql: false, introspection: false, maxDepth: 12, mutations: false };
97
+ function resolveGraphqlConfig(project, isDev = false) {
98
+ const config = project?.graphql;
99
+ if (!config?.enabled)
100
+ return DISABLED;
101
+ return {
102
+ enabled: true,
103
+ graphiql: config.graphiql ?? isDev,
104
+ introspection: config.introspection ?? true,
105
+ maxDepth: config.maxDepth ?? 12,
106
+ mutations: config.mutations === true
107
+ };
108
+ }
109
+ // src/schema-builder.ts
110
+ import {
111
+ GraphQLSchema,
112
+ GraphQLObjectType as GraphQLObjectType2,
113
+ GraphQLInputObjectType,
114
+ GraphQLNonNull as GraphQLNonNull2,
115
+ GraphQLList as GraphQLList2,
116
+ GraphQLID as GraphQLID2,
117
+ GraphQLString as GraphQLString2,
118
+ GraphQLFloat,
119
+ GraphQLInt,
120
+ GraphQLBoolean,
121
+ GraphQLUnionType
122
+ } from "graphql";
123
+ import { activeFields } from "@tangen/types";
124
+
125
+ // src/scalars.ts
126
+ import { GraphQLScalarType, Kind as Kind2 } from "graphql";
127
+ var GraphQLJSON = new GraphQLScalarType({
128
+ name: "JSON",
129
+ description: "Arbitrary JSON value (objects, arrays, or scalars).",
130
+ serialize: (v) => v,
131
+ parseValue: (v) => v,
132
+ parseLiteral: function parseLiteral(ast) {
133
+ switch (ast.kind) {
134
+ case Kind2.STRING:
135
+ case Kind2.BOOLEAN:
136
+ return ast.value;
137
+ case Kind2.INT:
138
+ case Kind2.FLOAT:
139
+ return Number(ast.value);
140
+ case Kind2.NULL:
141
+ return null;
142
+ case Kind2.LIST:
143
+ return ast.values.map(parseLiteral);
144
+ case Kind2.OBJECT:
145
+ return Object.fromEntries(ast.fields.map((f) => [f.name.value, parseLiteral(f.value)]));
146
+ default:
147
+ return null;
148
+ }
149
+ }
150
+ });
151
+ var GraphQLDateTime = new GraphQLScalarType({
152
+ name: "DateTime",
153
+ description: "An ISO-8601 date-time string.",
154
+ serialize: (v) => v instanceof Date ? v.toISOString() : v,
155
+ parseValue: (v) => v,
156
+ parseLiteral: (ast) => ast.kind === Kind2.STRING ? ast.value : null
157
+ });
158
+
159
+ // src/subscriptions.ts
160
+ import {
161
+ GraphQLObjectType,
162
+ GraphQLNonNull,
163
+ GraphQLList,
164
+ GraphQLID,
165
+ GraphQLString,
166
+ GraphQLError as GraphQLError2,
167
+ parse as parse2,
168
+ validate,
169
+ getOperationAST,
170
+ specifiedRules
171
+ } from "graphql";
172
+
173
+ // src/naming.ts
174
+ var exports_naming = {};
175
+ __export(exports_naming, {
176
+ whereInputName: () => whereInputName,
177
+ typeName: () => typeName,
178
+ singularize: () => singularize,
179
+ singleQueryName: () => singleQueryName,
180
+ pluralize: () => pluralize,
181
+ pascal: () => pascal,
182
+ orderByName: () => orderByName,
183
+ listQueryNameFor: () => listQueryNameFor,
184
+ listQueryName: () => listQueryName,
185
+ connectionName: () => connectionName
186
+ });
187
+ import {
188
+ pascal,
189
+ pluralize,
190
+ singularize,
191
+ typeName,
192
+ singleQueryName,
193
+ listQueryName,
194
+ listQueryNameFor,
195
+ connectionName,
196
+ whereInputName,
197
+ orderByName
198
+ } from "@tangen/types";
199
+
200
+ // src/subscriptions.ts
201
+ function subscriptionTopic(args) {
202
+ return args.id ? `object:${args.id}` : `objects:${args.type}`;
203
+ }
204
+ function ofType(source, typeSlug) {
205
+ return {
206
+ [Symbol.asyncIterator]() {
207
+ const inner = source[Symbol.asyncIterator]();
208
+ const done = () => Promise.resolve({ value: undefined, done: true });
209
+ return {
210
+ async next() {
211
+ for (;; ) {
212
+ const r = await inner.next();
213
+ if (r.done || r.value.data.typeSlug === typeSlug)
214
+ return r;
215
+ }
216
+ },
217
+ return() {
218
+ return inner.return ? inner.return() : done();
219
+ },
220
+ throw(e) {
221
+ return inner.throw ? inner.throw(e) : Promise.reject(e);
222
+ }
223
+ };
224
+ }
225
+ };
226
+ }
227
+ function subscribeTo(typeSlug, id, ctx) {
228
+ if (!ctx.canRead(typeSlug)) {
229
+ throw new GraphQLError2(`You do not have permission to read '${typeSlug}'`, { extensions: { code: "FORBIDDEN" } });
230
+ }
231
+ if (!ctx.realtime) {
232
+ throw new GraphQLError2("Subscriptions run over the realtime WebSocket: open GET /api/v1/realtime?ticket=<ticket> with the graphql-transport-ws subprotocol", { extensions: { code: "SUBSCRIPTIONS_NEED_WEBSOCKET" } });
233
+ }
234
+ return ofType(ctx.realtime.subscribe(subscriptionTopic({ type: typeSlug, id })), typeSlug);
235
+ }
236
+ function buildSubscriptionType(types, scalars) {
237
+ const ObjectEvent = new GraphQLObjectType({
238
+ name: "ObjectEvent",
239
+ description: "A realtime envelope: what changed, never the document. Refetch through a query.",
240
+ fields: {
241
+ id: { type: new GraphQLNonNull(GraphQLID), description: "Per-channel monotonic event id (the realtime cursor)." },
242
+ topic: { type: new GraphQLNonNull(GraphQLString) },
243
+ type: { type: new GraphQLNonNull(GraphQLString), description: "object.created | object.updated | object.published | object.unpublished | object.deleted | object.scheduled | publish.started | publish.completed | publish.failed" },
244
+ t: { type: new GraphQLNonNull(scalars.DateTime), resolve: (e) => new Date(e.t) },
245
+ objectId: { type: new GraphQLNonNull(GraphQLID), resolve: (e) => String(e.data.objectId ?? "") },
246
+ typeSlug: { type: new GraphQLNonNull(GraphQLString), resolve: (e) => String(e.data.typeSlug ?? "") },
247
+ changedFields: { type: new GraphQLList(new GraphQLNonNull(GraphQLString)), resolve: (e) => Array.isArray(e.data.changedFields) ? e.data.changedFields : null },
248
+ actorId: { type: GraphQLID, resolve: (e) => typeof e.data.actorId === "string" ? e.data.actorId : null },
249
+ actorName: { type: GraphQLString, resolve: (e) => typeof e.data.actorName === "string" ? e.data.actorName : null },
250
+ data: { type: new GraphQLNonNull(scalars.JSON), description: "The whole envelope data, as the realtime client sees it." }
251
+ }
252
+ });
253
+ const fields = {
254
+ objectsChanged: {
255
+ type: new GraphQLNonNull(ObjectEvent),
256
+ description: "Every object of a type (objects:<type>), or one object of it when id is given (object:<id>).",
257
+ args: { type: { type: new GraphQLNonNull(GraphQLString) }, id: { type: GraphQLID } },
258
+ subscribe: (_root, args, ctx) => subscribeTo(args.type, args.id, ctx),
259
+ resolve: (event) => event
260
+ }
261
+ };
262
+ for (const def of types) {
263
+ fields[`${singleQueryName(def.name)}Changed`] = {
264
+ type: new GraphQLNonNull(ObjectEvent),
265
+ description: `Changes to ${def.name} objects: objects:${def.name}, or object:<id> when id is given.`,
266
+ args: { id: { type: GraphQLID } },
267
+ subscribe: (_root, args, ctx) => subscribeTo(def.name, args.id, ctx),
268
+ resolve: (event) => event
269
+ };
270
+ }
271
+ return new GraphQLObjectType({ name: "Subscription", fields });
272
+ }
273
+ function prepareSubscription(schema, source, operationName) {
274
+ let document;
275
+ try {
276
+ document = parse2(source);
277
+ } catch (e) {
278
+ return { ok: false, errors: [e] };
279
+ }
280
+ const errors = validate(schema, document, specifiedRules);
281
+ if (errors.length > 0)
282
+ return { ok: false, errors: [...errors] };
283
+ const operation = getOperationAST(document, operationName ?? undefined);
284
+ if (!operation) {
285
+ return { ok: false, errors: [new GraphQLError2(operationName ? `Unknown operation "${operationName}"` : "The document must contain exactly one operation, or name the one to run")] };
286
+ }
287
+ if (operation.operation !== "subscription") {
288
+ return { ok: false, errors: [new GraphQLError2("Only subscription operations run over the realtime socket; send queries and mutations to POST /api/v1/graphql", { extensions: { code: "NOT_A_SUBSCRIPTION" } })] };
289
+ }
290
+ return { ok: true, document };
291
+ }
292
+
293
+ // src/schema-builder.ts
294
+ function scalarOutput(fieldType) {
295
+ switch (fieldType) {
296
+ case "number":
297
+ case "currency":
298
+ case "rating":
299
+ return GraphQLFloat;
300
+ case "boolean":
301
+ return GraphQLBoolean;
302
+ case "date":
303
+ return GraphQLDateTime;
304
+ case "json":
305
+ case "repeater":
306
+ case "component":
307
+ case "group":
308
+ case "geopoint":
309
+ case "richtext":
310
+ case "range":
311
+ case "object":
312
+ return GraphQLJSON;
313
+ case "multiselect":
314
+ case "tags":
315
+ return new GraphQLList2(GraphQLString2);
316
+ case "text":
317
+ case "textarea":
318
+ case "slug":
319
+ case "email":
320
+ case "time":
321
+ case "url":
322
+ case "phone":
323
+ case "select":
324
+ case "color":
325
+ case "code":
326
+ case "password":
327
+ return GraphQLString2;
328
+ default:
329
+ return null;
330
+ }
331
+ }
332
+ function filterScalarInput(fieldType) {
333
+ switch (fieldType) {
334
+ case "number":
335
+ case "currency":
336
+ case "rating":
337
+ return GraphQLFloat;
338
+ case "boolean":
339
+ return GraphQLBoolean;
340
+ default:
341
+ return GraphQLString2;
342
+ }
343
+ }
344
+ function tableColumnType(colType) {
345
+ switch (colType) {
346
+ case "number":
347
+ return GraphQLFloat;
348
+ case "boolean":
349
+ return GraphQLBoolean;
350
+ case "timestamp":
351
+ return GraphQLDateTime;
352
+ case "json":
353
+ return GraphQLJSON;
354
+ default:
355
+ return GraphQLString2;
356
+ }
357
+ }
358
+ function buildContentSchema(schema, opts = {}) {
359
+ const types = (schema.types ?? []).filter((t) => t.disabled !== true).map((t) => ({ ...t, fields: activeFields(t.fields ?? []) }));
360
+ const byName = new Map(types.map((t) => [t.name, t]));
361
+ const objectTypes = new Map;
362
+ const connectionTypes = new Map;
363
+ const whereInputs = new Map;
364
+ const orderByInputs = new Map;
365
+ const QueryMeta = new GraphQLObjectType2({
366
+ name: "QueryMeta",
367
+ fields: {
368
+ total: { type: new GraphQLNonNull2(GraphQLInt) },
369
+ limit: { type: GraphQLInt },
370
+ offset: { type: GraphQLInt },
371
+ nextCursor: { type: GraphQLString2 }
372
+ }
373
+ });
374
+ const Media = new GraphQLObjectType2({
375
+ name: "Media",
376
+ fields: {
377
+ id: { type: GraphQLID2 },
378
+ url: { type: GraphQLString2 },
379
+ thumbnailUrl: { type: GraphQLString2 },
380
+ filename: { type: GraphQLString2 },
381
+ originalName: { type: GraphQLString2 },
382
+ mimeType: { type: GraphQLString2 },
383
+ sizeBytes: { type: GraphQLFloat },
384
+ width: { type: GraphQLFloat },
385
+ height: { type: GraphQLFloat },
386
+ altText: { type: GraphQLString2 },
387
+ alt: { type: GraphQLString2, resolve: (p) => p?.altText ?? null },
388
+ tags: { type: new GraphQLList2(GraphQLString2) },
389
+ storagePath: { type: GraphQLString2 },
390
+ thumbnailPath: { type: GraphQLString2 },
391
+ variants: { type: GraphQLJSON },
392
+ variantUrls: { type: GraphQLJSON },
393
+ variantsStatus: { type: GraphQLString2 }
394
+ }
395
+ });
396
+ const TableOrderBy = new GraphQLInputObjectType({
397
+ name: "TableOrderBy",
398
+ fields: { field: { type: new GraphQLNonNull2(GraphQLString2) }, direction: { type: GraphQLString2 } }
399
+ });
400
+ const r = opts.resolvers;
401
+ const getObjectType = (name) => {
402
+ if (objectTypes.has(name))
403
+ return objectTypes.get(name);
404
+ const def = byName.get(name);
405
+ if (!def)
406
+ return;
407
+ const gqlType = new GraphQLObjectType2({
408
+ name: typeName(name),
409
+ description: def.label,
410
+ fields: () => buildObjectFields(def)
411
+ });
412
+ objectTypes.set(name, gqlType);
413
+ return gqlType;
414
+ };
415
+ const getConnectionType = (name) => {
416
+ if (connectionTypes.has(name))
417
+ return connectionTypes.get(name);
418
+ const conn = new GraphQLObjectType2({
419
+ name: connectionName(name),
420
+ fields: () => ({
421
+ data: { type: new GraphQLNonNull2(new GraphQLList2(new GraphQLNonNull2(getObjectType(name)))) },
422
+ meta: { type: new GraphQLNonNull2(QueryMeta) }
423
+ })
424
+ });
425
+ connectionTypes.set(name, conn);
426
+ return conn;
427
+ };
428
+ function buildObjectFields(def) {
429
+ const fields = {
430
+ id: { type: new GraphQLNonNull2(GraphQLID2) },
431
+ status: { type: GraphQLString2 },
432
+ title: { type: GraphQLString2 },
433
+ slug: { type: GraphQLString2 },
434
+ createdAt: { type: GraphQLDateTime },
435
+ updatedAt: { type: GraphQLDateTime },
436
+ publishedAt: { type: GraphQLDateTime },
437
+ hasDraftChanges: { type: GraphQLBoolean }
438
+ };
439
+ for (const f of def.fields ?? []) {
440
+ fields[f.name] = fieldConfig(def, f);
441
+ }
442
+ return fields;
443
+ }
444
+ const unionTypes = new Map;
445
+ const getObjectUnion = (ownerName, fieldName, members) => {
446
+ const key = `${ownerName}:${fieldName}`;
447
+ if (unionTypes.has(key))
448
+ return unionTypes.get(key);
449
+ const union = new GraphQLUnionType({
450
+ name: `${typeName(ownerName)}${fieldName.charAt(0).toUpperCase()}${fieldName.slice(1).replace(/[^A-Za-z0-9]/g, "")}Ref`,
451
+ types: () => members.map((m) => getObjectType(m)).filter((t) => !!t),
452
+ resolveType: (value) => typeName(String(value?.type ?? ""))
453
+ });
454
+ unionTypes.set(key, union);
455
+ return union;
456
+ };
457
+ const registry = opts.componentRegistry ?? [];
458
+ const blockTypes = new Map;
459
+ const rowTypes = new Map;
460
+ const pascal2 = (v) => v.replace(/(^|[^A-Za-z0-9]+)([a-z0-9])/gi, (_m, _s, c) => String(c).toUpperCase()).replace(/[^A-Za-z0-9]/g, "");
461
+ function subFieldConfig(owner, sf) {
462
+ const cfg = sf.config ?? {};
463
+ const name = sf.name;
464
+ const ft = sf.fieldType;
465
+ if (ft === "relation" && cfg.targetType && byName.has(cfg.targetType)) {
466
+ return cfg.many === true ? { type: getConnectionType(cfg.targetType), resolve: r?.relationMany?.(owner, name, cfg.targetType) } : { type: getObjectType(cfg.targetType), resolve: r?.relationOne?.(owner, name, cfg.targetType) };
467
+ }
468
+ if (ft === "component") {
469
+ const list = getBlockListConfig(`${owner}${pascal2(name)}`, cfg.components);
470
+ if (list)
471
+ return list;
472
+ return { type: GraphQLJSON };
473
+ }
474
+ if (ft === "repeater") {
475
+ const row = getRowType(`${owner}${pascal2(name)}`, cfg.fields ?? []);
476
+ return row ? { type: new GraphQLList2(row) } : { type: GraphQLJSON };
477
+ }
478
+ if (ft === "media")
479
+ return { type: Media };
480
+ const scalar = scalarOutput(ft);
481
+ return { type: scalar ?? GraphQLJSON };
482
+ }
483
+ function getBlockType(def) {
484
+ const key = def.name;
485
+ if (blockTypes.has(key))
486
+ return blockTypes.get(key);
487
+ const t = new GraphQLObjectType2({
488
+ name: `Block${pascal2(def.name)}`,
489
+ description: def.label,
490
+ fields: () => {
491
+ const out = {
492
+ _key: { type: GraphQLString2 },
493
+ _type: { type: GraphQLString2 },
494
+ _label: { type: GraphQLString2 }
495
+ };
496
+ for (const sf of def.fields ?? []) {
497
+ const conf = subFieldConfig(`Block${pascal2(def.name)}`, sf);
498
+ if (conf)
499
+ out[sf.name] = conf;
500
+ }
501
+ return out;
502
+ }
503
+ });
504
+ blockTypes.set(key, t);
505
+ return t;
506
+ }
507
+ function resolveBlockDefs(refs) {
508
+ const out = [];
509
+ for (const ref of Array.isArray(refs) ? refs : []) {
510
+ const def = typeof ref === "string" ? registry.find((c) => c.name === ref) : ref;
511
+ if (def && typeof def.name === "string")
512
+ out.push(def);
513
+ }
514
+ return out;
515
+ }
516
+ function getBlockListConfig(unionBase, refs) {
517
+ const defs = resolveBlockDefs(refs);
518
+ if (defs.length === 0)
519
+ return null;
520
+ const knownNames = new Set(defs.map((d) => d.name));
521
+ const union = defs.length === 1 ? getBlockType(defs[0]) : new GraphQLUnionType({
522
+ name: `${unionBase}Block`,
523
+ types: () => defs.map((d) => getBlockType(d)),
524
+ resolveType: (value) => `Block${pascal2(String(value?._type ?? ""))}`
525
+ });
526
+ return {
527
+ type: new GraphQLList2(union),
528
+ resolve: (parent, _a, _c, info) => {
529
+ const v = parent?.[info.fieldName];
530
+ if (!Array.isArray(v))
531
+ return [];
532
+ return v.filter((b) => knownNames.has(String(b?._type ?? b?.type ?? "")));
533
+ }
534
+ };
535
+ }
536
+ function getRowType(base, fields) {
537
+ if (!fields.length)
538
+ return null;
539
+ const key = base;
540
+ if (rowTypes.has(key))
541
+ return rowTypes.get(key);
542
+ const t = new GraphQLObjectType2({
543
+ name: `${base}Row`,
544
+ fields: () => {
545
+ const out = { _key: { type: GraphQLString2 } };
546
+ for (const sf of fields) {
547
+ const conf = subFieldConfig(`${base}Row`, sf);
548
+ if (conf)
549
+ out[sf.name] = conf;
550
+ }
551
+ return out;
552
+ }
553
+ });
554
+ rowTypes.set(key, t);
555
+ return t;
556
+ }
557
+ function fieldConfig(def, f) {
558
+ const cfg = f.config ?? {};
559
+ if (f.fieldType === "relation" && cfg.targetType && byName.has(cfg.targetType)) {
560
+ if (cfg.many) {
561
+ return {
562
+ type: getConnectionType(cfg.targetType),
563
+ resolve: r?.relationMany?.(def.name, f.name, cfg.targetType)
564
+ };
565
+ }
566
+ return {
567
+ type: getObjectType(cfg.targetType),
568
+ resolve: r?.relationOne?.(def.name, f.name, cfg.targetType)
569
+ };
570
+ }
571
+ if (f.fieldType === "media")
572
+ return { type: Media };
573
+ if (f.fieldType === "component") {
574
+ const typed = getBlockListConfig(`${typeName(def.name)}${pascal2(f.name)}`, f.config?.components);
575
+ if (typed)
576
+ return typed;
577
+ return { type: GraphQLJSON };
578
+ }
579
+ if (f.fieldType === "repeater") {
580
+ const row = getRowType(`${typeName(def.name)}${pascal2(f.name)}`, f.config?.fields ?? []);
581
+ if (row)
582
+ return { type: new GraphQLList2(row) };
583
+ return { type: GraphQLJSON };
584
+ }
585
+ if (f.fieldType === "object") {
586
+ const members = (cfg.include ?? []).filter((n) => byName.has(n));
587
+ if (members.length > 0) {
588
+ const union = getObjectUnion(def.name, f.name, members);
589
+ return {
590
+ type: cfg.many === true ? new GraphQLList2(union) : union,
591
+ resolve: r?.objectRef?.(def.name, f.name)
592
+ };
593
+ }
594
+ return { type: GraphQLJSON };
595
+ }
596
+ const scalar = scalarOutput(f.fieldType);
597
+ return { type: scalar ?? GraphQLJSON };
598
+ }
599
+ const getWhereInput = (name) => {
600
+ if (whereInputs.has(name))
601
+ return whereInputs.get(name);
602
+ const def = byName.get(name);
603
+ const input = new GraphQLInputObjectType({
604
+ name: whereInputName(name),
605
+ fields: () => {
606
+ const fields = {
607
+ id: { type: fieldFilterInput("id", GraphQLID2) },
608
+ status: { type: fieldFilterInput("status", GraphQLString2) },
609
+ slug: { type: fieldFilterInput("slug", GraphQLString2) },
610
+ _and: { type: new GraphQLList2(new GraphQLNonNull2(input)) },
611
+ _or: { type: new GraphQLList2(new GraphQLNonNull2(input)) }
612
+ };
613
+ for (const f of def.fields ?? []) {
614
+ if (f.fieldType === "relation" || f.fieldType === "media" || f.fieldType === "json")
615
+ continue;
616
+ fields[f.name] = { type: fieldFilterInput(f.name, filterScalarInput(f.fieldType)) };
617
+ }
618
+ return fields;
619
+ }
620
+ });
621
+ whereInputs.set(name, input);
622
+ return input;
623
+ };
624
+ const filterInputCache = new Map;
625
+ function fieldFilterInput(key, scalar) {
626
+ const cacheKey = scalar.name ?? key;
627
+ if (filterInputCache.has(cacheKey))
628
+ return filterInputCache.get(cacheKey);
629
+ const input = new GraphQLInputObjectType({
630
+ name: `${scalar.name ?? "String"}Filter`,
631
+ fields: {
632
+ eq: { type: scalar },
633
+ ne: { type: scalar },
634
+ gt: { type: scalar },
635
+ lt: { type: scalar },
636
+ gte: { type: scalar },
637
+ lte: { type: scalar },
638
+ in: { type: new GraphQLList2(new GraphQLNonNull2(scalar)) },
639
+ contains: { type: scalar }
640
+ }
641
+ });
642
+ filterInputCache.set(cacheKey, input);
643
+ return input;
644
+ }
645
+ const getOrderByInput = (name) => {
646
+ if (orderByInputs.has(name))
647
+ return orderByInputs.get(name);
648
+ const input = new GraphQLInputObjectType({
649
+ name: orderByName(name),
650
+ fields: { field: { type: new GraphQLNonNull2(GraphQLString2) }, direction: { type: GraphQLString2 } }
651
+ });
652
+ orderByInputs.set(name, input);
653
+ return input;
654
+ };
655
+ const PublishPlanNode = new GraphQLObjectType2({
656
+ name: "PublishPlanNode",
657
+ fields: {
658
+ typeName: { type: new GraphQLNonNull2(GraphQLString2) },
659
+ typeLabel: { type: new GraphQLNonNull2(GraphQLString2) },
660
+ id: { type: new GraphQLNonNull2(GraphQLID2) },
661
+ title: { type: new GraphQLNonNull2(GraphQLString2) },
662
+ status: { type: new GraphQLNonNull2(GraphQLString2) },
663
+ reason: { type: GraphQLString2 }
664
+ }
665
+ });
666
+ const PublishPlan = new GraphQLObjectType2({
667
+ name: "PublishPlan",
668
+ fields: {
669
+ needsCascade: { type: new GraphQLNonNull2(GraphQLBoolean) },
670
+ dependencies: { type: new GraphQLNonNull2(new GraphQLList2(new GraphQLNonNull2(PublishPlanNode))) },
671
+ blockers: { type: new GraphQLNonNull2(new GraphQLList2(new GraphQLNonNull2(PublishPlanNode))) }
672
+ }
673
+ });
674
+ const queryFields = {};
675
+ for (const def of types) {
676
+ const listArgs = {
677
+ where: { type: getWhereInput(def.name) },
678
+ orderBy: { type: getOrderByInput(def.name) },
679
+ limit: { type: GraphQLInt },
680
+ offset: { type: GraphQLInt },
681
+ after: { type: GraphQLString2 },
682
+ locale: { type: GraphQLString2 },
683
+ status: { type: GraphQLString2 }
684
+ };
685
+ queryFields[listQueryNameFor(def.name, def.plural)] = {
686
+ type: new GraphQLNonNull2(getConnectionType(def.name)),
687
+ args: listArgs,
688
+ resolve: r?.list?.(def.name)
689
+ };
690
+ queryFields[singleQueryName(def.name)] = {
691
+ type: getObjectType(def.name),
692
+ args: { id: { type: GraphQLID2 }, slug: { type: GraphQLString2 }, locale: { type: GraphQLString2 }, status: { type: GraphQLString2 } },
693
+ resolve: r?.single?.(def.name)
694
+ };
695
+ queryFields[`preflight${typeName(def.name)}`] = {
696
+ type: PublishPlan,
697
+ args: { id: { type: new GraphQLNonNull2(GraphQLID2) } },
698
+ resolve: r?.preflight?.(def.name)
699
+ };
700
+ }
701
+ for (const table of opts.customTables ?? []) {
702
+ const rowTypeName = `${typeName(table.name)}Row`;
703
+ const rowType = new GraphQLObjectType2({
704
+ name: rowTypeName,
705
+ fields: () => {
706
+ const f = { id: { type: new GraphQLNonNull2(GraphQLID2) } };
707
+ for (const [col, def] of Object.entries(table.columns ?? {})) {
708
+ f[col] = { type: tableColumnType(def.type) };
709
+ }
710
+ return f;
711
+ }
712
+ });
713
+ const rowConn = new GraphQLObjectType2({
714
+ name: `${typeName(table.name)}RowConnection`,
715
+ fields: () => ({
716
+ data: { type: new GraphQLNonNull2(new GraphQLList2(new GraphQLNonNull2(rowType))) },
717
+ meta: { type: new GraphQLNonNull2(QueryMeta) }
718
+ })
719
+ });
720
+ queryFields[`table_${table.name}`] = {
721
+ type: new GraphQLNonNull2(rowConn),
722
+ args: { where: { type: GraphQLJSON }, orderBy: { type: TableOrderBy }, limit: { type: GraphQLInt }, offset: { type: GraphQLInt } },
723
+ resolve: r?.table?.(table.name)
724
+ };
725
+ }
726
+ if ((opts.globalNames ?? []).length > 0) {
727
+ queryFields.global = {
728
+ type: GraphQLJSON,
729
+ args: { name: { type: new GraphQLNonNull2(GraphQLString2) } },
730
+ resolve: r?.global?.()
731
+ };
732
+ }
733
+ if (Object.keys(queryFields).length === 0) {
734
+ queryFields._empty = { type: GraphQLString2, resolve: () => null };
735
+ }
736
+ let mutationType;
737
+ if (opts.mutations && types.length > 0) {
738
+ const inputTypes = new Map;
739
+ const getInputType = (name) => {
740
+ if (inputTypes.has(name))
741
+ return inputTypes.get(name);
742
+ const def = byName.get(name);
743
+ const input = new GraphQLInputObjectType({
744
+ name: `${typeName(name)}Input`,
745
+ fields: () => {
746
+ const f = {
747
+ title: { type: GraphQLString2 },
748
+ slug: { type: GraphQLString2 }
749
+ };
750
+ for (const fd of def.fields ?? []) {
751
+ const cfg = fd.config ?? {};
752
+ if (fd.fieldType === "relation") {
753
+ f[fd.name] = { type: cfg.many ? new GraphQLList2(new GraphQLNonNull2(GraphQLID2)) : GraphQLID2 };
754
+ } else if (fd.fieldType === "media") {
755
+ f[fd.name] = { type: GraphQLID2 };
756
+ } else {
757
+ f[fd.name] = { type: filterScalarInput(fd.fieldType) === GraphQLFloat ? GraphQLFloat : fd.fieldType === "boolean" ? GraphQLBoolean : GraphQLString2 };
758
+ }
759
+ }
760
+ return f;
761
+ }
762
+ });
763
+ inputTypes.set(name, input);
764
+ return input;
765
+ };
766
+ const DeleteResult = new GraphQLObjectType2({
767
+ name: "DeleteResult",
768
+ fields: { id: { type: new GraphQLNonNull2(GraphQLID2) }, deleted: { type: GraphQLBoolean } }
769
+ });
770
+ const mutationFields = {};
771
+ for (const def of types) {
772
+ const T = typeName(def.name);
773
+ const objType = getObjectType(def.name);
774
+ mutationFields[`create${T}`] = {
775
+ type: objType,
776
+ args: { input: { type: new GraphQLNonNull2(getInputType(def.name)) } },
777
+ resolve: r?.create?.(def.name)
778
+ };
779
+ mutationFields[`update${T}`] = {
780
+ type: objType,
781
+ args: { id: { type: new GraphQLNonNull2(GraphQLID2) }, input: { type: new GraphQLNonNull2(getInputType(def.name)) } },
782
+ resolve: r?.update?.(def.name)
783
+ };
784
+ mutationFields[`publish${T}`] = {
785
+ type: objType,
786
+ args: { id: { type: new GraphQLNonNull2(GraphQLID2) }, cascade: { type: GraphQLBoolean } },
787
+ resolve: r?.publish?.(def.name)
788
+ };
789
+ mutationFields[`unpublish${T}`] = {
790
+ type: objType,
791
+ args: { id: { type: new GraphQLNonNull2(GraphQLID2) } },
792
+ resolve: r?.unpublish?.(def.name)
793
+ };
794
+ mutationFields[`delete${T}`] = {
795
+ type: DeleteResult,
796
+ args: { id: { type: new GraphQLNonNull2(GraphQLID2) } },
797
+ resolve: r?.remove?.(def.name)
798
+ };
799
+ }
800
+ mutationType = new GraphQLObjectType2({ name: "Mutation", fields: mutationFields });
801
+ }
802
+ return new GraphQLSchema({
803
+ query: new GraphQLObjectType2({ name: "Query", fields: queryFields }),
804
+ ...mutationType ? { mutation: mutationType } : {},
805
+ ...opts.subscriptions ? { subscription: buildSubscriptionType(types, { JSON: GraphQLJSON, DateTime: GraphQLDateTime }) } : {},
806
+ types: [Media, QueryMeta, GraphQLJSON, GraphQLDateTime]
807
+ });
808
+ }
809
+ // src/resolvers.ts
810
+ import { GraphQLError as GraphQLError3 } from "graphql";
811
+ import { RouteError } from "@tangen/types";
812
+
813
+ // src/filter.ts
814
+ var OPERATORS = new Set(["eq", "ne", "gt", "lt", "gte", "lte", "in", "contains", "ncontains", "startsWith", "nin", "exists"]);
815
+ function whereToFilter(where) {
816
+ if (!where || typeof where !== "object")
817
+ return {};
818
+ const out = {};
819
+ for (const [key, value] of Object.entries(where)) {
820
+ if (value == null)
821
+ continue;
822
+ if (key === "_and" || key === "_or") {
823
+ const groups = value.map((g) => whereToFilter(g));
824
+ out[key] = groups;
825
+ continue;
826
+ }
827
+ if (typeof value === "object" && !Array.isArray(value)) {
828
+ const ops = {};
829
+ for (const [op, v] of Object.entries(value)) {
830
+ if (OPERATORS.has(op) && v !== undefined)
831
+ ops[op] = v;
832
+ }
833
+ if (Object.keys(ops).length > 0)
834
+ out[key] = ops;
835
+ } else {
836
+ out[key] = value;
837
+ }
838
+ }
839
+ return out;
840
+ }
841
+
842
+ // src/loaders.ts
843
+ function createBatchLoaders(client, canRead) {
844
+ const batches = new Map;
845
+ function flush(type) {
846
+ const batch = batches.get(type);
847
+ batches.delete(type);
848
+ const ids = [...batch.ids];
849
+ if (ids.length === 0 || !canRead(type)) {
850
+ for (const r of batch.resolvers)
851
+ r.resolve(null);
852
+ return;
853
+ }
854
+ client.objects(type).where({ id: { in: ids } }).status("published").get().then((res) => {
855
+ const byId = new Map(res.data.map((r) => [String(r.id), r]));
856
+ for (const r of batch.resolvers)
857
+ r.resolve(byId.get(r.id) ?? null);
858
+ }).catch(() => {
859
+ for (const r of batch.resolvers)
860
+ r.resolve(null);
861
+ });
862
+ }
863
+ function load(type, id) {
864
+ if (!id)
865
+ return Promise.resolve(null);
866
+ let batch = batches.get(type);
867
+ if (!batch) {
868
+ batch = { ids: new Set, resolvers: [], scheduled: false };
869
+ batches.set(type, batch);
870
+ }
871
+ batch.ids.add(id);
872
+ if (!batch.scheduled) {
873
+ batch.scheduled = true;
874
+ queueMicrotask(() => flush(type));
875
+ }
876
+ return new Promise((resolve) => batch.resolvers.push({ id, resolve }));
877
+ }
878
+ return {
879
+ load,
880
+ async loadMany(type, ids) {
881
+ const rows = await Promise.all(ids.map((id) => load(type, id)));
882
+ return rows.filter((r) => r != null);
883
+ }
884
+ };
885
+ }
886
+
887
+ // src/resolvers.ts
888
+ function createRequestContext(input) {
889
+ return {
890
+ client: input.client,
891
+ canRead: input.canRead,
892
+ canWrite: input.canWrite ?? (() => false),
893
+ canReadDrafts: input.canReadDrafts ?? (() => false),
894
+ canPublish: input.canPublish ?? (() => false),
895
+ loaders: createBatchLoaders(input.client, input.canRead),
896
+ ...input.realtime ? { realtime: input.realtime } : {}
897
+ };
898
+ }
899
+ function requireRead(ctx, type) {
900
+ if (!ctx.canRead(type)) {
901
+ throw new GraphQLError3(`You do not have permission to read '${type}'`, {
902
+ extensions: { code: "FORBIDDEN" }
903
+ });
904
+ }
905
+ }
906
+ function requireDraftRead(ctx, type) {
907
+ if (!ctx.canReadDrafts?.(type)) {
908
+ throw new GraphQLError3(`Draft access to '${type}' requires the objects:read_draft grant`, {
909
+ extensions: { code: "FORBIDDEN" }
910
+ });
911
+ }
912
+ }
913
+ function requirePublish(ctx, type) {
914
+ if (!ctx.canPublish || !ctx.canPublish(type)) {
915
+ throw new GraphQLError3(`You do not have permission to publish '${type}'`, {
916
+ extensions: { code: "FORBIDDEN" }
917
+ });
918
+ }
919
+ }
920
+ function requireWrite(ctx, type) {
921
+ if (!ctx.canWrite(type)) {
922
+ throw new GraphQLError3(`You do not have permission to write '${type}'`, {
923
+ extensions: { code: "FORBIDDEN" }
924
+ });
925
+ }
926
+ }
927
+ function idOf(value) {
928
+ if (typeof value === "string")
929
+ return value;
930
+ if (value && typeof value === "object" && "id" in value)
931
+ return String(value.id);
932
+ return "";
933
+ }
934
+ function idsOf(value) {
935
+ if (Array.isArray(value))
936
+ return value.map(idOf).filter(Boolean);
937
+ if (typeof value === "string") {
938
+ const trimmed = value.trim();
939
+ if (trimmed.startsWith("[")) {
940
+ try {
941
+ const p = JSON.parse(trimmed);
942
+ if (Array.isArray(p))
943
+ return p.map(idOf).filter(Boolean);
944
+ } catch {}
945
+ }
946
+ if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
947
+ return trimmed.slice(1, -1).split(",").map((s) => s.trim().replace(/^"|"$/g, "")).filter(Boolean);
948
+ }
949
+ return trimmed ? [trimmed] : [];
950
+ }
951
+ return [];
952
+ }
953
+ function createResolvers() {
954
+ const list = (type) => async (_parent, args, ctx) => {
955
+ requireRead(ctx, type);
956
+ let b = ctx.client.objects(type).where(whereToFilter(args.where)).depth(0);
957
+ if (args.orderBy?.field)
958
+ b = b.sort(args.orderBy.field, args.orderBy.direction === "desc" ? "desc" : "asc");
959
+ if (typeof args.limit === "number")
960
+ b = b.limit(args.limit);
961
+ if (typeof args.offset === "number")
962
+ b = b.offset(args.offset);
963
+ if (args.after)
964
+ b = b.after(args.after);
965
+ if (args.locale)
966
+ b = b.locale(args.locale);
967
+ const wanted = String(args.status ?? "published");
968
+ if (wanted !== "published")
969
+ requireDraftRead(ctx, type);
970
+ b = b.status(wanted);
971
+ const res = await b.get();
972
+ return { data: res.data ?? [], meta: res.meta ?? { total: (res.data ?? []).length } };
973
+ };
974
+ const single = (type) => async (_parent, args, ctx) => {
975
+ requireRead(ctx, type);
976
+ const wanted = String(args.status ?? "published");
977
+ if (wanted !== "published")
978
+ requireDraftRead(ctx, type);
979
+ try {
980
+ let b = ctx.client.objects(type);
981
+ if (args.locale)
982
+ b = b.locale(String(args.locale));
983
+ b = b.status(wanted);
984
+ if (args.id)
985
+ return (await b.find(String(args.id))).data ?? null;
986
+ if (args.slug)
987
+ return (await b.findBySlug(String(args.slug))).data ?? null;
988
+ } catch {
989
+ return null;
990
+ }
991
+ return null;
992
+ };
993
+ const objectRef = (_parent, fieldName) => async (parent, _args, ctx) => {
994
+ const val = parent?.[fieldName];
995
+ const resolveOne = async (ref) => {
996
+ const r = ref;
997
+ if (!r || typeof r.id !== "string" || typeof r.type !== "string")
998
+ return null;
999
+ if (!ctx.canRead(r.type))
1000
+ return null;
1001
+ const row = await ctx.loaders.load(r.type, r.id);
1002
+ return row ? { ...row, type: r.type } : null;
1003
+ };
1004
+ if (Array.isArray(val)) {
1005
+ const out = await Promise.all(val.map(resolveOne));
1006
+ return out.filter((x) => x !== null);
1007
+ }
1008
+ return resolveOne(val);
1009
+ };
1010
+ const relationOne = (_parent, fieldName, targetType) => (parent, _args, ctx) => {
1011
+ const id = idOf(parent?.[fieldName]);
1012
+ return id ? ctx.loaders.load(targetType, id) : null;
1013
+ };
1014
+ const relationMany = (_parent, fieldName, targetType) => async (parent, _args, ctx) => {
1015
+ const ids = idsOf(parent?.[fieldName]);
1016
+ const rows = await ctx.loaders.loadMany(targetType, ids);
1017
+ return { data: rows, meta: { total: rows.length, limit: rows.length, offset: 0, nextCursor: null } };
1018
+ };
1019
+ const table = (name) => async (_parent, args, ctx) => {
1020
+ if (!ctx.client.table)
1021
+ return { data: [], meta: { total: 0 } };
1022
+ let b = ctx.client.table(name).where(args.where ?? {});
1023
+ if (args.orderBy?.field)
1024
+ b = b.sort(args.orderBy.field, args.orderBy.direction === "desc" ? "desc" : "asc");
1025
+ if (typeof args.limit === "number")
1026
+ b = b.limit(args.limit);
1027
+ if (typeof args.offset === "number")
1028
+ b = b.offset(args.offset);
1029
+ const res = await b.find();
1030
+ return { data: res.data ?? [], meta: res.meta ?? { total: (res.data ?? []).length } };
1031
+ };
1032
+ const global = () => async (_parent, args, ctx) => {
1033
+ if (!ctx.client.globals)
1034
+ return null;
1035
+ return ctx.client.globals(String(args.name)).get();
1036
+ };
1037
+ const create = (type) => async (_p, args, ctx) => {
1038
+ requireWrite(ctx, type);
1039
+ const { title, slug, ...values } = args.input ?? {};
1040
+ return (await ctx.client.objects(type).create({
1041
+ title: String(title ?? "Untitled"),
1042
+ values: { ...slug !== undefined ? { slug } : {}, ...values }
1043
+ })).data;
1044
+ };
1045
+ const update = (type) => async (_p, args, ctx) => {
1046
+ requireWrite(ctx, type);
1047
+ const input = { ...args.input ?? {} };
1048
+ return (await ctx.client.objects(type).update(String(args.id), input)).data;
1049
+ };
1050
+ const publish = (type) => async (_p, args, ctx) => {
1051
+ requirePublish(ctx, type);
1052
+ try {
1053
+ return (await ctx.client.objects(type).publish(String(args.id), { cascade: args.cascade === true })).data;
1054
+ } catch (e) {
1055
+ throw asCascadeError(e);
1056
+ }
1057
+ };
1058
+ const preflight = (type) => async (_p, args, ctx) => {
1059
+ requirePublish(ctx, type);
1060
+ return (await ctx.client.objects(type).publishPreflight(String(args.id))).data;
1061
+ };
1062
+ const unpublish = (type) => async (_p, args, ctx) => {
1063
+ requirePublish(ctx, type);
1064
+ return (await ctx.client.objects(type).unpublish(String(args.id))).data;
1065
+ };
1066
+ const remove = (type) => async (_p, args, ctx) => {
1067
+ requireWrite(ctx, type);
1068
+ await ctx.client.objects(type).delete(String(args.id));
1069
+ return { id: String(args.id), deleted: true };
1070
+ };
1071
+ return { list, single, relationOne, relationMany, objectRef, table, global, create, update, publish, preflight, unpublish, remove };
1072
+ }
1073
+ function asCascadeError(e) {
1074
+ if (e instanceof RouteError) {
1075
+ const code = e.status === 409 ? "NEEDS_CASCADE" : e.status === 422 ? "CASCADE_BLOCKED" : "REQUEST_ERROR";
1076
+ return new GraphQLError3(e.message, { extensions: { code, status: e.status, plan: e.details } });
1077
+ }
1078
+ return e;
1079
+ }
1080
+ // src/permissions.ts
1081
+ import { canWriteTypeObjects } from "@tangen/types";
1082
+ import { canReadType, canReadDraftsType, canPublishTypeObjects } from "@tangen/types";
1083
+ function canWriteType(permissions, typeName2) {
1084
+ return canWriteTypeObjects(permissions, typeName2);
1085
+ }
1086
+ // src/graphiql.ts
1087
+ function graphiqlHTML(endpoint) {
1088
+ const ep = endpoint.replace(/"/g, "&quot;");
1089
+ return `<!doctype html>
1090
+ <html lang="en">
1091
+ <head>
1092
+ <meta charset="utf-8">
1093
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1094
+ <title>Tangen GraphQL</title>
1095
+ <style>
1096
+ :root { color-scheme: light dark; }
1097
+ * { box-sizing: border-box; }
1098
+ body { margin: 0; font: 14px/1.5 ui-sans-serif, system-ui, sans-serif; background: #0f1115; color: #e6e6e6; }
1099
+ header { padding: 10px 16px; background: #171a21; border-bottom: 1px solid #2a2f3a; display: flex; align-items: center; gap: 12px; }
1100
+ header b { font-weight: 600; } header code { color: #8ab4f8; }
1101
+ main { display: grid; grid-template-columns: 1fr 1fr; gap: 1px; background: #2a2f3a; height: calc(100vh - 49px); }
1102
+ textarea, pre { margin: 0; padding: 14px; background: #12151b; color: #e6e6e6; border: 0; font: 13px/1.55 ui-monospace, SFMono-Regular, Menlo, monospace; width: 100%; height: 100%; resize: none; overflow: auto; }
1103
+ pre { white-space: pre-wrap; word-break: break-word; }
1104
+ .bar { position: absolute; top: 8px; right: 16px; }
1105
+ button { background: #3b82f6; color: #fff; border: 0; border-radius: 6px; padding: 6px 14px; font-weight: 600; cursor: pointer; }
1106
+ button:hover { background: #2563eb; }
1107
+ </style>
1108
+ </head>
1109
+ <body>
1110
+ <header>
1111
+ <b>Tangen GraphQL</b>
1112
+ <code id="ep"></code>
1113
+ <span style="flex:1"></span>
1114
+ <button id="run">Run ▶ <span style="opacity:.7;font-weight:400">(⌘⏎)</span></button>
1115
+ </header>
1116
+ <main>
1117
+ <textarea id="q" spellcheck="false" placeholder="Type a query…">{
1118
+ __schema { queryType { fields { name } } }
1119
+ }</textarea>
1120
+ <pre id="out">Press Run to execute.</pre>
1121
+ </main>
1122
+ <script>
1123
+ var endpoint = "${ep}";
1124
+ document.getElementById('ep').textContent = endpoint;
1125
+ var q = document.getElementById('q'), out = document.getElementById('out');
1126
+ async function run() {
1127
+ out.textContent = '…';
1128
+ try {
1129
+ var res = await fetch(endpoint, {
1130
+ method: 'POST',
1131
+ headers: { 'content-type': 'application/json' },
1132
+ credentials: 'same-origin',
1133
+ body: JSON.stringify({ query: q.value })
1134
+ });
1135
+ var json = await res.json();
1136
+ out.textContent = JSON.stringify(json, null, 2);
1137
+ } catch (e) { out.textContent = 'Request failed: ' + e; }
1138
+ }
1139
+ document.getElementById('run').addEventListener('click', run);
1140
+ q.addEventListener('keydown', function (e) {
1141
+ if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') { e.preventDefault(); run(); }
1142
+ });
1143
+ </script>
1144
+ </body>
1145
+ </html>`;
1146
+ }
1147
+
1148
+ // src/index.ts
1149
+ import { subscribe } from "graphql";
1150
+ import { printSchema } from "graphql";
1151
+
1152
+ // src/extensions.ts
1153
+ import { extendSchema, parse as parse3, isObjectType, GraphQLError as GraphQLError4 } from "graphql";
1154
+ function fieldSet(schema) {
1155
+ const out = new Set;
1156
+ for (const type of Object.values(schema.getTypeMap())) {
1157
+ if (!isObjectType(type) || type.name.startsWith("__"))
1158
+ continue;
1159
+ for (const field of Object.keys(type.getFields()))
1160
+ out.add(`${type.name}.${field}`);
1161
+ }
1162
+ return out;
1163
+ }
1164
+ function wrap(extensionId, fn) {
1165
+ return async (source, args, context, info) => {
1166
+ const ctx = typeof context?.extensionCtx === "function" ? await context.extensionCtx(extensionId) : null;
1167
+ if (!ctx)
1168
+ throw new GraphQLError4(`Extension '${extensionId}' cannot serve '${info.parentType.name}.${info.fieldName}' for this request`, { extensions: { code: "FORBIDDEN" } });
1169
+ return fn(source, args, { ...context, ctx }, info);
1170
+ };
1171
+ }
1172
+ function applyGraphqlContributions(schema, items, opts = {}) {
1173
+ if (items.length === 0)
1174
+ return schema;
1175
+ const warn = opts.warn ?? (() => {});
1176
+ let current = schema;
1177
+ for (const item of items) {
1178
+ const before = fieldSet(current);
1179
+ let extended;
1180
+ try {
1181
+ extended = extendSchema(current, parse3(item.sdl), { assumeValidSDL: false });
1182
+ } catch (e) {
1183
+ warn(`graphql.types@1 from extension "${item.extensionId}" dropped: ${e instanceof Error ? e.message : String(e)}`);
1184
+ continue;
1185
+ }
1186
+ const added = fieldSet(extended);
1187
+ let ok = true;
1188
+ for (const [typeName2, fields] of Object.entries(item.resolvers ?? {})) {
1189
+ const type = extended.getType(typeName2);
1190
+ if (!type || !isObjectType(type)) {
1191
+ warn(`graphql.types@1 from extension "${item.extensionId}": resolvers for unknown type '${typeName2}' ignored`);
1192
+ continue;
1193
+ }
1194
+ const typeFields = type.getFields();
1195
+ for (const [fieldName, fn] of Object.entries(fields)) {
1196
+ const key = `${typeName2}.${fieldName}`;
1197
+ if (before.has(key) || !added.has(key)) {
1198
+ warn(`graphql.types@1 from extension "${item.extensionId}": resolver for '${key}' ignored - not a field this extension added`);
1199
+ continue;
1200
+ }
1201
+ if (typeof fn !== "function") {
1202
+ warn(`graphql.types@1 from extension "${item.extensionId}": resolver for '${key}' is not a function`);
1203
+ continue;
1204
+ }
1205
+ typeFields[fieldName].resolve = wrap(item.extensionId, fn);
1206
+ }
1207
+ }
1208
+ if (ok)
1209
+ current = extended;
1210
+ }
1211
+ return current;
1212
+ }
1213
+
1214
+ // src/index.ts
1215
+ async function executeGraphql(args) {
1216
+ const depthLimited = typeof args.maxDepth === "number" && args.maxDepth >= 1;
1217
+ let document;
1218
+ try {
1219
+ document = parse4(args.source);
1220
+ } catch (e) {
1221
+ return { errors: [e] };
1222
+ }
1223
+ if (getOperationAST2(document, args.operationName ?? undefined)?.operation === "subscription") {
1224
+ return { errors: [new GraphQLError5("Subscriptions run over the realtime WebSocket: open GET /api/v1/realtime?ticket=<ticket> with the graphql-transport-ws subprotocol", { extensions: { code: "SUBSCRIPTIONS_NEED_WEBSOCKET" } })] };
1225
+ }
1226
+ const rules = [...specifiedRules2];
1227
+ if (args.introspection === false)
1228
+ rules.push(NoSchemaIntrospectionCustomRule);
1229
+ if (depthLimited)
1230
+ rules.push(createMaxDepthRule(args.maxDepth));
1231
+ const validationErrors = validate2(args.schema, document, rules);
1232
+ if (validationErrors.length > 0)
1233
+ return { errors: validationErrors };
1234
+ return execute({
1235
+ schema: args.schema,
1236
+ document,
1237
+ variableValues: args.variableValues ?? undefined,
1238
+ operationName: args.operationName ?? undefined,
1239
+ contextValue: args.contextValue,
1240
+ rootValue: args.rootValue
1241
+ });
1242
+ }
1243
+ function pingSchema() {
1244
+ const resolvePing = () => "pong";
1245
+ return new GraphQLSchema2({
1246
+ query: new GraphQLObjectType3({
1247
+ name: "Query",
1248
+ fields: { ping: { type: GraphQLString3, resolve: resolvePing } }
1249
+ })
1250
+ });
1251
+ }
1252
+ export {
1253
+ whereToFilter,
1254
+ subscriptionTopic,
1255
+ subscribe as subscribeGraphql,
1256
+ resolveGraphqlConfig,
1257
+ printSchema as printSchemaSDL,
1258
+ prepareSubscription,
1259
+ pingSchema,
1260
+ exports_naming as naming,
1261
+ measureQueryDepth,
1262
+ graphiqlHTML,
1263
+ executeGraphql,
1264
+ createResolvers,
1265
+ createRequestContext,
1266
+ createMaxDepthRule,
1267
+ createBatchLoaders,
1268
+ canWriteType,
1269
+ canReadType,
1270
+ canReadDraftsType,
1271
+ canPublishTypeObjects,
1272
+ buildSubscriptionType,
1273
+ buildContentSchema,
1274
+ applyGraphqlContributions,
1275
+ GraphQLJSON,
1276
+ GraphQLDateTime
1277
+ };