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,6 +6,7 @@
6
6
  */
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
8
  exports.overrideField = void 0;
9
+ const strapi_compat_1 = require("./strapi-compat");
9
10
  const fp_1 = require("lodash/fp");
10
11
  const utils_1 = require("@strapi/utils");
11
12
  const getGraphQLService = (name) => strapi.plugin('graphql').service(name);
@@ -142,35 +143,27 @@ const addPolymorphicRelationalAttribute = (options) => {
142
143
  }
143
144
  };
144
145
  /**
145
- * Add a regular relational attribute to the type definition
146
+ * Add a regular relational attribute to the type definition.
147
+ *
148
+ * Uses the same field specs as Strapi itself (see `relationFieldSpecs`), so this works for both
149
+ * Strapi v4 (entity response types) and v5 (unwrapped types + `<field>_connection`).
146
150
  */
147
151
  const addRegularRelationalAttribute = (options) => {
148
- const { naming } = getGraphQLService('utils');
149
- const { getContentTypeArgs } = getGraphQLService('builders').utils;
150
- const { buildAssociationResolver } = getGraphQLService('builders').get('content-api');
151
152
  const extension = getGraphQLService('extension');
152
- const { builder } = options;
153
- const { attributeName, attribute, contentType } = options;
153
+ const { builder, attributeName, attribute, contentType, resolve, extensions } = options;
154
+ // @ts-ignore
154
155
  if (extension.shadowCRUD(attribute.target).isDisabled()) {
155
156
  return;
156
157
  }
157
- // @ts-ignore
158
- const isToManyRelation = attribute.relation.endsWith('Many');
159
- const resolve = buildAssociationResolver({
160
- contentTypeUID: contentType.uid,
161
- attributeName,
162
- strapi,
163
- });
164
- // @ts-ignore
165
- const targetContentType = strapi.getModel(attribute.target);
166
- const type = isToManyRelation
167
- ? naming.getRelationResponseCollectionName(targetContentType)
168
- : naming.getEntityResponseName(targetContentType);
169
- const args = isToManyRelation ? getContentTypeArgs(targetContentType) : undefined;
170
- const resolverPath = `${naming.getTypeName(contentType)}.${attributeName}`;
171
- const resolverScope = `${targetContentType.uid}.find`;
172
- extension.use({ resolversConfig: { [resolverPath]: { auth: { scope: [resolverScope] } } } });
173
- builder.field(attributeName, { type, resolve, args, ...options });
158
+ for (const spec of (0, strapi_compat_1.relationFieldSpecs)(contentType.uid, attributeName, resolve)) {
159
+ builder.field(spec.name, {
160
+ type: spec.type,
161
+ args: spec.args,
162
+ resolve: spec.resolve,
163
+ ...(extensions && { extensions }),
164
+ });
165
+ }
166
+ extension.use({ resolversConfig: (0, strapi_compat_1.relationResolversConfig)(contentType.uid, attributeName) });
174
167
  };
