@mgamadeus/ddd-web 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,82 @@
1
+ // src/contract/error-normalization.ts
2
+ var DEFAULT_ERROR_MESSAGE = "Request failed";
3
+ var DEFAULT_ERROR_MESSAGES = {
4
+ serverError: (status) => `Server error (HTTP ${status})`,
5
+ httpError: (status) => `Request failed (HTTP ${status})`,
6
+ networkError: "The server could not be reached",
7
+ timeoutError: "The request timed out"
8
+ };
9
+ var isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
10
+ var nonEmptyString = (value) => typeof value === "string" && value.trim() !== "" ? value : null;
11
+ var extractBody = (error) => {
12
+ if ("data" in error) return error.data;
13
+ if ("responseBody" in error) return error.responseBody;
14
+ if ("error" in error || "validationErrors" in error || "exceptionDetails" in error) return error;
15
+ return void 0;
16
+ };
17
+ var extractStatus = (error) => {
18
+ if (error.status === "PARSING_ERROR" && typeof error.originalStatus === "number") return error.originalStatus;
19
+ if (typeof error.status === "number" || typeof error.status === "string") return error.status;
20
+ if (typeof error.statusCode === "number") return error.statusCode;
21
+ return null;
22
+ };
23
+ var transportFailureMessage = (error, texts, fallbackMessage) => {
24
+ switch (error.status) {
25
+ case "PARSING_ERROR": {
26
+ const status = typeof error.originalStatus === "number" ? error.originalStatus : null;
27
+ if (status === null) return fallbackMessage;
28
+ return status >= 500 ? texts.serverError(status) : texts.httpError(status);
29
+ }
30
+ case "FETCH_ERROR":
31
+ return texts.networkError;
32
+ case "TIMEOUT_ERROR":
33
+ return texts.timeoutError;
34
+ default:
35
+ return null;
36
+ }
37
+ };
38
+ function normalizeDddError(error, fallbackMessage = DEFAULT_ERROR_MESSAGE, messages = {}) {
39
+ const texts = { ...DEFAULT_ERROR_MESSAGES, ...messages };
40
+ if (!isRecord(error)) {
41
+ return {
42
+ status: null,
43
+ message: nonEmptyString(error) ?? fallbackMessage,
44
+ validationErrors: null,
45
+ details: [],
46
+ body: void 0
47
+ };
48
+ }
49
+ const body = extractBody(error);
50
+ const failure = transportFailureMessage(error, texts, fallbackMessage);
51
+ if (failure !== null) {
52
+ return { status: extractStatus(error), message: failure, validationErrors: null, details: [], body };
53
+ }
54
+ const dddBody = isRecord(body) ? body : null;
55
+ const bodyRecord = isRecord(body) ? body : null;
56
+ const message = nonEmptyString(dddBody?.error) ?? nonEmptyString(bodyRecord?.message) ?? // RTK's non-HTTP errors carry the reason in `error` (e.g. "TypeError: Failed to fetch").
57
+ (body === void 0 || typeof body === "string" ? nonEmptyString(error.error) : null) ?? // A non-JSON error body (e.g. a download endpoint answering with plain text) is the message itself.
58
+ nonEmptyString(body)?.trim() ?? nonEmptyString(error.message) ?? fallbackMessage;
59
+ return {
60
+ status: extractStatus(error),
61
+ message,
62
+ validationErrors: dddBody?.validationErrors ?? null,
63
+ details: dddBody?.exceptionDetails?.elements ?? [],
64
+ body
65
+ };
66
+ }
67
+ function getErrorMessage(error, fallbackMessage = DEFAULT_ERROR_MESSAGE, messages = {}) {
68
+ return normalizeDddError(error, fallbackMessage, messages).message;
69
+ }
70
+ function getErrorStatus(error) {
71
+ const status = normalizeDddError(error).status;
72
+ return typeof status === "number" ? status : null;
73
+ }
74
+
75
+ export {
76
+ DEFAULT_ERROR_MESSAGE,
77
+ DEFAULT_ERROR_MESSAGES,
78
+ normalizeDddError,
79
+ getErrorMessage,
80
+ getErrorStatus
81
+ };
82
+ //# sourceMappingURL=chunk-WZTEQOE6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/contract/error-normalization.ts"],"sourcesContent":["import type { DddErrorBody, DddExceptionDetail } from './errors';\n\n/** A DDD API error in one predictable shape, whatever produced it (RTK Query, a thrown Error, a raw body). */\nexport interface DddNormalizedError {\n /**\n * HTTP status, or RTK Query's string status for non-HTTP failures (`FETCH_ERROR`, `TIMEOUT_ERROR`,\n * `CUSTOM_ERROR`); a `PARSING_ERROR` reports the original HTTP status. `null` when unknown.\n */\n status: number | string | null;\n /** Human-readable message: the backend's `error` key first, then a text body, then generic fallbacks. */\n message: string;\n /** The backend's `validationErrors` exactly as received (present on validation 400s), else `null`. */\n validationErrors: unknown;\n /** `exceptionDetails.elements` of the backend body; empty when absent. */\n details: DddExceptionDetail[];\n /** The raw response body (parsed JSON, text, or `undefined`). */\n body: unknown;\n}\n\n/** Message used when an error carries no message at all. */\nexport const DEFAULT_ERROR_MESSAGE = 'Request failed';\n\n/**\n * Messages for failures that carry no usable backend message. Pass your own (e.g. translated) texts as the third\n * argument of {@link normalizeDddError} / {@link getErrorMessage}.\n */\nexport interface DddErrorMessages {\n /** A response that is not JSON (an HTML error page, a PHP fatal) with an HTTP status ≥ 500. */\n serverError: (status: number) => string;\n /** A response that is not JSON with an HTTP status < 500. */\n httpError: (status: number) => string;\n /** The request never reached the server or got no response (`FETCH_ERROR`). */\n networkError: string;\n /** The request timed out (`TIMEOUT_ERROR`). */\n timeoutError: string;\n}\n\n/** The default {@link DddErrorMessages}. */\nexport const DEFAULT_ERROR_MESSAGES: DddErrorMessages = {\n serverError: (status) => `Server error (HTTP ${status})`,\n httpError: (status) => `Request failed (HTTP ${status})`,\n networkError: 'The server could not be reached',\n timeoutError: 'The request timed out',\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n\nconst nonEmptyString = (value: unknown): string | null =>\n typeof value === 'string' && value.trim() !== '' ? value : null;\n\n/** Unwraps the places a response body can sit: RTK `data`, an Error's `responseBody`, or the value itself. */\nconst extractBody = (error: Record<string, unknown>): unknown => {\n if ('data' in error) return error.data;\n if ('responseBody' in error) return error.responseBody;\n if ('error' in error || 'validationErrors' in error || 'exceptionDetails' in error) return error;\n return undefined;\n};\n\nconst extractStatus = (error: Record<string, unknown>): number | string | null => {\n if (error.status === 'PARSING_ERROR' && typeof error.originalStatus === 'number') return error.originalStatus;\n if (typeof error.status === 'number' || typeof error.status === 'string') return error.status;\n if (typeof error.statusCode === 'number') return error.statusCode;\n return null;\n};\n\n/**\n * The message of an RTK Query failure that is not a DDD response: an unparsable body (`PARSING_ERROR`), no response\n * (`FETCH_ERROR`), a timeout (`TIMEOUT_ERROR`); `null` for everything else.\n */\nconst transportFailureMessage = (\n error: Record<string, unknown>,\n texts: DddErrorMessages,\n fallbackMessage: string,\n): string | null => {\n switch (error.status) {\n case 'PARSING_ERROR': {\n const status = typeof error.originalStatus === 'number' ? error.originalStatus : null;\n if (status === null) return fallbackMessage;\n return status >= 500 ? texts.serverError(status) : texts.httpError(status);\n }\n case 'FETCH_ERROR':\n return texts.networkError;\n case 'TIMEOUT_ERROR':\n return texts.timeoutError;\n default:\n return null;\n }\n};\n\n/**\n * Normalises any API error into {@link DddNormalizedError}.\n *\n * Understands RTK Query's `FetchBaseQueryError` (`{ status, data }`, `{ status: 'FETCH_ERROR', error }`, …),\n * `SerializedError` / `Error` (`message`), errors carrying a parsed `responseBody`, and a bare DDD error body.\n * DDD error bodies put the message under `error` (not `message`).\n *\n * A response the client could not parse (`PARSING_ERROR`: an HTML error page, a PHP fatal, a proxy's 502) is an HTTP\n * error: `status` is the HTTP status and the message is {@link DddErrorMessages.serverError} /\n * {@link DddErrorMessages.httpError} — never the parser's `SyntaxError` text and never the raw body, which may show\n * internals (the body stays available in `body`). `FETCH_ERROR` and `TIMEOUT_ERROR` get\n * {@link DddErrorMessages.networkError} / {@link DddErrorMessages.timeoutError} instead of the browser's text.\n *\n * @param error whatever a request rejected with\n * @param fallbackMessage message when nothing usable is found\n * @param messages texts for failures without a backend message (default {@link DEFAULT_ERROR_MESSAGES})\n */\nexport function normalizeDddError(\n error: unknown,\n fallbackMessage: string = DEFAULT_ERROR_MESSAGE,\n messages: Partial<DddErrorMessages> = {},\n): DddNormalizedError {\n const texts: DddErrorMessages = { ...DEFAULT_ERROR_MESSAGES, ...messages };\n if (!isRecord(error)) {\n return {\n status: null,\n message: nonEmptyString(error) ?? fallbackMessage,\n validationErrors: null,\n details: [],\n body: undefined,\n };\n }\n\n const body = extractBody(error);\n const failure = transportFailureMessage(error, texts, fallbackMessage);\n if (failure !== null) {\n return { status: extractStatus(error), message: failure, validationErrors: null, details: [], body };\n }\n const dddBody: DddErrorBody | null = isRecord(body) ? (body as DddErrorBody) : null;\n const bodyRecord: Record<string, unknown> | null = isRecord(body) ? body : null;\n\n const message =\n nonEmptyString(dddBody?.error) ??\n nonEmptyString(bodyRecord?.message) ??\n // RTK's non-HTTP errors carry the reason in `error` (e.g. \"TypeError: Failed to fetch\").\n (body === undefined || typeof body === 'string' ? nonEmptyString(error.error) : null) ??\n // A non-JSON error body (e.g. a download endpoint answering with plain text) is the message itself.\n nonEmptyString(body)?.trim() ??\n nonEmptyString(error.message) ??\n fallbackMessage;\n\n return {\n status: extractStatus(error),\n message,\n validationErrors: dddBody?.validationErrors ?? null,\n details: dddBody?.exceptionDetails?.elements ?? [],\n body,\n };\n}\n\n/**\n * The message to show for an API error (`normalizeDddError(error).message`).\n *\n * @param error whatever a request rejected with\n * @param fallbackMessage message when nothing usable is found\n * @param messages texts for failures without a backend message\n */\nexport function getErrorMessage(\n error: unknown,\n fallbackMessage: string = DEFAULT_ERROR_MESSAGE,\n messages: Partial<DddErrorMessages> = {},\n): string {\n return normalizeDddError(error, fallbackMessage, messages).message;\n}\n\n/** HTTP status of an API error (also of an unparsable response), or `null` for non-HTTP failures. */\nexport function getErrorStatus(error: unknown): number | null {\n const status = normalizeDddError(error).status;\n return typeof status === 'number' ? status : null;\n}\n"],"mappings":";AAoBO,IAAM,wBAAwB;AAkB9B,IAAM,yBAA2C;AAAA,EACtD,aAAa,CAAC,WAAW,sBAAsB,MAAM;AAAA,EACrD,WAAW,CAAC,WAAW,wBAAwB,MAAM;AAAA,EACrD,cAAc;AAAA,EACd,cAAc;AAChB;AAEA,IAAM,WAAW,CAAC,UAChB,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAErE,IAAM,iBAAiB,CAAC,UACtB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AI,YAAY,MAAM;AACpB,WAAO,EAAE,QAAQ,cAAc,KAAK,GAAG,SAAS,SAAS,kBAAkB,MAAM,SAAS,CAAC,GAAG,KAAK;AAAA,EACrG;AACA,QAAM,UAA+B,SAAS,IAAI,IAAK,OAAwB;AAC/E,QAAM,aAA6C,SAAS,IAAI,IAAI,OAAO;AAE3E,QAAM,UACJ,eAAe,SAAS,KAAK,KAC7B,eAAe,YAAY,OAAO;AAAA,GAEjC,SAAS,UAAa,OAAO,SAAS,WAAW,eAAe,MAAM,KAAK,IAAI;AAAA,EAEhF,eAAe,IAAI,GAAG,KAAK,KAC3B,eAAe,MAAM,OAAO,KAC5B;AAEF,SAAO;AAAA,IACL,QAAQ,cAAc,KAAK;AAAA,IAC3B;AAAA,IACA,kBAAkB,SAAS,oBAAoB;AAAA,IAC/C,SAAS,SAAS,kBAAkB,YAAY,CAAC;AAAA,IACjD;AAAA,EACF;AACF;AASO,SAAS,gBACd,OACA,kBAA0B,uBAC1B,WAAsC,CAAC,GAC/B;AACR,SAAO,kBAAkB,OAAO,iBAAiB,QAAQ,EAAE;AAC7D;AAGO,SAAS,eAAe,OAA+B;AAC5D,QAAM,SAAS,kBAAkB,KAAK,EAAE;AACxC,SAAO,OAAO,WAAW,WAAW,SAAS;AAC/C;","names":[]}
@@ -4,7 +4,7 @@ import {
4
4
  consoleLogger,
5
5
  generateSdk,
6
6
  linkSkills
7
- } from "../chunk-J2RLNVKK.js";
7
+ } from "../chunk-HVYT2X4V.js";
8
8
 
