@nest-my-admin/core 0.8.0 → 0.9.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 (47) hide show
  1. package/README.md +27 -2
  2. package/dist/api/action.service.js +24 -6
  3. package/dist/api/admin-api.service.js +38 -16
  4. package/dist/appearance/appearance.service.d.ts +28 -0
  5. package/dist/appearance/appearance.service.js +63 -0
  6. package/dist/audit/audit-reader.js +3 -2
  7. package/dist/auth/auth.service.js +9 -1
  8. package/dist/contract.d.ts +6 -1
  9. package/dist/crud/computed-columns.js +9 -0
  10. package/dist/dashboard/dashboard.service.js +2 -1
  11. package/dist/dashboard/widget-data.d.ts +8 -0
  12. package/dist/dashboard/widget-data.js +55 -0
  13. package/dist/decorators/admin-action.d.ts +29 -5
  14. package/dist/decorators/admin-action.js +50 -14
  15. package/dist/decorators/admin-print.d.ts +4 -1
  16. package/dist/decorators/admin-print.js +0 -6
  17. package/dist/decorators/admin-resource.d.ts +6 -2
  18. package/dist/decorators/admin-scope.d.ts +5 -2
  19. package/dist/decorators/admin-scope.js +0 -6
  20. package/dist/decorators/admin-settings-page.d.ts +2 -1
  21. package/dist/decorators/admin-widget.d.ts +2 -1
  22. package/dist/decorators/hooks.d.ts +11 -6
  23. package/dist/decorators/hooks.js +3 -3
  24. package/dist/decorators/typed.d.ts +20 -0
  25. package/dist/decorators/typed.js +2 -0
  26. package/dist/files/file-owner.js +2 -1
  27. package/dist/host-contract.d.ts +30 -0
  28. package/dist/host-contract.js +91 -0
  29. package/dist/http/admin-http.server.js +34 -5
  30. package/dist/http/error-response.js +4 -0
  31. package/dist/http/http-io.d.ts +2 -0
  32. package/dist/http/http-io.js +19 -1
  33. package/dist/http/ui-assets.d.ts +15 -2
  34. package/dist/http/ui-assets.js +29 -3
  35. package/dist/i18n/texts.js +9 -3
  36. package/dist/index.d.ts +2 -1
  37. package/dist/inlines/inline-reader.js +3 -2
  38. package/dist/inlines/inline-writer.js +3 -2
  39. package/dist/options.js +23 -1
  40. package/dist/pages/page-registry.js +3 -2
  41. package/dist/policy/admin-policy.service.js +30 -11
  42. package/dist/policy/explain.js +3 -2
  43. package/dist/rbac/rbac-routes.js +2 -1
  44. package/dist/registry/resource-registry.js +1 -1
  45. package/dist/resource/admin-resource-base.js +16 -5
  46. package/dist/resource/admin-source-base.d.ts +2 -0
  47. package/package.json +2 -2
