@nest-my-admin/core 0.6.0 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/README.md +125 -6
  2. package/dist/api/action.service.js +2 -3
  3. package/dist/api/admin-api.service.d.ts +17 -2
  4. package/dist/api/admin-api.service.js +104 -44
  5. package/dist/api/menu.d.ts +35 -2
  6. package/dist/api/menu.js +51 -6
  7. package/dist/api/write-runner.d.ts +2 -2
  8. package/dist/api/write-runner.js +8 -2
  9. package/dist/audit/audit-participant.js +2 -1
  10. package/dist/audit/audit.service.js +5 -3
  11. package/dist/contract.d.ts +6 -0
  12. package/dist/crud/relation-writes.d.ts +6 -0
  13. package/dist/crud/relation-writes.js +32 -0
  14. package/dist/dashboard/dashboard.service.js +1 -2
  15. package/dist/decorators/admin-action.d.ts +3 -2
  16. package/dist/decorators/admin-action.js +9 -8
  17. package/dist/decorators/admin-print.d.ts +2 -1
  18. package/dist/decorators/admin-print.js +2 -3
  19. package/dist/decorators/admin-settings-page.d.ts +1 -0
  20. package/dist/http/admin-http.server.js +8 -1
  21. package/dist/http/ui-messages.d.ts +9 -0
  22. package/dist/http/ui-messages.js +43 -0
  23. package/dist/i18n/texts.d.ts +26 -0
  24. package/dist/i18n/texts.js +31 -0
  25. package/dist/index.d.ts +2 -1
  26. package/dist/inlines/inline-config.d.ts +6 -2
  27. package/dist/inlines/inline-config.js +9 -6
  28. package/dist/inlines/inline-writer.d.ts +1 -1
  29. package/dist/inlines/inline-writer.js +6 -2
  30. package/dist/options.d.ts +28 -5
  31. package/dist/options.js +15 -3
  32. package/dist/pages/page.service.js +5 -4
  33. package/dist/policy/admin-policy.service.d.ts +11 -2
  34. package/dist/policy/admin-policy.service.js +23 -11
  35. package/dist/policy/explain.js +2 -1
  36. package/dist/rbac/rbac.service.js +4 -2
  37. package/dist/registry/resource-registry.js +13 -3
  38. package/dist/resource/admin-context.d.ts +13 -1
  39. package/dist/resource/admin-context.js +10 -0
  40. package/dist/resource/admin-resource-base.d.ts +30 -8
  41. package/dist/resource/admin-resource-base.js +28 -1
  42. package/dist/schema/build-resource-schema.js +3 -3
  43. package/dist/schema/dto-form.d.ts +2 -2
  44. package/dist/schema/dto-form.js +2 -2
  45. package/dist/schema/field-config.d.ts +23 -5
  46. package/dist/schema/field-config.js +33 -18
  47. package/package.json +3 -4
  48. package/dist/admin.module.js.map +0 -1
  49. package/dist/api/action.service.js.map +0 -1
  50. package/dist/api/admin-api.service.js.map +0 -1
  51. package/dist/api/menu-routes.js.map +0 -1
  52. package/dist/api/menu.js.map +0 -1
  53. package/dist/api/write-participant.js.map +0 -1
  54. package/dist/api/write-queue.js.map +0 -1
  55. package/dist/api/write-runner.js.map +0 -1
  56. package/dist/appearance/appearance.service.js.map +0 -1
  57. package/dist/appearance/entities.js.map +0 -1
  58. package/dist/audit/audit-participant.js.map +0 -1
  59. package/dist/audit/audit-query.js.map +0 -1
  60. package/dist/audit/audit-reader.js.map +0 -1
  61. package/dist/audit/audit-routes.js.map +0 -1
  62. package/dist/audit/audit.service.js.map +0 -1
  63. package/dist/audit/diff.js.map +0 -1
  64. package/dist/audit/entities.js.map +0 -1
  65. package/dist/audit/login-failures.js.map +0 -1
  66. package/dist/audit/retention.js.map +0 -1
  67. package/dist/auth/auth-adapter.js.map +0 -1
  68. package/dist/auth/auth.service.js.map +0 -1
  69. package/dist/constants.js.map +0 -1
  70. package/dist/contract.js.map +0 -1
  71. package/dist/crud/computed-columns.js.map +0 -1
  72. package/dist/crud/count.js.map +0 -1
  73. package/dist/crud/cursor.js.map +0 -1
  74. package/dist/crud/list-query-builder.js.map +0 -1
  75. package/dist/crud/list-query.js.map +0 -1
  76. package/dist/crud/list-tabs.js.map +0 -1
  77. package/dist/crud/record-id.js.map +0 -1
  78. package/dist/crud/references.js.map +0 -1
  79. package/dist/crud/relation-writes.js.map +0 -1
  80. package/dist/crud/serialize-full.js.map +0 -1
  81. package/dist/crud/serialize.js.map +0 -1
  82. package/dist/crud/stored-row.js.map +0 -1
  83. package/dist/crud/validate-write.js.map +0 -1
  84. package/dist/dashboard/dashboard-routes.js.map +0 -1
  85. package/dist/dashboard/dashboard.service.js.map +0 -1
  86. package/dist/dashboard/widget-registry.js.map +0 -1
  87. package/dist/decorators/admin-action.js.map +0 -1
  88. package/dist/decorators/admin-field.js.map +0 -1
  89. package/dist/decorators/admin-group.js.map +0 -1
  90. package/dist/decorators/admin-print.js.map +0 -1
  91. package/dist/decorators/admin-resource.js.map +0 -1
  92. package/dist/decorators/admin-scope.js.map +0 -1
  93. package/dist/decorators/admin-settings-page.js.map +0 -1
  94. package/dist/decorators/admin-widget.js.map +0 -1
  95. package/dist/decorators/hooks.js.map +0 -1
  96. package/dist/errors.js.map +0 -1
  97. package/dist/export/export-cells.js.map +0 -1
  98. package/dist/export/xlsx.js.map +0 -1
  99. package/dist/files/admin-file.js.map +0 -1
  100. package/dist/files/admin-files.service.js.map +0 -1
  101. package/dist/files/entities.js.map +0 -1
  102. package/dist/files/file-owner.js.map +0 -1
  103. package/dist/files/file-routes.js.map +0 -1
  104. package/dist/files/files-participant.js.map +0 -1
  105. package/dist/files/files.service.js.map +0 -1
  106. package/dist/files/rich-text.js.map +0 -1
  107. package/dist/files/s3-storage.js.map +0 -1
  108. package/dist/files/sigv4.js.map +0 -1
  109. package/dist/files/sniff.js.map +0 -1
  110. package/dist/files/storage.js.map +0 -1
  111. package/dist/files/transaction-files.js.map +0 -1
  112. package/dist/http/admin-http.server.js.map +0 -1
  113. package/dist/http/cookies.js.map +0 -1
  114. package/dist/http/error-response.js.map +0 -1
  115. package/dist/http/http-io.js.map +0 -1
  116. package/dist/http/router.js.map +0 -1
  117. package/dist/http/session-user.js.map +0 -1
  118. package/dist/http/ui-assets.js.map +0 -1
  119. package/dist/i18n/localized-text.js.map +0 -1
  120. package/dist/i18n/persian.js.map +0 -1
  121. package/dist/index.js.map +0 -1
  122. package/dist/inlines/inline-config.js.map +0 -1
  123. package/dist/inlines/inline-reader.js.map +0 -1
  124. package/dist/inlines/inline-writer.js.map +0 -1
  125. package/dist/internal.js.map +0 -1
  126. package/dist/options.js.map +0 -1
  127. package/dist/pages/page-file-owner.js.map +0 -1
  128. package/dist/pages/page-registry.js.map +0 -1
  129. package/dist/pages/page-routes.js.map +0 -1
  130. package/dist/pages/page.service.js.map +0 -1
  131. package/dist/policy/admin-policy.service.js.map +0 -1
  132. package/dist/policy/catalog.js.map +0 -1
  133. package/dist/policy/effective.js.map +0 -1
  134. package/dist/policy/explain.js.map +0 -1
  135. package/dist/policy/roles.js.map +0 -1
  136. package/dist/print/html.js.map +0 -1
  137. package/dist/print/print-page.js.map +0 -1
  138. package/dist/rbac/entities.js.map +0 -1
  139. package/dist/rbac/escalation.js.map +0 -1
  140. package/dist/rbac/rbac-routes.js.map +0 -1
  141. package/dist/rbac/rbac.service.js.map +0 -1
  142. package/dist/registry/db-names.js.map +0 -1
  143. package/dist/registry/hook-warnings.js.map +0 -1
  144. package/dist/registry/resource-registry.js.map +0 -1
  145. package/dist/resource/admin-context.js.map +0 -1
  146. package/dist/resource/admin-resource-base.js.map +0 -1
  147. package/dist/schema/build-resource-schema.js.map +0 -1
  148. package/dist/schema/column-field.js.map +0 -1
  149. package/dist/schema/currency.js.map +0 -1
  150. package/dist/schema/dto-constraints.js.map +0 -1
  151. package/dist/schema/dto-fields.js.map +0 -1
  152. package/dist/schema/dto-form.js.map +0 -1
  153. package/dist/schema/field-config.js.map +0 -1
  154. package/dist/schema/field-paths.js.map +0 -1
  155. package/dist/schema/filter-operators.js.map +0 -1
  156. package/dist/schema/humanize.js.map +0 -1
  157. package/dist/schema/nested-fields.js.map +0 -1
  158. package/dist/schema/relation-fields.js.map +0 -1
  159. package/dist/schema/suggest.js.map +0 -1
  160. package/dist/schema/titles.js.map +0 -1