9
9
  // src/codegen/cli.ts
10
10
  import { parseArgs } from "util";
@@ -193,6 +193,13 @@ interface EndpointOptions {
193
193
  * class that moves keeps the name). `rtk` (default): the camel-cased schema name.
194
194
  */
195
195
  bodyArg?: 'rtk' | 'requestBody';
196
+ /**
197
+ * `true`: the request builder of every endpoint (its `query`) goes into `<stem>Requests.ts` next to the api file, as
198
+ * `export const <stem>Requests = { <endpoint>: (queryArg: <Arg>) => ({ url, params, body, … }) }`, and the endpoint
199
+ * uses it (`query: <stem>Requests.<endpoint>`). A bundle that only builds requests imports that module without the
200
+ * endpoint injection. Default `false`.
201
+ */
202
+ requestBuilders?: boolean;
196
203
  }
197
204
  /** The endpoint name of `naming: 'path'` (see {@link EndpointOptions.naming}). */
198
205
  declare function buildEndpointNameFromPath(method: string, path: string, stripPathPrefix?: string | RegExp): string;
@@ -11,7 +11,7 @@ import {
11
11
  loadSpec,
12
12
  silentLogger,
13
13
  validateSpec
14
- } from "../chunk-J2RLNVKK.js";
14
+ } from "../chunk-HVYT2X4V.js";
15
15
  export {
16
16
  SUPPORTED_CONTRACT,
17
17
  SdkGenerationError,
@@ -1,4 +1,4 @@
1
- export { a as DddErrorBody, D as DddExceptionDetail, b as DddExceptionDetails } from '../errors-B4KabvNa.js';
1
+ export { D as DEFAULT_ERROR_MESSAGE, a as DEFAULT_ERROR_MESSAGES, e as DddErrorBody, b as DddErrorMessages, f as DddExceptionDetail, h as DddExceptionDetails, c as DddNormalizedError, g as getErrorMessage, d as getErrorStatus, n as normalizeDddError } from '../error-normalization-ytMgz5HP.js';
2
2
  export { C as ComparisonOperator, D as DEFAULT_TOP, a as DddColumnKind, b as DddContractInfo, c as DddEntityAction, d as DddEntityIdentity, e as DddEntityInfo, f as DddExpandDefinition, g as DddFilterDefinition, h as DddFilterValueRule, i as DddInfoExtensions, j as DddOperationExtensions, k as DddPropertyExtensions, l as DddQueryDefinition, m as DddSchemaExtensions, n as DddTemporalKind, o as DddTranslatableInfo, F as FILTER_OPERATORS, p as FULLTEXT_OPERATORS, q as FilterJoinOperator, r as FilterOperator, s as FulltextOperator, H as HttpMethod, L as LIST_OPERATORS, t as ListOperator, N as NULL_OPERATORS, O as OrderDirection, Q as QueryOptionsParams, u as getContractInfo, v as hasSideEffects, w as isFilterOperator, x as isFulltextOperator, y as isHiddenProperty, z as isListOperator, A as isPreservedOnOmission, B as isTranslatableProperty, E as parseEntityIdentity } from '../extensions-CmINl0EY.js';
3
3
 
4
4
  /**
@@ -13,6 +13,13 @@ import {
13
13
  parseDddDateTime,
14
14
  parseDddDateTimeMs
15
15
  } from "../chunk-QLCE3QTP.js";
16
+ import {
17
+ DEFAULT_ERROR_MESSAGE,
18
+ DEFAULT_ERROR_MESSAGES,
19
+ getErrorMessage,
20
+ getErrorStatus,
21
+ normalizeDddError
22
+ } from "../chunk-WZTEQOE6.js";
16
23
 
17
24
  // src/contract/extensions.ts
18
25
  function hasSideEffects(method, operation) {
@@ -99,6 +106,8 @@ function parseTranslationKey(key) {
99
106
  };
100
107
  }
101
108
  export {
109
+ DEFAULT_ERROR_MESSAGE,
110
+ DEFAULT_ERROR_MESSAGES,
102
111
  DEFAULT_TOP,
103
112
  FILTER_OPERATORS,
104
113
  FULLTEXT_OPERATORS,
@@ -108,6 +117,8 @@ export {
108
117
  formatDddDate,
109
118
  formatDddDateTime,
110
119
  getContractInfo,
120
+ getErrorMessage,
121
+ getErrorStatus,
111
122
  hasSideEffects,
112
123
  isFilterOperator,
113
124
  isFulltextOperator,
@@ -116,6 +127,7 @@ export {
116
127
  isPreservedOnOmission,
117
128
  isTranslatableProperty,
118
129
  isValidDddDate,
130
+ normalizeDddError,
119
131
  normalizeTranslationInfos,
120
132
  normalizeTranslationsStore,
121
133
  parseDddDateTime,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/contract/extensions.ts","../../src/contract/translations.ts"],"sourcesContent":["import type { FilterOperator } from './operators';\n\n/**\n * Types of the `x-ddd-*` OpenAPI extensions emitted by DDD Core, plus the defaults that apply when an extension is\n * absent. All extensions are additive: a document without them is valid and is read with the defaults below.\n */\n\n/** `info.x-ddd-contract`: contract number and the emitting `mgamadeus/ddd` version. */\nexport interface DddContractInfo {\n /** Contract number; bumped on every change of an `x-ddd-*` key, an implicit part or a default. */\n contract: number;\n /** Version of the `mgamadeus/ddd` package that emitted the document, e.g. `3.14.0`. */\n ddd: string;\n}\n\n/**\n * Column kind of a filter (`FiltersDefinition::COLUMN_KIND_*`): what a filter value is validated and bound as.\n * `translatable` is a plain `#[Translatable]` (JSON of all languages), `translatable-searchable` one with\n * `fullTextIndex: true` (comparisons run on its virtual search column).\n */\nexport type DddColumnKind =\n | 'int'\n | 'float'\n | 'bool'\n | 'string'\n | 'datetime'\n | 'json'\n | 'translatable'\n | 'translatable-searchable';\n\n/**\n * Temporal kind of a filter (`FiltersDefinition::TEMPORAL_KIND_*`): `MOMENT` = an instant (date-time),\n * `DAY` = a calendar day (date, never zone-converted).\n */\nexport type DddTemporalKind = 'MOMENT' | 'DAY';\n\n/**\n * A value rule for one operator of a filter. Known rules:\n * - `wildcard-required`: the value must contain `*` (plain Translatable `eq` / `ne`, a LIKE on the JSON text);\n * - `null-only`: only a null comparison is allowed (JSON columns).\n * Further rules may be added by the contract; unknown rules must be ignored by clients.\n */\nexport type DddFilterValueRule = 'wildcard-required' | 'null-only' | (string & {});\n\n/** One filter definition inside `x-ddd-query.filters`. */\nexport interface DddFilterDefinition {\n /** Filter property name as used in `filters`, may be dotted (e.g. `author.name`). */\n name: string;\n /** Path of the filtered value in the response schema (e.g. `changeHistory.createdTime`); `null` if none. */\n path?: string | null;\n /** Column kind; absent or `null` = no value validation on the backend. */\n columnKind?: DddColumnKind | null;\n /** Temporal kind; absent or `null` = not temporal. */\n temporalKind?: DddTemporalKind | null;\n /** Whether `ft` / `fb` work on this filter (single-column FULLTEXT index). */\n supportsFulltext?: boolean;\n /** Allowed values (`FiltersDefinition::$options`); every value, also each list item, must be one of them. */\n options?: Array<string | number> | null;\n /** Operators allowed for this filter; absent = every operator the column kind accepts. */\n operators?: FilterOperator[];\n /** Value rules per operator. */\n valueRules?: Partial<Record<FilterOperator, DddFilterValueRule>>;\n /** Name of the expand that must be present in `expand` for this filter to be accepted; absent = none. */\n requiresExpand?: string | null;\n}\n\n/** One expand definition inside `x-ddd-query.expand`. */\nexport interface DddExpandDefinition {\n /** Property name to expand (no dots; nesting goes through `expand`). */\n name: string;\n /** `true` for a computed field (no relation, no clauses), e.g. a rendered SVG. */\n computed?: boolean;\n /** Default `top` inside the expand clause. */\n top?: number;\n /** Upper bound for `top` inside the expand clause. */\n maxTop?: number | null;\n /** Default `skip` inside the expand clause. */\n skip?: number;\n /** Filters available inside the expand clause (`filters=` in `(…)`). */\n filters?: DddFilterDefinition[];\n /** Sortable properties inside the expand clause. */\n orderBy?: string[];\n /** Nested expands (`expand=` in `(…)`). */\n expand?: DddExpandDefinition[];\n}\n\n/** `x-ddd-query` on an operation whose request DTO applies QueryOptions. */\nexport interface DddQueryDefinition {\n filters?: DddFilterDefinition[];\n /** Sortable property names. */\n orderBy?: string[];\n expand?: DddExpandDefinition[];\n /** `true` = `select` accepted (any property), a list = the selectable properties, `false`/absent = not exposed. */\n select?: boolean | string[];\n /** Default page size (backend default 50). */\n top?: number;\n /** Upper bound for `top` (`#[QueryOptions(maxTop: …)]`); a larger `top` answers 400. */\n maxTop?: number | null;\n}\n\n/** `x-ddd-entity.action`. DDD `#[Update]` is an upsert. */\nexport type DddEntityAction = 'list' | 'get' | 'upsert' | 'delete' | 'action';\n\n/**\n * `x-ddd-entity` on an operation. Absent = unknown entity: clients derive the identity from the path or the request body\n * and invalidate the whole tag type only when none is found.\n */\nexport interface DddEntityInfo {\n /** Entity schema name, e.g. `App.Domain.Library.Entities.Books.Book`. */\n schema: string;\n action: DddEntityAction;\n /** Identity source, `path:<parameter>` or `body:<dotted.path>` (e.g. `body:book.id`). */\n identity?: string;\n /** `true` when derived by DDD Core, `false` when set explicitly via `#[OperationEntity]`. */\n derived: boolean;\n}\n\n/** Field-level `x-ddd-translatable` (from `#[Translatable]`). */\nexport interface DddTranslatableInfo {\n fullTextIndex?: boolean;\n fullTextMode?: string;\n}\n\n/** Extensions on the document `info` object. */\nexport interface DddInfoExtensions {\n 'x-ddd-contract'?: DddContractInfo;\n}\n\n/** Extensions on an operation object. */\nexport interface DddOperationExtensions {\n 'x-ddd-query'?: DddQueryDefinition;\n /** Absent = default by HTTP method (see {@link hasSideEffects}). */\n 'x-ddd-side-effects'?: boolean;\n 'x-ddd-entity'?: DddEntityInfo;\n /** Cache TTL in seconds from `#[RequestCache]`. */\n 'x-ddd-cache-ttl'?: number;\n}\n\n/** Extensions on a schema property. */\nexport interface DddPropertyExtensions {\n 'x-ddd-translatable'?: DddTranslatableInfo;\n /** `#[HideProperty]`: never in responses, accepted in requests (write-only). Absent = visible. */\n 'x-ddd-hidden'?: boolean;\n /** The stored value is kept when the property is omitted on an update of an existing entity. */\n 'x-ddd-preserve-on-omission'?: boolean;\n}\n\n/** Extensions on an entity schema. */\nexport interface DddSchemaExtensions {\n /** Roles required to write the entity (`RolesRequiredForUpdate`). */\n 'x-ddd-roles-required-for-update'?: string[];\n}\n\n/** HTTP methods of OpenAPI operations (lowercase or uppercase accepted by the helpers). */\nexport type HttpMethod = 'get' | 'head' | 'post' | 'put' | 'patch' | 'delete' | 'options' | 'trace';\n\n/**\n * Whether an operation has side effects (contract defaults, Appendix A.6): `x-ddd-side-effects` wins when present,\n * otherwise `false` for GET/HEAD/OPTIONS/TRACE and `true` for POST/PUT/PATCH/DELETE.\n */\nexport function hasSideEffects(method: string, operation?: Pick<DddOperationExtensions, 'x-ddd-side-effects'> | null): boolean {\n const explicit = operation?.['x-ddd-side-effects'];\n if (typeof explicit === 'boolean') {\n return explicit;\n }\n return !['get', 'head', 'options', 'trace'].includes(method.toLowerCase());\n}\n\n/** Whether a property is write-only (`x-ddd-hidden: true`). Absent = visible. */\nexport function isHiddenProperty(property?: DddPropertyExtensions | null): boolean {\n return property?.['x-ddd-hidden'] === true;\n}\n\n/** Whether a property keeps its stored value when omitted on an update (`x-ddd-preserve-on-omission: true`). */\nexport function isPreservedOnOmission(property?: DddPropertyExtensions | null): boolean {\n return property?.['x-ddd-preserve-on-omission'] === true;\n}\n\n/** Whether a property is `#[Translatable]` (`x-ddd-translatable` present). */\nexport function isTranslatableProperty(property?: DddPropertyExtensions | null): boolean {\n return property?.['x-ddd-translatable'] !== undefined && property['x-ddd-translatable'] !== null;\n}\n\n/** Parsed `x-ddd-entity.identity`. */\nexport interface DddEntityIdentity {\n source: 'path' | 'body';\n /** Path parameter name (`source: 'path'`) or dotted body path (`source: 'body'`). */\n name: string;\n}\n\n/** Parses `x-ddd-entity.identity` (`path:bookId`, `body:book.id`); `null` for an absent or malformed value. */\nexport function parseEntityIdentity(identity: string | null | undefined): DddEntityIdentity | null {\n if (!identity) {\n return null;\n }\n const match = /^(path|body):(.+)$/.exec(identity);\n if (!match) {\n return null;\n }\n return { source: match[1] as 'path' | 'body', name: match[2] as string };\n}\n\n/** Reads `info.x-ddd-contract` from an OpenAPI document; `null` when the document carries no contract version. */\nexport function getContractInfo(document: { info?: DddInfoExtensions | null } | null | undefined): DddContractInfo | null {\n const contract = document?.info?.['x-ddd-contract'];\n if (!contract || typeof contract.contract !== 'number' || typeof contract.ddd !== 'string') {\n return null;\n }\n return contract;\n}\n","/**\n * `DDD.Domain.Base.Entities.Translatable.TranslationInfos` and helpers around its translations store.\n */\n\n/** Writing styles (`Translatable::WRITING_STYLE_*`). */\nexport type WritingStyle = 'FORMAL' | 'INFORMAL';\n\n/**\n * Translation key `<languageCode>:<countryCode>:<writingStyle>` as built by\n * `TranslatableService::getTranslationIndexForLanguageCodeCountryCodeAndWritingStyle()`: language and country\n * lowercase, an absent country is empty, e.g. `en::FORMAL`, `de:at:INFORMAL`.\n */\nexport type TranslationKey = string;\n\n/** Translations of one property: translation key → text. */\nexport type PropertyTranslations = Record<TranslationKey, string>;\n\n/** `translationsStore`: property name → translation key → text. */\nexport type TranslationsStore = Record<string, PropertyTranslations>;\n\n/** `TranslationInfos` as it appears in entity responses and requests (after {@link normalizeTranslationInfos}). */\nexport interface TranslationInfos {\n /** Translations per property. The wire sends `[]` for an empty store; use {@link normalizeTranslationsStore}. */\n translationsStore?: TranslationsStore;\n /** On persist, `true` replaces all stored translations instead of merging (JSON_MERGE_PATCH). */\n replaceExistingTranslations?: boolean;\n currentLanguageCode?: string;\n currentCountryCode?: string | null;\n currentWritingStyle?: WritingStyle;\n defaultLanguageCode?: string;\n defaultWritingStyle?: WritingStyle;\n /** Keys (language, locale, optionally `::style`) for which translations exist → `true`. */\n availableTranslations?: Record<string, boolean>;\n hasTranslationForCurrentLanguageCode?: boolean;\n hasTranslationForCurrentCountryCode?: boolean;\n hasTranslationForCurrentWritingStyle?: boolean;\n objectType?: string | null;\n}\n\n/** `TranslationInfos` as received on the wire: the maps may be empty arrays (`[]`). */\nexport type TranslationInfosWire = Omit<TranslationInfos, 'translationsStore' | 'availableTranslations'> & {\n translationsStore?: TranslationsStore | Record<string, PropertyTranslations | unknown[]> | unknown[] | null;\n availableTranslations?: Record<string, boolean> | unknown[] | null;\n};\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Turns the wire form of a translations store into a map. PHP serialises an empty associative array as `[]`\n * (`TranslationInfos::$translationsStore = []`, kept by the serializer), so an empty store — or an empty property\n * entry — arrives as `[]`; both become `{}`. `null`/`undefined` become `{}` as well. Non-string texts are dropped.\n */\nexport function normalizeTranslationsStore(store: unknown): TranslationsStore {\n if (!isPlainObject(store)) {\n return {};\n }\n const normalized: TranslationsStore = {};\n for (const [propertyName, translations] of Object.entries(store)) {\n const propertyTranslations: PropertyTranslations = {};\n if (isPlainObject(translations)) {\n for (const [key, text] of Object.entries(translations)) {\n if (typeof text === 'string') {\n propertyTranslations[key] = text;\n }\n }\n }\n normalized[propertyName] = propertyTranslations;\n }\n return normalized;\n}\n\n/** Normalises a wire `TranslationInfos`: `translationsStore` and `availableTranslations` become maps. */\nexport function normalizeTranslationInfos(infos: TranslationInfosWire): TranslationInfos {\n const availableTranslations: Record<string, boolean> = {};\n if (isPlainObject(infos.availableTranslations)) {\n for (const [key, available] of Object.entries(infos.availableTranslations)) {\n availableTranslations[key] = available === true;\n }\n }\n return {\n ...infos,\n translationsStore: normalizeTranslationsStore(infos.translationsStore),\n availableTranslations,\n };\n}\n\n/** Parts of a {@link TranslationKey}. */\nexport interface TranslationKeyParts {\n languageCode: string;\n countryCode?: string | null;\n writingStyle: WritingStyle;\n}\n\n/**\n * Builds a translation key the way the backend does\n * (`TranslatableService::getTranslationIndexForLanguageCodeCountryCodeAndWritingStyle()`):\n * `strtolower(language) . ':' . strtolower(country ?? '') . ':' . writingStyle`.\n */\nexport function buildTranslationKey(parts: TranslationKeyParts): TranslationKey {\n return `${parts.languageCode.toLowerCase()}:${(parts.countryCode ?? '').toLowerCase()}:${parts.writingStyle}`;\n}\n\n/** Splits a translation key into its parts; `null` when it is not `<language>:<country>:<style>`. */\nexport function parseTranslationKey(key: TranslationKey): TranslationKeyParts | null {\n const match = /^([^:]+):([^:]*):(FORMAL|INFORMAL)$/.exec(key);\n if (!match) {\n return null;\n }\n return {\n languageCode: match[1] as string,\n countryCode: match[2] ? match[2] : null,\n writingStyle: match[3] as WritingStyle,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgKO,SAAS,eAAe,QAAgB,WAAgF;AAC7H,QAAM,WAAW,YAAY,oBAAoB;AACjD,MAAI,OAAO,aAAa,WAAW;AACjC,WAAO;AAAA,EACT;AACA,SAAO,CAAC,CAAC,OAAO,QAAQ,WAAW,OAAO,EAAE,SAAS,OAAO,YAAY,CAAC;AAC3E;AAGO,SAAS,iBAAiB,UAAkD;AACjF,SAAO,WAAW,cAAc,MAAM;AACxC;AAGO,SAAS,sBAAsB,UAAkD;AACtF,SAAO,WAAW,4BAA4B,MAAM;AACtD;AAGO,SAAS,uBAAuB,UAAkD;AACvF,SAAO,WAAW,oBAAoB,MAAM,UAAa,SAAS,oBAAoB,MAAM;AAC9F;AAUO,SAAS,oBAAoB,UAA+D;AACjG,MAAI,CAAC,UAAU;AACb,WAAO;AAAA,EACT;AACA,QAAM,QAAQ,qBAAqB,KAAK,QAAQ;AAChD,MAAI,CAAC,OAAO;AACV,WAAO;AAAA,EACT;AACA,SAAO,EAAE,QAAQ,MAAM,CAAC,GAAsB,MAAM,MAAM,CAAC,EAAY;AAC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AAsC,KAAK,GAAG;AAC5D,MAAI,CAAC,OAAO;AACV,WAAO;AAAA,EACT;AACA,SAAO;AAAA,IACL,cAAc,MAAM,CAAC;AAAA,IACrB,aAAa,MAAM,CAAC,IAAI,MAAM,CAAC,IAAI;AAAA,IACnC,cAAc,MAAM,CAAC;AAAA,EACvB;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/contract/extensions.ts","../../src/contract/translations.ts"],"sourcesContent":["import type { FilterOperator } from './operators';\n\n/**\n * Types of the `x-ddd-*` OpenAPI extensions emitted by DDD Core, plus the defaults that apply when an extension is\n * absent. All extensions are additive: a document without them is valid and is read with the defaults below.\n */\n\n/** `info.x-ddd-contract`: contract number and the emitting `mgamadeus/ddd` version. */\nexport interface DddContractInfo {\n /** Contract number; bumped on every change of an `x-ddd-*` key, an implicit part or a default. */\n contract: number;\n /** Version of the `mgamadeus/ddd` package that emitted the document, e.g. `3.14.0`. */\n ddd: string;\n}\n\n/**\n * Column kind of a filter (`FiltersDefinition::COLUMN_KIND_*`): what a filter value is validated and bound as.\n * `translatable` is a plain `#[Translatable]` (JSON of all languages), `translatable-searchable` one with\n * `fullTextIndex: true` (comparisons run on its virtual search column).\n */\nexport type DddColumnKind =\n | 'int'\n | 'float'\n | 'bool'\n | 'string'\n | 'datetime'\n | 'json'\n | 'translatable'\n | 'translatable-searchable';\n\n/**\n * Temporal kind of a filter (`FiltersDefinition::TEMPORAL_KIND_*`): `MOMENT` = an instant (date-time),\n * `DAY` = a calendar day (date, never zone-converted).\n */\nexport type DddTemporalKind = 'MOMENT' | 'DAY';\n\n/**\n * A value rule for one operator of a filter. Known rules:\n * - `wildcard-required`: the value must contain `*` (plain Translatable `eq` / `ne`, a LIKE on the JSON text);\n * - `null-only`: only a null comparison is allowed (JSON columns).\n * Further rules may be added by the contract; unknown rules must be ignored by clients.\n */\nexport type DddFilterValueRule = 'wildcard-required' | 'null-only' | (string & {});\n\n/** One filter definition inside `x-ddd-query.filters`. */\nexport interface DddFilterDefinition {\n /** Filter property name as used in `filters`, may be dotted (e.g. `author.name`). */\n name: string;\n /** Path of the filtered value in the response schema (e.g. `changeHistory.createdTime`); `null` if none. */\n path?: string | null;\n /** Column kind; absent or `null` = no value validation on the backend. */\n columnKind?: DddColumnKind | null;\n /** Temporal kind; absent or `null` = not temporal. */\n temporalKind?: DddTemporalKind | null;\n /** Whether `ft` / `fb` work on this filter (single-column FULLTEXT index). */\n supportsFulltext?: boolean;\n /** Allowed values (`FiltersDefinition::$options`); every value, also each list item, must be one of them. */\n options?: Array<string | number> | null;\n /** Operators allowed for this filter; absent = every operator the column kind accepts. */\n operators?: FilterOperator[];\n /** Value rules per operator. */\n valueRules?: Partial<Record<FilterOperator, DddFilterValueRule>>;\n /** Name of the expand that must be present in `expand` for this filter to be accepted; absent = none. */\n requiresExpand?: string | null;\n}\n\n/** One expand definition inside `x-ddd-query.expand`. */\nexport interface DddExpandDefinition {\n /** Property name to expand (no dots; nesting goes through `expand`). */\n name: string;\n /** `true` for a computed field (no relation, no clauses), e.g. a rendered SVG. */\n computed?: boolean;\n /** Default `top` inside the expand clause. */\n top?: number;\n /** Upper bound for `top` inside the expand clause. */\n maxTop?: number | null;\n /** Default `skip` inside the expand clause. */\n skip?: number;\n /** Filters available inside the expand clause (`filters=` in `(…)`). */\n filters?: DddFilterDefinition[];\n /** Sortable properties inside the expand clause. */\n orderBy?: string[];\n /** Nested expands (`expand=` in `(…)`). */\n expand?: DddExpandDefinition[];\n}\n\n/** `x-ddd-query` on an operation whose request DTO applies QueryOptions. */\nexport interface DddQueryDefinition {\n filters?: DddFilterDefinition[];\n /** Sortable property names. */\n orderBy?: string[];\n expand?: DddExpandDefinition[];\n /** `true` = `select` accepted (any property), a list = the selectable properties, `false`/absent = not exposed. */\n select?: boolean | string[];\n /** Default page size (backend default 50). */\n top?: number;\n /** Upper bound for `top` (`#[QueryOptions(maxTop: …)]`); a larger `top` answers 400. */\n maxTop?: number | null;\n}\n\n/** `x-ddd-entity.action`. DDD `#[Update]` is an upsert. */\nexport type DddEntityAction = 'list' | 'get' | 'upsert' | 'delete' | 'action';\n\n/**\n * `x-ddd-entity` on an operation. Absent = unknown entity: clients derive the identity from the path or the request body\n * and invalidate the whole tag type only when none is found.\n */\nexport interface DddEntityInfo {\n /** Entity schema name, e.g. `App.Domain.Library.Entities.Books.Book`. */\n schema: string;\n action: DddEntityAction;\n /** Identity source, `path:<parameter>` or `body:<dotted.path>` (e.g. `body:book.id`). */\n identity?: string;\n /** `true` when derived by DDD Core, `false` when set explicitly via `#[OperationEntity]`. */\n derived: boolean;\n}\n\n/** Field-level `x-ddd-translatable` (from `#[Translatable]`). */\nexport interface DddTranslatableInfo {\n fullTextIndex?: boolean;\n fullTextMode?: string;\n}\n\n/** Extensions on the document `info` object. */\nexport interface DddInfoExtensions {\n 'x-ddd-contract'?: DddContractInfo;\n}\n\n/** Extensions on an operation object. */\nexport interface DddOperationExtensions {\n 'x-ddd-query'?: DddQueryDefinition;\n /** Absent = default by HTTP method (see {@link hasSideEffects}). */\n 'x-ddd-side-effects'?: boolean;\n 'x-ddd-entity'?: DddEntityInfo;\n /** Cache TTL in seconds from `#[RequestCache]`. */\n 'x-ddd-cache-ttl'?: number;\n}\n\n/** Extensions on a schema property. */\nexport interface DddPropertyExtensions {\n 'x-ddd-translatable'?: DddTranslatableInfo;\n /** `#[HideProperty]`: never in responses, accepted in requests (write-only). Absent = visible. */\n 'x-ddd-hidden'?: boolean;\n /** The stored value is kept when the property is omitted on an update of an existing entity. */\n 'x-ddd-preserve-on-omission'?: boolean;\n}\n\n/** Extensions on an entity schema. */\nexport interface DddSchemaExtensions {\n /** Roles required to write the entity (`RolesRequiredForUpdate`). */\n 'x-ddd-roles-required-for-update'?: string[];\n}\n\n/** HTTP methods of OpenAPI operations (lowercase or uppercase accepted by the helpers). */\nexport type HttpMethod = 'get' | 'head' | 'post' | 'put' | 'patch' | 'delete' | 'options' | 'trace';\n\n/**\n * Whether an operation has side effects (contract defaults, Appendix A.6): `x-ddd-side-effects` wins when present,\n * otherwise `false` for GET/HEAD/OPTIONS/TRACE and `true` for POST/PUT/PATCH/DELETE.\n */\nexport function hasSideEffects(method: string, operation?: Pick<DddOperationExtensions, 'x-ddd-side-effects'> | null): boolean {\n const explicit = operation?.['x-ddd-side-effects'];\n if (typeof explicit === 'boolean') {\n return explicit;\n }\n return !['get', 'head', 'options', 'trace'].includes(method.toLowerCase());\n}\n\n/** Whether a property is write-only (`x-ddd-hidden: true`). Absent = visible. */\nexport function isHiddenProperty(property?: DddPropertyExtensions | null): boolean {\n return property?.['x-ddd-hidden'] === true;\n}\n\n/** Whether a property keeps its stored value when omitted on an update (`x-ddd-preserve-on-omission: true`). */\nexport function isPreservedOnOmission(property?: DddPropertyExtensions | null): boolean {\n return property?.['x-ddd-preserve-on-omission'] === true;\n}\n\n/** Whether a property is `#[Translatable]` (`x-ddd-translatable` present). */\nexport function isTranslatableProperty(property?: DddPropertyExtensions | null): boolean {\n return property?.['x-ddd-translatable'] !== undefined && property['x-ddd-translatable'] !== null;\n}\n\n/** Parsed `x-ddd-entity.identity`. */\nexport interface DddEntityIdentity {\n source: 'path' | 'body';\n /** Path parameter name (`source: 'path'`) or dotted body path (`source: 'body'`). */\n name: string;\n}\n\n/** Parses `x-ddd-entity.identity` (`path:bookId`, `body:book.id`); `null` for an absent or malformed value. */\nexport function parseEntityIdentity(identity: string | null | undefined): DddEntityIdentity | null {\n if (!identity) {\n return null;\n }\n const match = /^(path|body):(.+)$/.exec(identity);\n if (!match) {\n return null;\n }\n return { source: match[1] as 'path' | 'body', name: match[2] as string };\n}\n\n/** Reads `info.x-ddd-contract` from an OpenAPI document; `null` when the document carries no contract version. */\nexport function getContractInfo(document: { info?: DddInfoExtensions | null } | null | undefined): DddContractInfo | null {\n const contract = document?.info?.['x-ddd-contract'];\n if (!contract || typeof contract.contract !== 'number' || typeof contract.ddd !== 'string') {\n return null;\n }\n return contract;\n}\n","/**\n * `DDD.Domain.Base.Entities.Translatable.TranslationInfos` and helpers around its translations store.\n */\n\n/** Writing styles (`Translatable::WRITING_STYLE_*`). */\nexport type WritingStyle = 'FORMAL' | 'INFORMAL';\n\n/**\n * Translation key `<languageCode>:<countryCode>:<writingStyle>` as built by\n * `TranslatableService::getTranslationIndexForLanguageCodeCountryCodeAndWritingStyle()`: language and country\n * lowercase, an absent country is empty, e.g. `en::FORMAL`, `de:at:INFORMAL`.\n */\nexport type TranslationKey = string;\n\n/** Translations of one property: translation key → text. */\nexport type PropertyTranslations = Record<TranslationKey, string>;\n\n/** `translationsStore`: property name → translation key → text. */\nexport type TranslationsStore = Record<string, PropertyTranslations>;\n\n/** `TranslationInfos` as it appears in entity responses and requests (after {@link normalizeTranslationInfos}). */\nexport interface TranslationInfos {\n /** Translations per property. The wire sends `[]` for an empty store; use {@link normalizeTranslationsStore}. */\n translationsStore?: TranslationsStore;\n /** On persist, `true` replaces all stored translations instead of merging (JSON_MERGE_PATCH). */\n replaceExistingTranslations?: boolean;\n currentLanguageCode?: string;\n currentCountryCode?: string | null;\n currentWritingStyle?: WritingStyle;\n defaultLanguageCode?: string;\n defaultWritingStyle?: WritingStyle;\n /** Keys (language, locale, optionally `::style`) for which translations exist → `true`. */\n availableTranslations?: Record<string, boolean>;\n hasTranslationForCurrentLanguageCode?: boolean;\n hasTranslationForCurrentCountryCode?: boolean;\n hasTranslationForCurrentWritingStyle?: boolean;\n objectType?: string | null;\n}\n\n/** `TranslationInfos` as received on the wire: the maps may be empty arrays (`[]`). */\nexport type TranslationInfosWire = Omit<TranslationInfos, 'translationsStore' | 'availableTranslations'> & {\n translationsStore?: TranslationsStore | Record<string, PropertyTranslations | unknown[]> | unknown[] | null;\n availableTranslations?: Record<string, boolean> | unknown[] | null;\n};\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Turns the wire form of a translations store into a map. PHP serialises an empty associative array as `[]`\n * (`TranslationInfos::$translationsStore = []`, kept by the serializer), so an empty store — or an empty property\n * entry — arrives as `[]`; both become `{}`. `null`/`undefined` become `{}` as well. Non-string texts are dropped.\n */\nexport function normalizeTranslationsStore(store: unknown): TranslationsStore {\n if (!isPlainObject(store)) {\n return {};\n }\n const normalized: TranslationsStore = {};\n for (const [propertyName, translations] of Object.entries(store)) {\n const propertyTranslations: PropertyTranslations = {};\n if (isPlainObject(translations)) {\n for (const [key, text] of Object.entries(translations)) {\n if (typeof text === 'string') {\n propertyTranslations[key] = text;\n }\n }\n }\n normalized[propertyName] = propertyTranslations;\n }\n return normalized;\n}\n\n/** Normalises a wire `TranslationInfos`: `translationsStore` and `availableTranslations` become maps. */\nexport function normalizeTranslationInfos(infos: TranslationInfosWire): TranslationInfos {\n const availableTranslations: Record<string, boolean> = {};\n if (isPlainObject(infos.availableTranslations)) {\n for (const [key, available] of Object.entries(infos.availableTranslations)) {\n availableTranslations[key] = available === true;\n }\n }\n return {\n ...infos,\n translationsStore: normalizeTranslationsStore(infos.translationsStore),\n availableTranslations,\n };\n}\n\n/** Parts of a {@link TranslationKey}. */\nexport interface TranslationKeyParts {\n languageCode: string;\n countryCode?: string | null;\n writingStyle: WritingStyle;\n}\n\n/**\n * Builds a translation key the way the backend does\n * (`TranslatableService::getTranslationIndexForLanguageCodeCountryCodeAndWritingStyle()`):\n * `strtolower(language) . ':' . strtolower(country ?? '') . ':' . writingStyle`.\n */\nexport function buildTranslationKey(parts: TranslationKeyParts): TranslationKey {\n return `${parts.languageCode.toLowerCase()}:${(parts.countryCode ?? '').toLowerCase()}:${parts.writingStyle}`;\n}\n\n/** Splits a translation key into its parts; `null` when it is not `<language>:<country>:<style>`. */\nexport function parseTranslationKey(key: TranslationKey): TranslationKeyParts | null {\n const match = /^([^:]+):([^:]*):(FORMAL|INFORMAL)$/.exec(key);\n if (!match) {\n return null;\n }\n return {\n languageCode: match[1] as string,\n countryCode: match[2] ? match[2] : null,\n writingStyle: match[3] as WritingStyle,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;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AO,QAAQ,YAAY,GAAG;AACtD,YAAI,OAAO,SAAS,UAAU;AAC5B,+BAAqB,GAAG,IAAI;AAAA,QAC9B;AAAA,MACF;AAAA,IACF;AACA,eAAW,YAAY,IAAI;AAAA,EAC7B;AACA,SAAO;AACT;AAGO,SAAS,0BAA0B,OAA+C;AACvF,QAAM,wBAAiD,CAAC;AACxD,MAAI,cAAc,MAAM,qBAAqB,GAAG;AAC9C,eAAW,CAAC,KAAK,SAAS,KAAK,OAAO,QAAQ,MAAM,qBAAqB,GAAG;AAC1E,4BAAsB,GAAG,IAAI,cAAc;AAAA,IAC7C;AAAA,EACF;AACA,SAAO;AAAA,IACL,GAAG;AAAA,IACH,mBAAmB,2BAA2B,MAAM,iBAAiB;AAAA,IACrE;AAAA,EACF;AACF;AAcO,SAAS,oBAAoB,OAA4C;AAC9E,SAAO,GAAG,MAAM,aAAa,YAAY,CAAC,KAAK,MAAM,eAAe,IAAI,YAAY,CAAC,IAAI,MAAM,YAAY;AAC7G;AAGO,SAAS,oBAAoB,KAAiD;AACnF,QAAM,QAAQ,sCAAsC,KAAK,GAAG;AAC5D,MAAI,CAAC,OAAO;AACV,WAAO;AAAA,EACT;AACA,SAAO;AAAA,IACL,cAAc,MAAM,CAAC;AAAA,IACrB,aAAa,MAAM,CAAC,IAAI,MAAM,CAAC,IAAI;AAAA,IACnC,cAAc,MAAM,CAAC;AAAA,EACvB;AACF;","names":[]}
@@ -0,0 +1,86 @@
1
+ /** One entry of `ExceptionDetails.elements` in a DDD error response. */
2
+ interface DddExceptionDetail {
3
+ message?: string | null;
4
+ details?: unknown[] | null;
5
+ objectType?: string | null;
6
+ }
7
+ /** `DDD.Infrastructure.Exceptions.ExceptionDetails`. */
8
+ interface DddExceptionDetails {
9
+ elements?: DddExceptionDetail[];
10
+ objectType?: string | null;
11
+ }
12
+ /**
13
+ * Body of every DDD error response (`DDD.Infrastructure.Exceptions.*Exception`, e.g. BadRequestException).
14
+ * `validationErrors` is present on 400 responses caused by DTO/entity validation.
15
+ */
16
+ interface DddErrorBody {
17
+ error?: string | null;
18
+ validationErrors?: unknown;
19
+ exceptionDetails?: DddExceptionDetails | null;
20
+ }
21
+
22
+ /** A DDD API error in one predictable shape, whatever produced it (RTK Query, a thrown Error, a raw body). */
23
+ interface DddNormalizedError {
24
+ /**
25
+ * HTTP status, or RTK Query's string status for non-HTTP failures (`FETCH_ERROR`, `TIMEOUT_ERROR`,
26
+ * `CUSTOM_ERROR`); a `PARSING_ERROR` reports the original HTTP status. `null` when unknown.
27
+ */
28
+ status: number | string | null;
29
+ /** Human-readable message: the backend's `error` key first, then a text body, then generic fallbacks. */
30
+ message: string;
31
+ /** The backend's `validationErrors` exactly as received (present on validation 400s), else `null`. */
32
+ validationErrors: unknown;
33
+ /** `exceptionDetails.elements` of the backend body; empty when absent. */
34
+ details: DddExceptionDetail[];
35
+ /** The raw response body (parsed JSON, text, or `undefined`). */
36
+ body: unknown;
37
+ }
38
+ /** Message used when an error carries no message at all. */
39
+ declare const DEFAULT_ERROR_MESSAGE = "Request failed";
40
+ /**
41
+ * Messages for failures that carry no usable backend message. Pass your own (e.g. translated) texts as the third
42
+ * argument of {@link normalizeDddError} / {@link getErrorMessage}.
43
+ */
44
+ interface DddErrorMessages {
45
+ /** A response that is not JSON (an HTML error page, a PHP fatal) with an HTTP status ≥ 500. */
46
+ serverError: (status: number) => string;
47
+ /** A response that is not JSON with an HTTP status < 500. */
48
+ httpError: (status: number) => string;
49
+ /** The request never reached the server or got no response (`FETCH_ERROR`). */
50
+ networkError: string;
51
+ /** The request timed out (`TIMEOUT_ERROR`). */
52
+ timeoutError: string;
53
+ }
54
+ /** The default {@link DddErrorMessages}. */
55
+ declare const DEFAULT_ERROR_MESSAGES: DddErrorMessages;
56
+ /**
57
+ * Normalises any API error into {@link DddNormalizedError}.
58
+ *
59
+ * Understands RTK Query's `FetchBaseQueryError` (`{ status, data }`, `{ status: 'FETCH_ERROR', error }`, …),
60
+ * `SerializedError` / `Error` (`message`), errors carrying a parsed `responseBody`, and a bare DDD error body.
61
+ * DDD error bodies put the message under `error` (not `message`).
62
+ *
63
+ * A response the client could not parse (`PARSING_ERROR`: an HTML error page, a PHP fatal, a proxy's 502) is an HTTP
64
+ * error: `status` is the HTTP status and the message is {@link DddErrorMessages.serverError} /
65
+ * {@link DddErrorMessages.httpError} — never the parser's `SyntaxError` text and never the raw body, which may show
66
+ * internals (the body stays available in `body`). `FETCH_ERROR` and `TIMEOUT_ERROR` get
67
+ * {@link DddErrorMessages.networkError} / {@link DddErrorMessages.timeoutError} instead of the browser's text.
68
+ *
69
+ * @param error whatever a request rejected with
70
+ * @param fallbackMessage message when nothing usable is found
71
+ * @param messages texts for failures without a backend message (default {@link DEFAULT_ERROR_MESSAGES})
72
+ */
73
+ declare function normalizeDddError(error: unknown, fallbackMessage?: string, messages?: Partial<DddErrorMessages>): DddNormalizedError;
74
+ /**
75
+ * The message to show for an API error (`normalizeDddError(error).message`).
76
+ *
77
+ * @param error whatever a request rejected with
78
+ * @param fallbackMessage message when nothing usable is found
79
+ * @param messages texts for failures without a backend message
80
+ */
81
+ declare function getErrorMessage(error: unknown, fallbackMessage?: string, messages?: Partial<DddErrorMessages>): string;
82
+ /** HTTP status of an API error (also of an unparsable response), or `null` for non-HTTP failures. */
83
+ declare function getErrorStatus(error: unknown): number | null;
84
+
85
+ export { DEFAULT_ERROR_MESSAGE as D, DEFAULT_ERROR_MESSAGES as a, getErrorStatus as d, getErrorMessage as g, normalizeDddError as n };
86
+ export type { DddErrorMessages as b, DddNormalizedError as c, DddErrorBody as e, DddExceptionDetail as f, DddExceptionDetails as h };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mgamadeus/ddd-web",
3
- "version": "0.12.0",
3
+ "version": "0.14.0",
4
4
  "description": "TypeScript web client for backends built with mgamadeus/ddd, the DDD entity framework for Symfony and Doctrine (Composer/Packagist). Generates a typed RTK Query SDK from the backend's OpenAPI document, builds DDD QueryOptions (filters, orderBy, expand, select, paging) and handles JWT auth with token refresh.",
5
5
  "keywords": [
6
6
  "ddd",