@nest-my-admin/core 0.8.1 → 0.9.1
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/README.md +34 -2
- package/dist/api/action.service.d.ts +9 -1
- package/dist/api/action.service.js +73 -7
- package/dist/api/admin-api.service.d.ts +3 -1
- package/dist/api/admin-api.service.js +42 -16
- package/dist/audit/audit-reader.js +3 -2
- package/dist/auth/auth.service.js +9 -1
- package/dist/contract.d.ts +9 -0
- package/dist/crud/computed-columns.js +9 -0
- package/dist/dashboard/dashboard.service.js +2 -1
- package/dist/dashboard/widget-data.d.ts +8 -0
- package/dist/dashboard/widget-data.js +55 -0
- package/dist/decorators/admin-action.d.ts +43 -5
- package/dist/decorators/admin-action.js +77 -15
- package/dist/decorators/admin-print.d.ts +4 -1
- package/dist/decorators/admin-print.js +0 -6
- package/dist/decorators/admin-resource.d.ts +6 -2
- package/dist/decorators/admin-scope.d.ts +5 -2
- package/dist/decorators/admin-scope.js +0 -6
- package/dist/decorators/admin-settings-page.d.ts +2 -1
- package/dist/decorators/admin-widget.d.ts +2 -1
- package/dist/decorators/hooks.d.ts +11 -6
- package/dist/decorators/hooks.js +3 -3
- package/dist/decorators/typed.d.ts +20 -0
- package/dist/decorators/typed.js +2 -0
- package/dist/files/file-owner.js +2 -1
- package/dist/host-contract.d.ts +30 -0
- package/dist/host-contract.js +91 -0
- package/dist/http/admin-http.server.js +1 -0
- package/dist/http/error-response.js +4 -0
- package/dist/i18n/texts.js +9 -3
- package/dist/index.d.ts +2 -1
- package/dist/inlines/inline-reader.js +3 -2
- package/dist/inlines/inline-writer.js +3 -2
- package/dist/options.js +23 -1
- package/dist/pages/page-registry.js +3 -2
- package/dist/policy/admin-policy.service.js +30 -11
- package/dist/policy/explain.js +3 -2
- package/dist/rbac/rbac-routes.js +2 -1
- package/dist/registry/resource-registry.js +1 -1
- package/dist/resource/admin-resource-base.js +16 -5
- package/dist/resource/admin-source-base.d.ts +2 -0
- package/package.json +2 -2
package/dist/i18n/texts.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { resolveText } from './localized-text.js';
|
|
2
|
+
import { describeValue, HostContractError } from '../host-contract.js';
|
|
2
3
|
/** The one place host texts are resolved. A `translate` that throws falls back to the declared text, logged once per key (once for all keyless texts). */
|
|
3
4
|
export function createTexts(options, logger) {
|
|
4
5
|
const { translate, locale: defaultLocale } = options;
|
|
@@ -6,10 +7,9 @@ export function createTexts(options, logger) {
|
|
|
6
7
|
return (text, locale) => resolveText(text, locale, defaultLocale);
|
|
7
8
|
const warned = new Set();
|
|
8
9
|
return (text, locale, key) => {
|
|
10
|
+
let answer;
|
|
9
11
|
try {
|
|
10
|
-
|
|
11
|
-
if (typeof answer === 'string' && answer !== '')
|
|
12
|
-
return answer;
|
|
12
|
+
answer = translate(key === undefined ? { text, locale } : { key, text, locale });
|
|
13
13
|
}
|
|
14
14
|
catch (error) {
|
|
15
15
|
// Keyless texts are often built from data (action messages): one warning for all of them keeps this set small.
|
|
@@ -18,6 +18,12 @@ export function createTexts(options, logger) {
|
|
|
18
18
|
warned.add(name);
|
|
19
19
|
logger.warn(`translate threw for "${name}" (${error instanceof Error ? error.message : String(error)}); the declared text is shown`);
|
|
20
20
|
}
|
|
21
|
+
return resolveText(text, locale, defaultLocale);
|
|
22
|
+
}
|
|
23
|
+
if (typeof answer === 'string' && answer !== '')
|
|
24
|
+
return answer;
|
|
25
|
+
if (answer !== undefined && answer !== '') {
|
|
26
|
+
throw new HostContractError(`translate must return a string or undefined at once, but it returned ${describeValue(answer)} for "${key ?? resolveText(text, locale, defaultLocale)}"`);
|
|
21
27
|
}
|
|
22
28
|
return resolveText(text, locale, defaultLocale);
|
|
23
29
|
};
|
package/dist/index.d.ts
CHANGED
|
@@ -13,7 +13,8 @@ export type { FieldConfig, FieldsConfig, LayoutConfig, LayoutInlineConfig, Layou
|
|
|
13
13
|
export type { RegisteredInline } from './inlines/inline-config.js';
|
|
14
14
|
export { AdminContext, type AdminWriteContext } from './resource/admin-context.js';
|
|
15
15
|
export { AdminCan, AdminScope, type RecordOperation, type ScopeCondition } from './decorators/admin-scope.js';
|
|
16
|
-
export { AdminAction, type ActionOutcome, type AdminActionOptions } from './decorators/admin-action.js';
|
|
16
|
+
export { AdminAction, type ActionOutcome, type ActionReturn, type AdminActionOptions } from './decorators/admin-action.js';
|
|
17
|
+
export type { Awaitable, RowOf, TypedClassDecorator, TypedMethodDecorator } from './decorators/typed.js';
|
|
17
18
|
export { AdminPrint, type AdminPrintOptions } from './decorators/admin-print.js';
|
|
18
19
|
export { html, raw, escapeHtml, HtmlString } from './print/html.js';
|
|
19
20
|
export { AdminSettingsPage, type AdminSettingsPageOptions, type AdminSettingsSource } from './decorators/admin-settings-page.js';
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { checkFindMany, checkQueryBuilder } from '../host-contract.js';
|
|
1
2
|
import { recordIdOf } from '../crud/record-id.js';
|
|
2
3
|
import { AdminResourceBase } from '../resource/admin-resource-base.js';
|
|
3
4
|
/**
|
|
@@ -43,7 +44,7 @@ export class InlineReader {
|
|
|
43
44
|
count: 'none',
|
|
44
45
|
pagination: 'offset',
|
|
45
46
|
};
|
|
46
|
-
const found = await child.resource.findMany(params, ctx);
|
|
47
|
+
const found = checkFindMany(await child.resource.findMany(params, ctx), child.className);
|
|
47
48
|
if (child.resource.findMany !== AdminResourceBase.prototype.findMany)
|
|
48
49
|
return this.overridden(inline, value, found, ctx);
|
|
49
50
|
const truncated = found.hasMore === true || found.items.length > inline.max;
|
|
@@ -85,7 +86,7 @@ export class InlineReader {
|
|
|
85
86
|
const { child } = inline;
|
|
86
87
|
const manager = ctx.manager ?? child.dataSource.manager; // a source has no relation, so it is never an inline child
|
|
87
88
|
const qb = manager.getRepository(child.metadata.target).createQueryBuilder('nma_inline');
|
|
88
|
-
return this.deps.policy.applyScopes(child.resource.query(qb, ctx), child, 'view', ctx).andWhere(`nma_inline.${inline.link} = :nmaInlineParent`, { nmaInlineParent: value });
|
|
89
|
+
return this.deps.policy.applyScopes(checkQueryBuilder(child.resource.query(qb, ctx), `${child.className}.query()`), child, 'view', ctx).andWhere(`nma_inline.${inline.link} = :nmaInlineParent`, { nmaInlineParent: value });
|
|
89
90
|
}
|
|
90
91
|
}
|
|
91
92
|
//# sourceMappingURL=inline-reader.js.map
|
|
@@ -7,6 +7,7 @@ import { validateWrite } from '../crud/validate-write.js';
|
|
|
7
7
|
import { AdminBadRequestError, AdminError, AdminForbiddenError, AdminForbiddenFieldsError, AdminNotFoundError, AdminValidationError } from '../errors.js';
|
|
8
8
|
import { codeForStatus, hostError, toErrorResponse } from '../http/error-response.js';
|
|
9
9
|
import { MAX_INLINE_ROWS } from '../schema/field-config.js';
|
|
10
|
+
import { checkQueryBuilder, checkFoundRecord } from '../host-contract.js';
|
|
10
11
|
const KEY = /^.{1,64}$/su;
|
|
11
12
|
const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
12
13
|
/**
|
|
@@ -154,7 +155,7 @@ export class InlineWriter {
|
|
|
154
155
|
const children = () => {
|
|
155
156
|
const manager = tx.manager ?? child.dataSource.manager; // a source has no relation, so it is never an inline child
|
|
156
157
|
const qb = manager.getRepository(child.metadata.target).createQueryBuilder('nma_child');
|
|
157
|
-
const restricted = policy.applyScopes(child.resource.query(qb, tx), child, 'view', tx);
|
|
158
|
+
const restricted = policy.applyScopes(checkQueryBuilder(child.resource.query(qb, tx), `${child.className}.query()`), child, 'view', tx);
|
|
158
159
|
return restricted.andWhere(`nma_child.${inline.link} = :nmaInlineParent`, { nmaInlineParent: linkValue });
|
|
159
160
|
};
|
|
160
161
|
// The order list is checked against the rows the user sees, and decides which of them move.
|
|
@@ -223,7 +224,7 @@ export class InlineWriter {
|
|
|
223
224
|
// Then each row as the child's own PATCH and DELETE read it: its findOne (an override may refuse a row or load
|
|
224
225
|
// more). That entity is what @AdminCan, readonlyIf, relationOptions() values and the participants see.
|
|
225
226
|
for (const [canonical, entry] of named) {
|
|
226
|
-
const entity = await child.resource.findOne(entry.id, tx);
|
|
227
|
+
const entity = checkFoundRecord(await child.resource.findOne(entry.id, tx), `${child.resource.constructor.name}.findOne()`);
|
|
227
228
|
if (!entity)
|
|
228
229
|
throw notFound(entry.raw);
|
|
229
230
|
rows.set(canonical, entity);
|
package/dist/options.js
CHANGED
|
@@ -2,6 +2,7 @@ import { createTexts } from './i18n/texts.js';
|
|
|
2
2
|
import { Logger } from '@nestjs/common';
|
|
3
3
|
import { checkCurrency } from './schema/currency.js';
|
|
4
4
|
import { DEFAULT_MAX_FILE_BYTES, MAX_FILE_BYTES } from './schema/field-config.js';
|
|
5
|
+
import { describeValue, HostContractError } from './host-contract.js';
|
|
5
6
|
export function resolveAdminOptions(options = {}) {
|
|
6
7
|
const raw = (options.path ?? '/admin').trim();
|
|
7
8
|
const path = '/' + raw.replace(/^\/+|\/+$/g, '');
|
|
@@ -110,7 +111,28 @@ function checkFiles(files) {
|
|
|
110
111
|
throw new Error(`nest-my-admin: files.maxBytes must be at most ${MAX_FILE_BYTES} bytes (2 GiB - 1)`);
|
|
111
112
|
if (files.sanitizeHtml !== undefined && typeof files.sanitizeHtml !== 'function')
|
|
112
113
|
throw new Error('nest-my-admin: files.sanitizeHtml must be a function');
|
|
113
|
-
return { ...files, maxBytes };
|
|
114
|
+
return { ...files, maxBytes, storage: checkedStorage(files.storage) };
|
|
115
|
+
}
|
|
116
|
+
/** The host's storage, with its answers checked where a wrong one would pass unnoticed (an async publicUrl). */
|
|
117
|
+
function checkedStorage(storage) {
|
|
118
|
+
const checked = Object.create(storage);
|
|
119
|
+
checked.publicUrl = (key) => {
|
|
120
|
+
const url = storage.publicUrl(key);
|
|
121
|
+
if (url === undefined || typeof url === 'string')
|
|
122
|
+
return url;
|
|
123
|
+
throw new HostContractError(`files.storage.publicUrl() must return a URL or undefined at once, but it returned ${describeValue(url)}`);
|
|
124
|
+
};
|
|
125
|
+
checked.get = async (key) => {
|
|
126
|
+
const object = await storage.get(key);
|
|
127
|
+
if (object === null || object === undefined)
|
|
128
|
+
return null;
|
|
129
|
+
const found = object;
|
|
130
|
+
if (typeof found !== 'object' || typeof found.body?.pipe !== 'function' || typeof found.contentType !== 'string' || typeof found.size !== 'number') {
|
|
131
|
+
throw new HostContractError(`files.storage.get() must return { body: Readable, contentType, size } or null, but it returned ${describeValue(object)}`);
|
|
132
|
+
}
|
|
133
|
+
return object;
|
|
134
|
+
};
|
|
135
|
+
return checked;
|
|
114
136
|
}
|
|
115
137
|
function checkAudit(audit) {
|
|
116
138
|
if (!audit)
|
|
@@ -23,6 +23,7 @@ import { ResourceRegistry, memberOrder } from '../registry/resource-registry.js'
|
|
|
23
23
|
import { buildDtoForm, nestedProtected } from '../schema/dto-form.js';
|
|
24
24
|
import { checkLayout } from '../schema/field-config.js';
|
|
25
25
|
import { humanize } from '../schema/humanize.js';
|
|
26
|
+
import { describeValue, HostContractError, isRecordObject } from '../host-contract.js';
|
|
26
27
|
/** Page names that are a segment of other permission codes: `page.update` would read as an operation. */
|
|
27
28
|
const RESERVED_NAMES = RESERVED_PAGE_NAMES;
|
|
28
29
|
/** Options that mean something on a resource's field only. */
|
|
@@ -171,8 +172,8 @@ export const unknownPage = (name) => new AdminNotFoundError(`Unknown page "${nam
|
|
|
171
172
|
/** The page's stored values, as its `load()` gives them (secrets included: callers decide what leaves). */
|
|
172
173
|
export async function loadPage(page, ctx) {
|
|
173
174
|
const values = await page.source.load(ctx);
|
|
174
|
-
if (
|
|
175
|
-
throw new
|
|
175
|
+
if (!isRecordObject(values))
|
|
176
|
+
throw new HostContractError(`${page.className}.load() must return an object of the page's values, but it returned ${describeValue(values)}`);
|
|
176
177
|
return values;
|
|
177
178
|
}
|
|
178
179
|
//# sourceMappingURL=page-registry.js.map
|
|
@@ -17,6 +17,7 @@ import { Brackets } from 'typeorm';
|
|
|
17
17
|
import { ADMIN_OPTIONS } from '../constants.js';
|
|
18
18
|
import { recordIdOf } from '../crud/record-id.js';
|
|
19
19
|
import { getCanRules, getScopes } from '../decorators/admin-scope.js';
|
|
20
|
+
import { checkBoolean, checkStringList, describeValue, HostContractError, isPlainObject, isThenable } from '../host-contract.js';
|
|
20
21
|
import { AdminForbiddenError, AdminForbiddenFieldsError, AdminNotFoundError } from '../errors.js';
|
|
21
22
|
import { AdminAuthService } from '../auth/auth.service.js';
|
|
22
23
|
import { PageRegistry, unknownPage } from '../pages/page-registry.js';
|
|
@@ -80,16 +81,20 @@ let AdminPolicy = class AdminPolicy {
|
|
|
80
81
|
if (!user || user.isSuperuser)
|
|
81
82
|
return user ? OPEN : new EffectivePermissions([], false);
|
|
82
83
|
let names = [];
|
|
84
|
+
let fromOptions;
|
|
85
|
+
let fromAdapter;
|
|
83
86
|
try {
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
names = [...fromOptions, ...fromAdapter, ...stored];
|
|
87
|
+
fromOptions = await this.options.resolveRoles?.(user);
|
|
88
|
+
fromAdapter = await this.auth.adapter?.resolveRoles?.(user);
|
|
89
|
+
names = await this.rbac.assignedRoleNames(String(user.id));
|
|
88
90
|
}
|
|
89
91
|
catch (error) {
|
|
90
92
|
this.warnOnce(`resolveRoles threw for user ${String(user.id)} (${error instanceof Error ? error.message : String(error)}); the user gets no roles`);
|
|
91
93
|
names = [];
|
|
94
|
+
fromOptions = fromAdapter = undefined;
|
|
92
95
|
}
|
|
96
|
+
// Outside the try: a wrong answer is the host's bug, not a failed lookup («no roles» would hide it).
|
|
97
|
+
names = [...checkStringList(fromOptions, 'the resolveRoles option'), ...checkStringList(fromAdapter, 'the auth adapter\'s resolveRoles()'), ...names];
|
|
93
98
|
const roles = [];
|
|
94
99
|
let known;
|
|
95
100
|
try {
|
|
@@ -472,20 +477,29 @@ let AdminPolicy = class AdminPolicy {
|
|
|
472
477
|
return this.globalScopes(entry, perms).map((scope) => scope.name);
|
|
473
478
|
}
|
|
474
479
|
globalScopes(entry, perms) {
|
|
475
|
-
return this.options.globalScopes.filter((scope) => !(scope.exemptSuperusers && perms.superuser) && (scope.appliesTo ? scope.appliesTo({ name: entry.schema.name, entity: entry.entity, metadata: entry.metadata }) : true));
|
|
480
|
+
return this.options.globalScopes.filter((scope) => !(scope.exemptSuperusers && perms.superuser) && (scope.appliesTo ? checkBoolean(scope.appliesTo({ name: entry.schema.name, entity: entry.entity, metadata: entry.metadata }), `global scope "${scope.name}" appliesTo()`) : true));
|
|
476
481
|
}
|
|
477
482
|
callScope(entry, name, ctx) {
|
|
478
483
|
const key = getScopes(entry.resource.constructor)[name];
|
|
479
|
-
|
|
484
|
+
const condition = entry.resource[key].call(entry.resource, ctx);
|
|
485
|
+
// An `async` scope would be read as an empty column map, «no restriction»: refuse it.
|
|
486
|
+
if (isThenable(condition) || !(typeof condition === 'function' || isPlainObject(condition))) {
|
|
487
|
+
throw new HostContractError(`${entry.className}.${String(key)} (@AdminScope("${name}")) returned ${describeValue(condition)}; a scope answers at once with a column map or a function (it cannot be async)`);
|
|
488
|
+
}
|
|
489
|
+
return condition;
|
|
480
490
|
}
|
|
481
491
|
/** A scope's result as SQL: a column map (array = IN, null = IS NULL, undefined = no rows) or a callback. */
|
|
482
492
|
condition(where, alias, entry, condition, what) {
|
|
483
493
|
if (typeof condition === 'function') {
|
|
484
|
-
|
|
494
|
+
// Conditions added after the query ran would restrict nothing: the callback cannot be async either.
|
|
495
|
+
const added = condition(where, alias);
|
|
496
|
+
if (isThenable(added))
|
|
497
|
+
throw new HostContractError(`${entry.className}: the callback of ${what} returned a Promise; it adds its conditions at once (it cannot be async)`);
|
|
485
498
|
return;
|
|
486
499
|
}
|
|
487
|
-
|
|
488
|
-
|
|
500
|
+
// An `async` scope gives a Promise, which would read as an empty column map: «no restriction».
|
|
501
|
+
if (!isPlainObject(condition))
|
|
502
|
+
throw new HostContractError(`${entry.className}: ${what} returned ${describeValue(condition)}; it must answer at once with a column map or a function (it cannot be async)`);
|
|
489
503
|
const entries = Object.entries(condition);
|
|
490
504
|
if (entries.length === 0) {
|
|
491
505
|
where.where('1 = 1');
|
|
@@ -532,14 +546,19 @@ let AdminPolicy = class AdminPolicy {
|
|
|
532
546
|
recordRule(entry, operation, entity, ctx) {
|
|
533
547
|
const methods = entry.resource;
|
|
534
548
|
for (const key of getCanRules(entry.resource.constructor, operation)) {
|
|
549
|
+
let answer;
|
|
535
550
|
try {
|
|
536
|
-
|
|
537
|
-
return false;
|
|
551
|
+
answer = methods[key].call(entry.resource, entity, ctx);
|
|
538
552
|
}
|
|
539
553
|
catch (error) {
|
|
540
554
|
this.warnOnce(`${entry.className}.${String(key)} (@AdminCan("${operation}")) threw: ${error instanceof Error ? error.message : String(error)}; the answer is no`);
|
|
541
555
|
return false;
|
|
542
556
|
}
|
|
557
|
+
// An `async` rule (a Promise) or a forgotten return (undefined) would quietly mean «no» everywhere.
|
|
558
|
+
if (typeof answer !== 'boolean')
|
|
559
|
+
throw new HostContractError(`${entry.className}.${String(key)} (@AdminCan("${operation}")) returned ${describeValue(answer)}; a rule answers at once with true or false (it cannot be async)`);
|
|
560
|
+
if (!answer)
|
|
561
|
+
return false;
|
|
543
562
|
}
|
|
544
563
|
return true;
|
|
545
564
|
}
|
package/dist/policy/explain.js
CHANGED
|
@@ -4,6 +4,7 @@ import { runInAdminContext } from '../resource/admin-context.js';
|
|
|
4
4
|
import { EffectivePermissions } from './effective.js';
|
|
5
5
|
import { RESOURCE_OPERATIONS, actionCode, codeMatches, pageCode } from './roles.js';
|
|
6
6
|
import { bootText } from '../i18n/texts.js';
|
|
7
|
+
import { checkFoundRecord } from '../host-contract.js';
|
|
7
8
|
const SCOPED = ['view', 'update', 'delete'];
|
|
8
9
|
/**
|
|
9
10
|
* Why a user may or may not do things with a resource (spec §6.7). Every answer comes from the code the API
|
|
@@ -105,7 +106,7 @@ async function explainRecord(policy, entry, raw, ctx) {
|
|
|
105
106
|
}
|
|
106
107
|
const keys = entry.schema.primaryKeys;
|
|
107
108
|
// A source's row exists when its own findOne finds it.
|
|
108
|
-
const stored = entry.dataSource ? await entry.dataSource.manager.getRepository(entry.metadata.target).createQueryBuilder('nma_explain').whereInIds([id]).getOne() : await entry.resource.findOne(id, ctx);
|
|
109
|
+
const stored = entry.dataSource ? await entry.dataSource.manager.getRepository(entry.metadata.target).createQueryBuilder('nma_explain').whereInIds([id]).getOne() : checkFoundRecord(await entry.resource.findOne(id, ctx), `${entry.resource.constructor.name}.findOne()`);
|
|
109
110
|
const exists = stored !== null;
|
|
110
111
|
const key = recordIdOf(typeof id === 'object' ? id : { [keys[0]]: id }, keys);
|
|
111
112
|
const inScope = async (operation) => (await policy.allowedIds(entry, [id], operation, ctx)).has(key);
|
|
@@ -116,7 +117,7 @@ async function explainRecord(policy, entry, raw, ctx) {
|
|
|
116
117
|
else if (!perms.canOn(r, 'view'))
|
|
117
118
|
reasons.view = 'permission';
|
|
118
119
|
else {
|
|
119
|
-
found = await entry.resource.findOne(id, ctx);
|
|
120
|
+
found = checkFoundRecord(await entry.resource.findOne(id, ctx), `${entry.resource.constructor.name}.findOne()`);
|
|
120
121
|
view = found !== null && (await inScope('view'));
|
|
121
122
|
if (!view)
|
|
122
123
|
reasons.view = 'scope';
|
package/dist/rbac/rbac-routes.js
CHANGED
|
@@ -3,6 +3,7 @@ import { AdminForbiddenError, AdminNotFoundError, AdminValidationError } from '.
|
|
|
3
3
|
import { readJsonBody, sendJson } from '../http/http-io.js';
|
|
4
4
|
import { RESOURCE_OPERATIONS } from '../policy/roles.js';
|
|
5
5
|
import { diffPlain } from '../audit/diff.js';
|
|
6
|
+
import { checkFoundRecord } from '../host-contract.js';
|
|
6
7
|
const noContent = (res) => {
|
|
7
8
|
res.statusCode = 204;
|
|
8
9
|
res.end();
|
|
@@ -55,7 +56,7 @@ export function addRbacRoutes(router, services) {
|
|
|
55
56
|
});
|
|
56
57
|
const findUser = async (id) => {
|
|
57
58
|
const adapter = auth.adapter;
|
|
58
|
-
const user = adapter?.getUser ? await adapter.getUser(id) : (await rbac.knownUserIds()).includes(id) ? { id, displayName: id, isSuperuser: false } : null;
|
|
59
|
+
const user = adapter?.getUser ? checkFoundRecord(await adapter.getUser(id), "the auth adapter's getUser()") : (await rbac.knownUserIds()).includes(id) ? { id, displayName: id, isSuperuser: false } : null;
|
|
59
60
|
if (!user)
|
|
60
61
|
throw new AdminNotFoundError(`User "${id}" not found`);
|
|
61
62
|
return user;
|
|
@@ -319,7 +319,7 @@ let ResourceRegistry = class ResourceRegistry {
|
|
|
319
319
|
});
|
|
320
320
|
const actions = resolveActions(resource.constructor, BASE_MEMBERS, (message) => {
|
|
321
321
|
throw new Error(`${className}: ${message}`);
|
|
322
|
-
});
|
|
322
|
+
}, definition.entity);
|
|
323
323
|
// Action inputs picked like one of the resource's relation fields (`@AdminField({ pickFrom })`).
|
|
324
324
|
for (const action of actions.values()) {
|
|
325
325
|
if (!action.form)
|
|
@@ -5,6 +5,8 @@ import { toRelationReferences } from '../crud/relation-writes.js';
|
|
|
5
5
|
import { toFileKeys } from '../files/admin-file.js';
|
|
6
6
|
import { AdminNotFoundError } from '../errors.js';
|
|
7
7
|
import { getHooks } from '../decorators/hooks.js';
|
|
8
|
+
import { checkQueryBuilder, describeValue, HostContractError, isThenable } from '../host-contract.js';
|
|
9
|
+
const HOOK_NAMES = { beforeSave: 'BeforeSave', afterSave: 'AfterSave', beforeDelete: 'BeforeDelete' };
|
|
8
10
|
import { AdminContext } from './admin-context.js';
|
|
9
11
|
/**
|
|
10
12
|
* Base class for admin resources. Override `create`/`update` (and the finders) to route
|
|
@@ -52,7 +54,7 @@ export class AdminResourceBase {
|
|
|
52
54
|
}
|
|
53
55
|
/** `query()` and then the signed-in user's row scopes: what every read of this resource starts from. */
|
|
54
56
|
restrict(qb, ctx) {
|
|
55
|
-
const restricted = this.query(qb, ctx);
|
|
57
|
+
const restricted = checkQueryBuilder(this.query(qb, ctx), `${this.constructor.name}.query()`);
|
|
56
58
|
return this.#scoper ? this.#scoper(restricted, ctx) : restricted;
|
|
57
59
|
}
|
|
58
60
|
#computedSort;
|
|
@@ -93,8 +95,13 @@ export class AdminResourceBase {
|
|
|
93
95
|
const qb = this.restrict(repository.createQueryBuilder(alias), context);
|
|
94
96
|
const sorter = this.#computedSort;
|
|
95
97
|
// The tab's own restriction (a tab with `where`); its filters arrive as normal filter params.
|
|
96
|
-
if (params.tab)
|
|
97
|
-
this.list?.tabs?.find((
|
|
98
|
+
if (params.tab) {
|
|
99
|
+
const tab = this.list?.tabs?.find((candidate) => candidate.key === params.tab);
|
|
100
|
+
const added = tab?.where?.(qb, context);
|
|
101
|
+
if (added !== undefined && (isThenable(added) || added !== qb)) {
|
|
102
|
+
throw new HostContractError(`${this.constructor.name} list tab "${tab.key}": where(qb, ctx) adds its conditions to qb at once and returns nothing, but it returned ${describeValue(added)}`);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
98
105
|
return applyListParams(qb, params, repository.metadata, sorter && ((query, field) => sorter(query, field, context)));
|
|
99
106
|
}
|
|
100
107
|
/**
|
|
@@ -225,8 +232,12 @@ export class AdminResourceBase {
|
|
|
225
232
|
/** Runs @BeforeSave/@AfterSave/@BeforeDelete methods in declaration order (parent class first). */
|
|
226
233
|
async runHooks(kind, ...args) {
|
|
227
234
|
const methods = this;
|
|
228
|
-
for (const key of getHooks(this.constructor, kind))
|
|
229
|
-
await methods[key].apply(this, args);
|
|
235
|
+
for (const key of getHooks(this.constructor, kind)) {
|
|
236
|
+
const returned = await methods[key].apply(this, args);
|
|
237
|
+
if (returned !== undefined) {
|
|
238
|
+
throw new HostContractError(`${this.constructor.name}.${String(key)}: a @${HOOK_NAMES[kind]} hook returns nothing, but it returned ${describeValue(returned)}`);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
230
241
|
}
|
|
231
242
|
}
|
|
232
243
|
//# sourceMappingURL=admin-resource-base.js.map
|
|
@@ -11,6 +11,8 @@ import { AdminResourceBase, type FindManyResult, type ListParams, type RecordId
|
|
|
11
11
|
* of AdminResourceBase (`query`, `buildListQuery`, `repository`, `restore`, `purge`) are not used.
|
|
12
12
|
*/
|
|
13
13
|
export declare abstract class AdminSourceBase<T extends ObjectLiteral = ObjectLiteral, Id extends RecordId = RecordId> extends AdminResourceBase<T, Id> {
|
|
14
|
+
/** Types only: tells a source class from a table resource, so `@AdminSource` refuses a class that is not one. */
|
|
15
|
+
private readonly sourceResource;
|
|
14
16
|
abstract findMany(params: ListParams, ctx: AdminContext): Promise<FindManyResult<T>>;
|
|
15
17
|
abstract findOne(id: Id, ctx: AdminContext, options?: {
|
|
16
18
|
withDeleted?: boolean;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nest-my-admin/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.1",
|
|
4
4
|
"description": "Django-admin-class admin panel for NestJS + TypeORM",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
"typecheck": "tsc -p tsconfig.json --noEmit"
|
|
36
36
|
},
|
|
37
37
|
"dependencies": {
|
|
38
|
-
"@nest-my-admin/ui": "0.
|
|
38
|
+
"@nest-my-admin/ui": "0.9.1"
|
|
39
39
|
},
|
|
40
40
|
"peerDependencies": {
|
|
41
41
|
"@nestjs/common": "^11.0.0 || ^12.0.0",
|