buro26-strapi-graphql 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +173 -16
  2. package/dist/server/index.d.ts +1 -1
  3. package/dist/server/nexus/plugins/field-authorize.plugin.d.ts +21 -0
  4. package/dist/server/nexus/plugins/field-authorize.plugin.js +68 -35
  5. package/dist/server/nexus/plugins/middleware.plugin.d.ts +10 -2
  6. package/dist/server/nexus/plugins/middleware.plugin.js +20 -33
  7. package/dist/server/services/file-service.d.ts +7 -6
  8. package/dist/server/services/file-service.js +36 -36
  9. package/dist/server/services/index.d.ts +1 -1
  10. package/dist/server/types.d.ts +18 -3
  11. package/dist/server/utils/collection-type.d.ts +13 -2
  12. package/dist/server/utils/collection-type.js +13 -2
  13. package/dist/server/utils/field-builder/builder.d.ts +13 -4
  14. package/dist/server/utils/field-builder/builder.js +214 -119
  15. package/dist/server/utils/field-builder/helpers.d.ts +21 -6
  16. package/dist/server/utils/field-builder/helpers.js +26 -4
  17. package/dist/server/utils/field-builder/types.d.ts +297 -76
  18. package/dist/server/utils/graphql-extension.d.ts +24 -3
  19. package/dist/server/utils/graphql-extension.js +73 -7
  20. package/dist/server/utils/index.d.ts +2 -0
  21. package/dist/server/utils/index.js +11 -0
  22. package/dist/server/utils/loaders.d.ts +110 -0
  23. package/dist/server/utils/loaders.js +222 -0
  24. package/dist/server/utils/misc.d.ts +6 -0
  25. package/dist/server/utils/misc.js +6 -0
  26. package/dist/server/utils/override.d.ts +32 -0
  27. package/dist/server/utils/override.js +54 -26
  28. package/dist/server/utils/registry/field-protection.d.ts +43 -0
  29. package/dist/server/utils/registry/field-protection.js +65 -0
  30. package/dist/server/utils/registry/global-registry.d.ts +69 -14
  31. package/dist/server/utils/registry/global-registry.js +53 -7
  32. package/dist/server/utils/registry/index.d.ts +2 -0
  33. package/dist/server/utils/registry/index.js +2 -0
  34. package/dist/server/utils/registry/resolve-field.d.ts +1 -0
  35. package/dist/server/utils/registry/resolve-field.js +67 -0
  36. package/dist/server/utils/shadow-crud.d.ts +28 -1
  37. package/dist/server/utils/shadow-crud.js +32 -1
  38. package/dist/server/utils/single-type.d.ts +30 -1
  39. package/dist/server/utils/single-type.js +25 -0
  40. package/dist/server/utils/strapi-compat.d.ts +90 -0
  41. package/dist/server/utils/strapi-compat.js +203 -0
  42. package/dist/server/utils/types.d.ts +25 -1
  43. package/dist/tsconfig.server.tsbuildinfo +1 -1
  44. package/package.json +3 -2
@@ -6,10 +6,20 @@
6
6
  */
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
8
  exports.toEntityResponse = exports.resolveEntityRelation = exports.resolveEntity = void 0;
9
+ const strapi_compat_1 = require("./strapi-compat");
10
+ /**
11
+ * Resolve a single entity with Strapi's own `findOne` query resolver.
12
+ * On Strapi v5 `args` must contain `documentId` instead of `id`.
13
+ *
14
+ * @throws Error on Strapi v5 when `args.documentId` is missing.
15
+ */
9
16
  async function resolveEntity(contentType, resolveArgs) {
10
17
  const { transformArgs } = strapi.plugin('graphql').service('builders').utils;
11
18
  const { toEntityResponse } = strapi.plugin('graphql').service('format').returnTypes;
12
19
  const { buildQueriesResolvers } = strapi.plugin('graphql').service('builders').get('content-api');
20
+ if ((0, strapi_compat_1.isStrapiV5)() && !('documentId' in resolveArgs.args)) {
21
+ throw new Error(`[buro26-strapi-graphql] resolveEntity("${contentType}") needs args.documentId on Strapi v5 (got args.id)`);
22
+ }
13
23
  const transformedArgs = transformArgs(resolveArgs.args, { contentType });
14
24
  const { findOne } = buildQueriesResolvers({ contentType });
15
25
  const item = await findOne(resolveArgs.parent, transformedArgs, resolveArgs.context);
@@ -19,6 +29,11 @@ async function resolveEntity(contentType, resolveArgs) {
19
29
  });
