@jskit-ai/crud-core 0.2.13 → 0.2.15
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/CHANGELOG.md +16 -0
- package/locales/en.json +1 -11
- package/package.json +19 -19
- package/patterns/{json-api-resource-package → crud-feature-package}/PATTERN.md +69 -37
- package/patterns/{json-api-resource-package → crud-feature-package}/example/packages/books/package.json +5 -4
- package/patterns/crud-feature-package/example/packages/books/src/server/BooksFeature.js +13 -0
- package/patterns/crud-feature-package/example/packages/books/src/shared/bookResource.js +74 -0
- package/patterns/crud-feature-package/example/packages/books/src/shared/index.js +1 -0
- package/src/server/createHooksToCollectChildren.js +56 -34
- package/src/server/crudContracts.js +54 -0
- package/src/server/defineCrudFeature.js +509 -0
- package/src/server/jsonApiModule/actions.js +44 -30
- package/src/server/jsonApiModule/routes.js +2 -2
- package/src/server/jsonApiModule/service.js +213 -32
- package/src/server/jsonApiResourceContract.js +41 -1
- package/src/server/listQueryValidators.js +1 -1
- package/src/server/removedApi.js +87 -0
- package/src/server/types.js +26 -50
- package/test/assistantActionConformance.test.js +20 -21
- package/test/assistantPagination.integration.test.js +32 -42
- package/test/createHooksToCollectChildren.test.js +61 -16
- package/test/crudFeaturePackagePattern.test.js +50 -0
- package/test/crudOnHandles.test.js +454 -0
- package/test/{defineCrudJsonApiFeature.test.js → defineCrudFeature.test.js} +444 -141
- package/test/errorCodes.test.js +11 -52
- package/test/hiddenFields.test.js +62 -0
- package/test/listQueryValidators.test.js +1 -1
- package/test/routeContracts.test.js +1 -1
- package/test/support/crudJsonApiActionOptions.js +3 -3
- package/test/unservedCrudAutomation.test.js +27 -22
- package/patterns/json-api-resource-package/example/packages/books/src/server/BooksFeature.js +0 -13
- package/patterns/json-api-resource-package/example/packages/books/src/shared/bookResource.js +0 -83
- package/patterns/json-api-resource-package/example/packages/books/src/shared/index.js +0 -1
- package/src/server/createCrudServiceFromResource.js +0 -63
- package/src/server/defineCrudJsonApiFeature.js +0 -346
- package/src/server/fieldAccess.js +0 -298
- package/src/server/jsonApiModule/repository.js +0 -355
- package/src/server/lookupPathSupport.js +0 -58
- package/src/server/lookups.js +0 -40
- package/src/server/repositorySupport.js +0 -528
- package/src/server/resourceRuntime/compiledRuntime.js +0 -284
- package/src/server/resourceRuntime/index.js +0 -659
- package/src/server/resourceRuntime/listControls.js +0 -333
- package/src/server/resourceRuntime/lookupHydration.js +0 -626
- package/src/server/resourceRuntime/operationStages.js +0 -140
- package/src/server/resourceRuntime/recordValidation.js +0 -65
- package/src/server/serviceMethods.js +0 -149
- package/test/createCrudServiceFromResource.test.js +0 -323
- package/test/fieldAccess.test.js +0 -86
- package/test/jsonApiRepository.test.js +0 -333
- package/test/jsonApiRepositoryDataCosts.test.js +0 -183
- package/test/jsonApiRepositoryPageLimits.test.js +0 -158
- package/test/jsonApiRepositoryRowLocks.test.js +0 -137
- package/test/jsonApiResourcePackagePattern.test.js +0 -20
- package/test/lookups.test.js +0 -111
- package/test/repositorySupport.test.js +0 -767
- package/test/resourceRuntime.test.js +0 -1014
- package/test/serviceMethods.test.js +0 -139
- /package/patterns/{json-api-resource-package → crud-feature-package}/example/migrations/20260815000000_books.cjs +0 -0
- /package/patterns/{json-api-resource-package → crud-feature-package}/example/packages/books/src/server/types.js +0 -0
|
@@ -1,346 +0,0 @@
|
|
|
1
|
-
import { toDatabaseDateTimeUtc } from "@jskit-ai/database-runtime/shared";
|
|
2
|
-
import {
|
|
3
|
-
addResourceIfMissing,
|
|
4
|
-
createJsonRestResourceScopeOptions
|
|
5
|
-
} from "@jskit-ai/json-rest-api-core/server/jsonRestApiHost";
|
|
6
|
-
import { defineFeature } from "@jskit-ai/kernel/server/features";
|
|
7
|
-
import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
|
|
8
|
-
import { isWorkspaceRouteVisibility } from "@jskit-ai/kernel/shared/support/visibility";
|
|
9
|
-
import { resolveCrudResourceScopeName } from "@jskit-ai/resource-crud-core/shared/crudLookup";
|
|
10
|
-
import {
|
|
11
|
-
assertCrudOperationName,
|
|
12
|
-
createCrudJsonApiActions,
|
|
13
|
-
normalizeCrudOperationLifecycle
|
|
14
|
-
} from "./jsonApiModule/actions.js";
|
|
15
|
-
import { createCrudJsonApiRepository } from "./jsonApiModule/repository.js";
|
|
16
|
-
import { registerCrudJsonApiRoutes } from "./jsonApiModule/routes.js";
|
|
17
|
-
import { createCrudJsonApiService as createDefaultService } from "./jsonApiModule/service.js";
|
|
18
|
-
|
|
19
|
-
const RESERVED_REQUIREMENT_NAMES = Object.freeze([
|
|
20
|
-
"context",
|
|
21
|
-
"database",
|
|
22
|
-
"http",
|
|
23
|
-
"input",
|
|
24
|
-
"jsonRestApi",
|
|
25
|
-
"repository",
|
|
26
|
-
"resource",
|
|
27
|
-
"result",
|
|
28
|
-
"service",
|
|
29
|
-
"standard",
|
|
30
|
-
"trx"
|
|
31
|
-
]);
|
|
32
|
-
const CRUD_SERVICE_METHOD_BY_OPERATION = Object.freeze({
|
|
33
|
-
list: "queryDocuments",
|
|
34
|
-
view: "getDocumentById",
|
|
35
|
-
create: "createDocument",
|
|
36
|
-
update: "patchDocumentById",
|
|
37
|
-
delete: "deleteDocumentById"
|
|
38
|
-
});
|
|
39
|
-
const CRUD_SERVICE_METHODS = new Set(Object.values(CRUD_SERVICE_METHOD_BY_OPERATION));
|
|
40
|
-
|
|
41
|
-
function normalizeAccess(resource = {}) {
|
|
42
|
-
const access = normalizeText(resource.apiAccess).toLowerCase() || "authenticated";
|
|
43
|
-
if (access !== "authenticated" && access !== "public") {
|
|
44
|
-
throw new TypeError('defineCrudJsonApiFeature resource.apiAccess must be "authenticated" or "public".');
|
|
45
|
-
}
|
|
46
|
-
return access;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
function normalizeScope(scope = {}) {
|
|
50
|
-
if (!scope || typeof scope !== "object" || Array.isArray(scope)) {
|
|
51
|
-
throw new TypeError("defineCrudJsonApiFeature scope must be an object.");
|
|
52
|
-
}
|
|
53
|
-
return Object.freeze({
|
|
54
|
-
routeBase: normalizeText(scope.routeBase) || "/",
|
|
55
|
-
actionInputValidator: scope.actionInputValidator || null,
|
|
56
|
-
routeParamsValidator: scope.routeParamsValidator || null,
|
|
57
|
-
inputKeys: Object.freeze([...new Set(
|
|
58
|
-
(Array.isArray(scope.inputKeys) ? scope.inputKeys : [])
|
|
59
|
-
.map((entry) => normalizeText(entry))
|
|
60
|
-
.filter(Boolean)
|
|
61
|
-
)]),
|
|
62
|
-
// readable-check: allow method-probe - input validation: the scope an application passes may define input()
|
|
63
|
-
input: typeof scope.input === "function" ? scope.input : null
|
|
64
|
-
});
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
function assertWorkspaceScope(scope, ownershipFilter) {
|
|
68
|
-
if (!isWorkspaceRouteVisibility(ownershipFilter)) {
|
|
69
|
-
return;
|
|
70
|
-
}
|
|
71
|
-
const missing = [];
|
|
72
|
-
if (scope.routeBase === "/") missing.push("routeBase");
|
|
73
|
-
if (!scope.actionInputValidator) missing.push("actionInputValidator");
|
|
74
|
-
if (!scope.routeParamsValidator) missing.push("routeParamsValidator");
|
|
75
|
-
if (scope.inputKeys.length < 1) missing.push("inputKeys");
|
|
76
|
-
if (!scope.input) missing.push("input");
|
|
77
|
-
if (missing.length > 0) {
|
|
78
|
-
throw new TypeError(
|
|
79
|
-
`Workspace CRUD feature requires explicit scope ${missing.join(", ")}.`
|
|
80
|
-
);
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
function normalizeFeatureRequirements(requires = {}) {
|
|
85
|
-
if (!requires || typeof requires !== "object" || Array.isArray(requires)) {
|
|
86
|
-
throw new TypeError("defineCrudJsonApiFeature requires must be an object.");
|
|
87
|
-
}
|
|
88
|
-
for (const name of RESERVED_REQUIREMENT_NAMES) {
|
|
89
|
-
if (Object.hasOwn(requires, name)) {
|
|
90
|
-
throw new TypeError(`defineCrudJsonApiFeature requires reserves the local name ${name}.`);
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
return Object.freeze({ ...requires });
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
function operationsFromResource(resource) {
|
|
97
|
-
const operationMap = Object.freeze({
|
|
98
|
-
list: "list",
|
|
99
|
-
view: "view",
|
|
100
|
-
create: "create",
|
|
101
|
-
patch: "update",
|
|
102
|
-
delete: "delete"
|
|
103
|
-
});
|
|
104
|
-
return Object.keys(resource?.operations || {})
|
|
105
|
-
.map((operation) => operationMap[operation])
|
|
106
|
-
.filter(Boolean);
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
function normalizeOperations(operations, resource) {
|
|
110
|
-
const source = operations === undefined ? operationsFromResource(resource) : operations;
|
|
111
|
-
if (!Array.isArray(source) || source.length < 1) {
|
|
112
|
-
throw new TypeError("defineCrudJsonApiFeature operations must be a non-empty array.");
|
|
113
|
-
}
|
|
114
|
-
return Object.freeze([...new Set(source.map((operation) => assertCrudOperationName(operation)))]);
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
/**
|
|
118
|
-
* @param {string} actionName
|
|
119
|
-
* @param {{ access: string, workspaceScoped: boolean, permissions: { namespace: string } & Record<string, unknown> }} policy
|
|
120
|
-
*/
|
|
121
|
-
function resolveActionPermission(actionName, { access, workspaceScoped, permissions }) {
|
|
122
|
-
const normalizedActionName = normalizeText(actionName).toLowerCase();
|
|
123
|
-
if (!normalizedActionName) {
|
|
124
|
-
throw new TypeError("CRUD action name is required.");
|
|
125
|
-
}
|
|
126
|
-
const explicitPermission = permissions[normalizedActionName];
|
|
127
|
-
if (explicitPermission && typeof explicitPermission === "object") {
|
|
128
|
-
return explicitPermission;
|
|
129
|
-
}
|
|
130
|
-
if (typeof explicitPermission === "string" && explicitPermission.trim()) {
|
|
131
|
-
return Object.freeze({
|
|
132
|
-
require: "all",
|
|
133
|
-
permissions: [explicitPermission.trim()]
|
|
134
|
-
});
|
|
135
|
-
}
|
|
136
|
-
if (access === "public") {
|
|
137
|
-
return Object.freeze({ require: "none" });
|
|
138
|
-
}
|
|
139
|
-
if (workspaceScoped) {
|
|
140
|
-
return Object.freeze({
|
|
141
|
-
require: "all",
|
|
142
|
-
permissions: [`crud.${permissions.namespace}.${normalizedActionName}`]
|
|
143
|
-
});
|
|
144
|
-
}
|
|
145
|
-
return Object.freeze({ require: "authenticated" });
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
function projectEnabledServiceOperations(service, operations) {
|
|
149
|
-
const enabledMethods = new Set(operations.map((operation) => CRUD_SERVICE_METHOD_BY_OPERATION[operation]));
|
|
150
|
-
return Object.freeze(Object.fromEntries(
|
|
151
|
-
Object.entries(service).filter(([name]) => !CRUD_SERVICE_METHODS.has(name) || enabledMethods.has(name))
|
|
152
|
-
));
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
/**
|
|
156
|
-
* @param {object} feature
|
|
157
|
-
* @param {import("./types.js").CrudResourceDefinition} feature.resource The CRUD resource definition the feature serves.
|
|
158
|
-
* @param {string} feature.surface The surface whose routes serve it.
|
|
159
|
-
* @param {string} [feature.id] Defaults to `crud.<namespace>`.
|
|
160
|
-
* @param {string} [feature.capability] Defaults to the feature id.
|
|
161
|
-
* @param {string} [feature.ownershipFilter] Defaults to the resource's autofilter, then "public".
|
|
162
|
-
* @param {string} [feature.relativePath] Defaults to the namespace, with dashes.
|
|
163
|
-
* @param {boolean} [feature.internal] True keeps the routes off the HTTP server.
|
|
164
|
-
* @param {boolean} [feature.routes] False registers no HTTP routes. Either way, an action no permission
|
|
165
|
-
* guards is then left off the automation channel, so the assistant cannot run it.
|
|
166
|
-
* @param {object | null} [feature.listFilterQueryValidator]
|
|
167
|
-
* @param {object | null} [feature.searchSchema]
|
|
168
|
-
* @param {object | null} [feature.permissions]
|
|
169
|
-
* @param {import("./types.js").CrudScope} [feature.scope] The route base, validators, input keys and input() of a scoped resource.
|
|
170
|
-
* @param {Record<string, string>} [feature.requires] More capabilities the feature requires, by name.
|
|
171
|
-
* @param {((dependencies: { repository: import("./types.js").CrudRepository, resource: import("./types.js").CrudResourceDefinition } & Record<string, any>) => import("./types.js").CrudRepository | Promise<import("./types.js").CrudRepository>) | null} [feature.decorateRepository]
|
|
172
|
-
* Receives the CRUD repository, the resource, runtime.database, runtime.http, runtime.json-rest-api and the feature's requires.
|
|
173
|
-
* @param {((dependencies: { service: import("./types.js").CrudService, repository: import("./types.js").CrudRepository, resource: import("./types.js").CrudResourceDefinition } & Record<string, any>) => import("./types.js").CrudService | Promise<import("./types.js").CrudService>) | null} [feature.decorateService]
|
|
174
|
-
* Receives the CRUD service, the (decorated) repository, the resource and the feature's requires.
|
|
175
|
-
* @param {import("./types.js").CrudOperationLifecycle} [feature.operationLifecycle]
|
|
176
|
-
* @param {object} [feature.operationInputs]
|
|
177
|
-
* @param {object} [feature.actions] Custom actions, by name.
|
|
178
|
-
* @param {string[]} [feature.operations] Defaults to every operation the resource defines.
|
|
179
|
-
* @param {string} [feature.realtimeAudience] Defaults to "event_scope".
|
|
180
|
-
*/
|
|
181
|
-
function defineCrudJsonApiFeature({
|
|
182
|
-
resource,
|
|
183
|
-
id = "",
|
|
184
|
-
capability = "",
|
|
185
|
-
surface,
|
|
186
|
-
ownershipFilter = "",
|
|
187
|
-
relativePath = "",
|
|
188
|
-
internal = false,
|
|
189
|
-
routes = true,
|
|
190
|
-
listFilterQueryValidator = null,
|
|
191
|
-
searchSchema = null,
|
|
192
|
-
permissions = null,
|
|
193
|
-
scope = {},
|
|
194
|
-
requires = {},
|
|
195
|
-
decorateRepository = null,
|
|
196
|
-
decorateService = null,
|
|
197
|
-
operationLifecycle = {},
|
|
198
|
-
operationInputs = {},
|
|
199
|
-
actions = {},
|
|
200
|
-
operations = undefined,
|
|
201
|
-
realtimeAudience = "event_scope"
|
|
202
|
-
}) {
|
|
203
|
-
if (!resource || typeof resource !== "object" || Array.isArray(resource)) {
|
|
204
|
-
throw new TypeError("defineCrudJsonApiFeature requires resource.");
|
|
205
|
-
}
|
|
206
|
-
const namespace = normalizeText(resource.namespace);
|
|
207
|
-
if (!namespace) {
|
|
208
|
-
throw new TypeError("defineCrudJsonApiFeature requires resource.namespace.");
|
|
209
|
-
}
|
|
210
|
-
const featureId = normalizeText(id) || `crud.${namespace}`;
|
|
211
|
-
const featureCapability = normalizeText(capability) || featureId;
|
|
212
|
-
const normalizedSurface = normalizeText(surface).toLowerCase();
|
|
213
|
-
if (!normalizedSurface) {
|
|
214
|
-
throw new TypeError("defineCrudJsonApiFeature requires surface.");
|
|
215
|
-
}
|
|
216
|
-
const normalizedOwnershipFilter = normalizeText(ownershipFilter || resource.autofilter).toLowerCase() || "public";
|
|
217
|
-
const normalizedRelativePath = normalizeText(relativePath) || `/${namespace.replace(/_/gu, "-")}`;
|
|
218
|
-
const access = normalizeAccess(resource);
|
|
219
|
-
if (access === "public" && normalizedOwnershipFilter !== "public") {
|
|
220
|
-
throw new TypeError('A public CRUD feature requires ownershipFilter "public".');
|
|
221
|
-
}
|
|
222
|
-
const normalizedScope = normalizeScope(scope);
|
|
223
|
-
const featureRequirements = normalizeFeatureRequirements(requires);
|
|
224
|
-
const enabledOperations = normalizeOperations(operations, resource);
|
|
225
|
-
if (typeof routes !== "boolean") {
|
|
226
|
-
throw new TypeError("defineCrudJsonApiFeature routes must be a boolean.");
|
|
227
|
-
}
|
|
228
|
-
if (decorateRepository != null && typeof decorateRepository !== "function") {
|
|
229
|
-
throw new TypeError("defineCrudJsonApiFeature decorateRepository must be a function.");
|
|
230
|
-
}
|
|
231
|
-
if (decorateService != null && typeof decorateService !== "function") {
|
|
232
|
-
throw new TypeError("defineCrudJsonApiFeature decorateService must be a function.");
|
|
233
|
-
}
|
|
234
|
-
const normalizedOperationLifecycle = normalizeCrudOperationLifecycle(operationLifecycle);
|
|
235
|
-
if (!operationInputs || typeof operationInputs !== "object" || Array.isArray(operationInputs)) {
|
|
236
|
-
throw new TypeError("defineCrudJsonApiFeature operationInputs must be an object.");
|
|
237
|
-
}
|
|
238
|
-
if (!actions || typeof actions !== "object" || Array.isArray(actions)) {
|
|
239
|
-
throw new TypeError("defineCrudJsonApiFeature actions must be an object.");
|
|
240
|
-
}
|
|
241
|
-
assertWorkspaceScope(normalizedScope, normalizedOwnershipFilter);
|
|
242
|
-
const workspaceScoped = isWorkspaceRouteVisibility(normalizedOwnershipFilter);
|
|
243
|
-
const resourceScopeName = resolveCrudResourceScopeName(namespace);
|
|
244
|
-
const permissionOptions = permissions && typeof permissions === "object" && !Array.isArray(permissions)
|
|
245
|
-
? { ...permissions, namespace }
|
|
246
|
-
: { namespace };
|
|
247
|
-
|
|
248
|
-
return defineFeature({
|
|
249
|
-
id: featureId,
|
|
250
|
-
domain: "crud",
|
|
251
|
-
requires: {
|
|
252
|
-
database: "runtime.database",
|
|
253
|
-
http: "runtime.http",
|
|
254
|
-
jsonRestApi: "runtime.json-rest-api",
|
|
255
|
-
...featureRequirements
|
|
256
|
-
},
|
|
257
|
-
provides: {
|
|
258
|
-
resourceApi: featureCapability
|
|
259
|
-
},
|
|
260
|
-
async setup({ database, http, jsonRestApi, ...featureDependencies }) {
|
|
261
|
-
await addResourceIfMissing(
|
|
262
|
-
jsonRestApi,
|
|
263
|
-
resourceScopeName,
|
|
264
|
-
createJsonRestResourceScopeOptions(resource, {
|
|
265
|
-
...(searchSchema ? { searchSchema } : {}),
|
|
266
|
-
writeSerializers: { "datetime-utc": toDatabaseDateTimeUtc }
|
|
267
|
-
})
|
|
268
|
-
);
|
|
269
|
-
const defaultRepository = createCrudJsonApiRepository({
|
|
270
|
-
api: jsonRestApi,
|
|
271
|
-
resource,
|
|
272
|
-
resourceScopeName
|
|
273
|
-
});
|
|
274
|
-
const repository = decorateRepository
|
|
275
|
-
? await decorateRepository(Object.freeze({
|
|
276
|
-
repository: defaultRepository,
|
|
277
|
-
resource,
|
|
278
|
-
database,
|
|
279
|
-
http,
|
|
280
|
-
jsonRestApi,
|
|
281
|
-
...featureDependencies
|
|
282
|
-
}))
|
|
283
|
-
: defaultRepository;
|
|
284
|
-
const defaultService = createDefaultService({ repository });
|
|
285
|
-
const decoratedService = decorateService
|
|
286
|
-
? await decorateService(Object.freeze({
|
|
287
|
-
service: defaultService,
|
|
288
|
-
repository,
|
|
289
|
-
resource,
|
|
290
|
-
...featureDependencies
|
|
291
|
-
}))
|
|
292
|
-
: defaultService;
|
|
293
|
-
const service = projectEnabledServiceOperations(decoratedService, enabledOperations);
|
|
294
|
-
if (routes) {
|
|
295
|
-
registerCrudJsonApiRoutes(http.router, {
|
|
296
|
-
namespace,
|
|
297
|
-
resource,
|
|
298
|
-
routeBase: normalizedScope.routeBase,
|
|
299
|
-
relativePath: normalizedRelativePath,
|
|
300
|
-
surface: normalizedSurface,
|
|
301
|
-
ownershipFilter: normalizedOwnershipFilter,
|
|
302
|
-
access,
|
|
303
|
-
internal,
|
|
304
|
-
operations: enabledOperations,
|
|
305
|
-
actions,
|
|
306
|
-
listFilterQueryValidator,
|
|
307
|
-
operationInputs,
|
|
308
|
-
routeParamsValidator: normalizedScope.routeParamsValidator,
|
|
309
|
-
scopeInput: normalizedScope.input
|
|
310
|
-
});
|
|
311
|
-
}
|
|
312
|
-
return {
|
|
313
|
-
resourceApi: Object.freeze({ repository, resource, service })
|
|
314
|
-
};
|
|
315
|
-
},
|
|
316
|
-
actions({ resourceApi, ...required }) {
|
|
317
|
-
const actionDependencies = Object.freeze(Object.fromEntries(
|
|
318
|
-
Object.keys(featureRequirements).map((name) => [name, required[name]])
|
|
319
|
-
));
|
|
320
|
-
return createCrudJsonApiActions({
|
|
321
|
-
namespace,
|
|
322
|
-
resource,
|
|
323
|
-
repository: resourceApi.repository,
|
|
324
|
-
service: resourceApi.service,
|
|
325
|
-
surface: normalizedSurface,
|
|
326
|
-
operations: enabledOperations,
|
|
327
|
-
listFilterQueryValidator,
|
|
328
|
-
operationLifecycle: normalizedOperationLifecycle,
|
|
329
|
-
operationInputs,
|
|
330
|
-
actions,
|
|
331
|
-
dependencies: actionDependencies,
|
|
332
|
-
permissionForOperation: (operation) => resolveActionPermission(operation, {
|
|
333
|
-
access,
|
|
334
|
-
workspaceScoped,
|
|
335
|
-
permissions: permissionOptions
|
|
336
|
-
}),
|
|
337
|
-
scopeInputValidator: normalizedScope.actionInputValidator,
|
|
338
|
-
scopeInputKeys: normalizedScope.inputKeys,
|
|
339
|
-
realtimeAudience,
|
|
340
|
-
servedOverHttp: routes && !internal
|
|
341
|
-
});
|
|
342
|
-
}
|
|
343
|
-
});
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
export { defineCrudJsonApiFeature };
|
|
@@ -1,298 +0,0 @@
|
|
|
1
|
-
import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
|
|
2
|
-
import { resolveCrudFieldSchemaProperties } from "@jskit-ai/resource-crud-core/shared/crudFieldContract";
|
|
3
|
-
import { isRecord, normalizeObject, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
|
|
4
|
-
import { normalizeObjectInput } from "@jskit-ai/kernel/shared/validators/inputNormalization";
|
|
5
|
-
|
|
6
|
-
function normalizeFieldSet(value, { context = "crudFieldAccess", label = "field list" } = {}) {
|
|
7
|
-
if (value == null || value === "*") {
|
|
8
|
-
return null;
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
const rawValues = value instanceof Set
|
|
12
|
-
? [...value]
|
|
13
|
-
: Array.isArray(value)
|
|
14
|
-
? value
|
|
15
|
-
: null;
|
|
16
|
-
if (!rawValues) {
|
|
17
|
-
throw new TypeError(`${context} ${label} must be an array, set, or "*".`);
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
const normalizedKeys = rawValues
|
|
21
|
-
.map((entry) => normalizeText(entry))
|
|
22
|
-
.filter(Boolean);
|
|
23
|
-
|
|
24
|
-
return new Set(normalizedKeys);
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
async function resolveFieldSet(resolver, input = {}, { context = "crudFieldAccess", label = "field list" } = {}) {
|
|
28
|
-
if (resolver == null) {
|
|
29
|
-
return null;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
const resolvedValue = typeof resolver === "function"
|
|
33
|
-
? await resolver(input)
|
|
34
|
-
: resolver;
|
|
35
|
-
|
|
36
|
-
return normalizeFieldSet(resolvedValue, { context, label });
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
function resolveWriteMode(fieldAccess = {}, { context = "crudFieldAccess" } = {}) {
|
|
40
|
-
const writeMode = normalizeText(fieldAccess.writeMode || "throw").toLowerCase();
|
|
41
|
-
if (writeMode === "throw" || writeMode === "strip") {
|
|
42
|
-
return writeMode;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
throw new TypeError(`${context} fieldAccess.writeMode must be "throw" or "strip".`);
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
function buildOutputFieldRules(resource) {
|
|
49
|
-
const outputProperties = resolveCrudFieldSchemaProperties(resource?.operations?.view?.output, {
|
|
50
|
-
context: "crudFieldAccess resource.operations.view.output"
|
|
51
|
-
});
|
|
52
|
-
if (Object.keys(outputProperties).length < 1) {
|
|
53
|
-
return null;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
const fieldRules = new Map();
|
|
57
|
-
|
|
58
|
-
for (const [fieldKey, fieldSchemaRaw] of Object.entries(outputProperties)) {
|
|
59
|
-
const normalizedFieldKey = normalizeText(fieldKey);
|
|
60
|
-
if (!normalizedFieldKey) {
|
|
61
|
-
continue;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
const fieldSchema = normalizeObject(fieldSchemaRaw);
|
|
65
|
-
fieldRules.set(
|
|
66
|
-
normalizedFieldKey,
|
|
67
|
-
Object.freeze({
|
|
68
|
-
required: fieldSchema.required === true,
|
|
69
|
-
nullable: fieldSchema.nullable === true,
|
|
70
|
-
hasDefault: Object.hasOwn(fieldSchema, "default"),
|
|
71
|
-
defaultValue: fieldSchema.default
|
|
72
|
-
})
|
|
73
|
-
);
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
return Object.freeze({
|
|
77
|
-
fieldRules: new Map(fieldRules)
|
|
78
|
-
});
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
function resolveRoleFromFieldAccessInput(input) {
|
|
82
|
-
const role = normalizeText(input?.context?.auth?.role).toLowerCase();
|
|
83
|
-
return role || "default";
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
function resolveActionFromFieldAccessInput(input) {
|
|
87
|
-
const action = normalizeText(input?.action).toLowerCase();
|
|
88
|
-
return action || "*";
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
function resolveOperationPolicyValue(operationPolicy, input = {}, action = "*") {
|
|
92
|
-
if (typeof operationPolicy === "function") {
|
|
93
|
-
return operationPolicy(input);
|
|
94
|
-
}
|
|
95
|
-
if (
|
|
96
|
-
operationPolicy == null ||
|
|
97
|
-
operationPolicy === "*" ||
|
|
98
|
-
Array.isArray(operationPolicy) ||
|
|
99
|
-
operationPolicy instanceof Set
|
|
100
|
-
) {
|
|
101
|
-
return operationPolicy;
|
|
102
|
-
}
|
|
103
|
-
if (typeof operationPolicy !== "object") {
|
|
104
|
-
return null;
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
if (Object.hasOwn(operationPolicy, action)) {
|
|
108
|
-
return operationPolicy[action];
|
|
109
|
-
}
|
|
110
|
-
if (Object.hasOwn(operationPolicy, "*")) {
|
|
111
|
-
return operationPolicy["*"];
|
|
112
|
-
}
|
|
113
|
-
if (Object.hasOwn(operationPolicy, "all")) {
|
|
114
|
-
return operationPolicy.all;
|
|
115
|
-
}
|
|
116
|
-
return null;
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
function resolveRoleMatrixPolicy(matrix = {}, operation = "readable", input = {}) {
|
|
120
|
-
const sourceMatrix = normalizeObject(matrix);
|
|
121
|
-
const role = resolveRoleFromFieldAccessInput(input);
|
|
122
|
-
const action = resolveActionFromFieldAccessInput(input);
|
|
123
|
-
|
|
124
|
-
const rolePolicy = normalizeObject(sourceMatrix[role]);
|
|
125
|
-
const roleValue = resolveOperationPolicyValue(rolePolicy[operation], input, action);
|
|
126
|
-
if (roleValue != null) {
|
|
127
|
-
return roleValue;
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
const defaultPolicy = normalizeObject(sourceMatrix.default);
|
|
131
|
-
return resolveOperationPolicyValue(defaultPolicy[operation], input, action);
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
function createFieldAccessForRoleMatrix(matrix = {}, { context = "crudFieldAccess" } = {}) {
|
|
135
|
-
const sourceMatrix = normalizeObject(matrix);
|
|
136
|
-
const writeMode = resolveWriteMode(
|
|
137
|
-
{ writeMode: sourceMatrix.writeMode },
|
|
138
|
-
{ context: `${context} createFieldAccessForRoleMatrix` }
|
|
139
|
-
);
|
|
140
|
-
|
|
141
|
-
function readable(input = {}) {
|
|
142
|
-
return resolveRoleMatrixPolicy(sourceMatrix, "readable", input);
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
function writable(input = {}) {
|
|
146
|
-
return resolveRoleMatrixPolicy(sourceMatrix, "writable", input);
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
return Object.freeze({
|
|
150
|
-
readable,
|
|
151
|
-
writable,
|
|
152
|
-
writeMode
|
|
153
|
-
});
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
/**
|
|
157
|
-
* The record with the fields the caller may not read removed, or nulled or
|
|
158
|
-
* defaulted where the output schema requires them. outputRules is present
|
|
159
|
-
* whenever allowedFields is: resolveReadableAllowedFields refuses a readable
|
|
160
|
-
* policy on a resource with no view output.
|
|
161
|
-
*/
|
|
162
|
-
function applyReadableFieldPolicyToRecord(record, allowedFields, outputRules, { context = "crudFieldAccess" } = {}) {
|
|
163
|
-
if (!isRecord(record) || !allowedFields) {
|
|
164
|
-
return record;
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
const nextRecord = { ...record };
|
|
168
|
-
const { fieldRules } = outputRules;
|
|
169
|
-
|
|
170
|
-
for (const fieldKey of Object.keys(nextRecord)) {
|
|
171
|
-
if (allowedFields.has(fieldKey)) {
|
|
172
|
-
continue;
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
const fieldRule = fieldRules.get(fieldKey);
|
|
176
|
-
if (!fieldRule || fieldRule.required !== true) {
|
|
177
|
-
delete nextRecord[fieldKey];
|
|
178
|
-
continue;
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
if (fieldRule.nullable) {
|
|
182
|
-
nextRecord[fieldKey] = null;
|
|
183
|
-
continue;
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
if (fieldRule.hasDefault) {
|
|
187
|
-
nextRecord[fieldKey] = fieldRule.defaultValue;
|
|
188
|
-
continue;
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
throw new Error(
|
|
192
|
-
`${context} cannot redact required non-nullable field "${fieldKey}" without a default value.`
|
|
193
|
-
);
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
return nextRecord;
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
function createCrudFieldAccessRuntime(resource = {}, { context = "crudFieldAccess" } = {}) {
|
|
200
|
-
const outputRules = buildOutputFieldRules(resource);
|
|
201
|
-
|
|
202
|
-
async function resolveReadableAllowedFields(fieldAccess = {}, input = {}) {
|
|
203
|
-
const allowedFields = await resolveFieldSet(
|
|
204
|
-
fieldAccess.readable,
|
|
205
|
-
input,
|
|
206
|
-
{
|
|
207
|
-
context,
|
|
208
|
-
label: "fieldAccess.readable"
|
|
209
|
-
}
|
|
210
|
-
);
|
|
211
|
-
if (!allowedFields) {
|
|
212
|
-
return null;
|
|
213
|
-
}
|
|
214
|
-
if (!outputRules) {
|
|
215
|
-
throw new TypeError(`${context} requires resource.operations.view.output for fieldAccess.readable.`);
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
return allowedFields;
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
async function enforceWritablePayload(payload = {}, fieldAccess = {}, input = {}) {
|
|
222
|
-
const allowedFields = await resolveFieldSet(
|
|
223
|
-
fieldAccess.writable,
|
|
224
|
-
input,
|
|
225
|
-
{
|
|
226
|
-
context,
|
|
227
|
-
label: "fieldAccess.writable"
|
|
228
|
-
}
|
|
229
|
-
);
|
|
230
|
-
if (!allowedFields) {
|
|
231
|
-
return payload;
|
|
232
|
-
}
|
|
233
|
-
const sourcePayload = normalizeObjectInput(payload);
|
|
234
|
-
|
|
235
|
-
const writeMode = resolveWriteMode(fieldAccess, { context });
|
|
236
|
-
const filteredPayload = {};
|
|
237
|
-
const forbiddenFields = [];
|
|
238
|
-
for (const [fieldKey, fieldValue] of Object.entries(sourcePayload)) {
|
|
239
|
-
if (allowedFields.has(fieldKey)) {
|
|
240
|
-
filteredPayload[fieldKey] = fieldValue;
|
|
241
|
-
} else {
|
|
242
|
-
forbiddenFields.push(fieldKey);
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
if (forbiddenFields.length > 0 && writeMode === "throw") {
|
|
247
|
-
const fields = forbiddenFields.join(", ");
|
|
248
|
-
throw new AppError(403, `Write access denied for fields: ${fields}.`, {
|
|
249
|
-
code: "crud.fieldAccess.writeDenied",
|
|
250
|
-
params: { fields }
|
|
251
|
-
});
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
return filteredPayload;
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
async function filterReadableRecord(record = null, fieldAccess = {}, input = {}) {
|
|
258
|
-
const allowedFields = await resolveReadableAllowedFields(fieldAccess, input);
|
|
259
|
-
if (!allowedFields) {
|
|
260
|
-
return record;
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
return applyReadableFieldPolicyToRecord(record, allowedFields, outputRules, {
|
|
264
|
-
context
|
|
265
|
-
});
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
async function filterReadableListResult(listResult = {}, fieldAccess = {}, input = {}) {
|
|
269
|
-
const allowedFields = await resolveReadableAllowedFields(fieldAccess, input);
|
|
270
|
-
if (!allowedFields) {
|
|
271
|
-
return listResult;
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
const sourceList = normalizeObject(listResult);
|
|
275
|
-
const sourceItems = Array.isArray(sourceList.items) ? sourceList.items : [];
|
|
276
|
-
if (sourceItems.length < 1) {
|
|
277
|
-
return sourceList;
|
|
278
|
-
}
|
|
279
|
-
const filteredItems = sourceItems.map((record) =>
|
|
280
|
-
applyReadableFieldPolicyToRecord(record, allowedFields, outputRules, {
|
|
281
|
-
context
|
|
282
|
-
})
|
|
283
|
-
);
|
|
284
|
-
|
|
285
|
-
return {
|
|
286
|
-
...sourceList,
|
|
287
|
-
items: filteredItems
|
|
288
|
-
};
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
return Object.freeze({
|
|
292
|
-
enforceWritablePayload,
|
|
293
|
-
filterReadableRecord,
|
|
294
|
-
filterReadableListResult
|
|
295
|
-
});
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
export { createCrudFieldAccessRuntime, createFieldAccessForRoleMatrix };
|