@nest-my-admin/core 0.8.1 → 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.
- package/README.md +23 -2
- package/dist/api/action.service.js +24 -6
- package/dist/api/admin-api.service.js +38 -16
- package/dist/audit/audit-reader.js +3 -2
- package/dist/auth/auth.service.js +9 -1
- 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 +29 -5
- package/dist/decorators/admin-action.js +50 -14
- 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/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/README.md
CHANGED
|
@@ -524,8 +524,8 @@ export class OrderAdmin extends AdminResourceBase<Order> {
|
|
|
524
524
|
- `target: 'record'` (the default): the method is `(record, input, ctx)` and gets one loaded entity. The button is in the record's detail header. With `bulk: true` it is also offered for a list selection.
|
|
525
525
|
- `target: 'resource'`: the method is `(input, ctx)`. The button is on the list toolbar and runs once, without records.
|
|
526
526
|
- `label` (default: the humanized name), `icon`, `variant: 'destructive'` (a red button), `confirm: true` or a question of your own (asked in a dialog before it runs). A destructive action, and any run on more than one record, is always asked about first, with a default question when `confirm` is not set.
|
|
527
|
-
- `input`: a DTO. Its properties become a form in the dialog, checked in the browser and validated on the server like any write (whitelisted; class-validator; `@AdminField` for labels, help and widgets). A property with a class initializer is optional and keeps its default. File, image, rich-text and secret fields are not allowed in an input.
|
|
528
|
-
- Return `{ message }` (a text or `{ en, fa }`) to say what happened: the UI shows it as a toast. Returning nothing gives a default "done".
|
|
527
|
+
- `input`: a DTO, and the type of the method's input parameter (boot fails when they differ). Left out, a DTO-class parameter is taken as the input. Its properties become a form in the dialog, checked in the browser and validated on the server like any write (whitelisted; class-validator; `@AdminField` for labels, help and widgets). A property with a class initializer is optional and keeps its default. File, image, rich-text and secret fields are not allowed in an input.
|
|
528
|
+
- Return `{ message }` (a text or `{ en, fa }`) to say what happened: the UI shows it as a toast. Returning nothing gives a default "done". Anything else is a compile error, and at run time an error that rolls the action back.
|
|
529
529
|
- Names that collide with `create`, `update`, `delete`, `restore`, `purge` or a method of `AdminResourceBase`, and options that do not fit together (`bulk` on a resource action, `atomic` without `bulk`), fail at boot.
|
|
530
530
|
- **Permissions.**
|
|
531
531
|
- Each action has the code `{r}.action.{name}`. `{r}.*` and `*` cover it, `{r}.action.*` covers every action of the resource, and `*.update` or `{r}.update` do not.
|
|
@@ -969,6 +969,27 @@ Things hosts tend to write by hand that the admin already does:
|
|
|
969
969
|
- **Inline children stay out of the sidebar** by default (`nav: false` unless they set `nav`): no extra group to hide them in.
|
|
970
970
|
- **Labels in one language** are plain strings; other languages can come from `translate` (see Languages, theme and branding).
|
|
971
971
|
|
|
972
|
+
## Upgrading to 0.9.0
|
|
973
|
+
|
|
974
|
+
The contracts between the admin and your code are now enforced: the decorators' types refuse a method or class of the wrong shape at compile time, and the admin refuses a wrong value at run time (a 500 with `nest-my-admin: …` in the log, or a boot error) instead of reading it as something else. Code that already followed the docs keeps working; code that compiled only through `any` or plain JavaScript may now fail. What to check:
|
|
975
|
+
|
|
976
|
+
- **Resource classes.** `@AdminResource(Entity)` needs a class that extends `AdminResourceBase<Entity>`, and `@AdminSource(Row)` one that extends `AdminSourceBase<Row>` (compile errors now, as well as the boot errors before).
|
|
977
|
+
- **Actions.** A method returns nothing or `{ message }` (`ActionOutcome`), sync or async. Anything else (the record, a string, `{ mesage }`) fails the run and its writes are rolled back. The first parameter of a record action is one of the resource's rows (typed: `extend(inst: Instance, …)` on an `AdminResourceBase<Instance>`). The next parameter is the input: give it the type of `input`, or leave `input` out and the parameter's class becomes the form. `input` that is not the parameter's class (or a parent of it), and a record parameter of another class, fail at boot. `label.for` returns a text or `null`, never a Promise.
|
|
978
|
+
- **Parameter types need `emitDecoratorMetadata`** (as Nest's own injection does; tsc, SWC and Bun emit it, esbuild, Vite and tsx do not). Without it, an action whose method takes an input parameter and sets no `input` fails at boot: set `input: SomeDto`, or `input: false` for an action that takes none.
|
|
979
|
+
- **`@AdminScope`** returns a column map or a callback at once, never a Promise: an async scope used to mean «no restriction»; now it is an error.
|
|
980
|
+
- **`@AdminCan`** returns `true` or `false` at once. A Promise or another value is an error (a rule that throws still means «no», with a warning).
|
|
981
|
+
- **`@AdminPrint`** returns `` html`…` `` (or a Promise of it). A plain string is refused: it was not escaped.
|
|
982
|
+
- **`readonlyIf`** returns a boolean, and `readonlyFields()` an array of names.
|
|
983
|
+
- **`findMany`** of a resource, a source or an inline child returns `{ items, total }` (`total` may be left out); an array is refused.
|
|
984
|
+
- **Computed columns:** `compute()` returns an object of values by id, and a badge's `map()` a `{ label, tone }` with a known tone.
|
|
985
|
+
- **Widgets** return the data of their `type` (a stat's `value` is text); `@AdminWidget` needs a class with `load()` and `@AdminSettingsPage` one with `load()` and `save()`.
|
|
986
|
+
- **Hooks:** `@BeforeSave`/`@AfterSave` take `(dto | entity, ctx, mode: 'create' | 'update')`, `@BeforeDelete` `(entity, ctx, mode: 'soft' | 'hard')`, and return nothing: a hook that returns a value (`return dto` in a `@BeforeSave` that meant to change it) is a compile error and fails the save. Change `dto` in place.
|
|
987
|
+
- **Resource methods:** `query()` returns the query builder it was given, at once (an `async query()` is an error); a list tab's `where(qb, ctx)` adds to `qb` at once; `relationOptions()` returns the query builder (or a Promise of it); `findOne()` a record or `null`; `create()`/`update()`/`restore()` the record or nothing (then it is reloaded); `links()` an array of `{ label, href }` (a link that is not http(s) or relative is still left out, now with a warning).
|
|
988
|
+
- **Module options and adapters:** `resolveRoles` (option or adapter) returns an array of role names (a string used to be read letter by letter); a thrown error still means «no roles». `authenticate()` returns `{ user }` or `null`; `getUser()` a user or `null`; a global scope's `appliesTo()` a boolean; `translate` a string or `undefined` at once (an async `translate` used to show the declared texts silently; a throw still falls back). An `errorMapper` that returns something other than an `AdminError` or `undefined` is logged as an error. `files.storage.publicUrl()` returns a URL or `undefined` at once, and `get()` `{ body, contentType, size }` or `null`.
|
|
989
|
+
- **What the types cannot see:** two DTO classes with the same properties are the same type to TypeScript; the boot check (with the parameter types) tells them apart.
|
|
990
|
+
|
|
991
|
+
New types: `ActionReturn` (what an action may return), `Awaitable<T>`, `RowOf<P>`, `TypedMethodDecorator<M>` and `TypedClassDecorator<I>` (for your own wrappers around the decorators).
|
|
992
|
+
|
|
972
993
|
## Upgrading to 0.8.1
|
|
973
994
|
|
|
974
995
|
Nothing to change. New: with `appearance` on, whoever holds `appearance.manage` uploads the **logo** (sidebar and sign-in page) and the **tab icon** (favicon) from the account menu, for everyone (PNG, JPEG, GIF, WebP, ICO or SVG, up to 512 KB; stored in `nma_setting`, served at `<path>/appearance/logo` and `/appearance/favicon`). An uploaded logo wins over `branding.logo`. Without a logo the sidebar shows the admin's own mark instead of the first letter of the title, and it is the default tab icon.
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { MAX_BULK } from '../constants.js';
|
|
2
2
|
import { parseRecordId, recordIdOf } from '../crud/record-id.js';
|
|
3
3
|
import { validateWrite } from '../crud/validate-write.js';
|
|
4
|
+
import { describeValue, HostContractError, isLocalizedText, checkFoundRecord } from '../host-contract.js';
|
|
4
5
|
import { AdminBadRequestError, AdminForbiddenError, AdminNotFoundError, AdminValidationError } from '../errors.js';
|
|
5
6
|
import { toErrorResponse } from '../http/error-response.js';
|
|
6
7
|
/**
|
|
@@ -40,7 +41,7 @@ export class ActionService {
|
|
|
40
41
|
return action.atomic ? this.runTogether(entry, action, label, ids, input, ctx) : this.runEach(entry, action, label, ids, input, ctx);
|
|
41
42
|
}
|
|
42
43
|
async runOnResource(entry, action, input, ctx) {
|
|
43
|
-
const outcome = await this.host.writes.run(entry, ctx, (tx) => this.host.writes.change({ kind: 'action', target: entry, action: { definition: action, input: input.sent } }, tx, async () => methodOf(entry, action).call(entry.resource, await input.fresh(), tx), () => undefined));
|
|
44
|
+
const outcome = await this.host.writes.run(entry, ctx, (tx) => this.host.writes.change({ kind: 'action', target: entry, action: { definition: action, input: input.sent } }, tx, async () => checkOutcome(await methodOf(entry, action).call(entry.resource, await input.fresh(), tx), entry, action), () => undefined));
|
|
44
45
|
return withMessage({}, messageOf(outcome, ctx, this.host.options));
|
|
45
46
|
}
|
|
46
47
|
runOnOne(entry, action, label, rawId, input, ctx) {
|
|
@@ -91,7 +92,7 @@ export class ActionService {
|
|
|
91
92
|
const id = parseRecordId(rawId, schema);
|
|
92
93
|
await policy.requireInScope(entry, id, rawId, 'view', tx);
|
|
93
94
|
await policy.requireInScope(entry, id, rawId, 'update', tx);
|
|
94
|
-
const record = await resource.findOne(id, tx);
|
|
95
|
+
const record = checkFoundRecord(await resource.findOne(id, tx), `${resource.constructor.name}.findOne()`);
|
|
95
96
|
if (!record)
|
|
96
97
|
throw new AdminNotFoundError(`${schema.label} "${rawId}" not found`);
|
|
97
98
|
// A per-record label of `null` means the action does not exist on this record (it is not offered there either).
|
|
@@ -112,7 +113,7 @@ export class ActionService {
|
|
|
112
113
|
const { id, record } = await this.loadAllowed(entry, action, label, rawId, tx);
|
|
113
114
|
// One change of the write: its participants see the record before the method runs (which may change the entity
|
|
114
115
|
// it is handed) and as it is read again afterwards, whether or not the user can still see it; null: it is gone.
|
|
115
|
-
const { outcome, reloaded } = await this.host.writes.change({ kind: 'action', target: entry, existing: record, id, action: { definition: action, input: input.sent } }, tx, async () => ({ outcome: await methodOf(entry, action).call(entry.resource, record, await input.fresh(), tx), reloaded: (await entry.resource.findOne(id, tx)) }), (result) => result.reloaded);
|
|
116
|
+
const { outcome, reloaded } = await this.host.writes.change({ kind: 'action', target: entry, existing: record, id, action: { definition: action, input: input.sent } }, tx, async () => ({ outcome: checkOutcome(await methodOf(entry, action).call(entry.resource, record, await input.fresh(), tx), entry, action), reloaded: (checkFoundRecord(await entry.resource.findOne(id, tx), `${entry.resource.constructor.name}.findOne()`)) }), (result) => result.reloaded);
|
|
116
117
|
// The action may have deleted the record or moved it out of the user's scopes (a findOne override may ignore them).
|
|
117
118
|
const visible = reloaded !== null && (await policy.allowedIds(entry, [id], 'view', tx)).size > 0;
|
|
118
119
|
return withMessage({ after: visible ? reloaded : null }, messageOf(outcome, tx, options));
|
|
@@ -183,11 +184,28 @@ async function validateInput(action, input) {
|
|
|
183
184
|
// A deep copy first: the instance must share nothing, nested lists included, with the body or another run's input.
|
|
184
185
|
return validateWrite(structuredClone(input ?? {}), { allowed: action.form?.fields.map((field) => field.name) ?? [], dto: action.input, keepDefaults: true });
|
|
185
186
|
}
|
|
186
|
-
/** `ActionOutcome.message` in the request's language
|
|
187
|
+
/** `ActionOutcome.message` in the request's language (the outcome was checked by `checkOutcome`). */
|
|
187
188
|
function messageOf(outcome, ctx, options) {
|
|
188
189
|
const message = isPlainObject(outcome) ? outcome.message : undefined;
|
|
189
|
-
|
|
190
|
-
|
|
190
|
+
return message === undefined ? undefined : options.texts(message, ctx.locale ?? options.locale) || undefined;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* What an action may answer: nothing, or `{ message }` with a text. Anything else (a record, a string, a typo such as
|
|
194
|
+
* `{ mesage }`) fails the action, inside its transaction, instead of being dropped without a word.
|
|
195
|
+
*/
|
|
196
|
+
function checkOutcome(outcome, entry, action) {
|
|
197
|
+
if (outcome === undefined || outcome === null)
|
|
198
|
+
return outcome;
|
|
199
|
+
const where = `${entry.className}.${action.name} (@AdminAction)`;
|
|
200
|
+
if (!isPlainObject(outcome))
|
|
201
|
+
throw new HostContractError(`${where} returned ${describeValue(outcome)}; an action returns nothing or { message }`);
|
|
202
|
+
const extra = Object.keys(outcome).filter((key) => key !== 'message');
|
|
203
|
+
if (extra.length > 0)
|
|
204
|
+
throw new HostContractError(`${where} returned { ${Object.keys(outcome).join(', ')} }; an action returns nothing or { message } (${extra.map((key) => `"${key}"`).join(', ')} is not part of it)`);
|
|
205
|
+
const { message } = outcome;
|
|
206
|
+
if (message !== undefined && !isLocalizedText(message))
|
|
207
|
+
throw new HostContractError(`${where} returned a message that is ${describeValue(message)}; it must be a text ('Done' or { en, fa })`);
|
|
208
|
+
return outcome;
|
|
191
209
|
}
|
|
192
210
|
/** One message for a bulk run only when every record that ran gave the same one. */
|
|
193
211
|
function sharedMessage(messages) {
|
|
@@ -10,6 +10,8 @@ var __metadata = (this && this.__metadata) || function (k, v) {
|
|
|
10
10
|
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
11
11
|
return function (target, key) { decorator(target, key, paramIndex); }
|
|
12
12
|
};
|
|
13
|
+
import { HtmlString } from '../print/html.js';
|
|
14
|
+
import { checkFindMany, checkFoundRecord, checkQueryBuilder, checkWriteResult, describeValue, HostContractError, isLocalizedText, isRecordObject } from '../host-contract.js';
|
|
13
15
|
import { Inject, Injectable, Logger } from '@nestjs/common';
|
|
14
16
|
import { applyFieldConfig, localizeLayout, mainLayout } from '../schema/field-config.js';
|
|
15
17
|
import { inlineOf, toLayoutInline } from '../inlines/inline-config.js';
|
|
@@ -202,7 +204,7 @@ let AdminApiService = class AdminApiService {
|
|
|
202
204
|
*/
|
|
203
205
|
async count(entry, params, ctx) {
|
|
204
206
|
const overridden = entry.resource.findMany !== AdminResourceBase.prototype.findMany;
|
|
205
|
-
const found = overridden && this.policy.scoped(entry, 'view', ctx) ? await AdminResourceBase.prototype.findMany.call(entry.resource, params, ctx) : await entry.resource.findMany(params, ctx);
|
|
207
|
+
const found = checkFindMany(overridden && this.policy.scoped(entry, 'view', ctx) ? await AdminResourceBase.prototype.findMany.call(entry.resource, params, ctx) : await entry.resource.findMany(params, ctx), entry.className);
|
|
206
208
|
return found.total === null || found.total === undefined ? undefined : { count: found.total, estimate: found.estimated === true };
|
|
207
209
|
}
|
|
208
210
|
/** `GET /api/resources/:resource/tab-counts`: each tab this user may use, counted in parallel (`null`: `count: 'none'`). */
|
|
@@ -311,7 +313,7 @@ let AdminApiService = class AdminApiService {
|
|
|
311
313
|
const sortPath = entry.sortPaths.get(params.sort.field);
|
|
312
314
|
if (sortPath)
|
|
313
315
|
params.sort = { ...params.sort, field: sortPath };
|
|
314
|
-
const found = await resource.findMany(params, ctx);
|
|
316
|
+
const found = checkFindMany(await resource.findMany(params, ctx), entry.className);
|
|
315
317
|
const { total, estimated, hasMore, nextCursor } = found;
|
|
316
318
|
let items = found.items;
|
|
317
319
|
// A findMany override may ignore the scopes; rows outside them never leave (spec §6.4).
|
|
@@ -370,7 +372,7 @@ let AdminApiService = class AdminApiService {
|
|
|
370
372
|
pagination: 'offset',
|
|
371
373
|
};
|
|
372
374
|
try {
|
|
373
|
-
const { items, hasMore } = await entry.resource.findMany(params, ctx);
|
|
375
|
+
const { items, hasMore } = checkFindMany(await entry.resource.findMany(params, ctx), entry.className);
|
|
374
376
|
if (items.length === 0)
|
|
375
377
|
return undefined;
|
|
376
378
|
return {
|
|
@@ -395,7 +397,7 @@ let AdminApiService = class AdminApiService {
|
|
|
395
397
|
this.policy.require(entry, 'view', ctx);
|
|
396
398
|
const { schema, resource } = entry;
|
|
397
399
|
const id = parseRecordId(rawId, schema);
|
|
398
|
-
const entity = await resource.findOne(id, ctx);
|
|
400
|
+
const entity = checkFoundRecord(await resource.findOne(id, ctx), `${resource.constructor.name}.findOne()`);
|
|
399
401
|
if (!entity)
|
|
400
402
|
throw new AdminNotFoundError(`${schema.label} "${rawId}" not found`);
|
|
401
403
|
await this.policy.requireInScope(entry, id, rawId, 'view', ctx); // a findOne override may ignore scopes
|
|
@@ -599,7 +601,7 @@ let AdminApiService = class AdminApiService {
|
|
|
599
601
|
await this.policy.requireInScope(entry, id, rawId, 'view', tx);
|
|
600
602
|
await this.policy.requireInScope(entry, id, rawId, 'update', tx);
|
|
601
603
|
await this.checkVersion(entry, id, version, tx);
|
|
602
|
-
const existing = await resource.findOne(id, tx);
|
|
604
|
+
const existing = checkFoundRecord(await resource.findOne(id, tx), `${resource.constructor.name}.findOne()`);
|
|
603
605
|
if (!existing)
|
|
604
606
|
throw new AdminNotFoundError(`${schema.label} "${rawId}" not found`);
|
|
605
607
|
this.policy.requireRecordRule(entry, 'update', existing, tx);
|
|
@@ -669,7 +671,7 @@ let AdminApiService = class AdminApiService {
|
|
|
669
671
|
await this.policy.requireInScope(entry, id, rawId, 'view', tx);
|
|
670
672
|
await this.policy.requireInScope(entry, id, rawId, 'delete', tx);
|
|
671
673
|
await this.checkVersion(entry, id, version, tx);
|
|
672
|
-
const existing = await resource.findOne(id, tx);
|
|
674
|
+
const existing = checkFoundRecord(await resource.findOne(id, tx), `${resource.constructor.name}.findOne()`);
|
|
673
675
|
if (!existing)
|
|
674
676
|
throw new AdminNotFoundError(`${schema.label} "${rawId}" not found`);
|
|
675
677
|
this.policy.requireRecordRule(entry, 'delete', existing, tx);
|
|
@@ -709,8 +711,8 @@ let AdminApiService = class AdminApiService {
|
|
|
709
711
|
// The target resource's query() restricts what may be picked, before this field's relationOptions().
|
|
710
712
|
const targetEntry = this.registry.forEntity(target.target, entry.dataSource);
|
|
711
713
|
// The target resource's query() and the user's view scopes there restrict what may be picked (spec §6.4).
|
|
712
|
-
const restricted = targetEntry ? this.policy.applyScopes(targetEntry.resource.query(qb, ctx), targetEntry, 'view', ctx) : qb;
|
|
713
|
-
return entry.resource.relationOptions(field, restricted, ctx, values);
|
|
714
|
+
const restricted = targetEntry ? this.policy.applyScopes(checkQueryBuilder(targetEntry.resource.query(qb, ctx), `${targetEntry.className}.query()`), targetEntry, 'view', ctx) : qb;
|
|
715
|
+
return checkQueryBuilder(await entry.resource.relationOptions(field, restricted, ctx, values), `${entry.className}.relationOptions()`);
|
|
714
716
|
}
|
|
715
717
|
/**
|
|
716
718
|
* Every id sent for a relation must name a record the field may point to (relationOptions()), else the write is a
|
|
@@ -871,7 +873,7 @@ let AdminApiService = class AdminApiService {
|
|
|
871
873
|
const entities = [];
|
|
872
874
|
for (const rawId of ids) {
|
|
873
875
|
const id = parseRecordId(rawId, entry.schema);
|
|
874
|
-
const entity = await entry.resource.findOne(id, ctx);
|
|
876
|
+
const entity = checkFoundRecord(await entry.resource.findOne(id, ctx), `${entry.resource.constructor.name}.findOne()`);
|
|
875
877
|
if (!entity)
|
|
876
878
|
throw new AdminNotFoundError(`${entry.schema.label} "${rawId}" not found`);
|
|
877
879
|
await this.policy.requireInScope(entry, id, rawId, 'view', ctx);
|
|
@@ -885,13 +887,16 @@ let AdminApiService = class AdminApiService {
|
|
|
885
887
|
catch (error) {
|
|
886
888
|
throw hostError(error);
|
|
887
889
|
}
|
|
890
|
+
// Only `html` output (which escaped every value) is put on the page: a plain string may carry a record's text as markup.
|
|
891
|
+
if (!(body instanceof HtmlString))
|
|
892
|
+
throw new HostContractError(`${entry.className}.${printName} (@AdminPrint) returned ${describeValue(body)}; return html\`…\` (it escapes every value), with raw() around markup you trust`);
|
|
888
893
|
const locale = ctx.locale ?? this.options.locale;
|
|
889
894
|
const label = this.options.texts(print.label, locale, `resource.${entry.schema.name}.prints.${print.name}.label`);
|
|
890
895
|
for (const entity of entities) {
|
|
891
896
|
await this.audit.recordAfter({ event: printCode(entry.schema.name, printName), entry, recordId: recordIdOf(entity, entry.schema.primaryKeys), title: entry.title(entity) }, ctx);
|
|
892
897
|
}
|
|
893
898
|
const title = entities.length === 1 ? `${label} · ${entry.title(entities[0])}` : label;
|
|
894
|
-
return printPage({ title, body:
|
|
899
|
+
return printPage({ title, body: body.value, size: print.size, locale });
|
|
895
900
|
}
|
|
896
901
|
/**
|
|
897
902
|
* `GET /resources/:name/export?<list query>`: the rows the list shows for this query (filters, search, tab, sort and
|
|
@@ -922,7 +927,7 @@ let AdminApiService = class AdminApiService {
|
|
|
922
927
|
const items = [];
|
|
923
928
|
let truncated = false;
|
|
924
929
|
for (let page = 1;; page++) {
|
|
925
|
-
const found = await entry.resource.findMany({ ...params, page, pageSize: EXPORT_PAGE, count: 'none', pagination: 'offset', after: undefined }, ctx);
|
|
930
|
+
const found = checkFindMany(await entry.resource.findMany({ ...params, page, pageSize: EXPORT_PAGE, count: 'none', pagination: 'offset', after: undefined }, ctx), entry.className);
|
|
926
931
|
let batch = found.items;
|
|
927
932
|
// A findMany override may ignore the scopes; rows outside them never leave (spec §6.4).
|
|
928
933
|
if (scoped) {
|
|
@@ -997,14 +1002,19 @@ let AdminApiService = class AdminApiService {
|
|
|
997
1002
|
for (const [name, options] of entry.fieldConfig) {
|
|
998
1003
|
if (!options.readonlyIf)
|
|
999
1004
|
continue;
|
|
1005
|
+
let answer;
|
|
1000
1006
|
try {
|
|
1001
|
-
|
|
1002
|
-
locked.add(name);
|
|
1007
|
+
answer = options.readonlyIf(entity);
|
|
1003
1008
|
}
|
|
1004
1009
|
catch (error) {
|
|
1005
1010
|
locked.add(name);
|
|
1006
1011
|
this.warnOnce(`${entry.className}.fields.${name}.readonlyIf threw (${error instanceof Error ? error.message : String(error)}); the field stays read-only`);
|
|
1012
|
+
continue;
|
|
1007
1013
|
}
|
|
1014
|
+
if (typeof answer !== 'boolean')
|
|
1015
|
+
throw new HostContractError(`${entry.className}.fields.${name}.readonlyIf returned ${describeValue(answer)}; it answers at once with true or false (it cannot be async)`);
|
|
1016
|
+
if (answer)
|
|
1017
|
+
locked.add(name);
|
|
1008
1018
|
}
|
|
1009
1019
|
let more;
|
|
1010
1020
|
try {
|
|
@@ -1014,6 +1024,8 @@ let AdminApiService = class AdminApiService {
|
|
|
1014
1024
|
more = entry.schema.form.update;
|
|
1015
1025
|
this.warnOnce(`${entry.className}.readonlyFields threw (${error instanceof Error ? error.message : String(error)}); the record stays read-only`);
|
|
1016
1026
|
}
|
|
1027
|
+
if (!Array.isArray(more))
|
|
1028
|
+
throw new HostContractError(`${entry.className}.readonlyFields() returned ${describeValue(more)}; it answers at once with an array of field names (it cannot be async)`);
|
|
1017
1029
|
const fields = new Set(entry.schema.fields.map((field) => field.name));
|
|
1018
1030
|
for (const name of more) {
|
|
1019
1031
|
if (fields.has(name) && !entry.schema.primaryKeys.includes(name))
|
|
@@ -1033,8 +1045,17 @@ let AdminApiService = class AdminApiService {
|
|
|
1033
1045
|
this.warnOnce(`${entry.className}.links() threw: ${error instanceof Error ? error.message : String(error)}`);
|
|
1034
1046
|
return [];
|
|
1035
1047
|
}
|
|
1036
|
-
|
|
1037
|
-
.
|
|
1048
|
+
if (!Array.isArray(links) || links.some((link) => !isRecordObject(link) || typeof link.href !== 'string' || !isLocalizedText(link.label))) {
|
|
1049
|
+
throw new HostContractError(`${entry.className}.links() must return an array of { label, href }, but it returned ${describeValue(links)}`);
|
|
1050
|
+
}
|
|
1051
|
+
// A link of another scheme (javascript:, data:) is never shown: it would run in the admin.
|
|
1052
|
+
return links
|
|
1053
|
+
.filter((link) => {
|
|
1054
|
+
const safe = /^https?:\/\//i.test(link.href) || !/^[a-z][a-z0-9+.-]*:/i.test(link.href.trim());
|
|
1055
|
+
if (!safe)
|
|
1056
|
+
this.warnOnce(`${entry.className}.links(): "${link.href.slice(0, 40)}" is not an http(s) or relative URL; it is not shown`);
|
|
1057
|
+
return safe;
|
|
1058
|
+
})
|
|
1038
1059
|
.map((link) => ({ label: this.options.texts(link.label, locale), href: link.href }));
|
|
1039
1060
|
}
|
|
1040
1061
|
warned = new Set();
|
|
@@ -1052,9 +1073,10 @@ let AdminApiService = class AdminApiService {
|
|
|
1052
1073
|
}
|
|
1053
1074
|
/** Host services often return nothing from update(); fall back to reading the record. */
|
|
1054
1075
|
async reloadIfEmpty(entry, result, id, ctx) {
|
|
1076
|
+
checkWriteResult(result, `${entry.className}: create(), update() and restore()`);
|
|
1055
1077
|
if (typeof result === 'object' && result !== null)
|
|
1056
1078
|
return result;
|
|
1057
|
-
const reloaded = await entry.resource.findOne(id, ctx);
|
|
1079
|
+
const reloaded = checkFoundRecord(await entry.resource.findOne(id, ctx), `${entry.className}.findOne()`);
|
|
1058
1080
|
if (!reloaded)
|
|
1059
1081
|
throw new AdminNotFoundError(`${entry.schema.label} "${typeof id === 'object' ? encodeRecordId(Object.values(id)) : id}" not found`);
|
|
1060
1082
|
return reloaded;
|
|
@@ -22,6 +22,7 @@ import { AdminResourceBase } from '../resource/admin-resource-base.js';
|
|
|
22
22
|
import { AUDIT_FILTERS, parseAuditQuery } from './audit-query.js';
|
|
23
23
|
import { AdminAudit } from './audit.service.js';
|
|
24
24
|
import { NmaAuditEntry } from './entities.js';
|
|
25
|
+
import { checkQueryBuilder, checkFoundRecord } from '../host-contract.js';
|
|
25
26
|
/** Entries per page. */
|
|
26
27
|
export const AUDIT_PAGE_SIZE = 50;
|
|
27
28
|
/** The code that opens the audit page (`policy/catalog.ts` adds it to the catalog while the audit log is on). */
|
|
@@ -332,7 +333,7 @@ let AuditReader = class AuditReader {
|
|
|
332
333
|
if (narrowed && entry.dataSource) {
|
|
333
334
|
const qb = entry.dataSource.getRepository(entry.metadata.target).createQueryBuilder('entity').withDeleted();
|
|
334
335
|
// The ids go on last: a `query()` that starts its own `where()` must not leave the select unbounded.
|
|
335
|
-
const restricted = this.policy.applyScopes(entry.resource.query(qb, ctx), entry, 'view', ctx).andWhereInIds([...ids.values()]);
|
|
336
|
+
const restricted = this.policy.applyScopes(checkQueryBuilder(entry.resource.query(qb, ctx), `${entry.className}.query()`), entry, 'view', ctx).andWhereInIds([...ids.values()]);
|
|
336
337
|
const found = await restricted.select(keys.map((key) => `${restricted.alias}.${key}`)).getMany();
|
|
337
338
|
const within = new Set(found.map((row) => recordIdOf(row, keys)));
|
|
338
339
|
seen = new Set([...seen].filter((raw) => within.has(raw)));
|
|
@@ -343,7 +344,7 @@ let AuditReader = class AuditReader {
|
|
|
343
344
|
for (const raw of [...seen]) {
|
|
344
345
|
let found;
|
|
345
346
|
try {
|
|
346
|
-
found = await entry.resource.findOne(ids.get(raw), ctx, { withDeleted: true });
|
|
347
|
+
found = checkFoundRecord(await entry.resource.findOne(ids.get(raw), ctx, { withDeleted: true }), `${entry.resource.constructor.name}.findOne()`);
|
|
347
348
|
}
|
|
348
349
|
catch {
|
|
349
350
|
found = null;
|
|
@@ -16,6 +16,7 @@ import { timingSafeEqual } from 'node:crypto';
|
|
|
16
16
|
import { ADMIN_OPTIONS } from '../constants.js';
|
|
17
17
|
import { AdminForbiddenError, AdminUnauthenticatedError } from '../errors.js';
|
|
18
18
|
import { OPEN_ADMIN_USER } from './auth-adapter.js';
|
|
19
|
+
import { describeValue, HostContractError, isRecordObject } from '../host-contract.js';
|
|
19
20
|
const MUTATING = new Set(['POST', 'PATCH', 'PUT', 'DELETE']);
|
|
20
21
|
/** Resolves the configured auth adapter at boot and authenticates each admin API request (spec §4: auth first). */
|
|
21
22
|
let AdminAuthService = class AdminAuthService {
|
|
@@ -69,7 +70,14 @@ let AdminAuthService = class AdminAuthService {
|
|
|
69
70
|
await (this.ready ??= this.resolve());
|
|
70
71
|
if (this.open)
|
|
71
72
|
return { user: OPEN_ADMIN_USER };
|
|
72
|
-
|
|
73
|
+
const principal = await this.adapterValue.authenticate(req);
|
|
74
|
+
if (principal === null || principal === undefined)
|
|
75
|
+
return null;
|
|
76
|
+
const user = principal.user;
|
|
77
|
+
if (!isRecordObject(principal) || typeof user !== 'object' || user === null || (typeof user.id !== 'string' && typeof user.id !== 'number')) {
|
|
78
|
+
throw new HostContractError(`the auth adapter's authenticate() must return { user: { id, displayName, isSuperuser } } or null, but it returned ${describeValue(principal)}`);
|
|
79
|
+
}
|
|
80
|
+
return principal;
|
|
73
81
|
}
|
|
74
82
|
/** The principal, or 401; mutating requests of cookie sessions must also carry the session's CSRF token (403). */
|
|
75
83
|
async require(req) {
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { resolvePath } from '../schema/relation-fields.js';
|
|
2
2
|
import { recordIdOf } from './record-id.js';
|
|
3
3
|
import { serializeValue } from './serialize.js';
|
|
4
|
+
import { describeValue, HostContractError, isPlainObject } from '../host-contract.js';
|
|
5
|
+
import { TONES } from '../dashboard/widget-data.js';
|
|
4
6
|
const KINDS = ['image', 'title', 'money', 'badge', 'count', 'toggle'];
|
|
5
7
|
const AGGREGATES = ['min', 'max', 'sum', 'count'];
|
|
6
8
|
/**
|
|
@@ -207,6 +209,8 @@ fieldFor) {
|
|
|
207
209
|
return byRow;
|
|
208
210
|
case 'compute': {
|
|
209
211
|
const values = await source.fn(rows, ctx);
|
|
212
|
+
if (!isPlainObject(values))
|
|
213
|
+
throw new HostContractError(`list.computed: compute()${source.fn.name && source.fn.name !== 'compute' ? ` (${source.fn.name})` : ''} returned ${describeValue(values)}; it answers an object of values by record id ({ [id]: value })`);
|
|
210
214
|
for (const row of rows)
|
|
211
215
|
byRow.set(recordIdOf(row, keys), values[recordIdOf(row, keys)] ?? null);
|
|
212
216
|
return byRow;
|
|
@@ -225,6 +229,11 @@ fieldFor) {
|
|
|
225
229
|
cell.previous = previous.get(id) ?? null;
|
|
226
230
|
if (compiled.column.map) {
|
|
227
231
|
const mapped = compiled.column.map(value, row);
|
|
232
|
+
const where = `list.computed.${compiled.key}.map()`;
|
|
233
|
+
if (!isPlainObject(mapped))
|
|
234
|
+
throw new HostContractError(`${where} returned ${describeValue(mapped)}; it answers { label, tone }`);
|
|
235
|
+
if (mapped.tone !== undefined && !TONES.includes(mapped.tone))
|
|
236
|
+
throw new HostContractError(`${where} returned the tone ${describeValue(mapped.tone)}; a tone is one of ${TONES.join(', ')}`);
|
|
228
237
|
cell.label = text(mapped.label);
|
|
229
238
|
cell.tone = mapped.tone;
|
|
230
239
|
}
|
|
@@ -15,6 +15,7 @@ import { ADMIN_OPTIONS } from '../constants.js';
|
|
|
15
15
|
import { AdminBadRequestError, AdminNotFoundError } from '../errors.js';
|
|
16
16
|
import { AdminPolicy } from '../policy/admin-policy.service.js';
|
|
17
17
|
import { WidgetRegistry } from './widget-registry.js';
|
|
18
|
+
import { checkWidgetData } from './widget-data.js';
|
|
18
19
|
const PERIODS = ['day', 'week', 'month', 'year', 'range'];
|
|
19
20
|
const MAX_SPAN_MS = 366 * 24 * 60 * 60 * 1000;
|
|
20
21
|
/** The dashboard (spec §5.8): the widgets a user may see, and each one's data for a period. */
|
|
@@ -44,7 +45,7 @@ let DashboardService = class DashboardService {
|
|
|
44
45
|
const widget = this.visible(ctx).find((candidate) => candidate.name === name);
|
|
45
46
|
if (!widget)
|
|
46
47
|
throw new AdminNotFoundError(`Unknown widget "${name}"`);
|
|
47
|
-
return widget.source.load(parsePeriod(query), ctx);
|
|
48
|
+
return checkWidgetData(widget.type, await widget.source.load(parsePeriod(query), ctx), widget.className);
|
|
48
49
|
}
|
|
49
50
|
};
|
|
50
51
|
DashboardService = __decorate([
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Tone, WidgetData, WidgetType } from '../contract.js';
|
|
2
|
+
/** The tones of badges, list items and computed cells. */
|
|
3
|
+
export declare const TONES: readonly Tone[];
|
|
4
|
+
/**
|
|
5
|
+
* A widget's `load()` answer checked against its `type` (spec §5.8), so a wrong shape fails here with a sentence
|
|
6
|
+
* instead of breaking the dashboard in the browser.
|
|
7
|
+
*/
|
|
8
|
+
export declare function checkWidgetData(type: WidgetType, data: unknown, where: string): WidgetData;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { describeValue, HostContractError, isPlainObject } from '../host-contract.js';
|
|
2
|
+
/** The tones of badges, list items and computed cells. */
|
|
3
|
+
export const TONES = ['ok', 'warn', 'bad', 'info', 'neutral', 'primary'];
|
|
4
|
+
const isText = (value) => typeof value === 'string';
|
|
5
|
+
const isNumber = (value) => typeof value === 'number' && Number.isFinite(value);
|
|
6
|
+
const isTone = (value) => TONES.includes(value);
|
|
7
|
+
/**
|
|
8
|
+
* A widget's `load()` answer checked against its `type` (spec §5.8), so a wrong shape fails here with a sentence
|
|
9
|
+
* instead of breaking the dashboard in the browser.
|
|
10
|
+
*/
|
|
11
|
+
export function checkWidgetData(type, data, where) {
|
|
12
|
+
const fail = (what) => {
|
|
13
|
+
throw new HostContractError(`${where}.load() (a ${type} widget) ${what}`);
|
|
14
|
+
};
|
|
15
|
+
if (!isPlainObject(data))
|
|
16
|
+
fail(`returned ${describeValue(data)}; it answers the ${type} widget's data`);
|
|
17
|
+
const d = data;
|
|
18
|
+
const need = (key, ok, expected) => {
|
|
19
|
+
if (!ok(d[key]))
|
|
20
|
+
fail(`returned ${key} = ${describeValue(d[key])}; ${key} must be ${expected}`);
|
|
21
|
+
};
|
|
22
|
+
const optional = (key, ok, expected) => {
|
|
23
|
+
if (d[key] !== undefined)
|
|
24
|
+
need(key, ok, expected);
|
|
25
|
+
};
|
|
26
|
+
switch (type) {
|
|
27
|
+
case 'stat':
|
|
28
|
+
need('value', isText, 'a text (format numbers yourself, or String(n))');
|
|
29
|
+
optional('unit', isText, 'a text');
|
|
30
|
+
optional('change', isNumber, 'a number (percent)');
|
|
31
|
+
optional('previousLabel', isText, 'a text');
|
|
32
|
+
break;
|
|
33
|
+
case 'chart':
|
|
34
|
+
need('kind', (v) => v === 'bar' || v === 'line', '"bar" or "line"');
|
|
35
|
+
need('labels', (v) => Array.isArray(v) && v.every(isText), 'an array of texts');
|
|
36
|
+
need('series', (v) => Array.isArray(v) && v.every((s) => isPlainObject(s) && isText(s.label) && Array.isArray(s.values) && s.values.every(isNumber)), 'an array of { label, values: number[] }');
|
|
37
|
+
optional('total', isText, 'a text');
|
|
38
|
+
optional('subtitle', isText, 'a text');
|
|
39
|
+
break;
|
|
40
|
+
case 'table':
|
|
41
|
+
need('columns', (v) => Array.isArray(v) && v.every((c) => isPlainObject(c) && isText(c.key) && isText(c.label)), 'an array of { key, label }');
|
|
42
|
+
need('rows', (v) => Array.isArray(v) && v.every((row) => isPlainObject(row) && Object.values(row).every((cell) => isText(cell) || isNumber(cell) || (isPlainObject(cell) && isText(cell.label) && isTone(cell.tone)))), `an array of rows whose cells are texts, numbers or { label, tone } (tone: ${TONES.join(', ')})`);
|
|
43
|
+
break;
|
|
44
|
+
case 'progress':
|
|
45
|
+
need('percent', isNumber, 'a number');
|
|
46
|
+
need('value', isText, 'a text');
|
|
47
|
+
need('caption', isText, 'a text');
|
|
48
|
+
break;
|
|
49
|
+
case 'list':
|
|
50
|
+
need('items', (v) => Array.isArray(v) && v.every((item) => isPlainObject(item) && isText(item.text) && (item.status === undefined || isTone(item.status))), `an array of { text, status? } (status: ${TONES.join(', ')})`);
|
|
51
|
+
break;
|
|
52
|
+
}
|
|
53
|
+
return data;
|
|
54
|
+
}
|
|
55
|
+
//# sourceMappingURL=widget-data.js.map
|
|
@@ -2,8 +2,10 @@ import 'reflect-metadata';
|
|
|
2
2
|
import type { ActionSchema } from '../contract.js';
|
|
3
3
|
import { type LocalizedText } from '../i18n/localized-text.js';
|
|
4
4
|
import { type DtoForm } from '../schema/dto-form.js';
|
|
5
|
-
import type
|
|
5
|
+
import { type DtoClass } from '../schema/dto-fields.js';
|
|
6
6
|
import type { ScopedText } from '../i18n/texts.js';
|
|
7
|
+
import type { AdminContext } from '../resource/admin-context.js';
|
|
8
|
+
import type { Awaitable, RecordMethodDecorator, TypedMethodDecorator } from './typed.js';
|
|
7
9
|
export interface AdminActionOptions {
|
|
8
10
|
/**
|
|
9
11
|
* `'Mark shipped'` or `{ en: 'Mark shipped', fa: 'ارسال شد' }`. Defaults to the humanized method name. A label per
|
|
@@ -38,14 +40,18 @@ export interface AdminActionOptions {
|
|
|
38
40
|
/**
|
|
39
41
|
* A DTO for a form in the dialog. It is validated like a write (whitelist, class-validator) before the method
|
|
40
42
|
* runs; `@AdminField` on its properties sets labels, help and widgets. Files and rich text are not supported.
|
|
43
|
+
* Left out, the class of the method's input parameter is used (it needs `emitDecoratorMetadata`); `false` says
|
|
44
|
+
* the action takes no input, where the parameter types cannot be read.
|
|
41
45
|
*/
|
|
42
|
-
input?: DtoClass;
|
|
46
|
+
input?: DtoClass | false;
|
|
43
47
|
icon?: string;
|
|
44
48
|
}
|
|
45
49
|
/** What an action method may return: a message for the person who ran it. */
|
|
46
50
|
export interface ActionOutcome {
|
|
47
51
|
message?: LocalizedText;
|
|
48
52
|
}
|
|
53
|
+
/** What an action method returns: nothing, or an `ActionOutcome`. */
|
|
54
|
+
export type ActionReturn = ActionOutcome | void | null | undefined;
|
|
49
55
|
/** An `@AdminAction` as declared. `name` is the method name: the URL segment and the `{resource}.action.{name}` code. */
|
|
50
56
|
export interface ActionDefinition extends AdminActionOptions {
|
|
51
57
|
name: string;
|
|
@@ -74,13 +80,31 @@ export interface RegisteredAction {
|
|
|
74
80
|
* wrote is undone when it throws, and `atomic` actions are refused at boot. Throw an `HttpException` (or
|
|
75
81
|
* `AdminFieldError` for input fields) to refuse.
|
|
76
82
|
*/
|
|
77
|
-
export declare function AdminAction(options
|
|
83
|
+
export declare function AdminAction<I extends object>(options: AdminActionOptions & {
|
|
84
|
+
target: 'resource';
|
|
85
|
+
input: new (...args: any[]) => I;
|
|
86
|
+
}): TypedMethodDecorator<(input: I, ctx: AdminContext) => Awaitable<ActionReturn>>;
|
|
87
|
+
export declare function AdminAction(options: AdminActionOptions & {
|
|
88
|
+
target: 'resource';
|
|
89
|
+
}): TypedMethodDecorator<(input: any, ctx: AdminContext) => Awaitable<ActionReturn>>;
|
|
90
|
+
export declare function AdminAction<I extends object>(options: AdminActionOptions & {
|
|
91
|
+
target?: 'record';
|
|
92
|
+
input: new (...args: any[]) => I;
|
|
93
|
+
}): RecordMethodDecorator<[input: I, ctx: AdminContext], Awaitable<ActionReturn>>;
|
|
94
|
+
export declare function AdminAction(options?: AdminActionOptions & {
|
|
95
|
+
target?: 'record';
|
|
96
|
+
}): RecordMethodDecorator<[input: any, ctx: AdminContext], Awaitable<ActionReturn>>;
|
|
97
|
+
export declare function AdminAction(options?: AdminActionOptions): TypedMethodDecorator<(...args: any[]) => Awaitable<ActionReturn>>;
|
|
78
98
|
/** The actions declared on a resource class (inherited ones first), by name. */
|
|
79
99
|
export declare function getActions(resourceClass: Function): Map<string, ActionDefinition>;
|
|
80
100
|
/**
|
|
81
101
|
* Boot-time checks of a resource class's actions and of its `@AdminCan` names; returns the actions ready to run.
|
|
82
|
-
* `reserved` are the method names of `AdminResourceBase`, which an action must not take over
|
|
102
|
+
* `reserved` are the method names of `AdminResourceBase`, which an action must not take over; `row` is the class of
|
|
103
|
+
* the records (the entity, or a source's row), checked against a record action's first parameter.
|
|
104
|
+
*
|
|
105
|
+
* The method's parameter types (when the build emits them: tsc, SWC, Bun; not esbuild or Vite) are checked against the
|
|
106
|
+
* action: `input` must be the class of its input parameter, and an action without `input` takes it from that parameter.
|
|
83
107
|
*/
|
|
84
|
-
export declare function resolveActions(resourceClass: Function, reserved: readonly string[], fail: (message: string) => never): Map<string, RegisteredAction>;
|
|
108
|
+
export declare function resolveActions(resourceClass: Function, reserved: readonly string[], fail: (message: string) => never, row?: Function): Map<string, RegisteredAction>;
|
|
85
109
|
/** The action as one request gets it, texts through `text` (keys `actions.<name>.…` of the resource). */
|
|
86
110
|
export declare function toActionSchema(action: RegisteredAction, text: ScopedText): ActionSchema;
|
|
@@ -1,17 +1,11 @@
|
|
|
1
1
|
import 'reflect-metadata';
|
|
2
2
|
import { ADMIN_ACTIONS_METADATA } from '../constants.js';
|
|
3
3
|
import { buildDtoForm, localizeDtoForm } from '../schema/dto-form.js';
|
|
4
|
+
import { dtoPropertyNames } from '../schema/dto-fields.js';
|
|
5
|
+
import { describeValue, HostContractError, isLocalizedText } from '../host-contract.js';
|
|
4
6
|
import { humanize } from '../schema/humanize.js';
|
|
5
7
|
import { didYouMean } from '../schema/suggest.js';
|
|
6
8
|
import { getCanRuleNames } from './admin-scope.js';
|
|
7
|
-
/**
|
|
8
|
-
* A custom action of a resource (spec §5.2): a button on a record, on a list selection (`bulk`) or on the list
|
|
9
|
-
* (`target: 'resource'`). The method name is the action's name; running it needs `{resource}.action.{name}`, and for
|
|
10
|
-
* record actions `{resource}.update`, the user's row scopes and any `@AdminCan('<name>')` rule. It runs inside the
|
|
11
|
-
* admin's write transaction (`ctx.manager`), unless the admin runs with `transactions: false`: then nothing a method
|
|
12
|
-
* wrote is undone when it throws, and `atomic` actions are refused at boot. Throw an `HttpException` (or
|
|
13
|
-
* `AdminFieldError` for input fields) to refuse.
|
|
14
|
-
*/
|
|
15
9
|
export function AdminAction(options = {}) {
|
|
16
10
|
return (target, propertyKey) => {
|
|
17
11
|
if (typeof propertyKey !== 'string')
|
|
@@ -33,7 +27,19 @@ const UPLOAD_WIDGETS = ['file', 'image', 'richtext'];
|
|
|
33
27
|
* Boot-time checks of a resource class's actions and of its `@AdminCan` names; returns the actions ready to run.
|
|
34
28
|
* `reserved` are the method names of `AdminResourceBase`, which an action must not take over.
|
|
35
29
|
*/
|
|
36
|
-
|
|
30
|
+
/** A class the method's parameter was declared as (emitted with `emitDecoratorMetadata`); not `Object` (an interface, `any`) or a built-in. */
|
|
31
|
+
const BUILT_INS = [Object, String, Number, Boolean, Array, Promise, Function, Date, Map, Set];
|
|
32
|
+
const declaredClass = (type) => (typeof type === 'function' && !BUILT_INS.includes(type) ? type : undefined);
|
|
33
|
+
const related = (a, b) => a === b || a.prototype instanceof b || b.prototype instanceof a;
|
|
34
|
+
/**
|
|
35
|
+
* Boot-time checks of a resource class's actions and of its `@AdminCan` names; returns the actions ready to run.
|
|
36
|
+
* `reserved` are the method names of `AdminResourceBase`, which an action must not take over; `row` is the class of
|
|
37
|
+
* the records (the entity, or a source's row), checked against a record action's first parameter.
|
|
38
|
+
*
|
|
39
|
+
* The method's parameter types (when the build emits them: tsc, SWC, Bun; not esbuild or Vite) are checked against the
|
|
40
|
+
* action: `input` must be the class of its input parameter, and an action without `input` takes it from that parameter.
|
|
41
|
+
*/
|
|
42
|
+
export function resolveActions(resourceClass, reserved, fail, row) {
|
|
37
43
|
const actions = new Map();
|
|
38
44
|
for (const definition of getActions(resourceClass).values()) {
|
|
39
45
|
const { name } = definition;
|
|
@@ -56,7 +62,30 @@ export function resolveActions(resourceClass, reserved, fail) {
|
|
|
56
62
|
fail(`${where}: \`bulk\` and \`atomic\` are for record actions`);
|
|
57
63
|
if (atomic && !bulk)
|
|
58
64
|
fail(`${where}: \`atomic\` needs \`bulk: true\``);
|
|
59
|
-
const { confirm,
|
|
65
|
+
const { confirm, icon, label } = definition;
|
|
66
|
+
const noInput = definition.input === false;
|
|
67
|
+
let input = definition.input === false ? undefined : definition.input;
|
|
68
|
+
const params = Reflect.getMetadata('design:paramtypes', resourceClass.prototype, name);
|
|
69
|
+
const method = resourceClass.prototype[name];
|
|
70
|
+
const takesInput = typeof method === 'function' && method.length > (target === 'record' ? 1 : 0);
|
|
71
|
+
if (params === undefined && input === undefined && !noInput && takesInput) {
|
|
72
|
+
fail(`${where}: the method takes an input parameter, but its type cannot be read (emitDecoratorMetadata is off, or the build drops it: esbuild, Vite, tsx); set \`input\` to its DTO class, or \`input: false\` if it takes none`);
|
|
73
|
+
}
|
|
74
|
+
const recordParam = target === 'record' ? declaredClass(params?.[0]) : undefined;
|
|
75
|
+
if (recordParam && row && !related(recordParam, row))
|
|
76
|
+
fail(`${where}: the method's first parameter is ${recordParam.name}, but the action runs on ${row.name} records`);
|
|
77
|
+
const inputParam = declaredClass(params?.[target === 'record' ? 1 : 0]);
|
|
78
|
+
const inputLike = inputParam !== undefined && inputParam !== row && dtoPropertyNames(inputParam).length > 0;
|
|
79
|
+
if (input !== undefined && typeof input === 'function' && inputParam && inputParam !== input && !(input.prototype instanceof inputParam)) {
|
|
80
|
+
fail(`${where}: \`input\` is ${input.name} but the method's input parameter is ${inputParam.name}; use the same class (or leave \`input\` out to take the parameter's)`);
|
|
81
|
+
}
|
|
82
|
+
if (noInput && inputLike)
|
|
83
|
+
fail(`${where}: \`input: false\`, but the method's input parameter is ${inputParam.name}`);
|
|
84
|
+
if (input === undefined && !noInput && inputLike) {
|
|
85
|
+
if (definition.primary === true)
|
|
86
|
+
fail(`${where}: a primary action runs in one click and takes no input, but the method's input parameter is ${inputParam.name}`);
|
|
87
|
+
input = inputParam;
|
|
88
|
+
}
|
|
60
89
|
if (confirm !== undefined && typeof confirm !== 'boolean' && !isText(confirm))
|
|
61
90
|
fail(`${where}: confirm must be true, false or a text`);
|
|
62
91
|
const perRecord = typeof label === 'object' && label !== null && 'for' in label;
|
|
@@ -90,7 +119,7 @@ export function resolveActions(resourceClass, reserved, fail) {
|
|
|
90
119
|
actions.set(name, {
|
|
91
120
|
name,
|
|
92
121
|
label: perRecord ? label.static : (label ?? humanize(name)),
|
|
93
|
-
...(perRecord ? { labelFor: label.for } : {}),
|
|
122
|
+
...(perRecord ? { labelFor: checkedLabelFor(`${resourceClass.name} @AdminAction "${name}" label.for`, label.for) } : {}),
|
|
94
123
|
primary,
|
|
95
124
|
target,
|
|
96
125
|
bulk,
|
|
@@ -118,9 +147,7 @@ export function resolveActions(resourceClass, reserved, fail) {
|
|
|
118
147
|
return actions;
|
|
119
148
|
}
|
|
120
149
|
function isText(value) {
|
|
121
|
-
|
|
122
|
-
return true;
|
|
123
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value) && Object.values(value).every((text) => typeof text === 'string');
|
|
150
|
+
return isLocalizedText(value);
|
|
124
151
|
}
|
|
125
152
|
/** The action as one request gets it, texts through `text` (keys `actions.<name>.…` of the resource). */
|
|
126
153
|
export function toActionSchema(action, text) {
|
|
@@ -139,4 +166,13 @@ export function toActionSchema(action, text) {
|
|
|
139
166
|
...(action.form ? { input: localizeDtoForm(action.form, (value, path) => text(value, `${at}.fields.${path}`)) } : {}),
|
|
140
167
|
};
|
|
141
168
|
}
|
|
169
|
+
/** `label.for` as called: a text, or `null` (not on this record); anything else (a Promise of an `async` one) fails loudly. */
|
|
170
|
+
function checkedLabelFor(where, labelFor) {
|
|
171
|
+
return (record) => {
|
|
172
|
+
const value = labelFor(record);
|
|
173
|
+
if (value !== null && !isLocalizedText(value))
|
|
174
|
+
throw new HostContractError(`${where} returned ${describeValue(value)}; it answers at once with a text, or null where the action does not apply (it cannot be async)`);
|
|
175
|
+
return value;
|
|
176
|
+
};
|
|
177
|
+
}
|
|
142
178
|
//# sourceMappingURL=admin-action.js.map
|