175
168
  const isPrivate = (contentType) => (attributeName) => {
176
169
  return utils_1.contentTypes.isPrivateAttribute(contentType, attributeName);
@@ -179,7 +172,29 @@ const isDisabled = (contentType) => (attributeName) => {
179
172
  const extension = getGraphQLService('extension');
180
173
  return !extension.shadowCRUD(contentType.uid).field(attributeName).hasOutputEnabled();
181
174
  };
175
+ /**
176
+ * Redefine a field Strapi generates for a content type attribute, inside a Nexus `extendType`, with the
177
+ * same type, arguments and resolver as Strapi uses (v4 and v5), plus your own `authorize`, `resolve` or
178
+ * middlewares.
179
+ *
180
+ * Private attributes and attributes disabled for output via shadow CRUD are skipped.
181
+ *
182
+ * @param t - The Nexus definition block (`definition(t)`).
183
+ * @throws Error when the attribute does not exist on the content type.
184
+ *
185
+ * @remarks To only restrict access use {@link protectFields}; for relations prefer
186
+ * {@link FieldExtensionBuilder.relation}. Both work without an extension and without redefining fields.
187
+ *
188
+ * @example
189
+ * extendType({
190
+ * type: 'Article',
191
+ * definition(t) {
192
+ * overrideField(t, { contentTypeName: ARTICLE, fieldName: 'titel', resolve: (plan) => plan.titel ?? '' })
193
+ * },
194
+ * })
195
+ */
182
196
  const overrideField = (t, overrideOptions) => {
197
+ var _a;
183
198
  const utils = getGraphQLService('utils');
184
199
  const { contentTypeName, fieldName } = overrideOptions;
185
200
  const { isStrapiScalar, isComponent, isDynamicZone, isEnumeration, isMedia, isMorphRelation, isRelation, } = utils.attributes;
@@ -187,10 +202,13 @@ const overrideField = (t, overrideOptions) => {
187
202
  const { attributes } = contentType;
188
203
  // @ts-ignore
189
204
  const attribute = attributes[fieldName];
190
- if (isPrivate(contentType)(attribute)) {
205
+ if (!attribute) {
206
+ throw new Error(`[buro26-strapi-graphql] overrideField: "${contentTypeName}.${String(fieldName)}" does not exist`);
207
+ }
208
+ if (isPrivate(contentType)(fieldName)) {
191
209
  return;
192
210
  }
193
- if (isDisabled(contentType)(attribute)) {
211
+ if (isDisabled(contentType)(fieldName)) {
194
212
  return;
195
213
  }
196
214
  // We create a copy of the builder (t) to apply custom
@@ -199,12 +217,22 @@ const overrideField = (t, overrideOptions) => {
199
217
  if (attribute.required) {
200
218
  builder = builder.nonNull;
201
219
  }
220
+ // `authorize` (deprecated, top-level) is only enforced when it ends up in `extensions.authorize`,
221
+ // which is what the package's Nexus authorize plugin reads.
222
+ const { authorize, extensions, resolve, type, contentTypeName: _ct, fieldName: _fn, ...rest } = overrideOptions;
223
+ const authorizeFn = (_a = extensions === null || extensions === void 0 ? void 0 : extensions.authorize) !== null && _a !== void 0 ? _a : authorize;
202
224
  const options = {
225
+ ...rest,
203
226
  builder,
204
227
  attributeName: fieldName,
205
228
  attribute,
206
229
  contentType,
207
- ...overrideOptions,
230
+ ...(type && { type }),
231
+ ...(resolve && { resolve }),
232
+ extensions: {
233
+ ...extensions,
234
+ ...(authorizeFn && { authorize: authorizeFn }),
235
+ },
208
236
  };
209
237
  // Enums
210
238
  if (isEnumeration(attribute)) {
@@ -0,0 +1,43 @@
1
+ import type { ResolverFunction } from '../../types';
2
+ import type { Middleware } from '../../nexus';
3
+ /**
4
+ * Returned by {@link protectFields}; add checks and middlewares. Mutates the registration, so calls
5
+ * can be chained or made later on the same builder.
6
+ */
7
+ export interface FieldProtectionBuilder<T = any> {
8
+ /**
9
+ * Add an authorization check. Runs after global and field checks; all must return `true`.
10
+ * Return `false` for "Not authorized" or an `Error` to send that error.
11
+ */
12
+ authorize(fn: ResolverFunction<T>): FieldProtectionBuilder<T>;
13
+ /** Add a middleware that wraps the field resolver (innermost, after global and field middlewares). */
14
+ middleware(fn: Middleware<T>): FieldProtectionBuilder<T>;
15
+ }
16
+ /**
17
+ * Protect fields of a content type, including the fields Strapi generates (scalars, enums, media,
18
+ * components and relations), without redefining them.
19
+ *
20
+ * The authorization and middleware are attached by the package's Nexus plugins when the schema is built,
21
+ * so Strapi's own types, arguments, filters, pagination and resolvers stay untouched. For to-many relations
22
+ * on Strapi v5 the matching `<field>_connection` field is protected as well.
23
+ *
24
+ * Call it at module level in a file inside a `graphql` folder; the file does not need to export anything.
25
+ *
26
+ * **Non-null fields:** when a check denies a non-null field, GraphQL nulls the nearest nullable parent
27
+ * instead of only the field (standard GraphQL error propagation). Strapi generates required attributes and,
28
+ * on v5, to-many relations (`[X]!`) as non-null; a warning is logged for those. Protect the
29
+ * `<field>_connection` field only, or check access in the parent query, when that is not acceptable.
30
+ * Several `protectFields` calls for the same field are combined.
31
+ *
32
+ * @typeParam T - Entity type, so `fields` is checked against its keys.
33
+ * @param contentType - Content type UID, e.g. `api::customer.customer`.
34
+ * @param fields - Attribute names to protect.
35
+ * @returns A {@link FieldProtectionBuilder} to add checks and middlewares.
36
+ *
37
+ * @example
38
+ * protectFields<Customer>('api::customer.customer', ['street', 'iban', 'orders'])
39
+ * .authorize((customer, _args, ctx) => isOwner(customer, ctx.state.user))
40
+ *
41
+ * @see {@link FieldExtensionBuilder.relation} to redefine a relation instead.
42
+ */
43
+ export declare function protectFields<T = any>(contentType: string, fields: ReadonlyArray<keyof T & string>): FieldProtectionBuilder<T>;
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resetFieldProtections = exports.getFieldProtections = exports.protectFields = void 0;
4
+ const protections = [];
5
+ /**
6
+ * Protect fields of a content type, including the fields Strapi generates (scalars, enums, media,
7
+ * components and relations), without redefining them.
8
+ *
9
+ * The authorization and middleware are attached by the package's Nexus plugins when the schema is built,
10
+ * so Strapi's own types, arguments, filters, pagination and resolvers stay untouched. For to-many relations
11
+ * on Strapi v5 the matching `<field>_connection` field is protected as well.
12
+ *
13
+ * Call it at module level in a file inside a `graphql` folder; the file does not need to export anything.
14
+ *
15
+ * **Non-null fields:** when a check denies a non-null field, GraphQL nulls the nearest nullable parent
16
+ * instead of only the field (standard GraphQL error propagation). Strapi generates required attributes and,
17
+ * on v5, to-many relations (`[X]!`) as non-null; a warning is logged for those. Protect the
18
+ * `<field>_connection` field only, or check access in the parent query, when that is not acceptable.
19
+ * Several `protectFields` calls for the same field are combined.
20
+ *
21
+ * @typeParam T - Entity type, so `fields` is checked against its keys.
22
+ * @param contentType - Content type UID, e.g. `api::customer.customer`.
23
+ * @param fields - Attribute names to protect.
24
+ * @returns A {@link FieldProtectionBuilder} to add checks and middlewares.
25
+ *
26
+ * @example
27
+ * protectFields<Customer>('api::customer.customer', ['street', 'iban', 'orders'])
28
+ * .authorize((customer, _args, ctx) => isOwner(customer, ctx.state.user))
29
+ *
30
+ * @see {@link FieldExtensionBuilder.relation} to redefine a relation instead.
31
+ */
32
+ function protectFields(contentType, fields) {
33
+ const protection = { contentType, fields: [...fields], authorizes: [], middlewares: [] };
34
+ protections.push(protection);
35
+ const builder = {
36
+ authorize(fn) {
37
+ protection.authorizes.push(fn);
38
+ return builder;
39
+ },
40
+ middleware(fn) {
41
+ protection.middlewares.push(fn);
42
+ return builder;
43
+ },
44
+ };
45
+ return builder;
46
+ }
47
+ exports.protectFields = protectFields;
48
+ const stripConnectionSuffix = (fieldName) => fieldName.replace(/_connection$/, '');
49
+ /**
50
+ * All protections that apply to `contentType.fieldName` (also matches `<field>_connection`).
51
+ *
52
+ * @internal Used by the Nexus plugins.
53
+ */
54
+ function getFieldProtections(contentType, fieldName) {
55
+ if (!contentType)
56
+ return [];
57
+ const baseName = stripConnectionSuffix(fieldName);
58
+ return protections.filter((p) => p.contentType === contentType && p.fields.includes(baseName));
59
+ }
60
+ exports.getFieldProtections = getFieldProtections;
61
+ /** @internal Only for tests. */
62
+ function resetFieldProtections() {
63
+ protections.length = 0;
64
+ }
65
+ exports.resetFieldProtections = resetFieldProtections;
@@ -1,19 +1,74 @@
1
1
  import type { ResolverFunction } from '../../types';
2
2
  import type { Middleware } from '../../nexus';
3
- export type FieldMatcher = (info: {
3
+ /**
4
+ * Information about a field, passed to matchers of global middleware/authorization.
5
+ *
6
+ * Matchers are evaluated when the GraphQL schema is built (not when a field builder is built), so
7
+ * registration order no longer matters.
8
+ */
9
+ export type FieldMatcherInfo = {
10
+ /** GraphQL parent type name, e.g. `Query` or `Customer` */
4
11
  type: string;
5
12
  fieldName: string;
13
+ /** Tags set via the field builder (`.tag()`); empty for fields not created by the builder */
6
14
  tags: string[];
7
- }) => boolean;
8
- export declare function registerGlobalMiddleware(matcher: FieldMatcher, middleware: Middleware): void;
9
- export declare function registerGlobalAuthorize(matcher: FieldMatcher, authorize: ResolverFunction): void;
10
- export declare function getGlobalMiddlewares(info: {
11
- type: string;
12
- fieldName: string;
13
- tags: string[];
14
- }): Middleware[];
15
- export declare function getGlobalAuthorizes(info: {
16
- type: string;
17
- fieldName: string;
18
- tags: string[];
19
- }): ResolverFunction[];
15
+ /** Content type UID when the parent type is a Strapi content type, e.g. `api::customer.customer` */
16
+ contentType?: string;
17
+ /** True when the field was created with `createGraphQLFieldBuilder()` */
18
+ isBuilderField: boolean;
19
+ };
20
+ /**
21
+ * Decides whether a global middleware/authorization applies to a field. Called once per field when the
22
+ * schema is built, not per request.
23
+ */
24
+ export type FieldMatcher = (info: FieldMatcherInfo) => boolean;
25
+ /**
26
+ * Options for {@link registerGlobalAuthorize} and {@link registerGlobalMiddleware}.
27
+ */
28
+ export type GlobalRegistrationOptions = {
29
+ /**
30
+ * Also apply to fields not created by the field builder: Strapi's generated fields, `overrideField`
31
+ * and plain Nexus fields. Matchers then run for **every** field in the schema, so keep them cheap and
32
+ * specific (use `contentType`, `type` or `fieldName`).
33
+ *
34
+ * @default false
35
+ */
36
+ includeNonBuilderFields?: boolean;
37
+ };
38
+ /**
39
+ * Register a middleware for all fields that match. Global middlewares wrap field middlewares (they run
40
+ * first). Matched when the schema is built, so registration order relative to fields does not matter;
41
+ * register before Strapi's bootstrap (i.e. at module level in a `graphql` folder).
42
+ *
43
+ * **Runs once per resolved field, not once per request.** A query that resolves 50 fields runs the
44
+ * middleware 50 times. Per-request concerns such as rate limiting or request logging belong in a
45
+ * Koa/Strapi middleware, not here.
46
+ *
47
+ * @param matcher - Decides per field; see {@link FieldMatcherInfo}.
48
+ * @param middleware - `(next) => resolver`, as in `.middleware()`.
49
+ * @param options - See {@link GlobalRegistrationOptions}.
50
+ *
51
+ * @example
52
+ * registerGlobalMiddleware(({ tags }) => tags.includes('audit'), auditLog)
53
+ */
54
+ export declare function registerGlobalMiddleware(matcher: FieldMatcher, middleware: Middleware, options?: GlobalRegistrationOptions): void;
55
+ /**
56
+ * Register an authorization check for all fields that match. Global checks run before the field's own
57
+ * checks; all must return `true`. Matched when the schema is built, so registration order does not matter.
58
+ *
59
+ * **Runs once per resolved field, not once per request.** A query that resolves 50 fields runs the
60
+ * check 50 times, so a per-field check must stay cheap and free of per-request side effects. Rate
61
+ * limiting and similar per-request concerns belong in a Koa/Strapi middleware, not here.
62
+ *
63
+ * @param matcher - Decides per field; see {@link FieldMatcherInfo}.
64
+ * @param authorize - Return `true` to allow, `false` or an `Error` to deny.
65
+ * @param options - See {@link GlobalRegistrationOptions}.
66
+ *
67
+ * @example
68
+ * // Require a paid subscription for every customer field
69
+ * registerGlobalAuthorize(
70
+ * ({ contentType }) => contentType === 'api::customer.customer',
71
+ * (_parent, _args, ctx) => Boolean(ctx.state.user?.subscription)
72
+ * )
73
+ */
74
+ export declare function registerGlobalAuthorize(matcher: FieldMatcher, authorize: ResolverFunction, options?: GlobalRegistrationOptions): void;
@@ -1,21 +1,67 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getGlobalAuthorizes = exports.getGlobalMiddlewares = exports.registerGlobalAuthorize = exports.registerGlobalMiddleware = void 0;
3
+ exports.resetGlobalRegistry = exports.getGlobalAuthorizes = exports.getGlobalMiddlewares = exports.registerGlobalAuthorize = exports.registerGlobalMiddleware = void 0;
4
4
  const globalMiddlewares = [];
5
5
  const globalAuthorizes = [];
6
- function registerGlobalMiddleware(matcher, middleware) {
7
- globalMiddlewares.push({ matcher, middleware });
6
+ /**
7
+ * Register a middleware for all fields that match. Global middlewares wrap field middlewares (they run
8
+ * first). Matched when the schema is built, so registration order relative to fields does not matter;
9
+ * register before Strapi's bootstrap (i.e. at module level in a `graphql` folder).
10
+ *
11
+ * **Runs once per resolved field, not once per request.** A query that resolves 50 fields runs the
12
+ * middleware 50 times. Per-request concerns such as rate limiting or request logging belong in a
13
+ * Koa/Strapi middleware, not here.
14
+ *
15
+ * @param matcher - Decides per field; see {@link FieldMatcherInfo}.
16
+ * @param middleware - `(next) => resolver`, as in `.middleware()`.
17
+ * @param options - See {@link GlobalRegistrationOptions}.
18
+ *
19
+ * @example
20
+ * registerGlobalMiddleware(({ tags }) => tags.includes('audit'), auditLog)
21
+ */
22
+ function registerGlobalMiddleware(matcher, middleware, options = {}) {
23
+ globalMiddlewares.push({ matcher, value: middleware, options });
8
24
  }
9
25
  exports.registerGlobalMiddleware = registerGlobalMiddleware;
10
- function registerGlobalAuthorize(matcher, authorize) {
11
- globalAuthorizes.push({ matcher, authorize });
26
+ /**
27
+ * Register an authorization check for all fields that match. Global checks run before the field's own
28
+ * checks; all must return `true`. Matched when the schema is built, so registration order does not matter.
29
+ *
30
+ * **Runs once per resolved field, not once per request.** A query that resolves 50 fields runs the
31
+ * check 50 times, so a per-field check must stay cheap and free of per-request side effects. Rate
32
+ * limiting and similar per-request concerns belong in a Koa/Strapi middleware, not here.
33
+ *
34
+ * @param matcher - Decides per field; see {@link FieldMatcherInfo}.
35
+ * @param authorize - Return `true` to allow, `false` or an `Error` to deny.
36
+ * @param options - See {@link GlobalRegistrationOptions}.
37
+ *
38
+ * @example
39
+ * // Require a paid subscription for every customer field
40
+ * registerGlobalAuthorize(
41
+ * ({ contentType }) => contentType === 'api::customer.customer',
42
+ * (_parent, _args, ctx) => Boolean(ctx.state.user?.subscription)
43
+ * )
44
+ */
45
+ function registerGlobalAuthorize(matcher, authorize, options = {}) {
46
+ globalAuthorizes.push({ matcher, value: authorize, options });
12
47
  }
13
48
  exports.registerGlobalAuthorize = registerGlobalAuthorize;
49
+ const matching = (entries, info) => entries
50
+ .filter(({ matcher, options }) => (info.isBuilderField || options.includeNonBuilderFields) && matcher(info))
51
+ .map(({ value }) => value);
52
+ /** @internal Used by the Nexus plugins. */
14
53
  function getGlobalMiddlewares(info) {
15
- return globalMiddlewares.filter(({ matcher }) => matcher(info)).map(({ middleware }) => middleware);
54
+ return matching(globalMiddlewares, info);
16
55
  }
17
56
  exports.getGlobalMiddlewares = getGlobalMiddlewares;
57
+ /** @internal Used by the Nexus plugins. */
18
58
  function getGlobalAuthorizes(info) {
19
- return globalAuthorizes.filter(({ matcher }) => matcher(info)).map(({ authorize }) => authorize);
59
+ return matching(globalAuthorizes, info);
20
60
  }
21
61
  exports.getGlobalAuthorizes = getGlobalAuthorizes;
62
+ /** @internal Only for tests. */
63
+ function resetGlobalRegistry() {
64
+ globalMiddlewares.length = 0;
65
+ globalAuthorizes.length = 0;
66
+ }
67
+ exports.resetGlobalRegistry = resetGlobalRegistry;
@@ -1 +1,3 @@
1
1
  export * from './global-registry';
2
+ export * from './field-protection';
3
+ export * from './resolve-field';
@@ -15,3 +15,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./global-registry"), exports);
18
+ __exportStar(require("./field-protection"), exports);
19
+ __exportStar(require("./resolve-field"), exports);
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveFieldPipeline = void 0;
4
+ const strapi_compat_1 = require("../strapi-compat");
5
+ const global_registry_1 = require("./global-registry");
6
+ const field_protection_1 = require("./field-protection");
7
+ /**
8
+ * `authorize`/`middlewares` can be set in `extensions` or as top-level Nexus field options
9
+ * (`t.field('x', { authorize })`, as declared in the plugins' typegen). Both are honoured.
10
+ */
11
+ const ownAuthorize = (extensions) => {
12
+ var _a, _b, _c;
13
+ const candidate = (_a = extensions === null || extensions === void 0 ? void 0 : extensions.authorize) !== null && _a !== void 0 ? _a : (_c = (_b = extensions === null || extensions === void 0 ? void 0 : extensions.nexus) === null || _b === void 0 ? void 0 : _b.config) === null || _c === void 0 ? void 0 : _c.authorize;
14
+ return typeof candidate === 'function' ? candidate : undefined;
15
+ };
16
+ const ownMiddlewares = (extensions) => {
17
+ var _a, _b, _c;
18
+ const candidate = (_a = extensions === null || extensions === void 0 ? void 0 : extensions.middlewares) !== null && _a !== void 0 ? _a : (_c = (_b = extensions === null || extensions === void 0 ? void 0 : extensions.nexus) === null || _b === void 0 ? void 0 : _b.config) === null || _c === void 0 ? void 0 : _c.middlewares;
19
+ return Array.isArray(candidate) ? candidate : [];
20
+ };
21
+ const contentTypeOf = (typeName) => {
22
+ try {
23
+ return (0, strapi_compat_1.uidOfTypeName)(typeName);
24
+ }
25
+ catch {
26
+ // Strapi/graphql plugin not available (e.g. in unit tests)
27
+ return undefined;
28
+ }
29
+ };
30
+ /**
31
+ * Everything that must run around a field resolver, in order:
32
+ *
33
+ * 1. authentication (`withAuth(true)` on builder fields)
34
+ * 2. authorization: global authorizes → the field's own `authorize` → `protectFields` authorizes
35
+ * 3. middlewares: global middlewares (outermost) → the field's own → `protectFields` middlewares
36
+ *
37
+ * Evaluated once per field when the schema is built.
38
+ *
39
+ * @internal Used by the Nexus plugins and `.test()`.
40
+ */
41
+ function resolveFieldPipeline(typeName, fieldName, extensions) {
42
+ var _a, _b, _c;
43
+ const contentType = contentTypeOf(typeName);
44
+ const info = {
45
+ type: typeName,
46
+ fieldName,
47
+ tags: (_b = (_a = extensions === null || extensions === void 0 ? void 0 : extensions.builder) === null || _a === void 0 ? void 0 : _a.tags) !== null && _b !== void 0 ? _b : [],
48
+ contentType,
49
+ isBuilderField: Boolean(extensions === null || extensions === void 0 ? void 0 : extensions.builder),
50
+ };
51
+ const protections = (0, field_protection_1.getFieldProtections)(contentType, fieldName);
52
+ return {
53
+ requireAuth: Boolean((_c = extensions === null || extensions === void 0 ? void 0 : extensions.builder) === null || _c === void 0 ? void 0 : _c.requireAuth),
54
+ isProtected: protections.length > 0,
55
+ authorizes: [
56
+ ...(0, global_registry_1.getGlobalAuthorizes)(info),
57
+ ...(ownAuthorize(extensions) ? [ownAuthorize(extensions)] : []),
58
+ ...protections.flatMap((p) => p.authorizes),
59
+ ],
60
+ middlewares: [
61
+ ...(0, global_registry_1.getGlobalMiddlewares)(info),
62
+ ...ownMiddlewares(extensions),
63
+ ...protections.flatMap((p) => p.middlewares),
64
+ ],
65
+ };
66
+ }
67
+ exports.resolveFieldPipeline = resolveFieldPipeline;
@@ -1,3 +1,5 @@
1
+ import type { ResolverFunction } from '../types';
2
+ import type { Middleware } from '../nexus';
1
3
  type Action = 'create' | 'update' | 'delete' | 'findOne' | 'find';
2
4
  interface FieldOperations<T> {
3
5
  disable(): this;
@@ -9,6 +11,16 @@ interface FieldOperations<T> {
9
11
  hasInputEnabled(): boolean;
10
12
  hasOutputEnabled(): boolean;
11
13
  hasFiltersEnabled(): boolean;
14
+ /**
15
+ * Add an authorization check to the generated output field. Same as
16
+ * `protectFields(uid, [field]).authorize(fn)`; see {@link protectFields}.
17
+ */
18
+ authorize(fn: ResolverFunction<T>): this;
19
+ /**
20
+ * Add a middleware to the generated output field. Same as
21
+ * `protectFields(uid, [field]).middleware(fn)`; see {@link protectFields}.
22
+ */
23
+ middleware(fn: Middleware<T>): this;
12
24
  }
13
25
  interface ShadowCRUD<T> {
14
26
  disable(): this;
@@ -16,7 +28,8 @@ interface ShadowCRUD<T> {
16
28
  disableAction(action: Action): this;
17
29
  disableQueries(): this;
18
30
  disableMutations(): this;
19
- field<K extends keyof T>(name: K): FieldOperations<T[K]>;
31
+ /** Configure one attribute; the returned object also supports `.authorize()` and `.middleware()`. */
32
+ field<K extends keyof T & string>(name: K): FieldOperations<T>;
20
33
  isEnabled(): boolean;
21
34
  isDisabled(): boolean;
22
35
  areQueriesEnabled(): boolean;
@@ -26,5 +39,19 @@ interface ShadowCRUD<T> {
26
39
  isActionEnabled(action: Action): boolean;
27
40
  isActionDisabled(action: Action): boolean;
28
41
  }
42
+ /**
43
+ * Typed access to Strapi's shadow CRUD configuration: disable generated queries, mutations or fields.
44
+ * Call it in an extension's `init()` or a builder's `.init()`.
45
+ *
46
+ * @typeParam Type - Entity type, so `.field()` only accepts its keys.
47
+ * @param contentTypeUID - Content type UID.
48
+ *
49
+ * @example
50
+ * shadowCRUD<Customer>('api::customer.customer').disableActions(['create', 'update', 'delete'])
51
+ * shadowCRUD<Customer>('api::customer.customer').field('internalNotes').disableFilters()
52
+ * shadowCRUD<Customer>('api::customer.customer').field('iban').authorize(isSelf)
53
+ *
54
+ * @see https://docs.strapi.io/dev-docs/plugins/graphql#shadow-crud
55
+ */
29
56
  export declare const shadowCRUD: <Type extends unknown = null>(contentTypeUID: string) => ShadowCRUD<Type>;
30
57
  export {};
@@ -1,8 +1,39 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.shadowCRUD = void 0;
4
+ const field_protection_1 = require("./registry/field-protection");
5
+ /**
6
+ * Typed access to Strapi's shadow CRUD configuration: disable generated queries, mutations or fields.
7
+ * Call it in an extension's `init()` or a builder's `.init()`.
8
+ *
9
+ * @typeParam Type - Entity type, so `.field()` only accepts its keys.
10
+ * @param contentTypeUID - Content type UID.
11
+ *
12
+ * @example
13
+ * shadowCRUD<Customer>('api::customer.customer').disableActions(['create', 'update', 'delete'])
14
+ * shadowCRUD<Customer>('api::customer.customer').field('internalNotes').disableFilters()
15
+ * shadowCRUD<Customer>('api::customer.customer').field('iban').authorize(isSelf)
16
+ *
17
+ * @see https://docs.strapi.io/dev-docs/plugins/graphql#shadow-crud
18
+ */
4
19
  const shadowCRUD = (contentTypeUID) => {
5
20
  const extensionService = strapi.plugin('graphql').service('extension');
6
- return extensionService.shadowCRUD(contentTypeUID);
21
+ const crud = extensionService.shadowCRUD(contentTypeUID);
22
+ return Object.assign(Object.create(crud), {
23
+ field(name) {
24
+ const fieldOperations = crud.field(name);
25
+ const extended = Object.assign(Object.create(fieldOperations), {
26
+ authorize(fn) {
27
+ (0, field_protection_1.protectFields)(contentTypeUID, [name]).authorize(fn);
28
+ return extended;
29
+ },
30
+ middleware(fn) {
31
+ (0, field_protection_1.protectFields)(contentTypeUID, [name]).middleware(fn);
32
+ return extended;
33
+ },
34
+ });
35
+ return extended;
36
+ },
37
+ });
7
38
  };
8
39
  exports.shadowCRUD = shadowCRUD;
@@ -7,10 +7,29 @@ import { Entity, ResolveArgs } from './types';
7
7
  type ResolveEntityArgs = Omit<ResolveArgs, 'args'> & {
8
8
  args: {
9
9
  id: string;
10
+ } | {
11
+ documentId: string;
10
12
  };
11
13
  };
14
+ /**
15
+ * Resolve a single entity with Strapi's own `findOne` query resolver.
16
+ * On Strapi v5 `args` must contain `documentId` instead of `id`.
17
+ *
18
+ * @throws Error on Strapi v5 when `args.documentId` is missing.
19
+ */
12
20
  export declare function resolveEntity<T extends Object>(contentType: string, resolveArgs: ResolveEntityArgs): Promise<Entity<T> | null>;
13
- export declare const resolveEntityRelation: <T extends Object>(contentType: string, relationFieldName: keyof T, resolveArgs: ResolveArgs) => Promise<Entity<T>[]>;
21
+ /**
22
+ * Resolve a relation with Strapi's own association resolver (validation, sanitizing and draft/publish
23
+ * handling included). Returns Strapi's response wrapper: `{ value, info }` for to-one relations and
24
+ * `{ nodes, info }` for to-many relations. Prefer `.relation()` on the field builder for relation fields.
25
+ */
26
+ export declare const resolveEntityRelation: <T extends Object, R extends Object = any>(contentType: string, relationFieldName: keyof T, resolveArgs: ResolveArgs) => Promise<EntityResponse<R> | {
27
+ nodes: R[];
28
+ info: {
29
+ args: Record<string, any>;
30
+ resourceUID: string;
31
+ };
32
+ }>;
14
33
  type EntityResponse<T extends Object> = {
15
34
  value: Entity<T> | null;
16
35
  info: {
@@ -18,6 +37,16 @@ type EntityResponse<T extends Object> = {
18
37
  resourceUID: string;
19
38
  };
20
39
  };
40
+ /**
41
+ * Wrap an entity in Strapi's entity response (`{ value, info }`), the return shape of `XEntityResponse`
42
+ * fields such as single-entity queries.
43
+ *
44
+ * @param args - The field arguments, used by Strapi when resolving nested fields.
45
+ * @param resourceUID - Content type UID of `item`.
46
+ *
47
+ * @remarks Strapi v5 to-one relation fields expect the bare entity; use {@link toRelationValue} or
48
+ * {@link FieldExtensionBuilder.relation} for relations.
49
+ */
21
50
  export declare function toEntityResponse<T extends Object>(item: T | null, { args, resourceUID }: {
22
51
  args: Record<string, any>;
23
52
  resourceUID: string;