20
30
  }
21
31
  exports.resolveEntity = resolveEntity;
32
+ /**
33
+ * Resolve a relation with Strapi's own association resolver (validation, sanitizing and draft/publish
34
+ * handling included). Returns Strapi's response wrapper: `{ value, info }` for to-one relations and
35
+ * `{ nodes, info }` for to-many relations. Prefer `.relation()` on the field builder for relation fields.
36
+ */
22
37
  const resolveEntityRelation = async (contentType, relationFieldName, resolveArgs) => {
23
38
  const { buildAssociationResolver } = strapi.plugin('graphql').service('builders').get('content-api');
24
39
  const find = buildAssociationResolver({
@@ -28,6 +43,16 @@ const resolveEntityRelation = async (contentType, relationFieldName, resolveArgs
28
43
  return find(resolveArgs.parent, resolveArgs.args, resolveArgs.context);
29
44
  };
30
45
  exports.resolveEntityRelation = resolveEntityRelation;
46
+ /**
47
+ * Wrap an entity in Strapi's entity response (`{ value, info }`), the return shape of `XEntityResponse`
48
+ * fields such as single-entity queries.
49
+ *
50
+ * @param args - The field arguments, used by Strapi when resolving nested fields.
51
+ * @param resourceUID - Content type UID of `item`.
52
+ *
53
+ * @remarks Strapi v5 to-one relation fields expect the bare entity; use {@link toRelationValue} or
54
+ * {@link FieldExtensionBuilder.relation} for relations.
55
+ */
31
56
  async function toEntityResponse(item, { args, resourceUID }) {
32
57
  const { toEntityResponse } = strapi.plugin('graphql').service('format').returnTypes;
33
58
  return toEntityResponse(item, {
@@ -0,0 +1,90 @@
1
+ import type { GraphQLResolveInfo } from 'graphql';
2
+ import type { ResolveContext } from './types';
3
+ type AnyRecord = Record<string, any>;
4
+ /**
5
+ * True when running on Strapi v5. The document service (`strapi.documents`) only exists in v5.
6
+ */
7
+ export declare const isStrapiV5: () => boolean;
8
+ /**
9
+ * Whether the GraphQL plugin runs in v4 compatibility mode (only relevant on v5).
10
+ */
11
+ export declare const isV4CompatibilityMode: () => boolean;
12
+ /**
13
+ * GraphQL object type name Strapi generates for a content type, e.g. `api::customer.customer` → `Customer`.
14
+ */
15
+ export declare const typeNameOf: (uid: string) => string;
16
+ /**
17
+ * Reverse lookup of {@link typeNameOf}: the content type UID behind a generated GraphQL type name.
18
+ * Built lazily (content types do not change at runtime).
19
+ */
20
+ export declare const uidOfTypeName: (typeName: string) => string | undefined;
21
+ /**
22
+ * One GraphQL field Strapi generates for a relation attribute.
23
+ *
24
+ * @see {@link relationFieldSpecs}
25
+ */
26
+ export type RelationFieldSpec = {
27
+ /** Field name on the parent type */
28
+ name: string;
29
+ /** Nexus output type */
30
+ type: unknown;
31
+ args?: AnyRecord;
32
+ resolve: (parent: unknown, args: AnyRecord, context: ResolveContext, info: GraphQLResolveInfo) => unknown;
33
+ /** `Type.field` paths Strapi protects with the `<target>.find` permission scope */
34
+ resolverConfigPaths: string[];
35
+ };
36
+ /**
37
+ * Describes the GraphQL field(s) Strapi itself generates for a relation or media attribute, so we can
38
+ * (re)define them with exactly the same type, arguments, resolver and permission scope.
39
+ *
40
+ * - v4: to-one → `XEntityResponse`, to-many → `XRelationResponseCollection` (with filters/pagination args).
41
+ * - v5: to-one → `X` (unwrapped), to-many → `[X]!` (unwrapped `nodes`) **and** `<field>_connection`
42
+ * returning `XRelationResponseCollection`.
43
+ *
44
+ * Media (`type: 'media'`) resolves against `plugin::upload.file`; Strapi generates the same fields as
45
+ * for a relation, with `multiple` deciding the to-one/to-many shape.
46
+ *
47
+ * All variants use Strapi's own `buildAssociationResolver`, so query validation, output sanitizing and
48
+ * draft/publish handling stay identical to the generated field.
49
+ *
50
+ * Low-level building block for {@link FieldExtensionBuilder.relation} and `overrideField`; prefer those.
51
+ *
52
+ * @param resolveOverride - Replaces Strapi's association resolver. It must return Strapi's response
53
+ * wrapper (`{ value }` / `{ nodes }`); v5 unwrapping is applied on top.
54
+ * @throws Error when the content type is unknown or the attribute is not a relation or media attribute.
55
+ */
56
+ export declare const relationFieldSpecs: (contentTypeUID: string, attributeName: string, resolveOverride?: RelationFieldSpec['resolve']) => RelationFieldSpec[];
57
+ /**
58
+ * Resolver config that applies Strapi's own permission scope (`<target>.find`) to relation fields,
59
+ * exactly like the generated relation fields do. Pass it to an extension's `resolversConfig` when you
60
+ * define relation fields yourself.
61
+ *
62
+ * Media fields get no scope, because Strapi does not attach one to the media fields it generates.
63
+ *
64
+ * @returns A map of `Type.field` paths to `{ auth: { scope } }`, or `{}` for media.
65
+ */
66
+ export declare const relationResolversConfig: (contentTypeUID: string, attributeName: string) => {
67
+ [k: string]: {
68
+ auth: {
69
+ scope: string[];
70
+ };
71
+ };
72
+ };
73
+ /**
74
+ * Sanitize raw database output for the content API (removes private/password fields and fields the
75
+ * current auth may not read). v4: `@strapi/utils` sanitize, v5: `strapi.contentAPI.sanitize`.
76
+ *
77
+ * Use it on data from {@link loaders} or `strapi.db.query()` before returning it from a resolver.
78
+ *
79
+ * @param uid - Content type of `data`.
80
+ * @param context - The resolver context; its `state.auth` decides what may be read.
81
+ */
82
+ export declare const sanitizeOutput: <T>(data: T, uid: string, context: ResolveContext) => Promise<T>;
83
+ /**
84
+ * Wrap a single entity the way the given relation field expects: an entity response in v4, the bare
85
+ * entity in v5.
86
+ *
87
+ * @param targetUID - Content type of `entity`.
88
+ */
89
+ export declare const toRelationValue: (entity: unknown, targetUID: string) => unknown;
90
+ export {};
@@ -0,0 +1,203 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.toRelationValue = exports.sanitizeOutput = exports.relationResolversConfig = exports.relationFieldSpecs = exports.resetTypeNameCache = exports.uidOfTypeName = exports.typeNameOf = exports.isV4CompatibilityMode = exports.isStrapiV5 = void 0;
4
+ /**
5
+ * Small compatibility layer over the parts of `@strapi/plugin-graphql` that differ between Strapi v4 and v5.
6
+ *
7
+ * Everything that needs to know "which Strapi is this?" should go through here, so the rest of the
8
+ * package can stay version-agnostic.
9
+ */
10
+ const nexus_1 = require("nexus");
11
+ const getGraphQLService = (name) => strapi.plugin('graphql').service(name);
12
+ /**
13
+ * True when running on Strapi v5. The document service (`strapi.documents`) only exists in v5.
14
+ */
15
+ const isStrapiV5 = () => typeof strapi.documents === 'function';
16
+ exports.isStrapiV5 = isStrapiV5;
17
+ /**
18
+ * Whether the GraphQL plugin runs in v4 compatibility mode (only relevant on v5).
19
+ */
20
+ const isV4CompatibilityMode = () => (0, exports.isStrapiV5)() && Boolean(strapi.plugin('graphql').config('v4CompatibilityMode', false));
21
+ exports.isV4CompatibilityMode = isV4CompatibilityMode;
22
+ const getModel = (uid) => {
23
+ const model = strapi.getModel(uid);
24
+ if (!model) {
25
+ throw new Error(`[buro26-strapi-graphql] Unknown content type "${uid}"`);
26
+ }
27
+ return model;
28
+ };
29
+ /**
30
+ * GraphQL object type name Strapi generates for a content type, e.g. `api::customer.customer` → `Customer`.
31
+ */
32
+ const typeNameOf = (uid) => getGraphQLService('utils').naming.getTypeName(getModel(uid));
33
+ exports.typeNameOf = typeNameOf;
34
+ let typeNameToUidCache = null;
35
+ /**
36
+ * Reverse lookup of {@link typeNameOf}: the content type UID behind a generated GraphQL type name.
37
+ * Built lazily (content types do not change at runtime).
38
+ */
39
+ const uidOfTypeName = (typeName) => {
40
+ var _a;
41
+ if (!typeNameToUidCache) {
42
+ typeNameToUidCache = new Map();
43
+ const { naming } = getGraphQLService('utils');
44
+ for (const contentType of Object.values((_a = strapi.contentTypes) !== null && _a !== void 0 ? _a : {})) {
45
+ try {
46
+ typeNameToUidCache.set(naming.getTypeName(contentType), contentType.uid);
47
+ }
48
+ catch {
49
+ // Content types that are not exposed in GraphQL can be ignored
50
+ }
51
+ }
52
+ }
53
+ return typeNameToUidCache.get(typeName);
54
+ };
55
+ exports.uidOfTypeName = uidOfTypeName;
56
+ /** @internal Only for tests. */
57
+ const resetTypeNameCache = () => {
58
+ typeNameToUidCache = null;
59
+ };
60
+ exports.resetTypeNameCache = resetTypeNameCache;
61
+ /**
62
+ * Describes the GraphQL field(s) Strapi itself generates for a relation or media attribute, so we can
63
+ * (re)define them with exactly the same type, arguments, resolver and permission scope.
64
+ *
65
+ * - v4: to-one → `XEntityResponse`, to-many → `XRelationResponseCollection` (with filters/pagination args).
66
+ * - v5: to-one → `X` (unwrapped), to-many → `[X]!` (unwrapped `nodes`) **and** `<field>_connection`
67
+ * returning `XRelationResponseCollection`.
68
+ *
69
+ * Media (`type: 'media'`) resolves against `plugin::upload.file`; Strapi generates the same fields as
70
+ * for a relation, with `multiple` deciding the to-one/to-many shape.
71
+ *
72
+ * All variants use Strapi's own `buildAssociationResolver`, so query validation, output sanitizing and
73
+ * draft/publish handling stay identical to the generated field.
74
+ *
75
+ * Low-level building block for {@link FieldExtensionBuilder.relation} and `overrideField`; prefer those.
76
+ *
77
+ * @param resolveOverride - Replaces Strapi's association resolver. It must return Strapi's response
78
+ * wrapper (`{ value }` / `{ nodes }`); v5 unwrapping is applied on top.
79
+ * @throws Error when the content type is unknown or the attribute is not a relation or media attribute.
80
+ */
81
+ const relationFieldSpecs = (contentTypeUID, attributeName, resolveOverride) => {
82
+ var _a;
83
+ const contentType = getModel(contentTypeUID);
84
+ const attribute = (_a = contentType.attributes) === null || _a === void 0 ? void 0 : _a[attributeName];
85
+ const isMedia = (attribute === null || attribute === void 0 ? void 0 : attribute.type) === 'media';
86
+ if (!attribute || (!isMedia && (attribute.type !== 'relation' || !attribute.target))) {
87
+ throw new Error(`[buro26-strapi-graphql] "${contentTypeUID}.${attributeName}" is not a relation or media attribute`);
88
+ }
89
+ const { naming } = getGraphQLService('utils');
90
+ const { getContentTypeArgs } = getGraphQLService('builders').utils;
91
+ const { buildAssociationResolver } = getGraphQLService('builders').get('content-api');
92
+ const targetUID = isMedia ? 'plugin::upload.file' : attribute.target;
93
+ const targetContentType = getModel(targetUID);
94
+ const isToMany = isMedia ? Boolean(attribute.multiple) : String(attribute.relation).endsWith('Many');
95
+ const parentTypeName = naming.getTypeName(contentType);
96
+ const associationResolver = resolveOverride !== null && resolveOverride !== void 0 ? resolveOverride : buildAssociationResolver({ contentTypeUID, attributeName, strapi });
97
+ if (!(0, exports.isStrapiV5)()) {
98
+ return [
99
+ {
100
+ name: attributeName,
101
+ type: isToMany
102
+ ? naming.getRelationResponseCollectionName(targetContentType)
103
+ : naming.getEntityResponseName(targetContentType),
104
+ args: isToMany ? getContentTypeArgs(targetContentType) : undefined,
105
+ resolve: associationResolver,
106
+ resolverConfigPaths: [`${parentTypeName}.${attributeName}`],
107
+ },
108
+ ];
109
+ }
110
+ const typeName = naming.getTypeName(targetContentType);
111
+ if (!isToMany) {
112
+ return [
113
+ {
114
+ name: attributeName,
115
+ type: typeName,
116
+ resolve: async (...resolveArgs) => {
117
+ var _a;
118
+ const response = (await associationResolver(...resolveArgs));
119
+ return (_a = response === null || response === void 0 ? void 0 : response.value) !== null && _a !== void 0 ? _a : null;
120
+ },
121
+ resolverConfigPaths: [`${parentTypeName}.${attributeName}`],
122
+ },
123
+ ];
124
+ }
125
+ const args = getContentTypeArgs(targetContentType, { isNested: true });
126
+ return [
127
+ {
128
+ name: `${attributeName}_connection`,
129
+ type: naming.getRelationResponseCollectionName(targetContentType),
130
+ args,
131
+ resolve: associationResolver,
132
+ resolverConfigPaths: [`${parentTypeName}.${attributeName}_connection`],
133
+ },
134
+ {
135
+ name: attributeName,
136
+ type: (0, nexus_1.nonNull)((0, nexus_1.list)(typeName)),
137
+ args,
138
+ resolve: async (...resolveArgs) => {
139
+ var _a;
140
+ const response = (await associationResolver(...resolveArgs));
141
+ return (_a = response === null || response === void 0 ? void 0 : response.nodes) !== null && _a !== void 0 ? _a : [];
142
+ },
143
+ resolverConfigPaths: [`${parentTypeName}.${attributeName}`],
144
+ },
145
+ ];
146
+ };
147
+ exports.relationFieldSpecs = relationFieldSpecs;
148
+ /**
149
+ * Resolver config that applies Strapi's own permission scope (`<target>.find`) to relation fields,
150
+ * exactly like the generated relation fields do. Pass it to an extension's `resolversConfig` when you
151
+ * define relation fields yourself.
152
+ *
153
+ * Media fields get no scope, because Strapi does not attach one to the media fields it generates.
154
+ *
155
+ * @returns A map of `Type.field` paths to `{ auth: { scope } }`, or `{}` for media.
156
+ */
157
+ const relationResolversConfig = (contentTypeUID, attributeName) => {
158
+ var _a;
159
+ const attribute = (_a = getModel(contentTypeUID).attributes) === null || _a === void 0 ? void 0 : _a[attributeName];
160
+ if ((attribute === null || attribute === void 0 ? void 0 : attribute.type) === 'media')
161
+ return {};
162
+ const scope = [`${attribute.target}.find`];
163
+ return Object.fromEntries((0, exports.relationFieldSpecs)(contentTypeUID, attributeName).flatMap((spec) => spec.resolverConfigPaths.map((path) => [path, { auth: { scope } }])));
164
+ };
165
+ exports.relationResolversConfig = relationResolversConfig;
166
+ /**
167
+ * Sanitize raw database output for the content API (removes private/password fields and fields the
168
+ * current auth may not read). v4: `@strapi/utils` sanitize, v5: `strapi.contentAPI.sanitize`.
169
+ *
170
+ * Use it on data from {@link loaders} or `strapi.db.query()` before returning it from a resolver.
171
+ *
172
+ * @param uid - Content type of `data`.
173
+ * @param context - The resolver context; its `state.auth` decides what may be read.
174
+ */
175
+ const sanitizeOutput = async (data, uid, context) => {
176
+ var _a;
177
+ if (data == null)
178
+ return data;
179
+ const schema = getModel(uid);
180
+ const auth = (_a = context === null || context === void 0 ? void 0 : context.state) === null || _a === void 0 ? void 0 : _a.auth;
181
+ if ((0, exports.isStrapiV5)()) {
182
+ return strapi.contentAPI.sanitize.output(data, schema, { auth });
183
+ }
184
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
185
+ const { sanitize } = require('@strapi/utils');
186
+ return sanitize.contentAPI.output(data, schema, { auth });
187
+ };
188
+ exports.sanitizeOutput = sanitizeOutput;
189
+ /**
190
+ * Wrap a single entity the way the given relation field expects: an entity response in v4, the bare
191
+ * entity in v5.
192
+ *
193
+ * @param targetUID - Content type of `entity`.
194
+ */
195
+ const toRelationValue = (entity, targetUID) => {
196
+ if (entity == null)
197
+ return null;
198
+ if ((0, exports.isStrapiV5)())
199
+ return entity;
200
+ const { toEntityResponse } = getGraphQLService('format').returnTypes;
201
+ return toEntityResponse(entity, { args: {}, resourceUID: targetUID });
202
+ };
203
+ exports.toRelationValue = toRelationValue;
@@ -20,7 +20,31 @@ export type BaseUser = {
20
20
  updatedAt: string;
21
21
  };
22
22
  };
23
- export type ResolveContext<UserType = BaseUser> = {
23
+ /**
24
+ * Project-wide type registration. Augment it once in your project:
25
+ *
26
+ * @example
27
+ * declare module 'buro26-strapi-graphql' {
28
+ * interface Register {
29
+ * user: User
30
+ * // GraphQL type name → entity type, used to type `parent` in `.rootType('Customer')`
31
+ * types: { Customer: Customer; Order: Order }
32
+ * }
33
+ * }
34
+ */
35
+ export interface Register {
36
+ }
37
+ /** The user type registered via {@link Register}, or {@link BaseUser}. */
38
+ export type RegisteredUser = Register extends {
39
+ user: infer U;
40
+ } ? U : BaseUser;
41
+ /** GraphQL type name → entity type map registered via {@link Register}. */
42
+ export type RegisteredTypes = Register extends {
43
+ types: infer T;
44
+ } ? T : {};
45
+ /** Parent type for fields on GraphQL type `N`, when registered. */
46
+ export type ParentOf<N extends string, Fallback = any> = N extends keyof RegisteredTypes ? RegisteredTypes[N] : Fallback;
47
+ export type ResolveContext<UserType = RegisteredUser> = {
24
48
  state: {
25
49
  route: {
26
50
  info: {