@@ -82,4 +82,36 @@ export function toRelationReferences(dto, metadata) {
82
82
  }
83
83
  return out;
84
84
  }
85
+ /**
86
+ * Relation values of a picker's `values` (form state the browser sent) in the target key's type, as write bodies
87
+ * already are: a to-one id parsed with `parseId`, a many-to-many list element-wise. A value that does not parse is
88
+ * left out; `null` stays; other keys are untouched.
89
+ */
90
+ export function normalizeRelationValues(values, schema) {
91
+ const out = { ...values };
92
+ const parse = (field, value) => {
93
+ if (typeof value !== 'string' && typeof value !== 'number')
94
+ return undefined;
95
+ const parsed = parseId(field, String(value));
96
+ return 'error' in parsed ? undefined : parsed.value;
97
+ };
98
+ for (const field of schema.fields) {
99
+ if (field.type !== 'relation' || !Object.hasOwn(values, field.name) || values[field.name] === null)
100
+ continue;
101
+ const value = values[field.name];
102
+ if (field.relation.kind === 'to-one') {
103
+ const id = parse(field, value);
104
+ if (id === undefined)
105
+ delete out[field.name];
106
+ else
107
+ out[field.name] = id;
108
+ }
109
+ else if (Array.isArray(value)) {
110
+ out[field.name] = value.map((item) => parse(field, item)).filter((id) => id !== undefined);
111
+ }
112
+ else
113
+ delete out[field.name];
114
+ }
115
+ return out;
116
+ }
85
117
  //# sourceMappingURL=relation-writes.js.map
@@ -13,7 +13,6 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
13
13
  import { Inject, Injectable } from '@nestjs/common';
14
14
  import { ADMIN_OPTIONS } from '../constants.js';
15
15
  import { AdminBadRequestError, AdminNotFoundError } from '../errors.js';
16
- import { resolveText } from '../i18n/localized-text.js';
17
16
  import { AdminPolicy } from '../policy/admin-policy.service.js';
18
17
  import { WidgetRegistry } from './widget-registry.js';
19
18
  const PERIODS = ['day', 'week', 'month', 'year', 'range'];
@@ -38,7 +37,7 @@ let DashboardService = class DashboardService {
38
37
  }
39
38
  layout(ctx) {
40
39
  const locale = ctx.locale ?? this.options.locale;
41
- return { widgets: this.visible(ctx).map((widget) => ({ name: widget.name, type: widget.type, title: resolveText(widget.title, locale, this.options.locale), size: widget.size })) };
40
+ return { widgets: this.visible(ctx).map((widget) => ({ name: widget.name, type: widget.type, title: this.options.texts(widget.title, locale, `widget.${widget.name}.title`), size: widget.size })) };
42
41
  }
