@contember/engine-http 2.2.0-alpha.19 → 2.2.0-alpha.20
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/CLAUDE.md +2 -0
- package/dist/development/index.cjs +8 -0
- package/dist/development/index.cjs.map +1 -1
- package/dist/development/index.js +9 -1
- package/dist/development/index.js.map +1 -1
- package/dist/development/src/MasterContainer.cjs +28 -14
- package/dist/development/src/MasterContainer.cjs.map +1 -1
- package/dist/development/src/MasterContainer.js +28 -14
- package/dist/development/src/MasterContainer.js.map +1 -1
- package/dist/development/src/config/configSchema.cjs +50 -0
- package/dist/development/src/config/configSchema.cjs.map +1 -1
- package/dist/development/src/config/configSchema.js +50 -0
- package/dist/development/src/config/configSchema.js.map +1 -1
- package/dist/development/src/config/configTemplate.cjs +8 -0
- package/dist/development/src/config/configTemplate.cjs.map +1 -1
- package/dist/development/src/config/configTemplate.js +8 -0
- package/dist/development/src/config/configTemplate.js.map +1 -1
- package/dist/development/src/content/ContentApiControllerFactory.cjs +12 -1
- package/dist/development/src/content/ContentApiControllerFactory.cjs.map +1 -1
- package/dist/development/src/content/ContentApiControllerFactory.js +12 -1
- package/dist/development/src/content/ContentApiControllerFactory.js.map +1 -1
- package/dist/development/src/content/ContentApiSpecificCache.cjs +20 -5
- package/dist/development/src/content/ContentApiSpecificCache.cjs.map +1 -1
- package/dist/development/src/content/ContentApiSpecificCache.js +20 -5
- package/dist/development/src/content/ContentApiSpecificCache.js.map +1 -1
- package/dist/development/src/content/ContentGraphQLEngine.cjs +17 -0
- package/dist/development/src/content/ContentGraphQLEngine.cjs.map +1 -0
- package/dist/development/src/content/ContentGraphQLEngine.js +17 -0
- package/dist/development/src/content/ContentGraphQLEngine.js.map +1 -0
- package/dist/development/src/content/ContentQueryHandlerFactory.cjs +4 -1
- package/dist/development/src/content/ContentQueryHandlerFactory.cjs.map +1 -1
- package/dist/development/src/content/ContentQueryHandlerFactory.js +5 -2
- package/dist/development/src/content/ContentQueryHandlerFactory.js.map +1 -1
- package/dist/development/src/content/ContentRequestLog.cjs +97 -0
- package/dist/development/src/content/ContentRequestLog.cjs.map +1 -0
- package/dist/development/src/content/ContentRequestLog.js +97 -0
- package/dist/development/src/content/ContentRequestLog.js.map +1 -0
- package/dist/development/src/content/GraphQlSchemaFactory.cjs +121 -45
- package/dist/development/src/content/GraphQlSchemaFactory.cjs.map +1 -1
- package/dist/development/src/content/GraphQlSchemaFactory.js +122 -46
- package/dist/development/src/content/GraphQlSchemaFactory.js.map +1 -1
- package/dist/development/src/graphql/execution.cjs +18 -5
- package/dist/development/src/graphql/execution.cjs.map +1 -1
- package/dist/development/src/graphql/execution.js +19 -6
- package/dist/development/src/graphql/execution.js.map +1 -1
- package/dist/development/src/project/ProjectContainer.cjs +2 -0
- package/dist/development/src/project/ProjectContainer.cjs.map +1 -1
- package/dist/development/src/project/ProjectContainer.js +2 -0
- package/dist/development/src/project/ProjectContainer.js.map +1 -1
- package/dist/development/src/projectGroup/ProjectGroupContainer.cjs +2 -0
- package/dist/development/src/projectGroup/ProjectGroupContainer.cjs.map +1 -1
- package/dist/development/src/projectGroup/ProjectGroupContainer.js +2 -0
- package/dist/development/src/projectGroup/ProjectGroupContainer.js.map +1 -1
- package/dist/development/src/system/ContentQueryExecutor.cjs +23 -6
- package/dist/development/src/system/ContentQueryExecutor.cjs.map +1 -1
- package/dist/development/src/system/ContentQueryExecutor.js +25 -8
- package/dist/development/src/system/ContentQueryExecutor.js.map +1 -1
- package/dist/development/src/system/SystemGraphQLHandlerFactory.cjs +1 -1
- package/dist/development/src/system/SystemGraphQLHandlerFactory.cjs.map +1 -1
- package/dist/development/src/system/SystemGraphQLHandlerFactory.js +2 -2
- package/dist/development/src/system/SystemGraphQLHandlerFactory.js.map +1 -1
- package/dist/development/src/tenant/TenantGraphQLHandlerFactory.cjs +1 -1
- package/dist/development/src/tenant/TenantGraphQLHandlerFactory.cjs.map +1 -1
- package/dist/development/src/tenant/TenantGraphQLHandlerFactory.js +2 -2
- package/dist/development/src/tenant/TenantGraphQLHandlerFactory.js.map +1 -1
- package/dist/production/index.cjs +8 -0
- package/dist/production/index.cjs.map +1 -1
- package/dist/production/index.js +9 -1
- package/dist/production/index.js.map +1 -1
- package/dist/production/src/MasterContainer.cjs +28 -14
- package/dist/production/src/MasterContainer.cjs.map +1 -1
- package/dist/production/src/MasterContainer.js +28 -14
- package/dist/production/src/MasterContainer.js.map +1 -1
- package/dist/production/src/config/configSchema.cjs +50 -0
- package/dist/production/src/config/configSchema.cjs.map +1 -1
- package/dist/production/src/config/configSchema.js +50 -0
- package/dist/production/src/config/configSchema.js.map +1 -1
- package/dist/production/src/config/configTemplate.cjs +8 -0
- package/dist/production/src/config/configTemplate.cjs.map +1 -1
- package/dist/production/src/config/configTemplate.js +8 -0
- package/dist/production/src/config/configTemplate.js.map +1 -1
- package/dist/production/src/content/ContentApiControllerFactory.cjs +12 -1
- package/dist/production/src/content/ContentApiControllerFactory.cjs.map +1 -1
- package/dist/production/src/content/ContentApiControllerFactory.js +12 -1
- package/dist/production/src/content/ContentApiControllerFactory.js.map +1 -1
- package/dist/production/src/content/ContentApiSpecificCache.cjs +20 -5
- package/dist/production/src/content/ContentApiSpecificCache.cjs.map +1 -1
- package/dist/production/src/content/ContentApiSpecificCache.js +20 -5
- package/dist/production/src/content/ContentApiSpecificCache.js.map +1 -1
- package/dist/production/src/content/ContentGraphQLEngine.cjs +17 -0
- package/dist/production/src/content/ContentGraphQLEngine.cjs.map +1 -0
- package/dist/production/src/content/ContentGraphQLEngine.js +17 -0
- package/dist/production/src/content/ContentGraphQLEngine.js.map +1 -0
- package/dist/production/src/content/ContentQueryHandlerFactory.cjs +4 -1
- package/dist/production/src/content/ContentQueryHandlerFactory.cjs.map +1 -1
- package/dist/production/src/content/ContentQueryHandlerFactory.js +5 -2
- package/dist/production/src/content/ContentQueryHandlerFactory.js.map +1 -1
- package/dist/production/src/content/ContentRequestLog.cjs +97 -0
- package/dist/production/src/content/ContentRequestLog.cjs.map +1 -0
- package/dist/production/src/content/ContentRequestLog.js +97 -0
- package/dist/production/src/content/ContentRequestLog.js.map +1 -0
- package/dist/production/src/content/GraphQlSchemaFactory.cjs +121 -45
- package/dist/production/src/content/GraphQlSchemaFactory.cjs.map +1 -1
- package/dist/production/src/content/GraphQlSchemaFactory.js +122 -46
- package/dist/production/src/content/GraphQlSchemaFactory.js.map +1 -1
- package/dist/production/src/graphql/execution.cjs +18 -5
- package/dist/production/src/graphql/execution.cjs.map +1 -1
- package/dist/production/src/graphql/execution.js +19 -6
- package/dist/production/src/graphql/execution.js.map +1 -1
- package/dist/production/src/project/ProjectContainer.cjs +2 -0
- package/dist/production/src/project/ProjectContainer.cjs.map +1 -1
- package/dist/production/src/project/ProjectContainer.js +2 -0
- package/dist/production/src/project/ProjectContainer.js.map +1 -1
- package/dist/production/src/projectGroup/ProjectGroupContainer.cjs +2 -0
- package/dist/production/src/projectGroup/ProjectGroupContainer.cjs.map +1 -1
- package/dist/production/src/projectGroup/ProjectGroupContainer.js +2 -0
- package/dist/production/src/projectGroup/ProjectGroupContainer.js.map +1 -1
- package/dist/production/src/system/ContentQueryExecutor.cjs +23 -6
- package/dist/production/src/system/ContentQueryExecutor.cjs.map +1 -1
- package/dist/production/src/system/ContentQueryExecutor.js +25 -8
- package/dist/production/src/system/ContentQueryExecutor.js.map +1 -1
- package/dist/production/src/system/SystemGraphQLHandlerFactory.cjs +1 -1
- package/dist/production/src/system/SystemGraphQLHandlerFactory.cjs.map +1 -1
- package/dist/production/src/system/SystemGraphQLHandlerFactory.js +2 -2
- package/dist/production/src/system/SystemGraphQLHandlerFactory.js.map +1 -1
- package/dist/production/src/tenant/TenantGraphQLHandlerFactory.cjs +1 -1
- package/dist/production/src/tenant/TenantGraphQLHandlerFactory.cjs.map +1 -1
- package/dist/production/src/tenant/TenantGraphQLHandlerFactory.js +2 -2
- package/dist/production/src/tenant/TenantGraphQLHandlerFactory.js.map +1 -1
- package/dist/tests/cases/unit/contentGraphqlCompat.test.d.ts +2 -0
- package/dist/tests/cases/unit/contentGraphqlCompat.test.d.ts.map +1 -0
- package/dist/tests/cases/unit/contentRequestLog.test.d.ts +2 -0
- package/dist/tests/cases/unit/contentRequestLog.test.d.ts.map +1 -0
- package/dist/tests/contentControllerHarness.d.ts +29 -0
- package/dist/tests/contentControllerHarness.d.ts.map +1 -0
- package/dist/tests/tsconfig.tsbuildinfo +1 -1
- package/dist/types/MasterContainer.d.ts +10 -1
- package/dist/types/MasterContainer.d.ts.map +1 -1
- package/dist/types/config/configSchema.d.ts +10 -0
- package/dist/types/config/configSchema.d.ts.map +1 -1
- package/dist/types/config/configTemplate.d.ts.map +1 -1
- package/dist/types/content/ContentApiControllerFactory.d.ts +3 -1
- package/dist/types/content/ContentApiControllerFactory.d.ts.map +1 -1
- package/dist/types/content/ContentApiSpecificCache.d.ts +2 -0
- package/dist/types/content/ContentApiSpecificCache.d.ts.map +1 -1
- package/dist/types/content/ContentGraphQLEngine.d.ts +18 -0
- package/dist/types/content/ContentGraphQLEngine.d.ts.map +1 -0
- package/dist/types/content/ContentQueryHandlerFactory.d.ts +3 -2
- package/dist/types/content/ContentQueryHandlerFactory.d.ts.map +1 -1
- package/dist/types/content/ContentRequestLog.d.ts +49 -0
- package/dist/types/content/ContentRequestLog.d.ts.map +1 -0
- package/dist/types/content/GraphQlSchemaFactory.d.ts +14 -4
- package/dist/types/content/GraphQlSchemaFactory.d.ts.map +1 -1
- package/dist/types/content/index.d.ts +2 -0
- package/dist/types/content/index.d.ts.map +1 -1
- package/dist/types/graphql/execution.d.ts +21 -3
- package/dist/types/graphql/execution.d.ts.map +1 -1
- package/dist/types/system/ContentQueryExecutor.d.ts +4 -1
- package/dist/types/system/ContentQueryExecutor.d.ts.map +1 -1
- package/dist/types/system/SystemGraphQLHandlerFactory.d.ts.map +1 -1
- package/dist/types/tenant/TenantGraphQLHandlerFactory.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +21 -18
- package/src/MasterContainer.ts +31 -14
- package/src/config/configSchema.ts +63 -0
- package/src/config/configTemplate.ts +8 -0
- package/src/content/ContentApiControllerFactory.ts +15 -2
- package/src/content/ContentApiSpecificCache.ts +22 -7
- package/src/content/ContentGraphQLEngine.ts +24 -0
- package/src/content/ContentQueryHandlerFactory.ts +16 -4
- package/src/content/ContentRequestLog.ts +138 -0
- package/src/content/GraphQlSchemaFactory.ts +173 -54
- package/src/content/index.ts +2 -0
- package/src/graphql/execution.ts +35 -7
- package/src/project/ProjectContainer.ts +1 -1
- package/src/system/ContentQueryExecutor.ts +43 -10
- package/src/system/SystemGraphQLHandlerFactory.ts +8 -2
- package/src/tenant/TenantGraphQLHandlerFactory.ts +2 -2
- package/src/tsconfig.json +1 -0
- package/tests/cases/unit/__snapshots__/contentGraphqlCompat.test.ts.snap +14295 -0
- package/tests/cases/unit/contentGraphqlCompat.test.ts +372 -0
- package/tests/cases/unit/contentRequestLog.test.ts +141 -0
- package/tests/cases/unit/forcePrimary.test.ts +93 -284
- package/tests/cases/unit/graphQlSchemaFactory.test.ts +227 -35
- package/tests/cases/unit/requestMemoryBudget.test.ts +96 -78
- package/tests/cases/unit/serverConfig.test.ts +133 -0
- package/tests/contentControllerHarness.ts +222 -0
- package/tests/tsconfig.json +3 -1
|
@@ -1,65 +1,141 @@
|
|
|
1
|
-
import { Authorizator, IntrospectionSchemaDefinitionFactory, IntrospectionSchemaFactory, EntityRulesResolver } from "@contember/engine-content-api";
|
|
1
|
+
import { Authorizator, IntrospectionSchemaDefinitionFactory, IntrospectionSchemaFactory, EntityRulesResolver, JsonContentSchemaBuilder, createJsonIntrospectionExtension, createGraphQLJsBridge, JsonContentSchemaShared } from "@contember/engine-content-api";
|
|
2
2
|
import { GraphQLSchema } from "graphql";
|
|
3
3
|
import { createHash } from "node:crypto";
|
|
4
|
+
import { ContentGraphQLEngineResolver } from "./ContentGraphQLEngine.js";
|
|
4
5
|
var __defProp = Object.defineProperty;
|
|
5
6
|
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
6
|
-
var __publicField = (obj, key, value) => __defNormalProp(obj, key + "", value);
|
|
7
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
8
|
+
const MIN_EVICTED_FOR_NEW_GENERATION = 16;
|
|
9
|
+
const BUILD_SLICE_MS = 10;
|
|
10
|
+
const runInSlices = async (steps) => {
|
|
11
|
+
let sliceEnd = performance.now() + BUILD_SLICE_MS;
|
|
12
|
+
for (; ; ) {
|
|
13
|
+
const step = steps.next();
|
|
14
|
+
if (step.done) {
|
|
15
|
+
return step.value;
|
|
16
|
+
}
|
|
17
|
+
if (performance.now() >= sliceEnd) {
|
|
18
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
19
|
+
sliceEnd = performance.now() + BUILD_SLICE_MS;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
};
|
|
7
23
|
class GraphQlSchemaFactory {
|
|
8
|
-
constructor(cache, graphqlSchemaBuilderFactory, permissionFactory, schemaContributors) {
|
|
24
|
+
constructor(cache, graphqlSchemaBuilderFactory, permissionFactory, schemaContributors, engineResolver = new ContentGraphQLEngineResolver()) {
|
|
9
25
|
this.cache = cache;
|
|
10
26
|
this.graphqlSchemaBuilderFactory = graphqlSchemaBuilderFactory;
|
|
11
27
|
this.permissionFactory = permissionFactory;
|
|
12
28
|
this.schemaContributors = schemaContributors;
|
|
29
|
+
this.engineResolver = engineResolver;
|
|
13
30
|
__publicField(this, "permissionsKeys", /* @__PURE__ */ new WeakMap());
|
|
31
|
+
__publicField(this, "generations", /* @__PURE__ */ new WeakMap());
|
|
32
|
+
__publicField(this, "generationOf", /* @__PURE__ */ new WeakMap());
|
|
33
|
+
__publicField(this, "building", /* @__PURE__ */ new WeakMap());
|
|
14
34
|
}
|
|
15
|
-
create(schema, identity, project) {
|
|
35
|
+
async create(schema, identity, project) {
|
|
16
36
|
const { permissionsKey, computedPermissions } = this.getPermissionsKey(schema, identity.projectRoles);
|
|
17
37
|
const contributorsKey = this.schemaContributors.map((it) => it.getCacheKey?.({ schema, identity, project }) ?? "").join("ÿ");
|
|
18
|
-
const
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
38
|
+
const engine = this.engineResolver.resolve(project.slug);
|
|
39
|
+
const cacheKey = `${engine}ÿÿ${permissionsKey}ÿÿ${contributorsKey}`;
|
|
40
|
+
const cached = this.cache.get(schema, cacheKey);
|
|
41
|
+
if (cached) {
|
|
42
|
+
return cached;
|
|
43
|
+
}
|
|
44
|
+
let building = this.building.get(schema);
|
|
45
|
+
if (!building) {
|
|
46
|
+
building = /* @__PURE__ */ new Map();
|
|
47
|
+
this.building.set(schema, building);
|
|
48
|
+
}
|
|
49
|
+
const inProgress = building.get(cacheKey);
|
|
50
|
+
if (inProgress) {
|
|
51
|
+
return await inProgress;
|
|
52
|
+
}
|
|
53
|
+
const build = engine === "graphql-js" ? Promise.resolve(this.buildGraphQLJs(schema, identity, project, computedPermissions)) : this.buildGraphQLJson(schema, identity, project, computedPermissions);
|
|
54
|
+
building.set(cacheKey, build);
|
|
55
|
+
try {
|
|
56
|
+
return this.cache.set(schema, cacheKey, await build);
|
|
57
|
+
} finally {
|
|
58
|
+
building.delete(cacheKey);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/** The graphql-js schema, built as before graphql-json existed. */
|
|
62
|
+
buildGraphQLJs(schema, identity, project, computedPermissions) {
|
|
63
|
+
const { root: permissions, all: allPermissions } = computedPermissions ?? this.permissionFactory.createContextual(schema, identity.projectRoles);
|
|
64
|
+
const customPrimary = schema.acl.customPrimary ?? false;
|
|
65
|
+
const refreshMaterializedView = this.permissionFactory.isRefreshMaterializedViewAllowed(schema, identity.projectRoles);
|
|
66
|
+
const authorizator = new Authorizator(allPermissions, customPrimary, refreshMaterializedView);
|
|
67
|
+
const rootAuthorizator = new Authorizator(permissions, customPrimary, refreshMaterializedView);
|
|
68
|
+
const dataSchemaBuilder = this.graphqlSchemaBuilderFactory.create(schema.model, authorizator, rootAuthorizator);
|
|
69
|
+
const introspectionSchemaFactory = new IntrospectionSchemaDefinitionFactory(
|
|
70
|
+
new IntrospectionSchemaFactory(
|
|
71
|
+
schema.model,
|
|
72
|
+
new EntityRulesResolver(schema.validation, schema.model),
|
|
73
|
+
authorizator
|
|
74
|
+
)
|
|
75
|
+
);
|
|
76
|
+
const introspectionSchema = introspectionSchemaFactory.createConfig();
|
|
77
|
+
const otherSchemas = this.schemaContributors.map((it) => it.createSchema({ schema, identity, project })).filter((it) => it !== void 0);
|
|
78
|
+
const queries = /* @__PURE__ */ new Map();
|
|
79
|
+
const mutations = /* @__PURE__ */ new Map();
|
|
80
|
+
const types = [];
|
|
81
|
+
for (const schema2 of [introspectionSchema, ...otherSchemas]) {
|
|
82
|
+
if (schema2 instanceof GraphQLSchema) {
|
|
83
|
+
for (const [field, config] of Object.entries(schema2.getQueryType()?.toConfig().fields ?? {})) {
|
|
84
|
+
queries.set(field, config);
|
|
54
85
|
}
|
|
86
|
+
for (const [field, config] of Object.entries(schema2.getQueryType()?.toConfig().fields ?? {})) {
|
|
87
|
+
mutations.set(field, config);
|
|
88
|
+
}
|
|
89
|
+
} else {
|
|
90
|
+
for (const [field, config] of Object.entries(schema2.query?.toConfig().fields ?? {})) {
|
|
91
|
+
queries.set(field, config);
|
|
92
|
+
}
|
|
93
|
+
for (const [field, config] of Object.entries(schema2.mutation?.toConfig().fields ?? {})) {
|
|
94
|
+
mutations.set(field, config);
|
|
95
|
+
}
|
|
96
|
+
types.push(...schema2.types ?? []);
|
|
55
97
|
}
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
return { schema: graphQlSchema, permissions, allPermissions };
|
|
98
|
+
}
|
|
99
|
+
const graphQlSchema = dataSchemaBuilder.build({
|
|
100
|
+
mutations,
|
|
101
|
+
queries,
|
|
102
|
+
types
|
|
62
103
|
});
|
|
104
|
+
return { schema: { engine: "graphql-js", schema: graphQlSchema }, permissions, allPermissions };
|
|
105
|
+
}
|
|
106
|
+
async buildGraphQLJson(schema, identity, project, computedPermissions) {
|
|
107
|
+
const { root: permissions, all: allPermissions } = computedPermissions ?? this.permissionFactory.createContextual(schema, identity.projectRoles);
|
|
108
|
+
const customPrimary = schema.acl.customPrimary ?? false;
|
|
109
|
+
const refreshMaterializedView = this.permissionFactory.isRefreshMaterializedViewAllowed(schema, identity.projectRoles);
|
|
110
|
+
const authorizator = new Authorizator(allPermissions, customPrimary, refreshMaterializedView);
|
|
111
|
+
const rootAuthorizator = new Authorizator(permissions, customPrimary, refreshMaterializedView);
|
|
112
|
+
const introspectionSchemaFactory = new IntrospectionSchemaFactory(
|
|
113
|
+
schema.model,
|
|
114
|
+
new EntityRulesResolver(schema.validation, schema.model),
|
|
115
|
+
authorizator
|
|
116
|
+
);
|
|
117
|
+
const otherSchemas = this.schemaContributors.map((it) => it.createSchema({ schema, identity, project })).filter((it) => it !== void 0);
|
|
118
|
+
const generation = this.getGeneration(schema);
|
|
119
|
+
const builder = new JsonContentSchemaBuilder(schema.model, authorizator, rootAuthorizator, generation.shared);
|
|
120
|
+
const jsonSchema = await runInSlices(builder.buildSteps([
|
|
121
|
+
createJsonIntrospectionExtension(introspectionSchemaFactory),
|
|
122
|
+
...otherSchemas.map(createGraphQLJsBridge)
|
|
123
|
+
]));
|
|
124
|
+
generation.built.push(new WeakRef(jsonSchema));
|
|
125
|
+
this.generationOf.set(jsonSchema, generation);
|
|
126
|
+
return { schema: { engine: "graphql-json", schema: jsonSchema }, permissions, allPermissions };
|
|
127
|
+
}
|
|
128
|
+
getGeneration(schema) {
|
|
129
|
+
const current = this.generations.get(schema)?.deref();
|
|
130
|
+
if (current) {
|
|
131
|
+
const evicted = current.built.filter((it) => it.deref() === void 0).length;
|
|
132
|
+
if (evicted < MIN_EVICTED_FOR_NEW_GENERATION || evicted < current.built.length - evicted) {
|
|
133
|
+
return current;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
const generation = { shared: new JsonContentSchemaShared(), built: [] };
|
|
137
|
+
this.generations.set(schema, new WeakRef(generation));
|
|
138
|
+
return generation;
|
|
63
139
|
}
|
|
64
140
|
// Role combinations with identical permissions share one GraphQL schema. The key is memoized per combination,
|
|
65
141
|
// so a request does not rebuild the permissions only to find its schema.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"GraphQlSchemaFactory.js","sources":["../../../../../packages/engine-http/src/content/GraphQlSchemaFactory.ts"],"sourcesContent":["import {\n\tAuthorizator,\n\tContext,\n\tContextualPermissions,\n\tEntityRulesResolver,\n\tGraphQlSchemaBuilderFactory,\n\tIntrospectionSchemaDefinitionFactory,\n\tIntrospectionSchemaFactory,\n\tPermissionFactory,\n} from '@contember/engine-content-api'\nimport { Acl, Schema } from '@contember/schema'\nimport { GraphQLFieldConfig, GraphQLNamedType, GraphQLSchema } from 'graphql'\nimport { createHash } from 'node:crypto'\nimport { GraphQLSchemaContributor } from './GraphQLSchemaContributor.js'\nimport { Identity } from './Identity.js'\nimport { ContentApiSpecificCache } from './ContentApiSpecificCache.js'\nimport { ProjectConfig } from '../project/config.js'\n\nexport interface GraphQLSchemaFactoryResult {\n\tpermissions: Acl.Permissions\n\tallPermissions?: Acl.Permissions\n\tschema: GraphQLSchema\n}\n\nexport class GraphQlSchemaFactory {\n\tprivate readonly permissionsKeys = new WeakMap<Schema, Map<string, string>>()\n\n\tconstructor(\n\t\tprivate readonly cache: ContentApiSpecificCache<Schema, GraphQLSchemaFactoryResult>,\n\t\tprivate readonly graphqlSchemaBuilderFactory: GraphQlSchemaBuilderFactory,\n\t\tprivate readonly permissionFactory: PermissionFactory,\n\t\tprivate readonly schemaContributors: GraphQLSchemaContributor[],\n\t) {}\n\n\tpublic create(schema: Schema, identity: Identity, project: ProjectConfig): GraphQLSchemaFactoryResult {\n\t\tconst { permissionsKey, computedPermissions } = this.getPermissionsKey(schema, identity.projectRoles)\n\t\tconst contributorsKey = this.schemaContributors.map(it => it.getCacheKey?.({ schema, identity, project }) ?? '').join('\\xff')\n\t\tconst cacheKey = `${permissionsKey}\\xff\\xff${contributorsKey}`\n\n\t\treturn this.cache.fetch(schema, cacheKey, () => {\n\t\t\tconst { root: permissions, all: allPermissions } = computedPermissions ?? this.permissionFactory.createContextual(schema, identity.projectRoles)\n\n\t\t\tconst customPrimary = schema.acl.customPrimary ?? false\n\t\t\tconst refreshMaterializedView = this.permissionFactory.isRefreshMaterializedViewAllowed(schema, identity.projectRoles)\n\t\t\t// Types are shaped by the nested set, so a field granted only through a relation still exists\n\t\t\t// on the shared type; the root query and mutation fields are gated on the root set alone.\n\t\t\tconst authorizator = new Authorizator(allPermissions, customPrimary, refreshMaterializedView)\n\t\t\tconst rootAuthorizator = new Authorizator(permissions, customPrimary, refreshMaterializedView)\n\t\t\tconst dataSchemaBuilder = this.graphqlSchemaBuilderFactory.create(schema.model, authorizator, rootAuthorizator)\n\t\t\tconst introspectionSchemaFactory = new IntrospectionSchemaDefinitionFactory(\n\t\t\t\tnew IntrospectionSchemaFactory(\n\t\t\t\t\tschema.model,\n\t\t\t\t\tnew EntityRulesResolver(schema.validation, schema.model),\n\t\t\t\t\tauthorizator,\n\t\t\t\t),\n\t\t\t)\n\t\t\tconst introspectionSchema = introspectionSchemaFactory.createConfig()\n\n\t\t\tconst otherSchemas = this.schemaContributors\n\t\t\t\t.map(it => it.createSchema({ schema, identity, project }))\n\t\t\t\t.filter(<T>(it: T | undefined): it is T => it !== undefined)\n\n\t\t\tconst queries = new Map<string, GraphQLFieldConfig<any, Context, any>>()\n\t\t\tconst mutations = new Map<string, GraphQLFieldConfig<any, Context, any>>()\n\t\t\tconst types: GraphQLNamedType[] = []\n\n\t\t\tfor (const schema of [introspectionSchema, ...otherSchemas]) {\n\t\t\t\tif (schema instanceof GraphQLSchema) {\n\t\t\t\t\tfor (const [field, config] of Object.entries(schema.getQueryType()?.toConfig().fields ?? {})) {\n\t\t\t\t\t\tqueries.set(field, config)\n\t\t\t\t\t}\n\t\t\t\t\tfor (const [field, config] of Object.entries(schema.getQueryType()?.toConfig().fields ?? {})) {\n\t\t\t\t\t\tmutations.set(field, config)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfor (const [field, config] of Object.entries(schema.query?.toConfig().fields ?? {})) {\n\t\t\t\t\t\tqueries.set(field, config)\n\t\t\t\t\t}\n\t\t\t\t\tfor (const [field, config] of Object.entries(schema.mutation?.toConfig().fields ?? {})) {\n\t\t\t\t\t\tmutations.set(field, config)\n\t\t\t\t\t}\n\t\t\t\t\ttypes.push(...(schema.types ?? []))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst graphQlSchema = dataSchemaBuilder.build({\n\t\t\t\tmutations,\n\t\t\t\tqueries,\n\t\t\t\ttypes,\n\t\t\t})\n\n\t\t\treturn { schema: graphQlSchema, permissions, allPermissions }\n\t\t})\n\t}\n\n\t// Role combinations with identical permissions share one GraphQL schema. The key is memoized per combination,\n\t// so a request does not rebuild the permissions only to find its schema.\n\tprivate getPermissionsKey(\n\t\tschema: Schema,\n\t\troles: readonly string[],\n\t): { permissionsKey: string; computedPermissions?: ContextualPermissions } {\n\t\tlet keysByRoles = this.permissionsKeys.get(schema)\n\t\tif (!keysByRoles) {\n\t\t\tkeysByRoles = new Map()\n\t\t\tthis.permissionsKeys.set(schema, keysByRoles)\n\t\t}\n\t\tconst rolesKey = [...roles].sort().join('\\xff')\n\t\tconst cachedKey = keysByRoles.get(rolesKey)\n\t\tif (cachedKey !== undefined) {\n\t\t\treturn { permissionsKey: cachedKey }\n\t\t}\n\t\tconst computedPermissions = this.permissionFactory.createContextual(schema, roles)\n\t\tconst refreshMaterializedView = this.permissionFactory.isRefreshMaterializedViewAllowed(schema, roles)\n\t\tconst permissionsKey = createHash('sha256')\n\t\t\t.update(JSON.stringify([computedPermissions.root, computedPermissions.all, refreshMaterializedView]))\n\t\t\t.digest('hex')\n\t\tkeysByRoles.set(rolesKey, permissionsKey)\n\t\treturn { permissionsKey, computedPermissions }\n\t}\n}\n"],"names":["schema"],"mappings":";;;;;;AAwBO,MAAM,qBAAqB;AAAA,EAGjC,YACkB,OACA,6BACA,mBACA,oBAChB;AAJgB,SAAA,QAAA;AACA,SAAA,8BAAA;AACA,SAAA,oBAAA;AACA,SAAA,qBAAA;AANlB,kBAAA,MAAiB,uCAAsB,QAAA,CAAqC;AAAA,EAOzE;AAAA,EAEI,OAAO,QAAgB,UAAoB,SAAoD;AACrG,UAAM,EAAE,gBAAgB,wBAAwB,KAAK,kBAAkB,QAAQ,SAAS,YAAY;AACpG,UAAM,kBAAkB,KAAK,mBAAmB,IAAI,CAAA,OAAM,GAAG,cAAc,EAAE,QAAQ,UAAU,SAAS,KAAK,EAAE,EAAE,KAAK,GAAM;AAC5H,UAAM,WAAW,GAAG,cAAc,KAAW,eAAe;AAE5D,WAAO,KAAK,MAAM,MAAM,QAAQ,UAAU,MAAM;AAC/C,YAAM,EAAE,MAAM,aAAa,KAAK,eAAA,IAAmB,uBAAuB,KAAK,kBAAkB,iBAAiB,QAAQ,SAAS,YAAY;AAE/I,YAAM,gBAAgB,OAAO,IAAI,iBAAiB;AAClD,YAAM,0BAA0B,KAAK,kBAAkB,iCAAiC,QAAQ,SAAS,YAAY;AAGrH,YAAM,e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AAAA,UAC5B;AACA,gBAAM,KAAK,GAAIA,QAAO,SAAS,CAAA,CAAG;AAAA,QACnC;AAAA,MACD;AAEA,YAAM,gBAAgB,kBAAkB,MAAM;AAAA,QAC7C;AAAA,QACA;AAAA,QACA;AAAA,MAAA,CACA;AAED,aAAO,EAAE,QAAQ,eAAe,aAAa,eAAA;AAAA,IAC9C,CAAC;AAAA,EACF;AAAA;AAAA;AAAA,EAIQ,kBACP,QACA,OAC0E;AAC1E,QAAI,cAAc,KAAK,gBAAgB,IAAI,MAAM;AACjD,QAAI,CAAC,aAAa;AACjB,wCAAkB,IAAA;AAClB,WAAK,gBAAgB,IAAI,QAAQ,WAAW;AAAA,IAC7C;AACA,UAAM,WAAW,CAAC,GAAG,KAAK,EAAE,KAAA,EAAO,KAAK,GAAM;AAC9C,UAAM,YAAY,YAAY,IAAI,QAAQ;AAC1C,QAAI,cAAc,QAAW;AAC5B,aAAO,EAAE,gBAAgB,UAAA;AAAA,IAC1B;AACA,UAAM,sBAAsB,KAAK,kBAAkB,iBAAiB,QAAQ,KAAK;AACjF,UAAM,0BAA0B,KAAK,kBAAkB,iCAAiC,QAAQ,KAAK;AACrG,UAAM,iBAAiB,WAAW,QAAQ,EACxC,OAAO,KAAK,UAAU,CAAC,oBAAoB,MAAM,oBAAoB,KAAK,uBAAuB,CAAC,CAAC,EACnG,OAAO,KAAK;AACd,gBAAY,IAAI,UAAU,cAAc;AACxC,WAAO,EAAE,gBAAgB,oBAAA;AAAA,EAC1B;AACD;"}
|
|
1
|
+
{"version":3,"file":"GraphQlSchemaFactory.js","sources":["../../../../../packages/engine-http/src/content/GraphQlSchemaFactory.ts"],"sourcesContent":["import {\n\tAuthorizator,\n\tContext,\n\tContextualPermissions,\n\tcreateGraphQLJsBridge,\n\tcreateJsonIntrospectionExtension,\n\tEntityRulesResolver,\n\tGraphQlSchemaBuilderFactory,\n\tIntrospectionSchemaDefinitionFactory,\n\tIntrospectionSchemaFactory,\n\tJsonContentSchema,\n\tJsonContentSchemaBuilder,\n\tJsonContentSchemaShared,\n\tPermissionFactory,\n} from '@contember/engine-content-api'\nimport { Acl, Schema } from '@contember/schema'\nimport { GraphQLFieldConfig, GraphQLNamedType, GraphQLSchema } from 'graphql'\nimport { createHash } from 'node:crypto'\nimport { ContentGraphQLEngineResolver, ContentGraphQLSchema } from './ContentGraphQLEngine.js'\nimport { GraphQLSchemaContributor } from './GraphQLSchemaContributor.js'\nimport { Identity } from './Identity.js'\nimport { ContentApiSpecificCache } from './ContentApiSpecificCache.js'\nimport { ProjectConfig } from '../project/config.js'\n\nexport interface GraphQLSchemaFactoryResult {\n\tpermissions: Acl.Permissions\n\tallPermissions?: Acl.Permissions\n\tschema: ContentGraphQLSchema\n}\n\n/**\n * Schemas of one model built against one shared state. Its interner keeps everything it interned, also the data of\n * schemas the cache has evicted, so the state is replaced once evictions dominate and freed when none is in use.\n */\ninterface SharedGeneration {\n\treadonly shared: JsonContentSchemaShared\n\treadonly built: WeakRef<JsonContentSchema>[]\n}\n\n// A new generation interns the role-independent part again, which costs about as much as the unique data of ~10 roles.\nconst MIN_EVICTED_FOR_NEW_GENERATION = 16\n\n// A large model with permissive roles takes seconds to build; other requests of the process wait at most one slice.\nconst BUILD_SLICE_MS = 10\n\n/** Between slices, `setImmediate` lets the event loop run I/O; a microtask (`process.nextTick`, a promise) would not. */\nconst runInSlices = async <T>(steps: Generator<void, T>): Promise<T> => {\n\tlet sliceEnd = performance.now() + BUILD_SLICE_MS\n\tfor (;;) {\n\t\tconst step = steps.next()\n\t\tif (step.done) {\n\t\t\treturn step.value\n\t\t}\n\t\tif (performance.now() >= sliceEnd) {\n\t\t\tawait new Promise<void>(resolve => setImmediate(resolve))\n\t\t\tsliceEnd = performance.now() + BUILD_SLICE_MS\n\t\t}\n\t}\n}\n\nexport class GraphQlSchemaFactory {\n\tprivate readonly permissionsKeys = new WeakMap<Schema, Map<string, string>>()\n\t/** Weak, so that only the cached schemas keep their generation alive (via `generationOf`). */\n\tprivate readonly generations = new WeakMap<Schema, WeakRef<SharedGeneration>>()\n\tprivate readonly generationOf = new WeakMap<JsonContentSchema, SharedGeneration>()\n\t/** Builds in progress, so that concurrent requests of one role combination build it once. */\n\tprivate readonly building = new WeakMap<Schema, Map<string, Promise<GraphQLSchemaFactoryResult>>>()\n\n\tconstructor(\n\t\tprivate readonly cache: ContentApiSpecificCache<Schema, GraphQLSchemaFactoryResult>,\n\t\tprivate readonly graphqlSchemaBuilderFactory: GraphQlSchemaBuilderFactory,\n\t\tprivate readonly permissionFactory: PermissionFactory,\n\t\tprivate readonly schemaContributors: GraphQLSchemaContributor[],\n\t\tprivate readonly engineResolver: ContentGraphQLEngineResolver = new ContentGraphQLEngineResolver(),\n\t) {}\n\n\tpublic async create(schema: Schema, identity: Identity, project: ProjectConfig): Promise<GraphQLSchemaFactoryResult> {\n\t\tconst { permissionsKey, computedPermissions } = this.getPermissionsKey(schema, identity.projectRoles)\n\t\tconst contributorsKey = this.schemaContributors.map(it => it.getCacheKey?.({ schema, identity, project }) ?? '').join('\\xff')\n\t\tconst engine = this.engineResolver.resolve(project.slug)\n\t\tconst cacheKey = `${engine}\\xff\\xff${permissionsKey}\\xff\\xff${contributorsKey}`\n\n\t\tconst cached = this.cache.get(schema, cacheKey)\n\t\tif (cached) {\n\t\t\treturn cached\n\t\t}\n\t\tlet building = this.building.get(schema)\n\t\tif (!building) {\n\t\t\tbuilding = new Map()\n\t\t\tthis.building.set(schema, building)\n\t\t}\n\t\tconst inProgress = building.get(cacheKey)\n\t\tif (inProgress) {\n\t\t\treturn await inProgress\n\t\t}\n\t\tconst build = engine === 'graphql-js'\n\t\t\t? Promise.resolve(this.buildGraphQLJs(schema, identity, project, computedPermissions))\n\t\t\t: this.buildGraphQLJson(schema, identity, project, computedPermissions)\n\t\tbuilding.set(cacheKey, build)\n\t\ttry {\n\t\t\treturn this.cache.set(schema, cacheKey, await build)\n\t\t} finally {\n\t\t\tbuilding.delete(cacheKey)\n\t\t}\n\t}\n\n\t/** The graphql-js schema, built as before graphql-json existed. */\n\tprivate buildGraphQLJs(\n\t\tschema: Schema,\n\t\tidentity: Identity,\n\t\tproject: ProjectConfig,\n\t\tcomputedPermissions: ContextualPermissions | undefined,\n\t): GraphQLSchemaFactoryResult {\n\t\tconst { root: permissions, all: allPermissions } = computedPermissions ?? this.permissionFactory.createContextual(schema, identity.projectRoles)\n\n\t\tconst customPrimary = schema.acl.customPrimary ?? false\n\t\tconst refreshMaterializedView = this.permissionFactory.isRefreshMaterializedViewAllowed(schema, identity.projectRoles)\n\t\t// Types are shaped by the nested set, so a field granted only through a relation still exists\n\t\t// on the shared type; the root query and mutation fields are gated on the root set alone.\n\t\tconst authorizator = new Authorizator(allPermissions, customPrimary, refreshMaterializedView)\n\t\tconst rootAuthorizator = new Authorizator(permissions, customPrimary, refreshMaterializedView)\n\t\tconst dataSchemaBuilder = this.graphqlSchemaBuilderFactory.create(schema.model, authorizator, rootAuthorizator)\n\t\tconst introspectionSchemaFactory = new IntrospectionSchemaDefinitionFactory(\n\t\t\tnew IntrospectionSchemaFactory(\n\t\t\t\tschema.model,\n\t\t\t\tnew EntityRulesResolver(schema.validation, schema.model),\n\t\t\t\tauthorizator,\n\t\t\t),\n\t\t)\n\t\tconst introspectionSchema = introspectionSchemaFactory.createConfig()\n\n\t\tconst otherSchemas = this.schemaContributors\n\t\t\t.map(it => it.createSchema({ schema, identity, project }))\n\t\t\t.filter(<T>(it: T | undefined): it is T => it !== undefined)\n\n\t\tconst queries = new Map<string, GraphQLFieldConfig<any, Context, any>>()\n\t\tconst mutations = new Map<string, GraphQLFieldConfig<any, Context, any>>()\n\t\tconst types: GraphQLNamedType[] = []\n\n\t\tfor (const schema of [introspectionSchema, ...otherSchemas]) {\n\t\t\tif (schema instanceof GraphQLSchema) {\n\t\t\t\tfor (const [field, config] of Object.entries(schema.getQueryType()?.toConfig().fields ?? {})) {\n\t\t\t\t\tqueries.set(field, config)\n\t\t\t\t}\n\t\t\t\tfor (const [field, config] of Object.entries(schema.getQueryType()?.toConfig().fields ?? {})) {\n\t\t\t\t\tmutations.set(field, config)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (const [field, config] of Object.entries(schema.query?.toConfig().fields ?? {})) {\n\t\t\t\t\tqueries.set(field, config)\n\t\t\t\t}\n\t\t\t\tfor (const [field, config] of Object.entries(schema.mutation?.toConfig().fields ?? {})) {\n\t\t\t\t\tmutations.set(field, config)\n\t\t\t\t}\n\t\t\t\ttypes.push(...(schema.types ?? []))\n\t\t\t}\n\t\t}\n\n\t\tconst graphQlSchema = dataSchemaBuilder.build({\n\t\t\tmutations,\n\t\t\tqueries,\n\t\t\ttypes,\n\t\t})\n\n\t\treturn { schema: { engine: 'graphql-js', schema: graphQlSchema }, permissions, allPermissions }\n\t}\n\n\tprivate async buildGraphQLJson(\n\t\tschema: Schema,\n\t\tidentity: Identity,\n\t\tproject: ProjectConfig,\n\t\tcomputedPermissions: ContextualPermissions | undefined,\n\t): Promise<GraphQLSchemaFactoryResult> {\n\t\tconst { root: permissions, all: allPermissions } = computedPermissions ?? this.permissionFactory.createContextual(schema, identity.projectRoles)\n\n\t\tconst customPrimary = schema.acl.customPrimary ?? false\n\t\tconst refreshMaterializedView = this.permissionFactory.isRefreshMaterializedViewAllowed(schema, identity.projectRoles)\n\t\t// Types are shaped by the nested set, so a field granted only through a relation still exists\n\t\t// on the shared type; the root query and mutation fields are gated on the root set alone.\n\t\tconst authorizator = new Authorizator(allPermissions, customPrimary, refreshMaterializedView)\n\t\tconst rootAuthorizator = new Authorizator(permissions, customPrimary, refreshMaterializedView)\n\t\tconst introspectionSchemaFactory = new IntrospectionSchemaFactory(\n\t\t\tschema.model,\n\t\t\tnew EntityRulesResolver(schema.validation, schema.model),\n\t\t\tauthorizator,\n\t\t)\n\t\tconst otherSchemas = this.schemaContributors\n\t\t\t.map(it => it.createSchema({ schema, identity, project }))\n\t\t\t.filter(<T>(it: T | undefined): it is T => it !== undefined)\n\n\t\tconst generation = this.getGeneration(schema)\n\t\tconst builder = new JsonContentSchemaBuilder(schema.model, authorizator, rootAuthorizator, generation.shared)\n\t\tconst jsonSchema = await runInSlices(builder.buildSteps([\n\t\t\tcreateJsonIntrospectionExtension(introspectionSchemaFactory),\n\t\t\t...otherSchemas.map(createGraphQLJsBridge),\n\t\t]))\n\t\tgeneration.built.push(new WeakRef(jsonSchema))\n\t\tthis.generationOf.set(jsonSchema, generation)\n\t\treturn { schema: { engine: 'graphql-json', schema: jsonSchema }, permissions, allPermissions }\n\t}\n\n\tprivate getGeneration(schema: Schema): SharedGeneration {\n\t\tconst current = this.generations.get(schema)?.deref()\n\t\tif (current) {\n\t\t\tconst evicted = current.built.filter(it => it.deref() === undefined).length\n\t\t\tif (evicted < MIN_EVICTED_FOR_NEW_GENERATION || evicted < current.built.length - evicted) {\n\t\t\t\treturn current\n\t\t\t}\n\t\t}\n\t\tconst generation: SharedGeneration = { shared: new JsonContentSchemaShared(), built: [] }\n\t\tthis.generations.set(schema, new WeakRef(generation))\n\t\treturn generation\n\t}\n\n\t// Role combinations with identical permissions share one GraphQL schema. The key is memoized per combination,\n\t// so a request does not rebuild the permissions only to find its schema.\n\tprivate getPermissionsKey(\n\t\tschema: Schema,\n\t\troles: readonly string[],\n\t): { permissionsKey: string; computedPermissions?: ContextualPermissions } {\n\t\tlet keysByRoles = this.permissionsKeys.get(schema)\n\t\tif (!keysByRoles) {\n\t\t\tkeysByRoles = new Map()\n\t\t\tthis.permissionsKeys.set(schema, keysByRoles)\n\t\t}\n\t\tconst rolesKey = [...roles].sort().join('\\xff')\n\t\tconst cachedKey = keysByRoles.get(rolesKey)\n\t\tif (cachedKey !== undefined) {\n\t\t\treturn { permissionsKey: cachedKey }\n\t\t}\n\t\tconst computedPermissions = this.permissionFactory.createContextual(schema, roles)\n\t\tconst refreshMaterializedView = this.permissionFactory.isRefreshMaterializedViewAllowed(schema, roles)\n\t\tconst permissionsKey = createHash('sha256')\n\t\t\t.update(JSON.stringify([computedPermissions.root, computedPermissions.all, refreshMaterializedView]))\n\t\t\t.digest('hex')\n\t\tkeysByRoles.set(rolesKey, permissionsKey)\n\t\treturn { permissionsKey, computedPermissions }\n\t}\n}\n"],"names":["schema"],"mappings":";;;;;;;AAwCA,MAAM,iCAAiC;AAGvC,MAAM,iBAAiB;AAGvB,MAAM,cAAc,OAAU,UAA0C;AACvE,MAAI,WAAW,YAAY,IAAA,IAAQ;AACnC,aAAS;AACR,UAAM,OAAO,MAAM,KAAA;AACnB,QAAI,KAAK,MAAM;AACd,aAAO,KAAK;AAAA,IACb;AACA,QAAI,YAAY,IAAA,KAAS,UAAU;AAClC,YAAM,IAAI,QAAc,CAAA,YAAW,aAAa,OAAO,CAAC;AACxD,iBAAW,YAAY,QAAQ;AAAA,IAChC;AAAA,EACD;AACD;AAEO,MAAM,qBAAqB;AAAA,EAQjC,YACkB,OACA,6BACA,mBACA,oBACA,iBAA+C,IAAI,gCACnE;AALgB,SAAA,QAAA;AACA,SAAA,8BAAA;AACA,SAAA,oBAAA;AACA,SAAA,qBAAA;AACA,SAAA,iBAAA;AAZlB,kBAAA,MAAiB,uCAAsB,QAAA,CAAqC;AAE5E,kBAAA,MAAiB,mCAAkB,QAAA,CAA2C;AAC9E,kBAAA,MAAiB,oCAAmB,QAAA,CAA6C;AAEjF,kBAAA,MAAiB,gCAAe,QAAA,CAAkE;AAAA,EAQ/F;AAAA,EAEH,MAAa,OAAO,QAAgB,UAAoB,SAA6D;AACpH,UAAM,EAAE,gBAAgB,wBAAwB,KAAK,kBAAkB,QAAQ,SAAS,YAAY;AACpG,UAAM,kBAAkB,KAAK,mBAAmB,IAAI,CAAA,OAAM,GAAG,cAAc,EAAE,QAAQ,UAAU,SAAS,KAAK,EAAE,EAAE,KAAK,GAAM;AAC5H,UAAM,SAAS,KAAK,eAAe,QAAQ,QAAQ,IAAI;AACvD,UAAM,WAAW,GAAG,MAAM,KAAW,cAAc,KAAW,eAAe;AAE7E,UAAM,SAAS,KAAK,MAAM,IAAI,QAAQ,Q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,IAAI,QAAQ,IAAI,QAAQ,UAAU,CAAC;AACpD,WAAO;AAAA,EACR;AAAA;AAAA;AAAA,EAIQ,kBACP,QACA,OAC0E;AAC1E,QAAI,cAAc,KAAK,gBAAgB,IAAI,MAAM;AACjD,QAAI,CAAC,aAAa;AACjB,wCAAkB,IAAA;AAClB,WAAK,gBAAgB,IAAI,QAAQ,WAAW;AAAA,IAC7C;AACA,UAAM,WAAW,CAAC,GAAG,KAAK,EAAE,KAAA,EAAO,KAAK,GAAM;AAC9C,UAAM,YAAY,YAAY,IAAI,QAAQ;AAC1C,QAAI,cAAc,QAAW;AAC5B,aAAO,EAAE,gBAAgB,UAAA;AAAA,IAC1B;AACA,UAAM,sBAAsB,KAAK,kBAAkB,iBAAiB,QAAQ,KAAK;AACjF,UAAM,0BAA0B,KAAK,kBAAkB,iCAAiC,QAAQ,KAAK;AACrG,UAAM,iBAAiB,WAAW,QAAQ,EACxC,OAAO,KAAK,UAAU,CAAC,oBAAoB,MAAM,oBAAoB,KAAK,uBAAuB,CAAC,CAAC,EACnG,OAAO,KAAK;AACd,gBAAY,IAAI,UAAU,cAAc;AACxC,WAAO,EAAE,gBAAgB,oBAAA;AAAA,EAC1B;AACD;"}
|
|
@@ -7,6 +7,18 @@ const logger = require("@contember/logger");
|
|
|
7
7
|
const graphqlUtils = require("@contember/graphql-utils");
|
|
8
8
|
const engineContentApi = require("@contember/engine-content-api");
|
|
9
9
|
const Database = require("@contember/database");
|
|
10
|
+
const graphqlJson = require("@contember/graphql-json");
|
|
11
|
+
const createGraphQLJsExecutor = (schema) => ({
|
|
12
|
+
validateSchema: () => graphql.validateSchema(schema),
|
|
13
|
+
validate: (document) => graphql.validate(schema, document),
|
|
14
|
+
execute: async (args) => await graphql.execute({ schema, ...args })
|
|
15
|
+
});
|
|
16
|
+
const createGraphQLJsonExecutor = ({ schema, resolvers, scalars }) => ({
|
|
17
|
+
// the content builder output is validated as a graphql-js schema in tests; there is no runtime schema validation
|
|
18
|
+
validateSchema: () => [],
|
|
19
|
+
validate: (document) => graphqlJson.validate(schema, document, { scalars }),
|
|
20
|
+
execute: async ({ document, operationName, variableValues, contextValue }) => await graphqlJson.execute({ schema, document, resolvers, scalars, operationName: operationName ?? void 0, variableValues, contextValue })
|
|
21
|
+
});
|
|
10
22
|
const memoryBudgetErrorCode = "RESOURCE_EXHAUSTED";
|
|
11
23
|
const hitCacheMaxAgeSeconds = 10 * 60;
|
|
12
24
|
const documentCacheMaxAgeSeconds = hitCacheMaxAgeSeconds * 10;
|
|
@@ -14,7 +26,7 @@ const pruneIntervalSeconds = documentCacheMaxAgeSeconds / 2;
|
|
|
14
26
|
const documentCacheMax = 100;
|
|
15
27
|
const hitCacheMax = documentCacheMax * 2;
|
|
16
28
|
const createGraphQLQueryHandler = ({
|
|
17
|
-
|
|
29
|
+
executor,
|
|
18
30
|
listeners,
|
|
19
31
|
getMemoryBudget
|
|
20
32
|
}) => {
|
|
@@ -42,7 +54,7 @@ const createGraphQLQueryHandler = ({
|
|
|
42
54
|
};
|
|
43
55
|
try {
|
|
44
56
|
if (!schemaValidated) {
|
|
45
|
-
const validationResult =
|
|
57
|
+
const validationResult = executor.validateSchema();
|
|
46
58
|
if (validationResult.length) {
|
|
47
59
|
return respond(400, {
|
|
48
60
|
errors: validationResult
|
|
@@ -60,7 +72,7 @@ const createGraphQLQueryHandler = ({
|
|
|
60
72
|
let doc = documentCache.get(queryHash);
|
|
61
73
|
if (!doc) {
|
|
62
74
|
doc = graphql.parse(resolvedRequest.query);
|
|
63
|
-
const validationResult =
|
|
75
|
+
const validationResult = executor.validate(doc);
|
|
64
76
|
if (validationResult.length) {
|
|
65
77
|
return respond(400, { errors: validationResult });
|
|
66
78
|
}
|
|
@@ -76,8 +88,7 @@ const createGraphQLQueryHandler = ({
|
|
|
76
88
|
listenersQueue.forEach((it) => {
|
|
77
89
|
it.onExecute && listenersQueue.push(it.onExecute({ context, document, operation }) || {});
|
|
78
90
|
});
|
|
79
|
-
const executionResult = await
|
|
80
|
-
schema,
|
|
91
|
+
const executionResult = await executor.execute({
|
|
81
92
|
document,
|
|
82
93
|
operationName,
|
|
83
94
|
variableValues: resolvedRequest.variables,
|
|
@@ -156,6 +167,8 @@ const resolveOperationType = (document, operationName) => {
|
|
|
156
167
|
}
|
|
157
168
|
throw new graphql.GraphQLError("Must provide an operation.");
|
|
158
169
|
};
|
|
170
|
+
exports.createGraphQLJsExecutor = createGraphQLJsExecutor;
|
|
171
|
+
exports.createGraphQLJsonExecutor = createGraphQLJsonExecutor;
|
|
159
172
|
exports.createGraphQLQueryHandler = createGraphQLQueryHandler;
|
|
160
173
|
exports.extractOriginalError = extractOriginalError;
|
|
161
174
|
//# sourceMappingURL=execution.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execution.cjs","sources":["../../../../../packages/engine-http/src/graphql/execution.ts"],"sourcesContent":["import {\n\tDocumentNode,\n\texecute,\n\tGraphQLError,\n\tGraphQLSchema,\n\tKind,\n\tOperationDefinitionNode,\n\tOperationTypeNode,\n\tparse,\n\tvalidate,\n\tvalidateSchema,\n} from 'graphql'\nimport { LRUCache } from '@contember/utilities'\nimport { createHash } from 'node:crypto'\nimport { Request, Response } from 'koa'\nimport { logger } from '@contember/logger'\nimport { ForbiddenError } from '@contember/graphql-utils'\nimport { UserError } from '@contember/engine-content-api'\nimport { RequestMemoryBudget, RequestMemoryBudgetExceededError } from '@contember/database'\n\nexport interface GraphQLListener<Context> {\n\tonStart?: (ctx: {}) => Omit<GraphQLListener<Context>, 'onStart'> | void\n\tonExecute?: (ctx: {\n\t\tcontext: Context\n\t\tdocument: DocumentNode\n\t\toperation: OperationTypeNode\n\t}) => Omit<GraphQLListener<Context>, 'onStart' | 'onExecute'> | void\n\tonResponse?: (ctx: {\n\t\tresponse: any\n\t\tcontext: Context\n\t}) => Omit<GraphQLListener<Context>, 'onStart' | 'onExecute' | 'onResponse'> | void\n\tonShutdown?: (ctx: {\n\t\tresponse: any\n\t}) => Omit<GraphQLListener<Context>, 'onStart' | 'onExecute' | 'onResponse' | 'onShutdown'> | void\n}\n\ninterface FactoryArgs<Context> {\n\tschema: GraphQLSchema\n\tlisteners: GraphQLListener<Context>[]\n\tgetMemoryBudget?: (context: Context) => RequestMemoryBudget | undefined\n}\n\nexport type GraphQLQueryHandler<Context> = (\n\targs: { request: Request; response: Response; createContext: ({}: { operation: OperationTypeNode; queryHash: string }) => Context },\n) => any\n\nconst memoryBudgetErrorCode = 'RESOURCE_EXHAUSTED'\n\nconst hitCacheMaxAgeSeconds = 10 * 60\nconst documentCacheMaxAgeSeconds = hitCacheMaxAgeSeconds * 10\nconst pruneIntervalSeconds = documentCacheMaxAgeSeconds / 2\nconst documentCacheMax = 100\nconst hitCacheMax = documentCacheMax * 2\n\nexport const createGraphQLQueryHandler = <Context>({\n\tschema,\n\tlisteners,\n\tgetMemoryBudget,\n}: FactoryArgs<Context>): GraphQLQueryHandler<Context> => {\n\tlet schemaValidated = false\n\tconst hitCache = new LRUCache<string, true>(hitCacheMax, { ttl: hitCacheMaxAgeSeconds * 1000 })\n\tconst documentCache = new LRUCache<string, DocumentNode>(documentCacheMax, { ttl: documentCacheMaxAgeSeconds * 1000 })\n\tlet lastPrune = Date.now()\n\n\treturn async ({ request, response, createContext }) => {\n\t\tconst now = Date.now()\n\t\tif ((now - lastPrune) > pruneIntervalSeconds * 1000) {\n\t\t\tdocumentCache.purgeStale()\n\t\t\tlastPrune = now\n\t\t}\n\t\tconst listenersQueue = [...listeners]\n\n\t\tlistenersQueue.forEach(it => {\n\t\t\tit.onStart && listenersQueue.push(it.onStart({}) || {})\n\t\t})\n\n\t\tconst respond = (code: number, data: any) => {\n\t\t\tresponse.status = code\n\t\t\tresponse.body = JSON.stringify(data)\n\t\t\tresponse.set('Content-type', 'application/json')\n\n\t\t\tlistenersQueue.forEach(it => {\n\t\t\t\tit.onShutdown && listenersQueue.push(it.onShutdown({ response: data }) || {})\n\t\t\t})\n\t\t}\n\t\ttry {\n\t\t\tif (!schemaValidated) {\n\t\t\t\tconst validationResult = validateSchema(schema)\n\t\t\t\tif (validationResult.length) {\n\t\t\t\t\treturn respond(400, {\n\t\t\t\t\t\terrors: validationResult,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tschemaValidated = true\n\t\t\t}\n\t\t\tconst resolvedRequest = request.method === 'POST' ? (request.body as any) : request.query\n\t\t\tif (!resolvedRequest.query) {\n\t\t\t\treturn respond(400, {\n\t\t\t\t\terrors: [{ message: 'Missing request query' }],\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst queryHash = createHash('md5').update(resolvedRequest.query).digest('hex')\n\t\t\tlet doc = documentCache.get(queryHash)\n\t\t\tif (!doc) {\n\t\t\t\tdoc = parse(resolvedRequest.query)\n\t\t\t\tconst validationResult = validate(schema, doc)\n\t\t\t\tif (validationResult.length) {\n\t\t\t\t\treturn respond(400, { errors: validationResult })\n\t\t\t\t}\n\t\t\t\tif (hitCache.get(queryHash)) {\n\t\t\t\t\tdocumentCache.set(queryHash, doc)\n\t\t\t\t}\n\t\t\t\thitCache.set(queryHash, true)\n\t\t\t}\n\t\t\tconst document = doc\n\t\t\tconst operationName = resolvedRequest.operationName ?? null\n\t\t\tconst operation = resolveOperationType(document, operationName)\n\n\t\t\tconst context = createContext({ operation, queryHash })\n\t\t\tlistenersQueue.forEach(it => {\n\t\t\t\tit.onExecute && listenersQueue.push(it.onExecute({ context, document, operation }) || {})\n\t\t\t})\n\t\t\tconst executionResult = await execute({\n\t\t\t\tschema,\n\t\t\t\tdocument,\n\t\t\t\toperationName: operationName,\n\t\t\t\tvariableValues: resolvedRequest.variables,\n\t\t\t\tcontextValue: context,\n\t\t\t})\n\t\t\t// GraphQL turns a budget failure inside a nullable resolver into partial data; reject the whole response instead.\n\t\t\t// A mutation reports it in its own result, because sibling mutations may already be committed.\n\t\t\tconst response = operation === 'query' && getMemoryBudget?.(context)?.exceeded\n\t\t\t\t? { data: null, errors: withMemoryBudgetError(executionResult.errors) }\n\t\t\t\t: executionResult\n\t\t\tlistenersQueue.forEach(it => {\n\t\t\t\tit.onResponse && listenersQueue.push(it.onResponse({ context, response }) || {})\n\t\t\t})\n\t\t\tif (response.errors && response.errors.length > 0) {\n\t\t\t\tconst [code, errors] = processErrors(response.errors)\n\t\t\t\trespond(code && !response.data ? code : 200, { ...response, errors })\n\t\t\t} else {\n\t\t\t\trespond(200, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof GraphQLError) {\n\t\t\t\treturn respond(e instanceof ForbiddenError ? 403 : 400, { errors: [e] })\n\t\t\t}\n\t\t\tlogger.error(e)\n\t\t\treturn respond(500, { errors: [{ message: 'Internal error' }] })\n\t\t}\n\t}\n}\n\nexport const extractOriginalError = (e: Error): Error => {\n\tif (e instanceof GraphQLError && e.originalError) {\n\t\treturn extractOriginalError(e.originalError)\n\t}\n\tif ('errors' in e && Array.isArray((e as any).errors) && (e as any).errors.length === 1) {\n\t\treturn extractOriginalError((e as any).errors[0])\n\t}\n\treturn e\n}\n\nconst withMemoryBudgetError = (errors: readonly GraphQLError[] = []): readonly GraphQLError[] => {\n\tif (errors.some(it => extractOriginalError(it) instanceof RequestMemoryBudgetExceededError)) {\n\t\treturn errors\n\t}\n\t// The resolver that hit the budget did not report it (its error was swallowed); the response still must not pass as valid.\n\tconst originalError = new RequestMemoryBudgetExceededError()\n\treturn [...errors, new GraphQLError(originalError.message, { originalError })]\n}\n\nconst processErrors = (errors: readonly any[]): [number | null, any[]] => {\n\tconst resultErrors = []\n\tlet has400 = false\n\tlet has403 = false\n\tlet has500 = false\n\tlet hasExhaustedMemoryBudget = false\n\tfor (const error of errors) {\n\t\tconst originalError = extractOriginalError(error)\n\t\tif (originalError instanceof GraphQLError) {\n\t\t\tresultErrors.push(error)\n\t\t\thas400 = true\n\t\t} else if (originalError instanceof ForbiddenError) {\n\t\t\tresultErrors.push(error)\n\t\t\thas403 = true\n\t\t} else if (originalError instanceof RequestMemoryBudgetExceededError) {\n\t\t\tresultErrors.push({ message: error.message, locations: error.locations, path: error.path, extensions: { code: memoryBudgetErrorCode } })\n\t\t\thasExhaustedMemoryBudget = true\n\t\t} else if (originalError instanceof UserError) {\n\t\t\tresultErrors.push({ message: error.message, locations: error.locations, path: error.path })\n\t\t\thas400 = true\n\t\t} else {\n\t\t\tlogger.error(originalError || error)\n\t\t\tresultErrors.push({ message: 'Internal server error', locations: undefined, path: undefined })\n\t\t\thas500 = true\n\t\t}\n\t}\n\treturn [has500 ? 500 : hasExhaustedMemoryBudget ? 422 : has400 ? 400 : has403 ? 403 : null, resultErrors]\n}\n\nconst resolveOperationType = (document: DocumentNode, operationName: string | null): OperationTypeNode => {\n\tfor (const definition of document.definitions) {\n\t\tif (definition.kind === Kind.OPERATION_DEFINITION) {\n\t\t\tif (operationName === null || definition.name?.value === operationName) {\n\t\t\t\treturn definition.operation\n\t\t\t}\n\t\t}\n\t}\n\tthrow new GraphQLError('Must provide an operation.')\n}\n"],"names":["LRUCache","validateSchema","createHash","parse","validate","execute","response","GraphQLError","ForbiddenError","logger","RequestMemoryBudgetExceededError","UserError","Kind"],"mappings":";;;;;;;;;AA8CA,MAAM,wBAAwB;AAE9B,MAAM,wBAAwB,KAAK;AACnC,MAAM,6BAA6B,wBAAwB;AAC3D,MAAM,uBAAuB,6BAA6B;AAC1D,MAAM,mBAAmB;AACzB,MAAM,cAAc,mBAAmB;AAEhC,MAAM,4BAA4B,CAAU;AAAA,EAClD;AAAA,EACA;AAAA,EACA;AACD,MAA0D;AACzD,MAAI,kBAAkB;AACtB,QAAM,WAAW,IAAIA,mBAAuB,aAAa,EAAE,KAAK,wBAAwB,KAAM;AAC9F,QAAM,gBAAgB,IAAIA,mBAA+B,kBAAkB,EAAE,KAAK,6BAA6B,KAAM;AACrH,MAAI,YAAY,KAAK,IAAA;AAErB,SAAO,OAAO,EAAE,SAAS,UAAU,oBAAoB;AACtD,UAAM,MAAM,KAAK,IAAA;AACjB,QAAK,MAAM,YAAa,uBAAuB,KAAM;AACpD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BAAO,MAAM,iBAAiB,KAAK;AACnC,mBAAa,KAAK,EAAE,SAAS,yBAAyB,WAAW,QAAW,MAAM,QAAW;AAC7F,eAAS;AAAA,IACV;AAAA,EACD;AACA,SAAO,CAAC,SAAS,MAAM,2BAA2B,MAAM,SAAS,MAAM,SAAS,MAAM,MAAM,YAAY;AACzG;AAEA,MAAM,uBAAuB,CAAC,UAAwB,kBAAoD;AACzG,aAAW,cAAc,SAAS,aAAa;AAC9C,QAAI,WAAW,SAASG,QAAAA,KAAK,sBAAsB;AAClD,UAAI,kBAAkB,QAAQ,WAAW,MAAM,UAAU,eAAe;AACvE,eAAO,WAAW;AAAA,MACnB;AAAA,IACD;AAAA,EACD;AACA,QAAM,IAAIL,QAAAA,aAAa,4BAA4B;AACpD;;;"}
|
|
1
|
+
{"version":3,"file":"execution.cjs","sources":["../../../../../packages/engine-http/src/graphql/execution.ts"],"sourcesContent":["import {\n\tDocumentNode,\n\texecute,\n\tExecutionResult,\n\tGraphQLError,\n\tGraphQLSchema,\n\tKind,\n\tOperationTypeNode,\n\tparse,\n\tvalidate,\n\tvalidateSchema,\n} from 'graphql'\nimport { LRUCache } from '@contember/utilities'\nimport { createHash } from 'node:crypto'\nimport { Request, Response } from 'koa'\nimport { logger } from '@contember/logger'\nimport { ForbiddenError } from '@contember/graphql-utils'\nimport { UserError } from '@contember/engine-content-api'\nimport { RequestMemoryBudget, RequestMemoryBudgetExceededError } from '@contember/database'\nimport { execute as executeJson, ResolverMap, ScalarMap, Schema as JsonSchema, validate as validateJson } from '@contember/graphql-json'\n\nexport interface GraphQLListener<Context> {\n\tonStart?: (ctx: {}) => Omit<GraphQLListener<Context>, 'onStart'> | void\n\tonExecute?: (ctx: {\n\t\tcontext: Context\n\t\tdocument: DocumentNode\n\t\toperation: OperationTypeNode\n\t}) => Omit<GraphQLListener<Context>, 'onStart' | 'onExecute'> | void\n\tonResponse?: (ctx: {\n\t\tresponse: any\n\t\tcontext: Context\n\t}) => Omit<GraphQLListener<Context>, 'onStart' | 'onExecute' | 'onResponse'> | void\n\tonShutdown?: (ctx: {\n\t\tresponse: any\n\t}) => Omit<GraphQLListener<Context>, 'onStart' | 'onExecute' | 'onResponse' | 'onShutdown'> | void\n}\n\n/** The GraphQL engine a handler runs on. */\nexport interface GraphQLExecutor<Context> {\n\tvalidateSchema(): readonly GraphQLError[]\n\tvalidate(document: DocumentNode): readonly GraphQLError[]\n\texecute(args: {\n\t\tdocument: DocumentNode\n\t\toperationName: string | null\n\t\tvariableValues: Record<string, unknown> | undefined\n\t\tcontextValue: Context\n\t}): Promise<Pick<ExecutionResult, 'data' | 'errors'>>\n}\n\nexport const createGraphQLJsExecutor = <Context>(schema: GraphQLSchema): GraphQLExecutor<Context> => ({\n\tvalidateSchema: () => validateSchema(schema),\n\tvalidate: document => validate(schema, document),\n\texecute: async args => await execute({ schema, ...args }),\n})\n\nexport const createGraphQLJsonExecutor = <Context>(\n\t{ schema, resolvers, scalars }: { schema: JsonSchema; resolvers: readonly ResolverMap<Context>[]; scalars: ScalarMap },\n): GraphQLExecutor<Context> => ({\n\t// the content builder output is validated as a graphql-js schema in tests; there is no runtime schema validation\n\tvalidateSchema: () => [],\n\tvalidate: document => validateJson(schema, document, { scalars }),\n\texecute: async ({ document, operationName, variableValues, contextValue }) =>\n\t\tawait executeJson({ schema, document, resolvers, scalars, operationName: operationName ?? undefined, variableValues, contextValue }),\n})\n\ninterface FactoryArgs<Context> {\n\texecutor: GraphQLExecutor<Context>\n\tlisteners: GraphQLListener<Context>[]\n\tgetMemoryBudget?: (context: Context) => RequestMemoryBudget | undefined\n}\n\nexport type GraphQLQueryHandler<Context> = (\n\targs: { request: Request; response: Response; createContext: ({}: { operation: OperationTypeNode; queryHash: string }) => Context },\n) => any\n\nconst memoryBudgetErrorCode = 'RESOURCE_EXHAUSTED'\n\nconst hitCacheMaxAgeSeconds = 10 * 60\nconst documentCacheMaxAgeSeconds = hitCacheMaxAgeSeconds * 10\nconst pruneIntervalSeconds = documentCacheMaxAgeSeconds / 2\nconst documentCacheMax = 100\nconst hitCacheMax = documentCacheMax * 2\n\nexport const createGraphQLQueryHandler = <Context>({\n\texecutor,\n\tlisteners,\n\tgetMemoryBudget,\n}: FactoryArgs<Context>): GraphQLQueryHandler<Context> => {\n\tlet schemaValidated = false\n\tconst hitCache = new LRUCache<string, true>(hitCacheMax, { ttl: hitCacheMaxAgeSeconds * 1000 })\n\tconst documentCache = new LRUCache<string, DocumentNode>(documentCacheMax, { ttl: documentCacheMaxAgeSeconds * 1000 })\n\tlet lastPrune = Date.now()\n\n\treturn async ({ request, response, createContext }) => {\n\t\tconst now = Date.now()\n\t\tif ((now - lastPrune) > pruneIntervalSeconds * 1000) {\n\t\t\tdocumentCache.purgeStale()\n\t\t\tlastPrune = now\n\t\t}\n\t\tconst listenersQueue = [...listeners]\n\n\t\tlistenersQueue.forEach(it => {\n\t\t\tit.onStart && listenersQueue.push(it.onStart({}) || {})\n\t\t})\n\n\t\tconst respond = (code: number, data: any) => {\n\t\t\tresponse.status = code\n\t\t\tresponse.body = JSON.stringify(data)\n\t\t\tresponse.set('Content-type', 'application/json')\n\n\t\t\tlistenersQueue.forEach(it => {\n\t\t\t\tit.onShutdown && listenersQueue.push(it.onShutdown({ response: data }) || {})\n\t\t\t})\n\t\t}\n\t\ttry {\n\t\t\tif (!schemaValidated) {\n\t\t\t\tconst validationResult = executor.validateSchema()\n\t\t\t\tif (validationResult.length) {\n\t\t\t\t\treturn respond(400, {\n\t\t\t\t\t\terrors: validationResult,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tschemaValidated = true\n\t\t\t}\n\t\t\tconst resolvedRequest = request.method === 'POST' ? (request.body as any) : request.query\n\t\t\tif (!resolvedRequest.query) {\n\t\t\t\treturn respond(400, {\n\t\t\t\t\terrors: [{ message: 'Missing request query' }],\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst queryHash = createHash('md5').update(resolvedRequest.query).digest('hex')\n\t\t\tlet doc = documentCache.get(queryHash)\n\t\t\tif (!doc) {\n\t\t\t\tdoc = parse(resolvedRequest.query)\n\t\t\t\tconst validationResult = executor.validate(doc)\n\t\t\t\tif (validationResult.length) {\n\t\t\t\t\treturn respond(400, { errors: validationResult })\n\t\t\t\t}\n\t\t\t\tif (hitCache.get(queryHash)) {\n\t\t\t\t\tdocumentCache.set(queryHash, doc)\n\t\t\t\t}\n\t\t\t\thitCache.set(queryHash, true)\n\t\t\t}\n\t\t\tconst document = doc\n\t\t\tconst operationName = resolvedRequest.operationName ?? null\n\t\t\tconst operation = resolveOperationType(document, operationName)\n\n\t\t\tconst context = createContext({ operation, queryHash })\n\t\t\tlistenersQueue.forEach(it => {\n\t\t\t\tit.onExecute && listenersQueue.push(it.onExecute({ context, document, operation }) || {})\n\t\t\t})\n\t\t\tconst executionResult = await executor.execute({\n\t\t\t\tdocument,\n\t\t\t\toperationName: operationName,\n\t\t\t\tvariableValues: resolvedRequest.variables,\n\t\t\t\tcontextValue: context,\n\t\t\t})\n\t\t\t// GraphQL turns a budget failure inside a nullable resolver into partial data; reject the whole response instead.\n\t\t\t// A mutation reports it in its own result, because sibling mutations may already be committed.\n\t\t\tconst response = operation === 'query' && getMemoryBudget?.(context)?.exceeded\n\t\t\t\t? { data: null, errors: withMemoryBudgetError(executionResult.errors) }\n\t\t\t\t: executionResult\n\t\t\tlistenersQueue.forEach(it => {\n\t\t\t\tit.onResponse && listenersQueue.push(it.onResponse({ context, response }) || {})\n\t\t\t})\n\t\t\tif (response.errors && response.errors.length > 0) {\n\t\t\t\tconst [code, errors] = processErrors(response.errors)\n\t\t\t\trespond(code && !response.data ? code : 200, { ...response, errors })\n\t\t\t} else {\n\t\t\t\trespond(200, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof GraphQLError) {\n\t\t\t\treturn respond(e instanceof ForbiddenError ? 403 : 400, { errors: [e] })\n\t\t\t}\n\t\t\tlogger.error(e)\n\t\t\treturn respond(500, { errors: [{ message: 'Internal error' }] })\n\t\t}\n\t}\n}\n\nexport const extractOriginalError = (e: Error): Error => {\n\tif (e instanceof GraphQLError && e.originalError) {\n\t\treturn extractOriginalError(e.originalError)\n\t}\n\tif ('errors' in e && Array.isArray((e as any).errors) && (e as any).errors.length === 1) {\n\t\treturn extractOriginalError((e as any).errors[0])\n\t}\n\treturn e\n}\n\nconst withMemoryBudgetError = (errors: readonly GraphQLError[] = []): readonly GraphQLError[] => {\n\tif (errors.some(it => extractOriginalError(it) instanceof RequestMemoryBudgetExceededError)) {\n\t\treturn errors\n\t}\n\t// The resolver that hit the budget did not report it (its error was swallowed); the response still must not pass as valid.\n\tconst originalError = new RequestMemoryBudgetExceededError()\n\treturn [...errors, new GraphQLError(originalError.message, { originalError })]\n}\n\nconst processErrors = (errors: readonly any[]): [number | null, any[]] => {\n\tconst resultErrors = []\n\tlet has400 = false\n\tlet has403 = false\n\tlet has500 = false\n\tlet hasExhaustedMemoryBudget = false\n\tfor (const error of errors) {\n\t\tconst originalError = extractOriginalError(error)\n\t\tif (originalError instanceof GraphQLError) {\n\t\t\tresultErrors.push(error)\n\t\t\thas400 = true\n\t\t} else if (originalError instanceof ForbiddenError) {\n\t\t\tresultErrors.push(error)\n\t\t\thas403 = true\n\t\t} else if (originalError instanceof RequestMemoryBudgetExceededError) {\n\t\t\tresultErrors.push({ message: error.message, locations: error.locations, path: error.path, extensions: { code: memoryBudgetErrorCode } })\n\t\t\thasExhaustedMemoryBudget = true\n\t\t} else if (originalError instanceof UserError) {\n\t\t\tresultErrors.push({ message: error.message, locations: error.locations, path: error.path })\n\t\t\thas400 = true\n\t\t} else {\n\t\t\tlogger.error(originalError || error)\n\t\t\tresultErrors.push({ message: 'Internal server error', locations: undefined, path: undefined })\n\t\t\thas500 = true\n\t\t}\n\t}\n\treturn [has500 ? 500 : hasExhaustedMemoryBudget ? 422 : has400 ? 400 : has403 ? 403 : null, resultErrors]\n}\n\nconst resolveOperationType = (document: DocumentNode, operationName: string | null): OperationTypeNode => {\n\tfor (const definition of document.definitions) {\n\t\tif (definition.kind === Kind.OPERATION_DEFINITION) {\n\t\t\tif (operationName === null || definition.name?.value === operationName) {\n\t\t\t\treturn definition.operation\n\t\t\t}\n\t\t}\n\t}\n\tthrow new GraphQLError('Must provide an operation.')\n}\n"],"names":["validateSchema","validate","execute","validateJson","executeJson","LRUCache","createHash","parse","response","GraphQLError","ForbiddenError","logger","RequestMemoryBudgetExceededError","UserError","Kind"],"mappings":";;;;;;;;;;AAiDO,MAAM,0BAA0B,CAAU,YAAqD;AAAA,EACrG,gBAAgB,MAAMA,QAAAA,eAAe,MAAM;AAAA,EAC3C,UAAU,CAAA,aAAYC,iBAAS,QAAQ,QAAQ;AAAA,EAC/C,SAAS,OAAM,SAAQ,MAAMC,QAAAA,QAAQ,EAAE,QAAQ,GAAG,KAAA,CAAM;AACzD;AAEO,MAAM,4BAA4B,CACxC,EAAE,QAAQ,WAAW,eACU;AAAA;AAAA,EAE/B,gBAAgB,MAAM,CAAA;AAAA,EACtB,UAAU,CAAA,aAAYC,YAAAA,SAAa,QAAQ,UAAU,EAAE,SAAS;AAAA,EAChE,SAAS,OAAO,EAAE,UAAU,eAAe,gBAAgB,aAAA,MAC1D,MAAMC,oBAAY,EAAE,QAAQ,UAAU,WAAW,SAAS,eAAe,iBAAiB,QAAW,gBAAgB,cAAc;AACrI;AAYA,MAAM,wBAAwB;AAE9B,MAAM,wBAAwB,KAAK;AACnC,MAAM,6BAA6B,wBAAwB;AAC3D,MAAM,uBAAuB,6BAA6B;AAC1D,MAAM,mBAAmB;AACzB,MAAM,cAAc,mBAAmB;AAEhC,MAAM,4BAA4B,CAAU;AAAA,EAClD;AAAA,EACA;AAAA,EACA;AACD,MAA0D;AACzD,MAAI,kBAAkB;AACtB,QAAM,WAAW,IAAIC,mBAAuB,aAAa,EAAE,KAAK,wBAAwB,KAAM;AAC9F,QAAM,gBAAgB,IAAIA,mBAA+B,kBAAkB,EAAE,KAAK,6BAA6B,KAAM;AACrH,MAAI,YAAY,KAAK,IA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AAS,MAAM,SAAS,WAAW,MAAM,WAAW,MAAM,MAAM,KAAA,CAAM;AAC1F,eAAS;AAAA,IACV,OAAO;AACNF,oBAAO,MAAM,iBAAiB,KAAK;AACnC,mBAAa,KAAK,EAAE,SAAS,yBAAyB,WAAW,QAAW,MAAM,QAAW;AAC7F,eAAS;AAAA,IACV;AAAA,EACD;AACA,SAAO,CAAC,SAAS,MAAM,2BAA2B,MAAM,SAAS,MAAM,SAAS,MAAM,MAAM,YAAY;AACzG;AAEA,MAAM,uBAAuB,CAAC,UAAwB,kBAAoD;AACzG,aAAW,cAAc,SAAS,aAAa;AAC9C,QAAI,WAAW,SAASG,QAAAA,KAAK,sBAAsB;AAClD,UAAI,kBAAkB,QAAQ,WAAW,MAAM,UAAU,eAAe;AACvE,eAAO,WAAW;AAAA,MACnB;AAAA,IACD;AAAA,EACD;AACA,QAAM,IAAIL,QAAAA,aAAa,4BAA4B;AACpD;;;;;"}
|
|
@@ -1,10 +1,22 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { execute, validate, validateSchema, parse, GraphQLError, Kind } from "graphql";
|
|
2
2
|
import { LRUCache } from "@contember/utilities";
|
|
3
3
|
import { createHash } from "node:crypto";
|
|
4
4
|
import { logger } from "@contember/logger";
|
|
5
5
|
import { ForbiddenError } from "@contember/graphql-utils";
|
|
6
6
|
import { UserError } from "@contember/engine-content-api";
|
|
7
7
|
import { RequestMemoryBudgetExceededError } from "@contember/database";
|
|
8
|
+
import { execute as execute$1, validate as validate$1 } from "@contember/graphql-json";
|
|
9
|
+
const createGraphQLJsExecutor = (schema) => ({
|
|
10
|
+
validateSchema: () => validateSchema(schema),
|
|
11
|
+
validate: (document) => validate(schema, document),
|
|
12
|
+
execute: async (args) => await execute({ schema, ...args })
|
|
13
|
+
});
|
|
14
|
+
const createGraphQLJsonExecutor = ({ schema, resolvers, scalars }) => ({
|
|
15
|
+
// the content builder output is validated as a graphql-js schema in tests; there is no runtime schema validation
|
|
16
|
+
validateSchema: () => [],
|
|
17
|
+
validate: (document) => validate$1(schema, document, { scalars }),
|
|
18
|
+
execute: async ({ document, operationName, variableValues, contextValue }) => await execute$1({ schema, document, resolvers, scalars, operationName: operationName ?? void 0, variableValues, contextValue })
|
|
19
|
+
});
|
|
8
20
|
const memoryBudgetErrorCode = "RESOURCE_EXHAUSTED";
|
|
9
21
|
const hitCacheMaxAgeSeconds = 10 * 60;
|
|
10
22
|
const documentCacheMaxAgeSeconds = hitCacheMaxAgeSeconds * 10;
|
|
@@ -12,7 +24,7 @@ const pruneIntervalSeconds = documentCacheMaxAgeSeconds / 2;
|
|
|
12
24
|
const documentCacheMax = 100;
|
|
13
25
|
const hitCacheMax = documentCacheMax * 2;
|
|
14
26
|
const createGraphQLQueryHandler = ({
|
|
15
|
-
|
|
27
|
+
executor,
|
|
16
28
|
listeners,
|
|
17
29
|
getMemoryBudget
|
|
18
30
|
}) => {
|
|
@@ -40,7 +52,7 @@ const createGraphQLQueryHandler = ({
|
|
|
40
52
|
};
|
|
41
53
|
try {
|
|
42
54
|
if (!schemaValidated) {
|
|
43
|
-
const validationResult = validateSchema(
|
|
55
|
+
const validationResult = executor.validateSchema();
|
|
44
56
|
if (validationResult.length) {
|
|
45
57
|
return respond(400, {
|
|
46
58
|
errors: validationResult
|
|
@@ -58,7 +70,7 @@ const createGraphQLQueryHandler = ({
|
|
|
58
70
|
let doc = documentCache.get(queryHash);
|
|
59
71
|
if (!doc) {
|
|
60
72
|
doc = parse(resolvedRequest.query);
|
|
61
|
-
const validationResult = validate(
|
|
73
|
+
const validationResult = executor.validate(doc);
|
|
62
74
|
if (validationResult.length) {
|
|
63
75
|
return respond(400, { errors: validationResult });
|
|
64
76
|
}
|
|
@@ -74,8 +86,7 @@ const createGraphQLQueryHandler = ({
|
|
|
74
86
|
listenersQueue.forEach((it) => {
|
|
75
87
|
it.onExecute && listenersQueue.push(it.onExecute({ context, document, operation }) || {});
|
|
76
88
|
});
|
|
77
|
-
const executionResult = await execute({
|
|
78
|
-
schema,
|
|
89
|
+
const executionResult = await executor.execute({
|
|
79
90
|
document,
|
|
80
91
|
operationName,
|
|
81
92
|
variableValues: resolvedRequest.variables,
|
|
@@ -155,6 +166,8 @@ const resolveOperationType = (document, operationName) => {
|
|
|
155
166
|
throw new GraphQLError("Must provide an operation.");
|
|
156
167
|
};
|
|
157
168
|
export {
|
|
169
|
+
createGraphQLJsExecutor,
|
|
170
|
+
createGraphQLJsonExecutor,
|
|
158
171
|
createGraphQLQueryHandler,
|
|
159
172
|
extractOriginalError
|
|
160
173
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execution.js","sources":["../../../../../packages/engine-http/src/graphql/execution.ts"],"sourcesContent":["import {\n\tDocumentNode,\n\texecute,\n\tGraphQLError,\n\tGraphQLSchema,\n\tKind,\n\tOperationDefinitionNode,\n\tOperationTypeNode,\n\tparse,\n\tvalidate,\n\tvalidateSchema,\n} from 'graphql'\nimport { LRUCache } from '@contember/utilities'\nimport { createHash } from 'node:crypto'\nimport { Request, Response } from 'koa'\nimport { logger } from '@contember/logger'\nimport { ForbiddenError } from '@contember/graphql-utils'\nimport { UserError } from '@contember/engine-content-api'\nimport { RequestMemoryBudget, RequestMemoryBudgetExceededError } from '@contember/database'\n\nexport interface GraphQLListener<Context> {\n\tonStart?: (ctx: {}) => Omit<GraphQLListener<Context>, 'onStart'> | void\n\tonExecute?: (ctx: {\n\t\tcontext: Context\n\t\tdocument: DocumentNode\n\t\toperation: OperationTypeNode\n\t}) => Omit<GraphQLListener<Context>, 'onStart' | 'onExecute'> | void\n\tonResponse?: (ctx: {\n\t\tresponse: any\n\t\tcontext: Context\n\t}) => Omit<GraphQLListener<Context>, 'onStart' | 'onExecute' | 'onResponse'> | void\n\tonShutdown?: (ctx: {\n\t\tresponse: any\n\t}) => Omit<GraphQLListener<Context>, 'onStart' | 'onExecute' | 'onResponse' | 'onShutdown'> | void\n}\n\ninterface FactoryArgs<Context> {\n\tschema: GraphQLSchema\n\tlisteners: GraphQLListener<Context>[]\n\tgetMemoryBudget?: (context: Context) => RequestMemoryBudget | undefined\n}\n\nexport type GraphQLQueryHandler<Context> = (\n\targs: { request: Request; response: Response; createContext: ({}: { operation: OperationTypeNode; queryHash: string }) => Context },\n) => any\n\nconst memoryBudgetErrorCode = 'RESOURCE_EXHAUSTED'\n\nconst hitCacheMaxAgeSeconds = 10 * 60\nconst documentCacheMaxAgeSeconds = hitCacheMaxAgeSeconds * 10\nconst pruneIntervalSeconds = documentCacheMaxAgeSeconds / 2\nconst documentCacheMax = 100\nconst hitCacheMax = documentCacheMax * 2\n\nexport const createGraphQLQueryHandler = <Context>({\n\tschema,\n\tlisteners,\n\tgetMemoryBudget,\n}: FactoryArgs<Context>): GraphQLQueryHandler<Context> => {\n\tlet schemaValidated = false\n\tconst hitCache = new LRUCache<string, true>(hitCacheMax, { ttl: hitCacheMaxAgeSeconds * 1000 })\n\tconst documentCache = new LRUCache<string, DocumentNode>(documentCacheMax, { ttl: documentCacheMaxAgeSeconds * 1000 })\n\tlet lastPrune = Date.now()\n\n\treturn async ({ request, response, createContext }) => {\n\t\tconst now = Date.now()\n\t\tif ((now - lastPrune) > pruneIntervalSeconds * 1000) {\n\t\t\tdocumentCache.purgeStale()\n\t\t\tlastPrune = now\n\t\t}\n\t\tconst listenersQueue = [...listeners]\n\n\t\tlistenersQueue.forEach(it => {\n\t\t\tit.onStart && listenersQueue.push(it.onStart({}) || {})\n\t\t})\n\n\t\tconst respond = (code: number, data: any) => {\n\t\t\tresponse.status = code\n\t\t\tresponse.body = JSON.stringify(data)\n\t\t\tresponse.set('Content-type', 'application/json')\n\n\t\t\tlistenersQueue.forEach(it => {\n\t\t\t\tit.onShutdown && listenersQueue.push(it.onShutdown({ response: data }) || {})\n\t\t\t})\n\t\t}\n\t\ttry {\n\t\t\tif (!schemaValidated) {\n\t\t\t\tconst validationResult = validateSchema(schema)\n\t\t\t\tif (validationResult.length) {\n\t\t\t\t\treturn respond(400, {\n\t\t\t\t\t\terrors: validationResult,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tschemaValidated = true\n\t\t\t}\n\t\t\tconst resolvedRequest = request.method === 'POST' ? (request.body as any) : request.query\n\t\t\tif (!resolvedRequest.query) {\n\t\t\t\treturn respond(400, {\n\t\t\t\t\terrors: [{ message: 'Missing request query' }],\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst queryHash = createHash('md5').update(resolvedRequest.query).digest('hex')\n\t\t\tlet doc = documentCache.get(queryHash)\n\t\t\tif (!doc) {\n\t\t\t\tdoc = parse(resolvedRequest.query)\n\t\t\t\tconst validationResult = validate(schema, doc)\n\t\t\t\tif (validationResult.length) {\n\t\t\t\t\treturn respond(400, { errors: validationResult })\n\t\t\t\t}\n\t\t\t\tif (hitCache.get(queryHash)) {\n\t\t\t\t\tdocumentCache.set(queryHash, doc)\n\t\t\t\t}\n\t\t\t\thitCache.set(queryHash, true)\n\t\t\t}\n\t\t\tconst document = doc\n\t\t\tconst operationName = resolvedRequest.operationName ?? null\n\t\t\tconst operation = resolveOperationType(document, operationName)\n\n\t\t\tconst context = createContext({ operation, queryHash })\n\t\t\tlistenersQueue.forEach(it => {\n\t\t\t\tit.onExecute && listenersQueue.push(it.onExecute({ context, document, operation }) || {})\n\t\t\t})\n\t\t\tconst executionResult = await execute({\n\t\t\t\tschema,\n\t\t\t\tdocument,\n\t\t\t\toperationName: operationName,\n\t\t\t\tvariableValues: resolvedRequest.variables,\n\t\t\t\tcontextValue: context,\n\t\t\t})\n\t\t\t// GraphQL turns a budget failure inside a nullable resolver into partial data; reject the whole response instead.\n\t\t\t// A mutation reports it in its own result, because sibling mutations may already be committed.\n\t\t\tconst response = operation === 'query' && getMemoryBudget?.(context)?.exceeded\n\t\t\t\t? { data: null, errors: withMemoryBudgetError(executionResult.errors) }\n\t\t\t\t: executionResult\n\t\t\tlistenersQueue.forEach(it => {\n\t\t\t\tit.onResponse && listenersQueue.push(it.onResponse({ context, response }) || {})\n\t\t\t})\n\t\t\tif (response.errors && response.errors.length > 0) {\n\t\t\t\tconst [code, errors] = processErrors(response.errors)\n\t\t\t\trespond(code && !response.data ? code : 200, { ...response, errors })\n\t\t\t} else {\n\t\t\t\trespond(200, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof GraphQLError) {\n\t\t\t\treturn respond(e instanceof ForbiddenError ? 403 : 400, { errors: [e] })\n\t\t\t}\n\t\t\tlogger.error(e)\n\t\t\treturn respond(500, { errors: [{ message: 'Internal error' }] })\n\t\t}\n\t}\n}\n\nexport const extractOriginalError = (e: Error): Error => {\n\tif (e instanceof GraphQLError && e.originalError) {\n\t\treturn extractOriginalError(e.originalError)\n\t}\n\tif ('errors' in e && Array.isArray((e as any).errors) && (e as any).errors.length === 1) {\n\t\treturn extractOriginalError((e as any).errors[0])\n\t}\n\treturn e\n}\n\nconst withMemoryBudgetError = (errors: readonly GraphQLError[] = []): readonly GraphQLError[] => {\n\tif (errors.some(it => extractOriginalError(it) instanceof RequestMemoryBudgetExceededError)) {\n\t\treturn errors\n\t}\n\t// The resolver that hit the budget did not report it (its error was swallowed); the response still must not pass as valid.\n\tconst originalError = new RequestMemoryBudgetExceededError()\n\treturn [...errors, new GraphQLError(originalError.message, { originalError })]\n}\n\nconst processErrors = (errors: readonly any[]): [number | null, any[]] => {\n\tconst resultErrors = []\n\tlet has400 = false\n\tlet has403 = false\n\tlet has500 = false\n\tlet hasExhaustedMemoryBudget = false\n\tfor (const error of errors) {\n\t\tconst originalError = extractOriginalError(error)\n\t\tif (originalError instanceof GraphQLError) {\n\t\t\tresultErrors.push(error)\n\t\t\thas400 = true\n\t\t} else if (originalError instanceof ForbiddenError) {\n\t\t\tresultErrors.push(error)\n\t\t\thas403 = true\n\t\t} else if (originalError instanceof RequestMemoryBudgetExceededError) {\n\t\t\tresultErrors.push({ message: error.message, locations: error.locations, path: error.path, extensions: { code: memoryBudgetErrorCode } })\n\t\t\thasExhaustedMemoryBudget = true\n\t\t} else if (originalError instanceof UserError) {\n\t\t\tresultErrors.push({ message: error.message, locations: error.locations, path: error.path })\n\t\t\thas400 = true\n\t\t} else {\n\t\t\tlogger.error(originalError || error)\n\t\t\tresultErrors.push({ message: 'Internal server error', locations: undefined, path: undefined })\n\t\t\thas500 = true\n\t\t}\n\t}\n\treturn [has500 ? 500 : hasExhaustedMemoryBudget ? 422 : has400 ? 400 : has403 ? 403 : null, resultErrors]\n}\n\nconst resolveOperationType = (document: DocumentNode, operationName: string | null): OperationTypeNode => {\n\tfor (const definition of document.definitions) {\n\t\tif (definition.kind === Kind.OPERATION_DEFINITION) {\n\t\t\tif (operationName === null || definition.name?.value === operationName) {\n\t\t\t\treturn definition.operation\n\t\t\t}\n\t\t}\n\t}\n\tthrow new GraphQLError('Must provide an operation.')\n}\n"],"names":["response"],"mappings":";;;;;;;AA8CA,MAAM,wBAAwB;AAE9B,MAAM,wBAAwB,KAAK;AACnC,MAAM,6BAA6B,wBAAwB;AAC3D,MAAM,uBAAuB,6BAA6B;AAC1D,MAAM,mBAAmB;AACzB,MAAM,cAAc,mBAAmB;AAEhC,MAAM,4BAA4B,CAAU;AAAA,EAClD;AAAA,EACA;AAAA,EACA;AACD,MAA0D;AACzD,MAAI,kBAAkB;AACtB,QAAM,WAAW,IAAI,SAAuB,aAAa,EAAE,KAAK,wBAAwB,KAAM;AAC9F,QAAM,gBAAgB,IAAI,SAA+B,kBAAkB,EAAE,KAAK,6BAA6B,KAAM;AACrH,MAAI,YAAY,KAAK,IAAA;AAErB,SAAO,OAAO,EAAE,SAAS,UAAU,oBAAoB;AACtD,UAAM,MAAM,KAAK,IAAA;AACjB,QAAK,MAAM,YAAa,uBAAuB,KAAM;AACpD,oBAAc,WAAA;AACd,kBAAY;AAAA,IACb;AACA,UAAM,iBAAiB,CAAC,GAAG,SAAS;AAEpC,mBAAe,QAAQ,CAAA,OAAM;AAC5B,SAAG,WAAW,eAAe,KAAK,GAAG,QAAQ,CAAA,CAAE,KAAK,EAAE;AAAA,IACvD,CAAC;AAED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WAAW,SAAS,KAAK,sBAAsB;AAClD,UAAI,kBAAkB,QAAQ,WAAW,MAAM,UAAU,eAAe;AACvE,eAAO,WAAW;AAAA,MACnB;AAAA,IACD;AAAA,EACD;AACA,QAAM,IAAI,aAAa,4BAA4B;AACpD;"}
|
|
1
|
+
{"version":3,"file":"execution.js","sources":["../../../../../packages/engine-http/src/graphql/execution.ts"],"sourcesContent":["import {\n\tDocumentNode,\n\texecute,\n\tExecutionResult,\n\tGraphQLError,\n\tGraphQLSchema,\n\tKind,\n\tOperationTypeNode,\n\tparse,\n\tvalidate,\n\tvalidateSchema,\n} from 'graphql'\nimport { LRUCache } from '@contember/utilities'\nimport { createHash } from 'node:crypto'\nimport { Request, Response } from 'koa'\nimport { logger } from '@contember/logger'\nimport { ForbiddenError } from '@contember/graphql-utils'\nimport { UserError } from '@contember/engine-content-api'\nimport { RequestMemoryBudget, RequestMemoryBudgetExceededError } from '@contember/database'\nimport { execute as executeJson, ResolverMap, ScalarMap, Schema as JsonSchema, validate as validateJson } from '@contember/graphql-json'\n\nexport interface GraphQLListener<Context> {\n\tonStart?: (ctx: {}) => Omit<GraphQLListener<Context>, 'onStart'> | void\n\tonExecute?: (ctx: {\n\t\tcontext: Context\n\t\tdocument: DocumentNode\n\t\toperation: OperationTypeNode\n\t}) => Omit<GraphQLListener<Context>, 'onStart' | 'onExecute'> | void\n\tonResponse?: (ctx: {\n\t\tresponse: any\n\t\tcontext: Context\n\t}) => Omit<GraphQLListener<Context>, 'onStart' | 'onExecute' | 'onResponse'> | void\n\tonShutdown?: (ctx: {\n\t\tresponse: any\n\t}) => Omit<GraphQLListener<Context>, 'onStart' | 'onExecute' | 'onResponse' | 'onShutdown'> | void\n}\n\n/** The GraphQL engine a handler runs on. */\nexport interface GraphQLExecutor<Context> {\n\tvalidateSchema(): readonly GraphQLError[]\n\tvalidate(document: DocumentNode): readonly GraphQLError[]\n\texecute(args: {\n\t\tdocument: DocumentNode\n\t\toperationName: string | null\n\t\tvariableValues: Record<string, unknown> | undefined\n\t\tcontextValue: Context\n\t}): Promise<Pick<ExecutionResult, 'data' | 'errors'>>\n}\n\nexport const createGraphQLJsExecutor = <Context>(schema: GraphQLSchema): GraphQLExecutor<Context> => ({\n\tvalidateSchema: () => validateSchema(schema),\n\tvalidate: document => validate(schema, document),\n\texecute: async args => await execute({ schema, ...args }),\n})\n\nexport const createGraphQLJsonExecutor = <Context>(\n\t{ schema, resolvers, scalars }: { schema: JsonSchema; resolvers: readonly ResolverMap<Context>[]; scalars: ScalarMap },\n): GraphQLExecutor<Context> => ({\n\t// the content builder output is validated as a graphql-js schema in tests; there is no runtime schema validation\n\tvalidateSchema: () => [],\n\tvalidate: document => validateJson(schema, document, { scalars }),\n\texecute: async ({ document, operationName, variableValues, contextValue }) =>\n\t\tawait executeJson({ schema, document, resolvers, scalars, operationName: operationName ?? undefined, variableValues, contextValue }),\n})\n\ninterface FactoryArgs<Context> {\n\texecutor: GraphQLExecutor<Context>\n\tlisteners: GraphQLListener<Context>[]\n\tgetMemoryBudget?: (context: Context) => RequestMemoryBudget | undefined\n}\n\nexport type GraphQLQueryHandler<Context> = (\n\targs: { request: Request; response: Response; createContext: ({}: { operation: OperationTypeNode; queryHash: string }) => Context },\n) => any\n\nconst memoryBudgetErrorCode = 'RESOURCE_EXHAUSTED'\n\nconst hitCacheMaxAgeSeconds = 10 * 60\nconst documentCacheMaxAgeSeconds = hitCacheMaxAgeSeconds * 10\nconst pruneIntervalSeconds = documentCacheMaxAgeSeconds / 2\nconst documentCacheMax = 100\nconst hitCacheMax = documentCacheMax * 2\n\nexport const createGraphQLQueryHandler = <Context>({\n\texecutor,\n\tlisteners,\n\tgetMemoryBudget,\n}: FactoryArgs<Context>): GraphQLQueryHandler<Context> => {\n\tlet schemaValidated = false\n\tconst hitCache = new LRUCache<string, true>(hitCacheMax, { ttl: hitCacheMaxAgeSeconds * 1000 })\n\tconst documentCache = new LRUCache<string, DocumentNode>(documentCacheMax, { ttl: documentCacheMaxAgeSeconds * 1000 })\n\tlet lastPrune = Date.now()\n\n\treturn async ({ request, response, createContext }) => {\n\t\tconst now = Date.now()\n\t\tif ((now - lastPrune) > pruneIntervalSeconds * 1000) {\n\t\t\tdocumentCache.purgeStale()\n\t\t\tlastPrune = now\n\t\t}\n\t\tconst listenersQueue = [...listeners]\n\n\t\tlistenersQueue.forEach(it => {\n\t\t\tit.onStart && listenersQueue.push(it.onStart({}) || {})\n\t\t})\n\n\t\tconst respond = (code: number, data: any) => {\n\t\t\tresponse.status = code\n\t\t\tresponse.body = JSON.stringify(data)\n\t\t\tresponse.set('Content-type', 'application/json')\n\n\t\t\tlistenersQueue.forEach(it => {\n\t\t\t\tit.onShutdown && listenersQueue.push(it.onShutdown({ response: data }) || {})\n\t\t\t})\n\t\t}\n\t\ttry {\n\t\t\tif (!schemaValidated) {\n\t\t\t\tconst validationResult = executor.validateSchema()\n\t\t\t\tif (validationResult.length) {\n\t\t\t\t\treturn respond(400, {\n\t\t\t\t\t\terrors: validationResult,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tschemaValidated = true\n\t\t\t}\n\t\t\tconst resolvedRequest = request.method === 'POST' ? (request.body as any) : request.query\n\t\t\tif (!resolvedRequest.query) {\n\t\t\t\treturn respond(400, {\n\t\t\t\t\terrors: [{ message: 'Missing request query' }],\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst queryHash = createHash('md5').update(resolvedRequest.query).digest('hex')\n\t\t\tlet doc = documentCache.get(queryHash)\n\t\t\tif (!doc) {\n\t\t\t\tdoc = parse(resolvedRequest.query)\n\t\t\t\tconst validationResult = executor.validate(doc)\n\t\t\t\tif (validationResult.length) {\n\t\t\t\t\treturn respond(400, { errors: validationResult })\n\t\t\t\t}\n\t\t\t\tif (hitCache.get(queryHash)) {\n\t\t\t\t\tdocumentCache.set(queryHash, doc)\n\t\t\t\t}\n\t\t\t\thitCache.set(queryHash, true)\n\t\t\t}\n\t\t\tconst document = doc\n\t\t\tconst operationName = resolvedRequest.operationName ?? null\n\t\t\tconst operation = resolveOperationType(document, operationName)\n\n\t\t\tconst context = createContext({ operation, queryHash })\n\t\t\tlistenersQueue.forEach(it => {\n\t\t\t\tit.onExecute && listenersQueue.push(it.onExecute({ context, document, operation }) || {})\n\t\t\t})\n\t\t\tconst executionResult = await executor.execute({\n\t\t\t\tdocument,\n\t\t\t\toperationName: operationName,\n\t\t\t\tvariableValues: resolvedRequest.variables,\n\t\t\t\tcontextValue: context,\n\t\t\t})\n\t\t\t// GraphQL turns a budget failure inside a nullable resolver into partial data; reject the whole response instead.\n\t\t\t// A mutation reports it in its own result, because sibling mutations may already be committed.\n\t\t\tconst response = operation === 'query' && getMemoryBudget?.(context)?.exceeded\n\t\t\t\t? { data: null, errors: withMemoryBudgetError(executionResult.errors) }\n\t\t\t\t: executionResult\n\t\t\tlistenersQueue.forEach(it => {\n\t\t\t\tit.onResponse && listenersQueue.push(it.onResponse({ context, response }) || {})\n\t\t\t})\n\t\t\tif (response.errors && response.errors.length > 0) {\n\t\t\t\tconst [code, errors] = processErrors(response.errors)\n\t\t\t\trespond(code && !response.data ? code : 200, { ...response, errors })\n\t\t\t} else {\n\t\t\t\trespond(200, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof GraphQLError) {\n\t\t\t\treturn respond(e instanceof ForbiddenError ? 403 : 400, { errors: [e] })\n\t\t\t}\n\t\t\tlogger.error(e)\n\t\t\treturn respond(500, { errors: [{ message: 'Internal error' }] })\n\t\t}\n\t}\n}\n\nexport const extractOriginalError = (e: Error): Error => {\n\tif (e instanceof GraphQLError && e.originalError) {\n\t\treturn extractOriginalError(e.originalError)\n\t}\n\tif ('errors' in e && Array.isArray((e as any).errors) && (e as any).errors.length === 1) {\n\t\treturn extractOriginalError((e as any).errors[0])\n\t}\n\treturn e\n}\n\nconst withMemoryBudgetError = (errors: readonly GraphQLError[] = []): readonly GraphQLError[] => {\n\tif (errors.some(it => extractOriginalError(it) instanceof RequestMemoryBudgetExceededError)) {\n\t\treturn errors\n\t}\n\t// The resolver that hit the budget did not report it (its error was swallowed); the response still must not pass as valid.\n\tconst originalError = new RequestMemoryBudgetExceededError()\n\treturn [...errors, new GraphQLError(originalError.message, { originalError })]\n}\n\nconst processErrors = (errors: readonly any[]): [number | null, any[]] => {\n\tconst resultErrors = []\n\tlet has400 = false\n\tlet has403 = false\n\tlet has500 = false\n\tlet hasExhaustedMemoryBudget = false\n\tfor (const error of errors) {\n\t\tconst originalError = extractOriginalError(error)\n\t\tif (originalError instanceof GraphQLError) {\n\t\t\tresultErrors.push(error)\n\t\t\thas400 = true\n\t\t} else if (originalError instanceof ForbiddenError) {\n\t\t\tresultErrors.push(error)\n\t\t\thas403 = true\n\t\t} else if (originalError instanceof RequestMemoryBudgetExceededError) {\n\t\t\tresultErrors.push({ message: error.message, locations: error.locations, path: error.path, extensions: { code: memoryBudgetErrorCode } })\n\t\t\thasExhaustedMemoryBudget = true\n\t\t} else if (originalError instanceof UserError) {\n\t\t\tresultErrors.push({ message: error.message, locations: error.locations, path: error.path })\n\t\t\thas400 = true\n\t\t} else {\n\t\t\tlogger.error(originalError || error)\n\t\t\tresultErrors.push({ message: 'Internal server error', locations: undefined, path: undefined })\n\t\t\thas500 = true\n\t\t}\n\t}\n\treturn [has500 ? 500 : hasExhaustedMemoryBudget ? 422 : has400 ? 400 : has403 ? 403 : null, resultErrors]\n}\n\nconst resolveOperationType = (document: DocumentNode, operationName: string | null): OperationTypeNode => {\n\tfor (const definition of document.definitions) {\n\t\tif (definition.kind === Kind.OPERATION_DEFINITION) {\n\t\t\tif (operationName === null || definition.name?.value === operationName) {\n\t\t\t\treturn definition.operation\n\t\t\t}\n\t\t}\n\t}\n\tthrow new GraphQLError('Must provide an operation.')\n}\n"],"names":["validateJson","executeJson","response"],"mappings":";;;;;;;;AAiDO,MAAM,0BAA0B,CAAU,YAAqD;AAAA,EACrG,gBAAgB,MAAM,eAAe,MAAM;AAAA,EAC3C,UAAU,CAAA,aAAY,SAAS,QAAQ,Q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;AAAA,EACD;AACA,QAAM,IAAI,aAAa,4BAA4B;AACpD;"}
|
|
@@ -11,6 +11,8 @@ require("@contember/utilities");
|
|
|
11
11
|
require("node:crypto");
|
|
12
12
|
require("@contember/logger");
|
|
13
13
|
require("@contember/graphql-utils");
|
|
14
|
+
require("@contember/graphql-json");
|
|
15
|
+
require("node:fs");
|
|
14
16
|
const ContentSchemaResolver = require("../content/ContentSchemaResolver.cjs");
|
|
15
17
|
require("../content/ProjectMembershipResolver.cjs");
|
|
16
18
|
const ProjectDatabaseMetadataResolver = require("./ProjectDatabaseMetadataResolver.cjs");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ProjectContainer.cjs","sources":["../../../../../packages/engine-http/src/project/ProjectContainer.ts"],"sourcesContent":["import { Builder } from '@contember/dic'\nimport { Connection, DatabaseMetadataResolver } from '@contember/database'\nimport {\n\tDatabaseContext,\n\tDatabaseContextFactory,\n\tProjectInitializer,\n\tSchemaProvider,\n\tStageCreator,\n\tSystemMigrationsRunner,\n} from '@contember/engine-system-api'\nimport {
|
|
1
|
+
{"version":3,"file":"ProjectContainer.cjs","sources":["../../../../../packages/engine-http/src/project/ProjectContainer.ts"],"sourcesContent":["import { Builder } from '@contember/dic'\nimport { Connection, DatabaseMetadataResolver } from '@contember/database'\nimport {\n\tDatabaseContext,\n\tDatabaseContextFactory,\n\tProjectInitializer,\n\tSchemaProvider,\n\tStageCreator,\n\tSystemMigrationsRunner,\n} from '@contember/engine-system-api'\nimport { PermissionFactory } from '@contember/engine-content-api'\nimport { Logger } from '@contember/logger'\nimport { ProjectConfig } from './config.js'\nimport { ContentSchemaResolver } from '../content/index.js'\nimport { Providers } from '../providers.js'\nimport { Plugin } from '../plugin/Plugin.js'\nimport { ServerConfig } from '../config/config.js'\nimport { ProjectDatabaseMetadataResolver } from './ProjectDatabaseMetadataResolver.js'\n\nexport interface ProjectContainer {\n\tsystemDatabaseContextFactory: DatabaseContextFactory\n\tsystemDatabaseContext: DatabaseContext\n\tsystemReadDatabaseContext: DatabaseContext\n\tproject: ProjectConfig\n\tlogger: Logger\n\tconnection: Connection\n\treadConnection: Connection\n\tcontentSchemaResolver: ContentSchemaResolver\n\tprojectInitializer: ProjectInitializer\n\tprojectDatabaseMetadataResolver: ProjectDatabaseMetadataResolver\n}\n\nexport class ProjectContainerFactoryFactory {\n\tconstructor(\n\t\tprivate readonly plugins: Plugin[],\n\t\tprivate readonly providers: Providers,\n\t\tprivate readonly databaseMetadataResolver: DatabaseMetadataResolver,\n\t) {\n\t}\n\n\tcreate(schemaProvider: SchemaProvider, logger: Logger): ProjectContainerFactory {\n\t\treturn new ProjectContainerFactory(\n\t\t\tthis.plugins,\n\t\t\tschemaProvider,\n\t\t\tthis.providers,\n\t\t\tlogger,\n\t\t\tthis.databaseMetadataResolver,\n\t\t)\n\t}\n}\n\ninterface ProjectContainerFactoryArgs {\n\tproject: ProjectConfig\n}\n\nexport class ProjectContainerFactory {\n\tconstructor(\n\t\tprivate readonly plugins: Plugin<any>[],\n\t\tprivate readonly schemaProvider: SchemaProvider,\n\t\tprivate readonly providers: Providers,\n\t\tprivate readonly logger: Logger,\n\t\tprivate readonly databaseMetadataResolver: DatabaseMetadataResolver,\n\t) {}\n\n\tpublic createContainer(args: ProjectContainerFactoryArgs): ProjectContainer {\n\t\treturn this.createBuilder(args)\n\t\t\t.build()\n\t\t\t.pick(\n\t\t\t\t'project',\n\t\t\t\t'connection',\n\t\t\t\t'readConnection',\n\t\t\t\t'systemDatabaseContextFactory',\n\t\t\t\t'systemDatabaseContext',\n\t\t\t\t'systemReadDatabaseContext',\n\t\t\t\t'contentSchemaResolver',\n\t\t\t\t'projectInitializer',\n\t\t\t\t'logger',\n\t\t\t\t'projectDatabaseMetadataResolver',\n\t\t\t)\n\t}\n\n\tprotected createBuilder({ project }: ProjectContainerFactoryArgs) {\n\t\treturn new Builder({})\n\t\t\t.addService('logger', () => this.logger.child({ project: project.slug }))\n\t\t\t.addService('project', () => project)\n\t\t\t.addService('connection', ({ project, logger }) => Connection.create(project.db, err => logger.error(err)))\n\t\t\t.addService('readConnection', ({ project, logger, connection }) => {\n\t\t\t\tif (!project.db.read) {\n\t\t\t\t\treturn connection\n\t\t\t\t}\n\t\t\t\treturn Connection.create(\n\t\t\t\t\t{\n\t\t\t\t\t\t...project.db,\n\t\t\t\t\t\t...project.db.read,\n\t\t\t\t\t\tpool: {\n\t\t\t\t\t\t\t...project.db.pool,\n\t\t\t\t\t\t\t...project.db.read.pool,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\terr => logger.error(err),\n\t\t\t\t\t{ retryStaleConnection: true },\n\t\t\t\t)\n\t\t\t})\n\t\t\t.addService('contentSchemaResolver', () => new ContentSchemaResolver(this.schemaProvider))\n\t\t\t.addService('systemSchemaName', ({ project }) => project.db.systemSchema ?? 'system')\n\t\t\t.addService('systemDatabaseContextFactory', ({ systemSchemaName }) => new DatabaseContextFactory(systemSchemaName, this.providers))\n\t\t\t.addService('systemDatabaseContext', ({ connection, systemDatabaseContextFactory }) => systemDatabaseContextFactory.create(connection))\n\t\t\t.addService('systemReadDatabaseContext', ({ readConnection, systemDatabaseContextFactory }) => systemDatabaseContextFactory.create(readConnection))\n\t\t\t.addService(\n\t\t\t\t'systemMigrationGroups',\n\t\t\t\t() => Object.fromEntries(this.plugins.flatMap(it => it.getSystemMigrations ? [[it.name, it.getSystemMigrations()]] : [])),\n\t\t\t)\n\t\t\t.addService(\n\t\t\t\t'systemMigrationsRunner',\n\t\t\t\t({ systemDatabaseContextFactory, project, systemSchemaName, systemMigrationGroups }) =>\n\t\t\t\t\tnew SystemMigrationsRunner(\n\t\t\t\t\t\tsystemDatabaseContextFactory,\n\t\t\t\t\t\t{ ...project, systemSchema: systemSchemaName },\n\t\t\t\t\t\tthis.schemaProvider,\n\t\t\t\t\t\tsystemMigrationGroups,\n\t\t\t\t\t\tthis.databaseMetadataResolver,\n\t\t\t\t\t),\n\t\t\t)\n\t\t\t.addService(\n\t\t\t\t'projectInitializer',\n\t\t\t\t({ systemMigrationsRunner, systemDatabaseContext, project, systemSchemaName }) =>\n\t\t\t\t\tnew ProjectInitializer(new StageCreator(), systemMigrationsRunner, systemDatabaseContext, { ...project, systemSchema: systemSchemaName }),\n\t\t\t)\n\t\t\t.addService('projectDatabaseMetadataResolver', () => new ProjectDatabaseMetadataResolver(this.databaseMetadataResolver))\n\t}\n}\n"],"names":["Builder","project","Connection","ContentSchemaResolver","DatabaseContextFactory","SystemMigrationsRunner","ProjectInitializer","StageCreator","ProjectDatabaseMetadataResolver"],"mappings":";;;;;;;;;;;;;;;;;;AAgCO,MAAM,+BAA+B;AAAA,EAC3C,YACkB,SACA,WACA,0BAChB;AAHgB,SAAA,UAAA;AACA,SAAA,YAAA;AACA,SAAA,2BAAA;AAAA,EAElB;AAAA,EAEA,OAAO,gBAAgC,QAAyC;AAC/E,WAAO,IAAI;AAAA,MACV,KAAK;AAAA,MACL;AAAA,MACA,KAAK;AAAA,MACL;AAAA,MACA,KAAK;AAAA,IAAA;AAAA,EAEP;AACD;AAMO,MAAM,wBAAwB;AAAA,EACpC,YACkB,SACA,gBACA,WACA,QACA,0BAChB;AALgB,SAAA,UAAA;AACA,SAAA,iBAAA;AACA,SAAA,YAAA;AACA,SAAA,SAAA;AACA,SAAA,2BAAA;AAAA,EACf;AAAA,EAEI,gBAAgB,MAAqD;AAC3E,WAAO,KAAK,cAAc,IAAI,EAC5B,QACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAAA,EAEH;AAAA,EAEU,cAAc,EAAE,WAAwC;AACjE,WAAO,IAAIA,IAAAA,QAAQ,CAAA,CAAE,EACnB,WAAW,UAAU,MAAM,KAAK,OAAO,MAAM,EAAE,SAAS,QAAQ,MAAM,CAAC,EACvE,WAAW,WAAW,MAAM,OAAO,EACnC,WAAW,cAAc,CAAC,E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,GAAGJ,UAAS,cAAc,iBAAA;AAAA,QAC5B,KAAK;AAAA,QACL;AAAA,QACA,KAAK;AAAA,MAAA;AAAA,IACN,EAED;AAAA,MACA;AAAA,MACA,CAAC,EAAE,wBAAwB,uBAAuB,SAAAA,UAAS,iBAAA,MAC1D,IAAIK,gBAAAA,mBAAmB,IAAIC,gBAAAA,aAAA,GAAgB,wBAAwB,uBAAuB,EAAE,GAAGN,UAAS,cAAc,kBAAkB;AAAA,IAAA,EAEzI,WAAW,mCAAmC,MAAM,IAAIO,gCAAAA,gCAAgC,KAAK,wBAAwB,CAAC;AAAA,EACzH;AACD;;;"}
|
|
@@ -9,6 +9,8 @@ import "@contember/utilities";
|
|
|
9
9
|
import "node:crypto";
|
|
10
10
|
import "@contember/logger";
|
|
11
11
|
import "@contember/graphql-utils";
|
|
12
|
+
import "@contember/graphql-json";
|
|
13
|
+
import "node:fs";
|
|
12
14
|
import { ContentSchemaResolver } from "../content/ContentSchemaResolver.js";
|
|
13
15
|
import "../content/ProjectMembershipResolver.js";
|
|
14
16
|
import { ProjectDatabaseMetadataResolver } from "./ProjectDatabaseMetadataResolver.js";
|