@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/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.
|
|
@@ -537,6 +537,13 @@ export class OrderAdmin extends AdminResourceBase<Order> {
|
|
|
537
537
|
- **Selections.** A bulk action runs on up to 100 records.
|
|
538
538
|
- By default each record gets its own transaction: the answer is `{ ok, failed: [{ id, code, message }], message? }`, and one failure does not stop the others. The list shows how many ran and why the others did not.
|
|
539
539
|
- `atomic: true` runs them all in one transaction: every record is checked first, and one failure is the answer, with nothing applied. It needs the admin's transactions (boot fails with `transactions: false`). The confirmation says "all or nothing".
|
|
540
|
+
- **A dropdown from live data.** `choices: { field: 'methodName' }` turns an input field into a dropdown whose options a method of the resource gives when the dialog opens: the branches of a repository, the services a provider offers today.
|
|
541
|
+
```ts
|
|
542
|
+
@AdminAction({ target: 'resource', input: DeployDto, choices: { backendRef: 'backendBranches' } })
|
|
543
|
+
async deploy(input: DeployDto) { … }
|
|
544
|
+
async backendBranches(ctx: AdminContext) { return this.github.branches('api'); } // strings, or { value, label }
|
|
545
|
+
```
|
|
546
|
+
The method runs for whoever may run the action (`GET …/actions/:action/choices/:field`), sync or async. A run reads the choices again and refuses a value that is not one of them (422 on the field). The field keeps its `default` while the list loads. Field names are checked against `input` by the types and at boot, and the method must exist.
|
|
540
547
|
- **Picking a record.** `@AdminField({ pickFrom: 'categoryId' })` on an input property shows the same picker as the resource's own relation field `categoryId`; the property receives the chosen id (validate it with `@IsInt()`, and check it exists in the method).
|
|
541
548
|
- **Refusing.** Throw from the method:
|
|
542
549
|
- an `HttpException` below 500 answers with its status and message (409 is `CONFLICT`, 400 is `BUSINESS_RULE`), and the UI shows the message;
|
|
@@ -969,6 +976,31 @@ Things hosts tend to write by hand that the admin already does:
|
|
|
969
976
|
- **Inline children stay out of the sidebar** by default (`nav: false` unless they set `nav`): no extra group to hide them in.
|
|
970
977
|
- **Labels in one language** are plain strings; other languages can come from `translate` (see Languages, theme and branding).
|
|
971
978
|
|
|
979
|
+
## Upgrading to 0.9.1
|
|
980
|
+
|
|
981
|
+
Nothing to change. New: `@AdminAction({ choices })` (see Actions): an input field whose dropdown a resource method fills when the dialog opens, re-checked when the action runs. Every dropdown in the dashboard (forms, filters, sort, page size, inline cell edits, language, roles, audit, debugger, the editor's heading level) is now the dashboard's own list, styled like the rest and right to left in Persian, instead of the browser's native `<select>`. Tests that drove a native select (`selectOption`) click the field, then the option (`getByRole('option', { name })`).
|
|
982
|
+
|
|
983
|
+
## Upgrading to 0.9.0
|
|
984
|
+
|
|
985
|
+
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:
|
|
986
|
+
|
|
987
|
+
- **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).
|
|
988
|
+
- **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.
|
|
989
|
+
- **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.
|
|
990
|
+
- **`@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.
|
|
991
|
+
- **`@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).
|
|
992
|
+
- **`@AdminPrint`** returns `` html`…` `` (or a Promise of it). A plain string is refused: it was not escaped.
|
|
993
|
+
- **`readonlyIf`** returns a boolean, and `readonlyFields()` an array of names.
|
|
994
|
+
- **`findMany`** of a resource, a source or an inline child returns `{ items, total }` (`total` may be left out); an array is refused.
|
|
995
|
+
- **Computed columns:** `compute()` returns an object of values by id, and a badge's `map()` a `{ label, tone }` with a known tone.
|
|
996
|
+
- **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()`.
|
|
997
|
+
- **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.
|
|
998
|
+
- **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).
|
|
999
|
+
- **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`.
|
|
1000
|
+
- **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.
|
|
1001
|
+
|
|
1002
|
+
New types: `ActionReturn` (what an action may return), `Awaitable<T>`, `RowOf<P>`, `TypedMethodDecorator<M>` and `TypedClassDecorator<I>` (for your own wrappers around the decorators).
|
|
1003
|
+
|
|
972
1004
|
## Upgrading to 0.8.1
|
|
973
1005
|
|
|
974
1006
|
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,5 +1,5 @@
|
|
|
1
1
|
import type { Logger } from '@nestjs/common';
|
|
2
|
-
import type { ActionResult, AdminRecord } from '../contract.js';
|
|
2
|
+
import type { ActionChoicesResponse, ActionResult, AdminRecord } from '../contract.js';
|
|
3
3
|
import type { ResolvedAdminOptions } from '../options.js';
|
|
4
4
|
import type { AdminPolicy } from '../policy/admin-policy.service.js';
|
|
5
5
|
import type { RegisteredResource } from '../registry/resource-registry.js';
|
|
@@ -23,6 +23,14 @@ export declare class ActionService {
|
|
|
23
23
|
private readonly host;
|
|
24
24
|
constructor(host: ActionHost);
|
|
25
25
|
run(entry: RegisteredResource, name: string, body: unknown, ctx: AdminContext): Promise<ActionResult>;
|
|
26
|
+
/**
|
|
27
|
+
* `GET …/actions/:action/choices/:field`: the dropdown of an input field, for whoever may run the action. The
|
|
28
|
+
* method is the resource's (`@AdminAction({ choices })`), called with the request's context.
|
|
29
|
+
*/
|
|
30
|
+
choices(entry: RegisteredResource, name: string, field: string, ctx: AdminContext): Promise<ActionChoicesResponse>;
|
|
31
|
+
private readChoices;
|
|
32
|
+
/** A choice field's value must still be one of its choices when the action runs. */
|
|
33
|
+
private checkChoices;
|
|
26
34
|
private runOnResource;
|
|
27
35
|
private runOnOne;
|
|
28
36
|
/** Each record in its own transaction: a failure is reported for its id (as the single run would answer) and undoes nothing else. */
|
|
@@ -1,7 +1,8 @@
|
|
|
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 {
|
|
4
|
+
import { checkFoundRecord, describeValue, HostContractError, isLocalizedText, isRecordObject } from '../host-contract.js';
|
|
5
|
+
import { AdminBadRequestError, AdminFieldError, AdminForbiddenError, AdminNotFoundError, AdminValidationError } from '../errors.js';
|
|
5
6
|
import { toErrorResponse } from '../http/error-response.js';
|
|
6
7
|
/**
|
|
7
8
|
* Runs `@AdminAction` methods (spec §5.2, §11): permission, input validation, then the method inside
|
|
@@ -27,6 +28,7 @@ export class ActionService {
|
|
|
27
28
|
// Validated once up front (a 422 before anything runs); every run then gets an instance of its own, and the
|
|
28
29
|
// first one, which no method ever sees, is what the participants of the write are told was sent.
|
|
29
30
|
const input = { sent: await validateInput(action, request.input), fresh: () => validateInput(action, request.input) };
|
|
31
|
+
await this.checkChoices(entry, action, input.sent, ctx);
|
|
30
32
|
if (action.target === 'resource') {
|
|
31
33
|
if (request.ids !== undefined)
|
|
32
34
|
throw new AdminBadRequestError(`"${label}" runs on the resource, not on records: send no ids`);
|
|
@@ -39,8 +41,55 @@ export class ActionService {
|
|
|
39
41
|
throw new AdminBadRequestError(`"${label}" runs on one record at a time`);
|
|
40
42
|
return action.atomic ? this.runTogether(entry, action, label, ids, input, ctx) : this.runEach(entry, action, label, ids, input, ctx);
|
|
41
43
|
}
|
|
44
|
+
/**
|
|
45
|
+
* `GET …/actions/:action/choices/:field`: the dropdown of an input field, for whoever may run the action. The
|
|
46
|
+
* method is the resource's (`@AdminAction({ choices })`), called with the request's context.
|
|
47
|
+
*/
|
|
48
|
+
async choices(entry, name, field, ctx) {
|
|
49
|
+
const { policy, options } = this.host;
|
|
50
|
+
policy.requireReach(entry, ctx);
|
|
51
|
+
const action = entry.actions.get(name);
|
|
52
|
+
if (!action)
|
|
53
|
+
throw new AdminNotFoundError(`${entry.schema.label} has no action "${name}"`);
|
|
54
|
+
policy.requireAction(entry, action, options.texts(action.label, ctx.locale ?? options.locale, `resource.${entry.schema.name}.actions.${action.name}.label`), ctx);
|
|
55
|
+
if (!action.choices?.has(field))
|
|
56
|
+
throw new AdminNotFoundError(`"${name}" has no choices for "${field}"`);
|
|
57
|
+
const locale = ctx.locale ?? options.locale;
|
|
58
|
+
return { items: (await this.readChoices(entry, action, field, ctx)).map((choice) => ({ value: choice.value, label: options.texts(choice.label, locale) })) };
|
|
59
|
+
}
|
|
60
|
+
async readChoices(entry, action, field, ctx) {
|
|
61
|
+
const method = action.choices.get(field);
|
|
62
|
+
const where = `${entry.className}.${method}() (choices of @AdminAction "${action.name}" field "${field}")`;
|
|
63
|
+
const answer = await entry.resource[method](ctx);
|
|
64
|
+
if (!Array.isArray(answer))
|
|
65
|
+
throw new HostContractError(`${where} must return an array of choices, but it returned ${describeValue(answer)}`);
|
|
66
|
+
return answer.map((choice) => {
|
|
67
|
+
if (typeof choice === 'string' || typeof choice === 'number')
|
|
68
|
+
return { value: String(choice), label: String(choice) };
|
|
69
|
+
if (isRecordObject(choice) && (typeof choice.value === 'string' || typeof choice.value === 'number') && (choice.label === undefined || isLocalizedText(choice.label))) {
|
|
70
|
+
return { value: String(choice.value), label: choice.label ?? String(choice.value) };
|
|
71
|
+
}
|
|
72
|
+
throw new HostContractError(`${where}: a choice is a string or { value, label }, but one is ${describeValue(choice)}`);
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
/** A choice field's value must still be one of its choices when the action runs. */
|
|
76
|
+
async checkChoices(entry, action, sent, ctx) {
|
|
77
|
+
if (!action.choices)
|
|
78
|
+
return;
|
|
79
|
+
const errors = {};
|
|
80
|
+
for (const field of action.choices.keys()) {
|
|
81
|
+
const value = sent[field];
|
|
82
|
+
if (value === undefined || value === null || value === '')
|
|
83
|
+
continue;
|
|
84
|
+
const choices = await this.readChoices(entry, action, field, ctx);
|
|
85
|
+
if (!choices.some((choice) => choice.value === String(value)))
|
|
86
|
+
errors[field] = ['is not one of the choices'];
|
|
87
|
+
}
|
|
88
|
+
if (Object.keys(errors).length > 0)
|
|
89
|
+
throw new AdminFieldError(errors);
|
|
90
|
+
}
|
|
42
91
|
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));
|
|
92
|
+
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
93
|
return withMessage({}, messageOf(outcome, ctx, this.host.options));
|
|
45
94
|
}
|
|
46
95
|
runOnOne(entry, action, label, rawId, input, ctx) {
|
|
@@ -91,7 +140,7 @@ export class ActionService {
|
|
|
91
140
|
const id = parseRecordId(rawId, schema);
|
|
92
141
|
await policy.requireInScope(entry, id, rawId, 'view', tx);
|
|
93
142
|
await policy.requireInScope(entry, id, rawId, 'update', tx);
|
|
94
|
-
const record = await resource.findOne(id, tx);
|
|
143
|
+
const record = checkFoundRecord(await resource.findOne(id, tx), `${resource.constructor.name}.findOne()`);
|
|
95
144
|
if (!record)
|
|
96
145
|
throw new AdminNotFoundError(`${schema.label} "${rawId}" not found`);
|
|
97
146
|
// A per-record label of `null` means the action does not exist on this record (it is not offered there either).
|
|
@@ -112,7 +161,7 @@ export class ActionService {
|
|
|
112
161
|
const { id, record } = await this.loadAllowed(entry, action, label, rawId, tx);
|
|
113
162
|
// One change of the write: its participants see the record before the method runs (which may change the entity
|
|
114
163
|
// 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);
|
|
164
|
+
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
165
|
// The action may have deleted the record or moved it out of the user's scopes (a findOne override may ignore them).
|
|
117
166
|
const visible = reloaded !== null && (await policy.allowedIds(entry, [id], 'view', tx)).size > 0;
|
|
118
167
|
return withMessage({ after: visible ? reloaded : null }, messageOf(outcome, tx, options));
|
|
@@ -183,11 +232,28 @@ async function validateInput(action, input) {
|
|
|
183
232
|
// A deep copy first: the instance must share nothing, nested lists included, with the body or another run's input.
|
|
184
233
|
return validateWrite(structuredClone(input ?? {}), { allowed: action.form?.fields.map((field) => field.name) ?? [], dto: action.input, keepDefaults: true });
|
|
185
234
|
}
|
|
186
|
-
/** `ActionOutcome.message` in the request's language
|
|
235
|
+
/** `ActionOutcome.message` in the request's language (the outcome was checked by `checkOutcome`). */
|
|
187
236
|
function messageOf(outcome, ctx, options) {
|
|
188
237
|
const message = isPlainObject(outcome) ? outcome.message : undefined;
|
|
189
|
-
|
|
190
|
-
|
|
238
|
+
return message === undefined ? undefined : options.texts(message, ctx.locale ?? options.locale) || undefined;
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* What an action may answer: nothing, or `{ message }` with a text. Anything else (a record, a string, a typo such as
|
|
242
|
+
* `{ mesage }`) fails the action, inside its transaction, instead of being dropped without a word.
|
|
243
|
+
*/
|
|
244
|
+
function checkOutcome(outcome, entry, action) {
|
|
245
|
+
if (outcome === undefined || outcome === null)
|
|
246
|
+
return outcome;
|
|
247
|
+
const where = `${entry.className}.${action.name} (@AdminAction)`;
|
|
248
|
+
if (!isPlainObject(outcome))
|
|
249
|
+
throw new HostContractError(`${where} returned ${describeValue(outcome)}; an action returns nothing or { message }`);
|
|
250
|
+
const extra = Object.keys(outcome).filter((key) => key !== 'message');
|
|
251
|
+
if (extra.length > 0)
|
|
252
|
+
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)`);
|
|
253
|
+
const { message } = outcome;
|
|
254
|
+
if (message !== undefined && !isLocalizedText(message))
|
|
255
|
+
throw new HostContractError(`${where} returned a message that is ${describeValue(message)}; it must be a text ('Done' or { en, fa })`);
|
|
256
|
+
return outcome;
|
|
191
257
|
}
|
|
192
258
|
/** One message for a bulk run only when every record that ran gave the same one. */
|
|
193
259
|
function sharedMessage(messages) {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ActionResult, AdminRecord, BulkResult, ListResponse, MenuBadges, TabCounts, MetaPageSummary, MetaResponse, OptionsResponse, PageResponse, ResourceSchema, SearchResponse } from '../contract.js';
|
|
1
|
+
import type { ActionChoicesResponse, ActionResult, AdminRecord, BulkResult, ListResponse, MenuBadges, TabCounts, MetaPageSummary, MetaResponse, OptionsResponse, PageResponse, ResourceSchema, SearchResponse } from '../contract.js';
|
|
2
2
|
import { type ResolvedMenu } from './menu.js';
|
|
3
3
|
import { DashboardService } from '../dashboard/dashboard.service.js';
|
|
4
4
|
import { WidgetRegistry } from '../dashboard/widget-registry.js';
|
|
@@ -140,6 +140,8 @@ export declare class AdminApiService {
|
|
|
140
140
|
* One record answers `{ message?, record }`, several `{ ok, failed, message? }`, a resource action `{ message? }`.
|
|
141
141
|
*/
|
|
142
142
|
runAction(name: string, action: string, body: unknown, ctx: AdminContext): Promise<ActionResult>;
|
|
143
|
+
/** `GET /resources/:name/actions/:action/choices/:field`: an action input's dropdown (`@AdminAction({ choices })`). */
|
|
144
|
+
actionChoices(name: string, action: string, field: string, ctx: AdminContext): Promise<ActionChoicesResponse>;
|
|
143
145
|
/**
|
|
144
146
|
* `GET /resources/:name/print/:print?id=…`: an `@AdminPrint` template's page for one record (or up to 100 with
|
|
145
147
|
* `bulk`). Each record is read like `GET /resources/:name/:id` (view permission, scopes) and its printing is audited.
|
|
@@ -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
|
|
@@ -851,6 +853,10 @@ let AdminApiService = class AdminApiService {
|
|
|
851
853
|
runAction(name, action, body, ctx) {
|
|
852
854
|
return this.actions.run(this.registry.get(name), action, body, ctx);
|
|
853
855
|
}
|
|
856
|
+
/** `GET /resources/:name/actions/:action/choices/:field`: an action input's dropdown (`@AdminAction({ choices })`). */
|
|
857
|
+
actionChoices(name, action, field, ctx) {
|
|
858
|
+
return this.actions.choices(this.registry.get(name), action, field, ctx);
|
|
859
|
+
}
|
|
854
860
|
/**
|
|
855
861
|
* `GET /resources/:name/print/:print?id=…`: an `@AdminPrint` template's page for one record (or up to 100 with
|
|
856
862
|
* `bulk`). Each record is read like `GET /resources/:name/:id` (view permission, scopes) and its printing is audited.
|
|
@@ -871,7 +877,7 @@ let AdminApiService = class AdminApiService {
|
|
|
871
877
|
const entities = [];
|
|
872
878
|
for (const rawId of ids) {
|
|
873
879
|
const id = parseRecordId(rawId, entry.schema);
|
|
874
|
-
const entity = await entry.resource.findOne(id, ctx);
|
|
880
|
+
const entity = checkFoundRecord(await entry.resource.findOne(id, ctx), `${entry.resource.constructor.name}.findOne()`);
|
|
875
881
|
if (!entity)
|
|
876
882
|
throw new AdminNotFoundError(`${entry.schema.label} "${rawId}" not found`);
|
|
877
883
|
await this.policy.requireInScope(entry, id, rawId, 'view', ctx);
|
|
@@ -885,13 +891,16 @@ let AdminApiService = class AdminApiService {
|
|
|
885
891
|
catch (error) {
|
|
886
892
|
throw hostError(error);
|
|
887
893
|
}
|
|
894
|
+
// Only `html` output (which escaped every value) is put on the page: a plain string may carry a record's text as markup.
|
|
895
|
+
if (!(body instanceof HtmlString))
|
|
896
|
+
throw new HostContractError(`${entry.className}.${printName} (@AdminPrint) returned ${describeValue(body)}; return html\`…\` (it escapes every value), with raw() around markup you trust`);
|
|
888
897
|
const locale = ctx.locale ?? this.options.locale;
|
|
889
898
|
const label = this.options.texts(print.label, locale, `resource.${entry.schema.name}.prints.${print.name}.label`);
|
|
890
899
|
for (const entity of entities) {
|
|
891
900
|
await this.audit.recordAfter({ event: printCode(entry.schema.name, printName), entry, recordId: recordIdOf(entity, entry.schema.primaryKeys), title: entry.title(entity) }, ctx);
|
|
892
901
|
}
|
|
893
902
|
const title = entities.length === 1 ? `${label} · ${entry.title(entities[0])}` : label;
|
|
894
|
-
return printPage({ title, body:
|
|
903
|
+
return printPage({ title, body: body.value, size: print.size, locale });
|
|
895
904
|
}
|
|
896
905
|
/**
|
|
897
906
|
* `GET /resources/:name/export?<list query>`: the rows the list shows for this query (filters, search, tab, sort and
|
|
@@ -922,7 +931,7 @@ let AdminApiService = class AdminApiService {
|
|
|
922
931
|
const items = [];
|
|
923
932
|
let truncated = false;
|
|
924
933
|
for (let page = 1;; page++) {
|
|
925
|
-
const found = await entry.resource.findMany({ ...params, page, pageSize: EXPORT_PAGE, count: 'none', pagination: 'offset', after: undefined }, ctx);
|
|
934
|
+
const found = checkFindMany(await entry.resource.findMany({ ...params, page, pageSize: EXPORT_PAGE, count: 'none', pagination: 'offset', after: undefined }, ctx), entry.className);
|
|
926
935
|
let batch = found.items;
|
|
927
936
|
// A findMany override may ignore the scopes; rows outside them never leave (spec §6.4).
|
|
928
937
|
if (scoped) {
|
|
@@ -997,14 +1006,19 @@ let AdminApiService = class AdminApiService {
|
|
|
997
1006
|
for (const [name, options] of entry.fieldConfig) {
|
|
998
1007
|
if (!options.readonlyIf)
|
|
999
1008
|
continue;
|
|
1009
|
+
let answer;
|
|
1000
1010
|
try {
|
|
1001
|
-
|
|
1002
|
-
locked.add(name);
|
|
1011
|
+
answer = options.readonlyIf(entity);
|
|
1003
1012
|
}
|
|
1004
1013
|
catch (error) {
|
|
1005
1014
|
locked.add(name);
|
|
1006
1015
|
this.warnOnce(`${entry.className}.fields.${name}.readonlyIf threw (${error instanceof Error ? error.message : String(error)}); the field stays read-only`);
|
|
1016
|
+
continue;
|
|
1007
1017
|
}
|
|
1018
|
+
if (typeof answer !== 'boolean')
|
|
1019
|
+
throw new HostContractError(`${entry.className}.fields.${name}.readonlyIf returned ${describeValue(answer)}; it answers at once with true or false (it cannot be async)`);
|
|
1020
|
+
if (answer)
|
|
1021
|
+
locked.add(name);
|
|
1008
1022
|
}
|
|
1009
1023
|
let more;
|
|
1010
1024
|
try {
|
|
@@ -1014,6 +1028,8 @@ let AdminApiService = class AdminApiService {
|
|
|
1014
1028
|
more = entry.schema.form.update;
|
|
1015
1029
|
this.warnOnce(`${entry.className}.readonlyFields threw (${error instanceof Error ? error.message : String(error)}); the record stays read-only`);
|
|
1016
1030
|
}
|
|
1031
|
+
if (!Array.isArray(more))
|
|
1032
|
+
throw new HostContractError(`${entry.className}.readonlyFields() returned ${describeValue(more)}; it answers at once with an array of field names (it cannot be async)`);
|
|
1017
1033
|
const fields = new Set(entry.schema.fields.map((field) => field.name));
|
|
1018
1034
|
for (const name of more) {
|
|
1019
1035
|
if (fields.has(name) && !entry.schema.primaryKeys.includes(name))
|
|
@@ -1033,8 +1049,17 @@ let AdminApiService = class AdminApiService {
|
|
|
1033
1049
|
this.warnOnce(`${entry.className}.links() threw: ${error instanceof Error ? error.message : String(error)}`);
|
|
1034
1050
|
return [];
|
|
1035
1051
|
}
|
|
1036
|
-
|
|
1037
|
-
.
|
|
1052
|
+
if (!Array.isArray(links) || links.some((link) => !isRecordObject(link) || typeof link.href !== 'string' || !isLocalizedText(link.label))) {
|
|
1053
|
+
throw new HostContractError(`${entry.className}.links() must return an array of { label, href }, but it returned ${describeValue(links)}`);
|
|
1054
|
+
}
|
|
1055
|
+
// A link of another scheme (javascript:, data:) is never shown: it would run in the admin.
|
|
1056
|
+
return links
|
|
1057
|
+
.filter((link) => {
|
|
1058
|
+
const safe = /^https?:\/\//i.test(link.href) || !/^[a-z][a-z0-9+.-]*:/i.test(link.href.trim());
|
|
1059
|
+
if (!safe)
|
|
1060
|
+
this.warnOnce(`${entry.className}.links(): "${link.href.slice(0, 40)}" is not an http(s) or relative URL; it is not shown`);
|
|
1061
|
+
return safe;
|
|
1062
|
+
})
|
|
1038
1063
|
.map((link) => ({ label: this.options.texts(link.label, locale), href: link.href }));
|
|
1039
1064
|
}
|
|
1040
1065
|
warned = new Set();
|
|
@@ -1052,9 +1077,10 @@ let AdminApiService = class AdminApiService {
|
|
|
1052
1077
|
}
|
|
1053
1078
|
/** Host services often return nothing from update(); fall back to reading the record. */
|
|
1054
1079
|
async reloadIfEmpty(entry, result, id, ctx) {
|
|
1080
|
+
checkWriteResult(result, `${entry.className}: create(), update() and restore()`);
|
|
1055
1081
|
if (typeof result === 'object' && result !== null)
|
|
1056
1082
|
return result;
|
|
1057
|
-
const reloaded = await entry.resource.findOne(id, ctx);
|
|
1083
|
+
const reloaded = checkFoundRecord(await entry.resource.findOne(id, ctx), `${entry.className}.findOne()`);
|
|
1058
1084
|
if (!reloaded)
|
|
1059
1085
|
throw new AdminNotFoundError(`${entry.schema.label} "${typeof id === 'object' ? encodeRecordId(Object.values(id)) : id}" not found`);
|
|
1060
1086
|
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) {
|
package/dist/contract.d.ts
CHANGED
|
@@ -30,6 +30,8 @@ export interface FieldSchema {
|
|
|
30
30
|
integer?: boolean;
|
|
31
31
|
/** An action input picked like this relation field of the resource (`@AdminField({ pickFrom })`): its options endpoint. */
|
|
32
32
|
optionsField?: string;
|
|
33
|
+
/** An action input with a dropdown whose options come from `GET /resources/:name/actions/:action/choices/:field` (`@AdminAction({ choices })`). */
|
|
34
|
+
choices?: true;
|
|
33
35
|
/** Set when `type` is `relation`. */
|
|
34
36
|
relation?: RelationSchema;
|
|
35
37
|
/** Set when `type` is `object`: the group's fields, named relative to it (`city` in `address`). */
|
|
@@ -1118,3 +1120,10 @@ export interface AdminRuntimeConfig {
|
|
|
1118
1120
|
/** UI texts the host rewords through `translate` (`ui.<key>`), per locale; only the overridden keys. */
|
|
1119
1121
|
messages?: Record<string, Record<string, string>>;
|
|
1120
1122
|
}
|
|
1123
|
+
/** `GET /resources/:name/actions/:action/choices/:field`: the options of an action input's dropdown. */
|
|
1124
|
+
export interface ActionChoicesResponse {
|
|
1125
|
+
items: Array<{
|
|
1126
|
+
value: string;
|
|
1127
|
+
label: string;
|
|
1128
|
+
}>;
|
|
1129
|
+
}
|
|
@@ -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
|