43
42
  /** One widget's data: 404 for a widget the user may not see (or that does not exist), 400 for a bad period. */
44
43
  async load(name, query, ctx) {
@@ -3,6 +3,7 @@ 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
5
  import type { DtoClass } from '../schema/dto-fields.js';
6
+ import type { ScopedText } from '../i18n/texts.js';
6
7
  export interface AdminActionOptions {
7
8
  /**
8
9
  * `'Mark shipped'` or `{ en: 'Mark shipped', fa: 'ارسال شد' }`. Defaults to the humanized method name. A label per
@@ -81,5 +82,5 @@ export declare function getActions(resourceClass: Function): Map<string, ActionD
81
82
  * `reserved` are the method names of `AdminResourceBase`, which an action must not take over.
82
83
  */
83
84
  export declare function resolveActions(resourceClass: Function, reserved: readonly string[], fail: (message: string) => never): Map<string, RegisteredAction>;
84
- /** The action as one request gets it, texts in `locale`. */
85
- export declare function toActionSchema(action: RegisteredAction, locale: string, defaultLocale: string): ActionSchema;
85
+ /** The action as one request gets it, texts through `text` (keys `actions.<name>.…` of the resource). */
86
+ export declare function toActionSchema(action: RegisteredAction, text: ScopedText): ActionSchema;
@@ -1,6 +1,5 @@
1
1
  import 'reflect-metadata';
2
2
  import { ADMIN_ACTIONS_METADATA } from '../constants.js';
3
- import { resolveText } from '../i18n/localized-text.js';
4
3
  import { buildDtoForm, localizeDtoForm } from '../schema/dto-form.js';
5
4
  import { humanize } from '../schema/humanize.js';
6
5
  import { didYouMean } from '../schema/suggest.js';
@@ -107,11 +106,12 @@ export function resolveActions(resourceClass, reserved, fail) {
107
106
  fail(`@AdminAction: only one action can be \`primary\` (${primaries.map((action) => action.name).join(', ')})`);
108
107
  // A rule under a name nothing checks would silently never apply.
109
108
  for (const rule of getCanRuleNames(resourceClass)) {
110
- if (rule === 'update' || rule === 'delete')
109
+ // `create` is an inline child's rule on its parent, checked once inlines are resolved (the registry).
110
+ if (rule === 'update' || rule === 'delete' || rule === 'create')
111
111
  continue;
112
112
  const action = actions.get(rule);
113
113
  if (!action)
114
- fail(`@AdminCan("${rule}") names no record action${didYouMean(rule, ['update', 'delete', ...actions.keys()])}`);
114
+ fail(`@AdminCan("${rule}") names no record action${didYouMean(rule, ['update', 'delete', 'create', ...actions.keys()])}`);
115
115
  if (action.target === 'resource')
116
116
  fail(`@AdminCan("${rule}"): "${rule}" runs on the resource, not on a record`);
117
117
  }
@@ -122,20 +122,21 @@ function isText(value) {
122
122
  return true;
123
123
  return typeof value === 'object' && value !== null && !Array.isArray(value) && Object.values(value).every((text) => typeof text === 'string');
124
124
  }
125
- /** The action as one request gets it, texts in `locale`. */
126
- export function toActionSchema(action, locale, defaultLocale) {
125
+ /** The action as one request gets it, texts through `text` (keys `actions.<name>.…` of the resource). */
126
+ export function toActionSchema(action, text) {
127
127
  const { confirm } = action;
128
+ const at = `actions.${action.name}`;
128
129
  return {
129
130
  name: action.name,
130
- label: resolveText(action.label, locale, defaultLocale),
131
+ label: text(action.label, `${at}.label`),
131
132
  target: action.target,
132
133
  bulk: action.bulk,
133
134
  atomic: action.atomic,
134
- ...(confirm !== undefined ? { confirm: confirm === true ? true : resolveText(confirm, locale, defaultLocale) } : {}),
135
+ ...(confirm !== undefined ? { confirm: confirm === true ? true : text(confirm, `${at}.confirm`) } : {}),
135
136
  variant: action.variant,
136
137
  ...(action.primary ? { primary: true } : {}),
137
138
  ...(action.icon ? { icon: action.icon } : {}),
138
- ...(action.form ? { input: localizeDtoForm(action.form, locale, defaultLocale) } : {}),
139
+ ...(action.form ? { input: localizeDtoForm(action.form, (value, path) => text(value, `${at}.fields.${path}`)) } : {}),
139
140
  };
140
141
  }
141
142
  //# sourceMappingURL=admin-action.js.map
@@ -1,6 +1,7 @@
1
1
  import 'reflect-metadata';
2
2
  import type { PrintSchema } from '../contract.js';
3
3
  import { type LocalizedText } from '../i18n/localized-text.js';
4
+ import type { ScopedText } from '../i18n/texts.js';
4
5
  /** Paper sizes by name; any other string is used as the CSS `@page { size }` value. */
5
6
  export declare const PAPERS: Record<string, string>;
6
7
  export interface AdminPrintOptions {
@@ -32,4 +33,4 @@ export declare function AdminPrint(options?: AdminPrintOptions): MethodDecorator
32
33
  export declare function resolvePrints(resourceClass: Function, taken: readonly string[], fail: (message: string) => never): Map<string, RegisteredPrint>;
33
34
  /** The permission code of a print template. */
34
35
  export declare const printCode: (resource: string, name: string) => string;
35
- export declare function toPrintSchema(print: RegisteredPrint, locale: string, defaultLocale: string): PrintSchema;
36
+ export declare function toPrintSchema(print: RegisteredPrint, text: ScopedText): PrintSchema;
@@ -1,6 +1,5 @@
1
1
  import 'reflect-metadata';
2
2
  import { ADMIN_PRINTS_METADATA } from '../constants.js';
3
- import { resolveText } from '../i18n/localized-text.js';
4
3
  import { humanize } from '../schema/humanize.js';
5
4
  /** Paper sizes by name; any other string is used as the CSS `@page { size }` value. */
6
5
  export const PAPERS = { A4: 'A4', A5: 'A5', label: '100mm 150mm' };
@@ -47,7 +46,7 @@ export function resolvePrints(resourceClass, taken, fail) {
47
46
  }
48
47
  /** The permission code of a print template. */
49
48
  export const printCode = (resource, name) => `${resource}.print.${name}`;
50
- export function toPrintSchema(print, locale, defaultLocale) {
51
- return { name: print.name, label: resolveText(print.label, locale, defaultLocale), bulk: print.bulk, ...(print.icon ? { icon: print.icon } : {}) };
49
+ export function toPrintSchema(print, text) {
50
+ return { name: print.name, label: text(print.label, `prints.${print.name}.label`), bulk: print.bulk, ...(print.icon ? { icon: print.icon } : {}) };
52
51
  }
53
52
  //# sourceMappingURL=admin-print.js.map
@@ -52,6 +52,7 @@ export interface AdminSettingsPageOptions<T extends object = any> {
52
52
  */
53
53
  export interface AdminSettingsSource<T extends object = Record<string, unknown>> {
54
54
  load(ctx: AdminContext): Partial<T> | Promise<Partial<T>>;
55
+ /** `ctx.manager` is always set here: type it `AdminWriteContext` in your implementation to use it without `!`. */
55
56
  save(changes: Partial<T>, ctx: AdminContext): void | Promise<void>;
56
57
  }
57
58
  export interface AdminSettingsPageDefinition extends AdminSettingsPageOptions {
@@ -38,6 +38,7 @@ import { Router } from './router.js';
38
38
  import { UiAssets, resolveUiDist } from './ui-assets.js';
39
39
  import { AdminApiService } from '../api/admin-api.service.js';
40
40
  import { ADMIN_OPTIONS } from '../constants.js';
41
+ import { readUiMessages, uiOverrides } from './ui-messages.js';
41
42
  /** The only API routes that answer without a session: reading it (to learn you are signed out) and logging in. */
42
43
  const PUBLIC_ROUTES = new Set(['GET /api/session', 'POST /api/session']);
43
44
  // Methods that carry a JSON body. DELETE is never a CORS "simple" request, so a foreign page cannot send one without a preflight.
@@ -351,7 +352,12 @@ let AdminHttpServer = class AdminHttpServer {
351
352
  if (type !== 'express') {
352
353
  throw new Error(`nest-my-admin: the "${type}" HTTP adapter is not supported yet; use @nestjs/platform-express`);
353
354
  }
354
- this.ui = new UiAssets(this.options.uiDistPath ?? resolveUiDist(), {
355
+ const distDir = this.options.uiDistPath ?? resolveUiDist();
356
+ const bundles = this.options.translate ? readUiMessages(distDir) : undefined;
357
+ if (this.options.translate && !bundles)
358
+ this.logger.warn(`no messages.json in ${distDir}: translate cannot reword the UI's own texts`);
359
+ const messages = bundles ? uiOverrides(bundles, this.options.locales, this.options.translate) : {};
360
+ this.ui = new UiAssets(distDir, {
355
361
  basePath: this.options.path,
356
362
  apiBase: `${this.options.path}/api`,
357
363
  title: resolveText(this.options.title, this.options.locale, this.options.locale),
@@ -359,6 +365,7 @@ let AdminHttpServer = class AdminHttpServer {
359
365
  locales: this.options.locales,
360
366
  branding: this.options.branding,
361
367
  ...(this.options.currency ? { currency: this.options.currency } : {}),
368
+ ...(Object.keys(messages).length > 0 ? { messages } : {}),
362
369
  }, { title: this.options.title });
363
370
  adapter.use(this.options.path, (req, res, next) => {
364
371
  this.handle(req, res, next).catch((error) => {
@@ -0,0 +1,9 @@
1
+ import type { AdminTranslate } from '../i18n/texts.js';
2
+ /** The UI's own texts per locale (`messages.json` of the built UI: `{ en: { key: template }, fa: … }`); undefined when the build has none. */
3
+ export declare function readUiMessages(distDir: string): Record<string, Record<string, string>> | undefined;
4
+ /**
5
+ * The UI texts `translate` rewords, per locale: only answers that differ from the built-in text. Asked once per locale
6
+ * and key at boot (`ui.<key>`, `text` the locale's built-in text, else the English one). An answer that changes the
7
+ * `{name}` placeholders, or a throw, fails boot.
8
+ */
9
+ export declare function uiOverrides(bundles: Record<string, Record<string, string>>, locales: readonly string[], translate: AdminTranslate | undefined): Record<string, Record<string, string>>;
@@ -0,0 +1,43 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ /** The UI's own texts per locale (`messages.json` of the built UI: `{ en: { key: template }, fa: … }`); undefined when the build has none. */
4
+ export function readUiMessages(distDir) {
5
+ const file = join(distDir, 'messages.json');
6
+ if (!existsSync(file))
7
+ return undefined;
8
+ return JSON.parse(readFileSync(file, 'utf8'));
9
+ }
10
+ const placeholders = (template) => [...new Set([...template.matchAll(/\{(\w+)\}/g)].map((match) => match[1]))].sort();
11
+ /**
12
+ * The UI texts `translate` rewords, per locale: only answers that differ from the built-in text. Asked once per locale
13
+ * and key at boot (`ui.<key>`, `text` the locale's built-in text, else the English one). An answer that changes the
14
+ * `{name}` placeholders, or a throw, fails boot.
15
+ */
16
+ export function uiOverrides(bundles, locales, translate) {
17
+ if (!translate)
18
+ return {};
19
+ const english = bundles.en ?? {};
20
+ const out = {};
21
+ for (const locale of locales) {
22
+ const own = bundles[locale] ?? {};
23
+ for (const [key, template] of Object.entries(english)) {
24
+ const text = own[key] ?? template;
25
+ let answer;
26
+ try {
27
+ answer = translate({ key: `ui.${key}`, text, locale });
28
+ }
29
+ catch (error) {
30
+ throw new Error(`nest-my-admin: translate threw for ui.${key} (${locale}): ${error instanceof Error ? error.message : String(error)}`);
31
+ }
32
+ if (typeof answer !== 'string' || answer === '' || answer === text)
33
+ continue;
34
+ const wanted = placeholders(template);
35
+ if (placeholders(answer).join() !== wanted.join()) {
36
+ throw new Error(`nest-my-admin: translate: ui.${key} (${locale}) must keep the placeholders ${wanted.map((name) => `{${name}}`).join(' ') || '(none)'}`);
37
+ }
38
+ (out[locale] ??= {})[key] = answer;
39
+ }
40
+ }
41
+ return out;
42
+ }
43
+ //# sourceMappingURL=ui-messages.js.map
@@ -0,0 +1,26 @@
1
+ import { type LocalizedText } from './localized-text.js';
2
+ /**
3
+ * Resolves a host text for a request (the `translate` option). `key` names the text when it has a stable identity
4
+ * (`resource.order.fields.total.label`); texts without one come with `text` only. Answer undefined to keep the
5
+ * declared text. Runs per request: keep it cheap. For `ui.` keys it runs once per locale at boot and must be pure.
6
+ */
7
+ export type AdminTranslate = (request: {
8
+ key?: string;
9
+ text: LocalizedText;
10
+ locale: string;
11
+ }) => string | undefined;
12
+ /** A text in a locale: the host's translation, else the declared text (`resolveText`). */
13
+ export type TextResolver = (text: LocalizedText, locale: string, key?: string) => string;
14
+ /** The one place host texts are resolved. A `translate` that throws falls back to the declared text, logged once per key (once for all keyless texts). */
15
+ export declare function createTexts(options: {
16
+ translate?: AdminTranslate;
17
+ locale: string;
18
+ }, logger: {
19
+ warn(message: string): void;
20
+ }): TextResolver;
21
+ /** A text of one owner (a resource, a page) in the request's locale; `path` is its key under the owner's prefix. */
22
+ export type ScopedText = (value: LocalizedText, path?: string) => string;
23
+ /** `texts` for one owner: `scopedText(texts, 'en', 'resource.order')` asks `resource.order.<path>`, or keyless without a path. */
24
+ export declare function scopedText(texts: TextResolver, locale: string, prefix: string): ScopedText;
25
+ /** Texts resolved at boot, for the stored schema: the default locale's, or the first one given. */
26
+ export declare const bootText: ScopedText;
@@ -0,0 +1,31 @@
1
+ import { resolveText } from './localized-text.js';
2
+ /** The one place host texts are resolved. A `translate` that throws falls back to the declared text, logged once per key (once for all keyless texts). */
3
+ export function createTexts(options, logger) {
4
+ const { translate, locale: defaultLocale } = options;
5
+ if (!translate)
6
+ return (text, locale) => resolveText(text, locale, defaultLocale);
7
+ const warned = new Set();
8
+ return (text, locale, key) => {
9
+ try {
10
+ const answer = translate(key === undefined ? { text, locale } : { key, text, locale });
11
+ if (typeof answer === 'string' && answer !== '')
12
+ return answer;
13
+ }
14
+ catch (error) {
15
+ // Keyless texts are often built from data (action messages): one warning for all of them keeps this set small.
16
+ const name = key ?? '(texts without a key)';
17
+ if (!warned.has(name)) {
18
+ warned.add(name);
19
+ logger.warn(`translate threw for "${name}" (${error instanceof Error ? error.message : String(error)}); the declared text is shown`);
20
+ }
21
+ }
22
+ return resolveText(text, locale, defaultLocale);
23
+ };
24
+ }
25
+ /** `texts` for one owner: `scopedText(texts, 'en', 'resource.order')` asks `resource.order.<path>`, or keyless without a path. */
26
+ export function scopedText(texts, locale, prefix) {
27
+ return (value, path) => texts(value, locale, path === undefined ? undefined : path === '' ? prefix : `${prefix}.${path}`);
28
+ }
29
+ /** Texts resolved at boot, for the stored schema: the default locale's, or the first one given. */
30
+ export const bootText = (value) => resolveText(value, '', '');
31
+ //# sourceMappingURL=texts.js.map
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export { AdminModule } from './admin.module.js';
2
2
  export type { AdminAuditOptions, AdminBranding, AdminCurrency, AdminFilesOptions, AdminMenuItem, AdminMenuOptions, AdminMenuSection, AdminModuleOptions, ErrorMapper, GlobalScope } from './options.js';
3
3
  export type { LocalizedText } from './i18n/localized-text.js';
4
+ export type { AdminTranslate } from './i18n/texts.js';
4
5
  export { ResourceRegistry, type RegisteredGroup, type RegisteredResource } from './registry/resource-registry.js';
5
6
  export type { DbNames } from './registry/db-names.js';
6
7
  export { AdminGroup, type AdminGroupOptions } from './decorators/admin-group.js';
@@ -9,7 +10,7 @@ export { AdminResourceBase, type FilterCondition, type FilterValue, type FindMan
9
10
  export { AdminField, BADGE_COLORS, WIDGETS, type AdminFieldOptions, type FileFieldOptions, type BadgeColor, type WidgetName } from './decorators/admin-field.js';
10
11
  export type { FieldConfig, FieldsConfig, LayoutConfig, LayoutInlineConfig, LayoutSectionConfig, LayoutTabConfig } from './schema/field-config.js';
11
12
  export type { RegisteredInline } from './inlines/inline-config.js';
12
- export { AdminContext } from './resource/admin-context.js';
13
+ export { AdminContext, type AdminWriteContext } from './resource/admin-context.js';
13
14
  export { AdminCan, AdminScope, type RecordOperation, type ScopeCondition } from './decorators/admin-scope.js';
14
15
  export { AdminAction, type ActionOutcome, type AdminActionOptions } from './decorators/admin-action.js';
15
16
  export { AdminPrint, type AdminPrintOptions } from './decorators/admin-print.js';
@@ -2,6 +2,7 @@ import type { FormLayoutInline } from '../contract.js';
2
2
  import { type LocalizedText } from '../i18n/localized-text.js';
3
3
  import type { RegisteredResource, RelationMetadataLike } from '../registry/resource-registry.js';
4
4
  import { type LayoutInlineConfig } from '../schema/field-config.js';
5
+ import { type ScopedText } from '../i18n/texts.js';
5
6
  /** An inline of a parent resource, resolved at boot against the child resource. */
6
7
  export interface RegisteredInline {
7
8
  /** The child resource's name: the key in `ResourceSchema.inlines` and `_inlines`. */
@@ -35,5 +36,8 @@ export interface RegisteredInline {
35
36
  export declare function resolveInlines(entries: RegisteredResource[]): void;
36
37
  /** The resolved inline of a layout node. */
37
38
  export declare function inlineOf(entry: RegisteredResource, node: LayoutInlineConfig): RegisteredInline;
38
- /** The inline node the UI gets, its label in `locale` (`label`: the section's title already in `locale`). */
39
- export declare function toLayoutInline(inline: RegisteredInline, label: string | undefined, locale: string, defaultLocale: string): FormLayoutInline;
39
+ /**
40
+ * The inline node the UI gets: `label` is the section's title already resolved, else `childLabel` (the child
41
+ * resource's label); `text` resolves the parent's texts (`form.<key>.markFirst`).
42
+ */
43
+ export declare function toLayoutInline(inline: RegisteredInline, label: string | undefined, text: ScopedText, childLabel: string): FormLayoutInline;
@@ -1,7 +1,7 @@
1
- import { resolveText } from '../i18n/localized-text.js';
2
1
  import { DEFAULT_INLINE_MAX, layoutInlines, localizeLayout, mainLayout } from '../schema/field-config.js';
3
2
  import { isToOne } from '../schema/relation-fields.js';
4
3
  import { didYouMean } from '../schema/suggest.js';
4
+ import { bootText } from '../i18n/texts.js';
5
5
  /**
6
6
  * Resolves the inline nodes of every resource's layout, once every resource is registered (a child may be registered
7
7
  * after its parent): the child resource, its link field, `order` and `fields`. Sets `entry.inlines` and puts the
@@ -24,7 +24,7 @@ export function resolveInlines(entries) {
24
24
  inlines.push(inline);
25
25
  }
26
26
  entry.inlines = inlines;
27
- entry.schema.form.layout = localizeLayout(layout, '', '', (node, label) => toLayoutInline(inlineOf(entry, node), label, '', ''));
27
+ entry.schema.form.layout = localizeLayout(layout, bootText, (node, label) => toLayoutInline(inlineOf(entry, node), label, bootText, bootText(inlineOf(entry, node).child.label)));
28
28
  }
29
29
  }
30
30
  /** The resolved inline of a layout node. */
@@ -34,11 +34,14 @@ export function inlineOf(entry, node) {
34
34
  throw new Error(`${entry.className}: an inline of the layout was not resolved`);
35
35
  return inline;
36
36
  }
37
- /** The inline node the UI gets, its label in `locale` (`label`: the section's title already in `locale`). */
38
- export function toLayoutInline(inline, label, locale, defaultLocale) {
37
+ /**
38
+ * The inline node the UI gets: `label` is the section's title already resolved, else `childLabel` (the child
39
+ * resource's label); `text` resolves the parent's texts (`form.<key>.markFirst`).
40
+ */
41
+ export function toLayoutInline(inline, label, text, childLabel) {
39
42
  return {
40
43
  inline: inline.name,
41
- label: label ?? resolveText(inline.child.label, locale, defaultLocale),
44
+ label: label ?? childLabel,
42
45
  display: inline.display,
43
46
  fields: [...inline.fields],
44
47
  ...(inline.order !== undefined ? { order: inline.order } : {}),
@@ -47,7 +50,7 @@ export function toLayoutInline(inline, label, locale, defaultLocale) {
47
50
  link: inline.link,
48
51
  ...(inline.readonly ? { readonly: true } : {}),
49
52
  ...(inline.computed.length > 0 ? { computed: [...inline.computed] } : {}),
50
- ...(inline.node.cards?.markFirst !== undefined ? { markFirst: resolveText(inline.node.cards.markFirst, locale, defaultLocale) } : {}),
53
+ ...(inline.node.cards?.markFirst !== undefined ? { markFirst: text(inline.node.cards.markFirst, inline.node.key === undefined ? undefined : `form.${inline.node.key}.markFirst`) } : {}),
51
54
  };
52
55
  }
53
56
  function resolveInline(entry, node, entries, fail) {
@@ -15,7 +15,7 @@ export interface InlineWriterDeps {
15
15
  change: <T>(change: WriteChange, tx: AdminContext, method: () => Promise<T>) => Promise<T>;
16
16
  checkRelationsExist: (entry: RegisteredResource, ids: Map<string, RelationId[]>, ctx: AdminContext, values: Record<string, unknown>) => Promise<void>;
17
17
  checkVersion: (entry: RegisteredResource, id: RecordId, expected: number | undefined, ctx: AdminContext) => Promise<void>;
18
- lockedFields: (entry: RegisteredResource, entity: object) => string[];
18
+ lockedFields: (entry: RegisteredResource, entity: object, ctx: AdminContext) => string[];
19
19
  /** A record's values as `relationOptions()` sees them (as the user sees the record, relations as ids). */
20
20
  values: (entry: RegisteredResource, entity: object, ctx: AdminContext) => Promise<Record<string, unknown>>;
21
21
  reloadIfEmpty: (entry: RegisteredResource, result: unknown, id: RecordId, ctx: AdminContext) => Promise<object>;
@@ -249,13 +249,13 @@ export class InlineWriter {
249
249
  throw new AdminForbiddenError(`You may not update ${label} "${named.get(canonical).raw}"`);
250
250
  }
251
251
  for (const entry of updates) {
252
- const locked = this.deps.lockedFields(child, rows.get(entry.canonical)).filter((name) => Object.hasOwn(entry.dto, name));
252
+ const locked = this.deps.lockedFields(child, rows.get(entry.canonical), tx).filter((name) => Object.hasOwn(entry.dto, name));
253
253
  for (const name of locked)
254
254
  errors[`${at}.update.${entry.raw}.${name}`] = ['is read-only'];
255
255
  }
256
256
  if (inline.order !== undefined) {
257
257
  for (const canonical of moves.keys()) {
258
- if (this.deps.lockedFields(child, rows.get(canonical)).includes(inline.order))
258
+ if (this.deps.lockedFields(child, rows.get(canonical), tx).includes(inline.order))
259
259
  errors[at] = [`${label} "${named.get(canonical).raw}" cannot be moved`];
260
260
  }
261
261
  }
@@ -313,6 +313,10 @@ export class InlineWriter {
313
313
  const { child } = inline;
314
314
  const resource = child.resource;
315
315
  const at = `_inlines.${inline.name}`;
316
+ // `@AdminCan('create')` judges the parent as this save leaves it (created, or with its changes): the save is one
317
+ // transaction, so a refusal here undoes the parent too.
318
+ if (creates.length > 0 && !this.deps.policy.createRule(child, parentEntity, tx))
319
+ throw new AdminForbiddenError(`You may not add ${child.schema.label} rows here`);
316
320
  const run = async (path, change, method) => {
317
321
  try {
318
322
  return await this.deps.change({ ...change, parent: parentRef }, tx, method);
package/dist/options.d.ts CHANGED
@@ -5,6 +5,7 @@ import type { RoleDefinition } from './policy/roles.js';
5
5
  import type { AdminContext } from './resource/admin-context.js';
6
6
  import type { AdminError } from './errors.js';
7
7
  import type { LocalizedText } from './i18n/localized-text.js';
8
+ import { type AdminTranslate, type TextResolver } from './i18n/texts.js';
8
9
  import type { AdminStorage } from './files/storage.js';
9
10
  import { type AdminCurrency } from './schema/currency.js';
10
11
  export type { AdminCurrency } from './schema/currency.js';
@@ -21,23 +22,37 @@ export interface AdminBranding {
21
22
  /** Corner radius, a CSS length such as `0.5rem`. */
22
23
  radius?: string;
23
24
  }
24
- /** One menu entry: a resource (with an optional count badge: `filter[...]` list parameters), a settings page, or a link. */
25
+ /**
26
+ * One menu entry: a resource (with an optional count badge: `filter[...]` list parameters), a settings page, or a link.
27
+ * A resource or page is named, or given as its class (`{ resource: OrderAdmin }`, `{ page: ShopSettingsPage }`).
28
+ */
25
29
  export type AdminMenuItem = {
26
- resource: string;
30
+ resource: string | Function;
27
31
  badge?: Record<string, string>;
28
32
  } | {
29
- page: string;
33
+ page: string | Function;
30
34
  } | {
31
35
  href: string;
32
36
  label: LocalizedText;
33
37
  };
34
- export interface AdminMenuSection {
38
+ /** A section of the menu: its own label, icon and items, or an `@AdminGroup`'s (`{ group: 'sales' }`). */
39
+ export type AdminMenuSection = {
35
40
  /** Unique; also the URL of the section's page (`/g/<key>`) and the badge key prefix. */
36
41
  key: string;
37
42
  label: LocalizedText;
38
43
  icon: string;
39
44
  items: AdminMenuItem[];
40
- }
45
+ group?: undefined;
46
+ } | {
47
+ /** The group's key: label, icon and (without `items`) the members come from the group; what you give wins. */
48
+ group: string;
49
+ /** Default: the group's key. */
50
+ key?: string;
51
+ label?: LocalizedText;
52
+ icon?: string;
53
+ /** Default: the group's resources and settings pages, in the group's order. */
54
+ items?: AdminMenuItem[];
55
+ };
41
56
  export interface AdminMenuOptions {
42
57
  sections: AdminMenuSection[];
43
58
  /** The last section holding everything not placed. Default label «Advanced». */
@@ -126,6 +141,11 @@ export interface AdminModuleOptions {
126
141
  transactions?: boolean;
127
142
  /** Translate your own exceptions into admin errors (see ErrorMapper). Default: none. */
128
143
  errorMapper?: ErrorMapper;
144
+ /**
145
+ * Resolves every text you declare (labels, help, enum labels, sections…) and the UI's own texts (`ui.<key>`) per
146
+ * locale, with your own i18n. Answer undefined to keep the declared text. See AdminTranslate for the keys.
147
+ */
148
+ translate?: AdminTranslate;
129
149
  /** Advanced: serve the UI from this directory instead of @nest-my-admin/ui (tests, UI development). */
130
150
  uiDistPath?: string;
131
151
  /**
@@ -176,6 +196,9 @@ export interface ResolvedAdminOptions {
176
196
  autoRegister: string[];
177
197
  transactions: boolean;
178
198
  errorMapper?: ErrorMapper;
199
+ translate?: AdminTranslate;
200
+ /** Every host text goes through this: `translate`, else the declared text. */
201
+ texts: TextResolver;
179
202
  uiDistPath?: string;
180
203
  auth?: AdminAuthConfig;
181
204
  roles: RoleDefinition[];
package/dist/options.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { createTexts } from './i18n/texts.js';
2
+ import { Logger } from '@nestjs/common';
1
3
  import { checkCurrency } from './schema/currency.js';
2
4
  import { DEFAULT_MAX_FILE_BYTES, MAX_FILE_BYTES } from './schema/field-config.js';
3
5
  export function resolveAdminOptions(options = {}) {
@@ -29,6 +31,8 @@ export function resolveAdminOptions(options = {}) {
29
31
  autoRegister: options.autoRegister === true ? ['default'] : Array.isArray(options.autoRegister) ? options.autoRegister : [],
30
32
  transactions: options.transactions ?? true,
31
33
  errorMapper: options.errorMapper,
34
+ translate: options.translate,
35
+ texts: createTexts({ translate: options.translate, locale }, new Logger('NestMyAdmin')),
32
36
  auth: options.auth,
33
37
  roles: options.roles ?? [],
34
38
  resolveRoles: options.resolveRoles,
@@ -67,6 +71,12 @@ function checkMenuShape(menu) {
67
71
  throw new Error('nest-my-admin: menu.sections must be a list');
68
72
  const keys = new Set();
69
73
  for (const section of menu.sections) {
74
+ if (section.group !== undefined && (typeof section.group !== 'string' || section.group === ''))
75
+ throw new Error('nest-my-admin: menu section `group` must be a group key');
76
+ }
77
+ // A group section is keyed by its group unless it says otherwise.
78
+ const sections = menu.sections.map((section) => (section.group !== undefined && section.key === undefined ? { ...section, key: section.group } : section));
79
+ for (const section of sections) {
70
80
  const where = `nest-my-admin: menu.sections.${String(section.key)}`;
71
81
  if (typeof section.key !== 'string' || !/^[a-z0-9][a-z0-9_-]*$/i.test(section.key))
72
82
  throw new Error(`nest-my-admin: menu section key "${String(section.key)}" must be letters, digits, - and _`);
@@ -75,14 +85,16 @@ function checkMenuShape(menu) {
75
85
  if (keys.has(section.key))
76
86
  throw new Error(`${where}: the key is used twice`);
77
87
  keys.add(section.key);
78
- if (!Array.isArray(section.items))
88
+ if (section.group === undefined && !Array.isArray(section.items))
89
+ throw new Error(`${where}: items must be a list`);
90
+ if (section.items !== undefined && !Array.isArray(section.items))
79
91
  throw new Error(`${where}: items must be a list`);
80
- for (const item of section.items) {
92
+ for (const item of section.items ?? []) {
81
93
  if ('href' in item && /^[a-z][a-z0-9+.-]*:/i.test(item.href.trim()) && !/^https?:\/\//i.test(item.href.trim()))
82
94
  throw new Error(`${where}: href must be an http(s) URL or a relative path`);
83
95
  }
84
96
  }
85
- return menu;
97
+ return { ...menu, sections };
86
98
  }
87
99
  function checkFiles(files) {
88
100
  if (!files)
@@ -1,7 +1,7 @@
1
1
  import { validateWrite } from '../crud/validate-write.js';
2
2
  import { AdminForbiddenError, AdminValidationError } from '../errors.js';
3
3
  import { hostError } from '../http/error-response.js';
4
- import { resolveText } from '../i18n/localized-text.js';
4
+ import { scopedText } from '../i18n/texts.js';
5
5
  import { localizeDtoForm } from '../schema/dto-form.js';
6
6
  import { localizeLayout } from '../schema/field-config.js';
7
7
  import { loadPage } from './page-registry.js';
@@ -21,7 +21,7 @@ export class PageService {
21
21
  this.host = host;
22
22
  }
23
23
  text(page, locale) {
24
- return resolveText(page.label, locale ?? this.host.options.locale, this.host.options.locale);
24
+ return this.host.options.texts(page.label, locale ?? this.host.options.locale, `page.${page.name}`);
25
25
  }
26
26
  /** The pages `ctx`'s user may view (all of them without a request), labelled in `locale`. */
27
27
  summaries(locale, ctx) {
@@ -34,13 +34,14 @@ export class PageService {
34
34
  schema(page, ctx) {
35
35
  const { options, files, policy } = this.host;
36
36
  const locale = ctx.locale ?? options.locale;
37
- const form = localizeDtoForm(page.form, locale, options.locale, { maxBytes: options.files?.maxBytes, enabled: files.enabled });
37
+ const text = scopedText(options.texts, locale, `page.${page.name}`);
38
+ const form = localizeDtoForm(page.form, (value, path) => text(value, `fields.${path}`), { maxBytes: options.files?.maxBytes, enabled: files.enabled });
38
39
  return {
39
40
  name: page.name,
40
41
  label: this.text(page, locale),
41
42
  ...(page.icon ? { icon: page.icon } : {}),
42
43
  fields: form.fields,
43
- ...(page.layout ? { layout: localizeLayout(page.layout, locale, options.locale) } : {}),
44
+ ...(page.layout ? { layout: localizeLayout(page.layout, (value, key) => text(value, key === undefined ? undefined : `form.${key}`)) } : {}),
44
45
  constraints: form.constraints,
45
46
  required: form.required,
46
47
  readonly: ctx.viewAs !== undefined || !policy.canPage(page, 'update', ctx),
@@ -14,6 +14,7 @@ import type { RecordId } from '../resource/admin-resource-base.js';
14
14
  import { AdminRbac } from '../rbac/rbac.service.js';
15
15
  import { EffectivePermissions, type FieldLevel } from './effective.js';
16
16
  import { type ResourceOperation, type ScopedOperation } from './roles.js';
17
+ import { type ScopedText } from '../i18n/texts.js';
17
18
  /** What the user may do with one resource: its schema cut to them, and the level of every field and path. */
18
19
  export interface ResourceView {
19
20
  schema: ResourceSchema;
@@ -103,6 +104,11 @@ export declare class AdminPolicy implements OnApplicationBootstrap {
103
104
  requireInScope(entry: RegisteredResource, id: RecordId, rawId: string, operation: ScopedOperation, ctx: AdminContext, withDeleted?: boolean): Promise<void>;
104
105
  /** `@AdminCan` rules for one record (`operation`: update, delete or a record action's name): all must agree; a rule that throws says no. */
105
106
  recordRule(entry: RegisteredResource, operation: RecordOperation | (string & {}), entity: object, ctx: AdminContext): boolean;
107
+ /**
108
+ * Whether a row of the inline `child` may be added under `parent` (the parent entity as its resource reads it): every
109
+ * `@AdminCan('create')` rule of the child agrees; a rule that throws says no. True for a child without one.
110
+ */
111
+ createRule(child: RegisteredResource, parent: object, ctx: AdminContext): boolean;
106
112
  /** 403 when `@AdminCan` says no for this record. */
107
113
  requireRecordRule(entry: RegisteredResource, operation: RecordOperation, entity: object, ctx: AdminContext): void;
108
114
  /**
@@ -125,5 +131,8 @@ export declare class AdminPolicy implements OnApplicationBootstrap {
125
131
  }
126
132
  /** Fields that are not paths. */
127
133
  export declare function topLevelFields(schema: ResourceSchema): FieldSchema[];
128
- /** An action's label on one record: `label.for(record)` in `locale` (`null` hides it there), else its label. */
129
- export declare function actionLabel(action: RegisteredAction, record: object, locale: string, defaultLocale: string): string | null;
134
+ /**
135
+ * An action's label on one record: `label.for(record)` (`null` hides it there), else its label, through `text`
136
+ * (the resource's texts; the key is the action's label key either way).
137
+ */
138
+ export declare function actionLabel(action: RegisteredAction, record: object, text: ScopedText): string | null;