@@ -6,3 +6,5 @@ export type AdminRequest = IncomingMessage & {
6
6
  export declare function sendJson(res: ServerResponse, status: number, body: unknown): void;
7
7
  /** Uses the host-parsed body when present (Nest registers express.json()); otherwise reads the stream. */
8
8
  export declare function readJsonBody(req: AdminRequest): Promise<unknown>;
9
+ /** The raw body of an upload, refused (413) past `limit` bytes. A body the host already read as a Buffer is used as is. */
10
+ export declare function readRawBody(req: AdminRequest, limit: number): Promise<Buffer>;
@@ -1,4 +1,4 @@
1
- import { AdminBadRequestError } from '../errors.js';
1
+ import { AdminBadRequestError, AdminPayloadTooLargeError } from '../errors.js';
2
2
  const MAX_BODY_BYTES = 1_048_576;
3
3
  export function sendJson(res, status, body) {
4
4
  const payload = JSON.stringify(body);
@@ -37,4 +37,22 @@ function parseJson(text) {
37
37
  throw new AdminBadRequestError('Request body is not valid JSON');
38
38
  }
39
39
  }
40
+ /** The raw body of an upload, refused (413) past `limit` bytes. A body the host already read as a Buffer is used as is. */
41
+ export async function readRawBody(req, limit) {
42
+ if (Buffer.isBuffer(req.body)) {
43
+ if (req.body.length > limit)
44
+ throw new AdminPayloadTooLargeError(`The file is larger than ${limit} bytes`);
45
+ return req.body;
46
+ }
47
+ const chunks = [];
48
+ let size = 0;
49
+ for await (const chunk of req) {
50
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
51
+ size += buffer.length;
52
+ if (size > limit)
53
+ throw new AdminPayloadTooLargeError(`The file is larger than ${limit} bytes`);
54
+ chunks.push(buffer);
55
+ }
56
+ return Buffer.concat(chunks);
57
+ }
40
58
  //# sourceMappingURL=http-io.js.map
@@ -22,12 +22,25 @@ export interface UiPageOptions {
22
22
  /** The admin's `title`, in every language given. Defaults to the runtime config's title. */
23
23
  title?: LocalizedText;
24
24
  }
25
+ /** Pictures uploaded in the admin (`appearance`), read on every page load: they win over `branding.logo`. */
26
+ export type UiPictures = () => {
27
+ logo: string | null;
28
+ favicon: string | null;
29
+ };
30
+ /** A `<link rel="icon">` in `<head>` (replacing the build's own, if any). */
31
+ export declare function withFavicon(html: string, href: string): string;
25
32
  export declare class UiAssets {
26
33
  private readonly runtime;
34
+ private readonly pictures?;
27
35
  private readonly root;
28
36
  /** index.html as served: in the admin's default locale, with `<base href>` and the runtime config. */
29
- private readonly indexHtml;
30
- constructor(distDir: string, runtime: AdminRuntimeConfig, page?: UiPageOptions);
37
+ private indexHtml;
38
+ /** The page before the runtime config, and the pictures the cached `indexHtml` was made with. */
39
+ private readonly localized;
40
+ private madeFor;
41
+ constructor(distDir: string, runtime: AdminRuntimeConfig, page?: UiPageOptions, pictures?: UiPictures | undefined);
42
+ /** The page with the pictures uploaded now (made again only when they change). */
43
+ private page;
31
44
  /** Serves a file, 404s a missing /assets/* file, and falls back to index.html for client-side routes. */
32
45
  serve(pathname: string, req: AdminRequest, res: ServerResponse): void;
33
46
  private sendFile;
@@ -92,13 +92,24 @@ export function resolveStaticFile(root, pathname) {
92
92
  return undefined;
93
93
  }
94
94
  }
95
+ /** A `<link rel="icon">` in `<head>` (replacing the build's own, if any). */
96
+ export function withFavicon(html, href) {
97
+ const link = `<link rel="icon" href="${escapeAttribute(href)}">`;
98
+ const withoutOwn = html.replace(/<link\b[^>]*\brel\s*=\s*["']?(?:shortcut )?icon["']?[^>]*>/gi, '');
99
+ return withoutOwn.replace(/<\/head\s*>/i, (close) => link + close);
100
+ }
95
101
  export class UiAssets {
96
102
  runtime;
103
+ pictures;
97
104
  root;
98
105
  /** index.html as served: in the admin's default locale, with `<base href>` and the runtime config. */
99
106
  indexHtml;
100
- constructor(distDir, runtime, page = {}) {
107
+ /** The page before the runtime config, and the pictures the cached `indexHtml` was made with. */
108
+ localized;
109
+ madeFor = '';
110
+ constructor(distDir, runtime, page = {}, pictures) {
101
111
  this.runtime = runtime;
112
+ this.pictures = pictures;
102
113
  this.root = resolve(distDir);
103
114
  const indexPath = join(this.root, 'index.html');
104
115
  // index.html as built, or the "missing build" page.
@@ -107,7 +118,22 @@ export class UiAssets {
107
118
  // saved another choice, which lives in their browser where the server cannot see it), so `lang`, `dir` and the
108
119
  // title are right from the first byte for everyone who has not switched. `Accept-Language` is not consulted.
109
120
  const title = resolveText(page.title ?? runtime.title, runtime.locale, runtime.locale);
110
- this.indexHtml = injectRuntime(localizeDocument(template, { locale: runtime.locale, title }), runtime);
121
+ this.localized = localizeDocument(template, { locale: runtime.locale, title });
122
+ this.indexHtml = injectRuntime(this.localized, runtime);
123
+ }
124
+ /** The page with the pictures uploaded now (made again only when they change). */
125
+ page() {
126
+ if (!this.pictures)
127
+ return this.indexHtml;
128
+ const now = this.pictures();
129
+ const key = `${now.logo ?? ''}|${now.favicon ?? ''}`;
130
+ if (key !== this.madeFor) {
131
+ const runtime = now.logo ? { ...this.runtime, branding: { ...this.runtime.branding, logo: now.logo } } : this.runtime;
132
+ const html = injectRuntime(this.localized, runtime);
133
+ this.indexHtml = now.favicon ? withFavicon(html, now.favicon) : html;
134
+ this.madeFor = key;
135
+ }
136
+ return this.indexHtml;
111
137
  }
112
138
  /** Serves a file, 404s a missing /assets/* file, and falls back to index.html for client-side routes. */
113
139
  serve(pathname, req, res) {
@@ -122,7 +148,7 @@ export class UiAssets {
122
148
  }
123
149
  // One page for every request: no `Vary` (a host's own `Vary` header is left as it is).
124
150
  res.setHeader('Content-Language', this.runtime.locale);
125
- this.send(req, res, 200, 'text/html; charset=utf-8', this.indexHtml, 'no-cache');
151
+ this.send(req, res, 200, 'text/html; charset=utf-8', this.page(), 'no-cache');
126
152
  }
127
153
  sendFile(file, pathname, req, res) {
128
154
  let size;
@@ -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
- const answer = translate(key === undefined ? { text, locale } : { key, text, locale });
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 (typeof values !== 'object' || values === null || Array.isArray(values))
175
- throw new Error(`${page.className}.load() must return an object of the page's values`);
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
- const fromOptions = (await this.options.resolveRoles?.(user)) ?? [];
85
- const fromAdapter = (await this.auth.adapter?.resolveRoles?.(user)) ?? [];
86
- const stored = await this.rbac.assignedRoleNames(String(user.id));
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
- return entry.resource[key].call(entry.resource, ctx);
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
- condition(where, alias);
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
- if (typeof condition !== 'object' || condition === null)
488
- throw new Error(`${entry.className}: ${what} must return a column map or a function`);
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
- if (methods[key].call(entry.resource, entity, ctx) !== true)
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
  }
@@ -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';
@@ -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((tab) => tab.key === params.tab)?.where?.(qb, context);
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.8.0",
3
+ "version": "0.9.0",
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.8.0"
38
+ "@nest-my-admin/ui": "0.9.0"
39
39
  },
40
40
  "peerDependencies": {
41
41
  "@nestjs/common": "^11.0.0 || ^12.0.0",