mn-angular-lib 2.0.33 → 2.0.35

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 (52) hide show
  1. package/fesm2022/mn-angular-lib-alert.mjs +515 -527
  2. package/fesm2022/mn-angular-lib-alert.mjs.map +1 -1
  3. package/fesm2022/mn-angular-lib-bottom-sheet.mjs +264 -357
  4. package/fesm2022/mn-angular-lib-bottom-sheet.mjs.map +1 -1
  5. package/fesm2022/mn-angular-lib-button.mjs +819 -382
  6. package/fesm2022/mn-angular-lib-button.mjs.map +1 -1
  7. package/fesm2022/mn-angular-lib-calendar-core.mjs +240 -365
  8. package/fesm2022/mn-angular-lib-calendar-core.mjs.map +1 -1
  9. package/fesm2022/mn-angular-lib-calendar.mjs +1691 -1545
  10. package/fesm2022/mn-angular-lib-calendar.mjs.map +1 -1
  11. package/fesm2022/mn-angular-lib-collection.mjs +2367 -2796
  12. package/fesm2022/mn-angular-lib-collection.mjs.map +1 -1
  13. package/fesm2022/mn-angular-lib-core.mjs +693 -1241
  14. package/fesm2022/mn-angular-lib-core.mjs.map +1 -1
  15. package/fesm2022/mn-angular-lib-display.mjs +679 -712
  16. package/fesm2022/mn-angular-lib-display.mjs.map +1 -1
  17. package/fesm2022/mn-angular-lib-forms.mjs +3671 -4647
  18. package/fesm2022/mn-angular-lib-forms.mjs.map +1 -1
  19. package/fesm2022/mn-angular-lib-keyboard.mjs +221 -190
  20. package/fesm2022/mn-angular-lib-keyboard.mjs.map +1 -1
  21. package/fesm2022/mn-angular-lib-modal-core.mjs +711 -896
  22. package/fesm2022/mn-angular-lib-modal-core.mjs.map +1 -1
  23. package/fesm2022/mn-angular-lib-modal-ui.mjs +2089 -2035
  24. package/fesm2022/mn-angular-lib-modal-ui.mjs.map +1 -1
  25. package/fesm2022/mn-angular-lib-modal.mjs +76 -121
  26. package/fesm2022/mn-angular-lib-modal.mjs.map +1 -1
  27. package/fesm2022/mn-angular-lib-rich-text-editor.mjs +289 -277
  28. package/fesm2022/mn-angular-lib-rich-text-editor.mjs.map +1 -1
  29. package/fesm2022/mn-angular-lib-segmented.mjs +189 -241
  30. package/fesm2022/mn-angular-lib-segmented.mjs.map +1 -1
  31. package/fesm2022/mn-angular-lib-tab.mjs +409 -642
  32. package/fesm2022/mn-angular-lib-tab.mjs.map +1 -1
  33. package/fesm2022/mn-angular-lib.mjs +16 -29
  34. package/package.json +1 -1
  35. package/types/mn-angular-lib-alert.d.ts +239 -241
  36. package/types/mn-angular-lib-bottom-sheet.d.ts +190 -150
  37. package/types/mn-angular-lib-button.d.ts +319 -317
  38. package/types/mn-angular-lib-calendar-core.d.ts +199 -209
  39. package/types/mn-angular-lib-calendar.d.ts +656 -511
  40. package/types/mn-angular-lib-collection.d.ts +1649 -1585
  41. package/types/mn-angular-lib-core.d.ts +524 -535
  42. package/types/mn-angular-lib-display.d.ts +946 -886
  43. package/types/mn-angular-lib-forms.d.ts +3012 -3013
  44. package/types/mn-angular-lib-keyboard.d.ts +125 -85
  45. package/types/mn-angular-lib-modal-core.d.ts +978 -994
  46. package/types/mn-angular-lib-modal-ui.d.ts +541 -493
  47. package/types/mn-angular-lib-modal.d.ts +24 -27
  48. package/types/mn-angular-lib-rich-text-editor.d.ts +131 -98
  49. package/types/mn-angular-lib-segmented.d.ts +354 -341
  50. package/types/mn-angular-lib-tab.d.ts +345 -336
  51. package/types/mn-angular-lib.d.ts +16 -16
  52. package/fesm2022/mn-angular-lib.mjs.map +0 -1
@@ -1,1265 +1,717 @@
1
- import * as i0 from '@angular/core';
2
- import { inject, ApplicationRef, signal, Injectable, APP_INITIALIZER, Pipe, InjectionToken, DestroyRef, Optional, SkipSelf, Attribute, Input, Directive } from '@angular/core';
3
- import { HttpClient, HttpErrorResponse, HttpStatusCode, HttpParams } from '@angular/common/http';
4
- import { BehaviorSubject, firstValueFrom, map, catchError, of } from 'rxjs';
5
-
6
- /**
7
- * Types for mn-lib configuration.
8
- */
9
-
10
- /**
11
- * Type guard: checks whether a value is a translatable marker object.
12
- */
1
+ import * as i0 from "@angular/core";
2
+ import { APP_INITIALIZER, ApplicationRef, Attribute, DestroyRef, Directive, Injectable, InjectionToken, Input, Optional, Pipe, SkipSelf, inject, signal } from "@angular/core";
3
+ import { HttpClient, HttpErrorResponse, HttpParams, HttpStatusCode } from "@angular/common/http";
4
+ import { BehaviorSubject, catchError, firstValueFrom, map, of } from "rxjs";
13
5
  function isTranslatable(value) {
14
- return (typeof value === 'object' &&
15
- value !== null &&
16
- typeof value['$translate'] === 'string');
6
+ return typeof value === "object" && value !== null && typeof value["$translate"] === "string";
17
7
  }
18
-
19
- /**
20
- * Key suffix per CLDR plural category.
21
- *
22
- * Only `one` earns a suffix: every locale shipped so far (`en`, `nl`) has exactly the two
23
- * categories `one` and `other`, and `other` keeps the bare key. A locale with `few`/`many`
24
- * (Polish, Russian, Arabic) resolves those to the plural until an entry is added here —
25
- * adding one is the whole change, since the lookup is category-driven already.
26
- */
27
- const PLURAL_SUFFIX = {
28
- one: 'One',
8
+ const PLURAL_SUFFIX = { one: "One" };
9
+ const COUNT_PARAM = "count";
10
+ var MnLanguageService = class MnLanguageService {
11
+ http = inject(HttpClient);
12
+ appRef = inject(ApplicationRef);
13
+ _translations = {};
14
+ _locale$ = new BehaviorSubject("en");
15
+ _locale = signal("en", ...ngDevMode ? [{ debugName: "_locale" }] : /* istanbul ignore next */ []);
16
+ _urlPattern = null;
17
+ _debug = false;
18
+ _pluralRules = /* @__PURE__ */ new Map();
19
+ locale$ = this._locale$.asObservable();
20
+ get locale() {
21
+ return this._locale();
22
+ }
23
+ setDebug(enabled) {
24
+ this._debug = enabled;
25
+ if (enabled) console.log(`[MnLanguage] Debug mode enabled`);
26
+ }
27
+ configure(urlPattern) {
28
+ if (this._debug) console.log(`[MnLanguage] Configured urlPattern: ${urlPattern}`);
29
+ this._urlPattern = urlPattern;
30
+ }
31
+ async loadLocale(locale) {
32
+ if (this._translations[locale]) return;
33
+ if (!this._urlPattern) {
34
+ console.warn(`[MnLanguage] No URL pattern configured. Call configure() or use provideMnLanguage().`);
35
+ return;
36
+ }
37
+ const url = this._urlPattern.replace("{locale}", locale);
38
+ if (this._debug) console.log(`[MnLanguage] Loading locale "${locale}" from ${url}`);
39
+ try {
40
+ const map = await firstValueFrom(this.http.get(url));
41
+ this._translations[locale] = map ?? {};
42
+ if (this._debug) console.log(`[MnLanguage] Loaded locale "${locale}"`, this._translations[locale]);
43
+ } catch (err) {
44
+ console.warn(`[MnLanguage] Failed to load translations from ${url}`, err);
45
+ this._translations[locale] = {};
46
+ }
47
+ }
48
+ async setLocale(locale) {
49
+ if (this._debug) console.log(`[MnLanguage] Setting locale to "${locale}"`);
50
+ await this.loadLocale(locale);
51
+ this._locale.set(locale);
52
+ this._locale$.next(locale);
53
+ this.appRef.tick();
54
+ }
55
+ registerTranslations(locale, translations) {
56
+ this._translations[locale] = {
57
+ ...this._translations[locale] ?? {},
58
+ ...translations
59
+ };
60
+ }
61
+ translate(key, params) {
62
+ const map = this._translations[this.locale] ?? {};
63
+ let value = this.getValueFromMap(map, this.resolvePluralKey(map, key, params));
64
+ if (value === void 0) {
65
+ if (this._debug) console.warn(`[MnLanguage] Missing translation for key: "${key}" in locale: "${this.locale}"`);
66
+ return key;
67
+ }
68
+ if (params) for (const [paramKey, paramValue] of Object.entries(params)) value = value.replace(new RegExp(`\\{\\{${paramKey}\\}\\}`, "g"), String(paramValue));
69
+ return value;
70
+ }
71
+ resolvePluralKey(map, key, params) {
72
+ const raw = params?.[COUNT_PARAM];
73
+ if (raw === void 0) return key;
74
+ const count = Number(raw);
75
+ if (!Number.isFinite(count)) return key;
76
+ const suffix = PLURAL_SUFFIX[this.pluralCategory(count)];
77
+ if (suffix === void 0) return key;
78
+ const variant = key + suffix;
79
+ return this.getValueFromMap(map, variant) !== void 0 ? variant : key;
80
+ }
81
+ pluralCategory(count) {
82
+ if (!this._pluralRules.has(this.locale)) try {
83
+ this._pluralRules.set(this.locale, new Intl.PluralRules(this.locale));
84
+ } catch {
85
+ this._pluralRules.set(this.locale, null);
86
+ }
87
+ const rules = this._pluralRules.get(this.locale);
88
+ if (!rules) return count === 1 ? "one" : "other";
89
+ return rules.select(count);
90
+ }
91
+ getValueFromMap(map, key) {
92
+ const direct = map[key];
93
+ if (typeof direct === "string") return direct;
94
+ const parts = key.split(".");
95
+ let current = map;
96
+ for (const part of parts) {
97
+ if (current === null || typeof current !== "object") return void 0;
98
+ current = current[part];
99
+ }
100
+ return typeof current === "string" ? current : void 0;
101
+ }
102
+ translateIfPresent(key, params) {
103
+ const map = this._translations[this.locale] ?? {};
104
+ if (this.getValueFromMap(map, key) === void 0) return void 0;
105
+ return this.translate(key, params);
106
+ }
107
+ t(key, params) {
108
+ return this.translate(key, params);
109
+ }
110
+ resolveLocaleForDomain(domainLocaleMap, fallback) {
111
+ if (!domainLocaleMap || typeof window === "undefined") return fallback;
112
+ return domainLocaleMap[window.location.hostname] ?? fallback;
113
+ }
114
+ static ɵfac = i0.ɵɵngDeclareFactory({
115
+ minVersion: "12.0.0",
116
+ version: "22.2.2",
117
+ ngImport: i0,
118
+ type: MnLanguageService,
119
+ deps: [],
120
+ target: i0.ɵɵFactoryTarget.Injectable
121
+ });
122
+ static ɵprov = i0.ɵɵngDeclareInjectable({
123
+ minVersion: "12.0.0",
124
+ version: "22.2.2",
125
+ ngImport: i0,
126
+ type: MnLanguageService,
127
+ providedIn: "root"
128
+ });
29
129
  };
30
- /** Params key whose presence turns a translation into a plural-aware lookup. */
31
- const COUNT_PARAM = 'count';
32
- class MnLanguageService {
33
- http = inject(HttpClient);
34
- appRef = inject(ApplicationRef);
35
- _translations = {};
36
- _locale$ = new BehaviorSubject('en');
37
- /**
38
- * The active locale as a signal, read by {@link locale} and so by every lookup.
39
- *
40
- * Components are OnPush, and `setLocale` only ran one `appRef.tick()`, which skips every view
41
- * nobody marked: a tab bar, a card heading or a bar label kept the old language until the page
42
- * was reloaded. A signal read while a template renders (through the `mnTranslate` pipe, or a
43
- * getter calling `translate`) is tracked by that view, so switching the locale marks exactly
44
- * the views that translated something, and a `computed` built on `translate` recomputes.
45
- */
46
- _locale = signal('en', /* @ts-ignore */
47
- ...(ngDevMode ? [{ debugName: "_locale" }] : /* istanbul ignore next */ []));
48
- _urlPattern = null;
49
- _debug = false;
50
- /**
51
- * `Intl.PluralRules` per locale. Cached because {@link translate} runs on every change
52
- * detection through the impure `mnTranslate` pipe, and constructing one is not cheap.
53
- */
54
- _pluralRules = new Map();
55
- /** Observable of the current active locale. */
56
- locale$ = this._locale$.asObservable();
57
- /** Current active locale. */
58
- get locale() {
59
- return this._locale();
60
- }
61
- /**
62
- * Enable or disable debug logging.
63
- */
64
- setDebug(enabled) {
65
- this._debug = enabled;
66
- if (enabled) {
67
- console.log(`[MnLanguage] Debug mode enabled`);
68
- }
69
- }
70
- /**
71
- * Configure the URL pattern used to fetch translation files.
72
- * Use `{locale}` as placeholder, e.g. `"assets/i18n/{locale}.json"`.
73
- */
74
- configure(urlPattern) {
75
- if (this._debug) {
76
- console.log(`[MnLanguage] Configured urlPattern: ${urlPattern}`);
77
- }
78
- this._urlPattern = urlPattern;
79
- }
80
- /**
81
- * Load translations for a locale from the configured URL pattern.
82
- * If translations are already loaded for this locale, this is a no-op.
83
- */
84
- async loadLocale(locale) {
85
- if (this._translations[locale])
86
- return;
87
- if (!this._urlPattern) {
88
- console.warn(`[MnLanguage] No URL pattern configured. Call configure() or use provideMnLanguage().`);
89
- return;
90
- }
91
- const url = this._urlPattern.replace('{locale}', locale);
92
- if (this._debug) {
93
- console.log(`[MnLanguage] Loading locale "${locale}" from ${url}`);
94
- }
95
- try {
96
- const map = await firstValueFrom(this.http.get(url));
97
- this._translations[locale] = map ?? {};
98
- if (this._debug) {
99
- console.log(`[MnLanguage] Loaded locale "${locale}"`, this._translations[locale]);
100
- }
101
- }
102
- catch (err) {
103
- console.warn(`[MnLanguage] Failed to load translations from ${url}`, err);
104
- this._translations[locale] = {};
105
- }
106
- }
107
- /**
108
- * Switch the active locale. Loads translations if not yet loaded.
109
- */
110
- async setLocale(locale) {
111
- if (this._debug) {
112
- console.log(`[MnLanguage] Setting locale to "${locale}"`);
113
- }
114
- await this.loadLocale(locale);
115
- this._locale.set(locale);
116
- this._locale$.next(locale);
117
- this.appRef.tick();
118
- }
119
- /**
120
- * Register translations for a locale directly from code (no HTTP needed).
121
- */
122
- registerTranslations(locale, translations) {
123
- this._translations[locale] = {
124
- ...(this._translations[locale] ?? {}),
125
- ...translations,
126
- };
127
- }
128
- /**
129
- * Translate a key using the current locale, with optional parameter interpolation.
130
- * Falls back to the key itself if no translation is found.
131
- *
132
- * Interpolation replaces `{{paramName}}` with the provided value.
133
- *
134
- * A `count` param additionally selects the wording that agrees with it: the key is
135
- * resolved against its CLDR plural category first (`key` + `One`/`Two`/`Few`/`Many`/
136
- * `Zero`), falling back to `key` when that sibling is undefined. Nothing has to opt in —
137
- * a key with no sibling behaves exactly as before.
138
- *
139
- * ```ts
140
- * // 'shift.asked' → '{{count}} members are notified'
141
- * // 'shift.askedOne' → '{{count}} member is notified'
142
- * lang.translate('shift.asked', { count: 3 }); // 3 members are notified
143
- * lang.translate('shift.asked', { count: 1 }); // 1 member is notified
144
- * ```
145
- */
146
- translate(key, params) {
147
- const map = this._translations[this.locale] ?? {};
148
- let value = this.getValueFromMap(map, this.resolvePluralKey(map, key, params));
149
- if (value === undefined) {
150
- if (this._debug) {
151
- console.warn(`[MnLanguage] Missing translation for key: "${key}" in locale: "${this.locale}"`);
152
- }
153
- return key;
154
- }
155
- if (params) {
156
- for (const [paramKey, paramValue] of Object.entries(params)) {
157
- value = value.replace(new RegExp(`\\{\\{${paramKey}\\}\\}`, 'g'), String(paramValue));
158
- }
159
- }
160
- return value;
161
- }
162
- /**
163
- * Picks the wording that agrees with a `count` param.
164
- *
165
- * A key carrying a count resolves against its CLDR plural category first, so
166
- * `askedMessage` + `askedMessageOne` render "3 leden krijgen bericht" and "1 lid krijgt
167
- * bericht" off the same call. Both languages change the verb as well as the noun, which
168
- * is why each form is a whole sentence under its own key rather than a swapped noun.
169
- *
170
- * Falls back to `key` whenever the sibling is undefined, so a key that never needed a
171
- * plural — or an app that has not written one yet — behaves exactly as it did before.
172
- * @param map The active locale's translations.
173
- * @param key The dot-notated translation key.
174
- * @param params The interpolation values, inspected for `count`.
175
- * @returns The key to look up: the plural sibling, or `key` itself.
176
- */
177
- resolvePluralKey(map, key, params) {
178
- const raw = params?.[COUNT_PARAM];
179
- if (raw === undefined)
180
- return key;
181
- // A count off a JSON payload arrives as a string often enough that comparing it
182
- // strictly would silently pick the plural for a count of one.
183
- const count = Number(raw);
184
- if (!Number.isFinite(count))
185
- return key;
186
- const suffix = PLURAL_SUFFIX[this.pluralCategory(count)];
187
- if (suffix === undefined)
188
- return key;
189
- const variant = key + suffix;
190
- return this.getValueFromMap(map, variant) !== undefined ? variant : key;
191
- }
192
- /**
193
- * The CLDR plural category of a count in the active locale.
194
- * @param count The count being quoted.
195
- * @returns The category, falling back to English rules for an unusable locale.
196
- */
197
- pluralCategory(count) {
198
- if (!this._pluralRules.has(this.locale)) {
199
- try {
200
- this._pluralRules.set(this.locale, new Intl.PluralRules(this.locale));
201
- }
202
- catch {
203
- // An unknown or malformed locale tag: fall back rather than break every string.
204
- this._pluralRules.set(this.locale, null);
205
- }
206
- }
207
- const rules = this._pluralRules.get(this.locale);
208
- if (!rules)
209
- return count === 1 ? 'one' : 'other';
210
- return rules.select(count);
211
- }
212
- /**
213
- * Helper to retrieve a value from a potentially nested translation map using a dot-notated key.
214
- */
215
- getValueFromMap(map, key) {
216
- // A flattened bundle holds the dotted key verbatim; a nested one is walked below.
217
- const direct = map[key];
218
- if (typeof direct === 'string')
219
- return direct;
220
- const parts = key.split('.');
221
- let current = map;
222
- for (const part of parts) {
223
- if (current === null || typeof current !== 'object')
224
- return undefined;
225
- current = current[part];
226
- }
227
- return typeof current === 'string' ? current : undefined;
228
- }
229
- /**
230
- * Translate a key **only if it is defined**, returning `undefined` otherwise.
231
- *
232
- * {@link translate} deliberately returns the key itself when it is missing, which
233
- * makes it unusable for a library's own default labels: a consumer that never
234
- * defined `mnCollection.rowsPerPage` would see that raw string in their UI. This
235
- * lets a caller try a conventional key and fall back to a readable English default
236
- * when the app has not translated it, so components ship translatable strings
237
- * without forcing every consumer to define them.
238
- *
239
- * @param key The dot-notated translation key.
240
- * @param params Optional `{{name}}` interpolation values.
241
- * @returns The translation, or `undefined` when the key is not defined.
242
- */
243
- translateIfPresent(key, params) {
244
- const map = this._translations[this.locale] ?? {};
245
- if (this.getValueFromMap(map, key) === undefined)
246
- return undefined;
247
- return this.translate(key, params);
248
- }
249
- /**
250
- * Shorthand alias for `translate`.
251
- */
252
- t(key, params) {
253
- return this.translate(key, params);
254
- }
255
- /**
256
- * Resolve the effective default locale from a domain-to-locale map.
257
- * Matches `window.location.hostname` against the map keys.
258
- * Returns the mapped locale, or the provided fallback if no match is found.
259
- */
260
- resolveLocaleForDomain(domainLocaleMap, fallback) {
261
- if (!domainLocaleMap || typeof window === 'undefined')
262
- return fallback;
263
- const hostname = window.location.hostname;
264
- return domainLocaleMap[hostname] ?? fallback;
265
- }
266
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: MnLanguageService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
267
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: MnLanguageService, providedIn: 'root' });
268
- }
269
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: MnLanguageService, decorators: [{
270
- type: Injectable,
271
- args: [{ providedIn: 'root' }]
272
- }] });
273
-
274
- /**
275
- * Provides an APP_INITIALIZER that configures the MnLanguageService and
276
- * preloads the requested locales during application bootstrap.
277
- *
278
- * Usage in app.config.ts:
279
- * ...provideMnLanguage({
280
- * urlPattern: 'assets/i18n/{locale}.json',
281
- * defaultLocale: 'en',
282
- * preload: ['en', 'nl'],
283
- * })
284
- */
130
+ i0.ɵɵngDeclareClassMetadata({
131
+ minVersion: "12.0.0",
132
+ version: "22.2.2",
133
+ ngImport: i0,
134
+ type: MnLanguageService,
135
+ decorators: [{
136
+ type: Injectable,
137
+ args: [{ providedIn: "root" }]
138
+ }]
139
+ });
285
140
  function provideMnLanguage(config) {
286
- return [
287
- {
288
- provide: APP_INITIALIZER,
289
- multi: true,
290
- useFactory: (svc) => async () => {
291
- if (config.debug) {
292
- svc.setDebug(true);
293
- }
294
- svc.configure(config.urlPattern);
295
- const effectiveLocale = svc.resolveLocaleForDomain(config.domainLocaleMap, config.defaultLocale);
296
- const localesToLoad = config.preload ?? [effectiveLocale];
297
- await Promise.all(localesToLoad.map(l => svc.loadLocale(l)));
298
- await svc.setLocale(effectiveLocale);
299
- },
300
- deps: [MnLanguageService],
301
- },
302
- ];
303
- }
304
-
305
- /**
306
- * Pipe that translates a key via MnLanguageService.
307
- *
308
- * Usage in templates:
309
- * {{ 'form.email.label' | mnTranslate }}
310
- * {{ 'greeting' | mnTranslate:{ name: 'World' } }}
311
- *
312
- * Note: This pipe is impure so it re-evaluates when the locale changes.
313
- */
314
- class MnTranslatePipe {
315
- lang = inject(MnLanguageService);
316
- transform(key, params) {
317
- return this.lang.translate(key, params);
318
- }
319
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: MnTranslatePipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe });
320
- static ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "22.1.7", ngImport: i0, type: MnTranslatePipe, isStandalone: true, name: "mnTranslate", pure: false });
141
+ return [{
142
+ provide: APP_INITIALIZER,
143
+ multi: true,
144
+ useFactory: (svc) => async () => {
145
+ if (config.debug) svc.setDebug(true);
146
+ svc.configure(config.urlPattern);
147
+ const effectiveLocale = svc.resolveLocaleForDomain(config.domainLocaleMap, config.defaultLocale);
148
+ const localesToLoad = config.preload ?? [effectiveLocale];
149
+ await Promise.all(localesToLoad.map((l) => svc.loadLocale(l)));
150
+ await svc.setLocale(effectiveLocale);
151
+ },
152
+ deps: [MnLanguageService]
153
+ }];
321
154
  }
322
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: MnTranslatePipe, decorators: [{
323
- type: Pipe,
324
- args: [{
325
- name: 'mnTranslate',
326
- standalone: true,
327
- pure: false,
328
- }]
329
- }] });
330
-
155
+ var MnTranslatePipe = class MnTranslatePipe {
156
+ lang = inject(MnLanguageService);
157
+ transform(key, params) {
158
+ return this.lang.translate(key, params);
159
+ }
160
+ static ɵfac = i0.ɵɵngDeclareFactory({
161
+ minVersion: "12.0.0",
162
+ version: "22.2.2",
163
+ ngImport: i0,
164
+ type: MnTranslatePipe,
165
+ deps: [],
166
+ target: i0.ɵɵFactoryTarget.Pipe
167
+ });
168
+ static ɵpipe = i0.ɵɵngDeclarePipe({
169
+ minVersion: "14.0.0",
170
+ version: "22.2.2",
171
+ ngImport: i0,
172
+ type: MnTranslatePipe,
173
+ isStandalone: true,
174
+ name: "mnTranslate",
175
+ pure: false
176
+ });
177
+ };
178
+ i0.ɵɵngDeclareClassMetadata({
179
+ minVersion: "12.0.0",
180
+ version: "22.2.2",
181
+ ngImport: i0,
182
+ type: MnTranslatePipe,
183
+ decorators: [{
184
+ type: Pipe,
185
+ args: [{
186
+ name: "mnTranslate",
187
+ standalone: true,
188
+ pure: false
189
+ }]
190
+ }]
191
+ });
331
192
  function isPlainObject(value) {
332
- return (typeof value === 'object' &&
333
- value !== null &&
334
- Object.prototype.toString.call(value) === '[object Object]');
193
+ return typeof value === "object" && value !== null && Object.prototype.toString.call(value) === "[object Object]";
335
194
  }
336
- /**
337
- * Parses a config file. Strict JSON goes through `JSON.parse`; only a file that needs JSON5
338
- * syntax (comments, unquoted keys, trailing commas) loads the `json5` parser, as its own chunk.
339
- * A static import put the CommonJS `json5` package (~32 kB) into every consumer's startup bundle.
340
- *
341
- * @param text The raw file content.
342
- * @returns The parsed value.
343
- */
344
195
  async function parseConfigText(text) {
345
- try {
346
- return JSON.parse(text);
347
- }
348
- catch {
349
- const { default: JSON5 } = await import('json5');
350
- return JSON5.parse(text);
351
- }
352
- }
353
- class MnConfigService {
354
- http = inject(HttpClient);
355
- _config = null;
356
- _settings = {};
357
- _debugMode = false;
358
- /** Reactive version counter — incremented on every config load. */
359
- _configVersion = signal(0, /* @ts-ignore */
360
- ...(ngDevMode ? [{ debugName: "_configVersion" }] : /* istanbul ignore next */ []));
361
- configVersion = this._configVersion.asReadonly();
362
- lang = inject(MnLanguageService);
363
- /** General settings from the config file (version, name, etc.). */
364
- get settings() {
365
- return this._settings;
366
- }
367
- /**
368
- * Load the configuration JSON from the provided URL and cache it in memory.
369
- * Consumers should typically call this via the APP_INITIALIZER helper.
370
- */
371
- async load(url, debugMode = false) {
372
- this._debugMode = debugMode;
373
- this.lang.setDebug(debugMode);
374
- let text;
375
- try {
376
- text = await firstValueFrom(this.http.get(url, { responseType: 'text' }));
377
- }
378
- catch (err) {
379
- console.warn(`[MnConfig] Failed to load config from ${url}`, err);
380
- this._config = { defaults: {}, overrides: {} };
381
- return;
382
- }
383
- let json;
384
- try {
385
- json = await parseConfigText(text);
386
- }
387
- catch (err) {
388
- console.warn(`[MnConfig] Failed to parse JSON5 from ${url}`, err, text);
389
- json = {};
390
- }
391
- const cfg = (isPlainObject(json) ? json : {});
392
- const defaults = isPlainObject(cfg['defaults']) ? cfg['defaults'] : {};
393
- const overrides = isPlainObject(cfg['overrides']) ? cfg['overrides'] : {};
394
- const settings = isPlainObject(cfg['settings']) ? cfg['settings'] : {};
395
- this._config = { settings, defaults, overrides };
396
- this._settings = settings;
397
- // Bootstrap language service from config if a "language" section is present.
398
- // This avoids circular dependency: config reads raw language settings and
399
- // pushes them into the language service (language service never imports config).
400
- const langCfg = cfg['language'];
401
- if (isPlainObject(langCfg) && typeof langCfg['urlPattern'] === 'string') {
402
- const lc = langCfg;
403
- if (this._debugMode) {
404
- console.log(`[MnConfig] Applying language config from file`, lc);
405
- }
406
- this.lang.configure(lc.urlPattern);
407
- const effectiveLocale = this.lang.resolveLocaleForDomain(lc.domainLocaleMap, lc.defaultLocale);
408
- const localesToLoad = Array.from(new Set([...(lc.preload ?? []), effectiveLocale]));
409
- await Promise.all(localesToLoad.map(l => this.lang.loadLocale(l)));
410
- await this.lang.setLocale(effectiveLocale);
411
- }
412
- this._configVersion.update(v => v + 1);
413
- }
414
- /**
415
- * Load configuration from a pre-parsed object (no HTTP fetch).
416
- * Used for live preview scenarios where config is pushed via postMessage.
417
- * Optionally re-bootstraps the language service if a `language` section is present.
418
- */
419
- async loadFromObject(config, bootstrapLanguage = false) {
420
- const defaults = isPlainObject(config['defaults']) ? config['defaults'] : {};
421
- const overrides = isPlainObject(config['overrides']) ? config['overrides'] : {};
422
- const settings = isPlainObject(config['settings']) ? config['settings'] : {};
423
- this._config = { settings, defaults, overrides };
424
- this._settings = settings;
425
- if (bootstrapLanguage) {
426
- const langCfg = config['language'];
427
- if (isPlainObject(langCfg) && typeof langCfg['urlPattern'] === 'string') {
428
- const lc = langCfg;
429
- if (this._debugMode) {
430
- console.log(`[MnConfig] Applying language config from object`, lc);
431
- }
432
- this.lang.configure(lc.urlPattern);
433
- const effectiveLocale = this.lang.resolveLocaleForDomain(lc.domainLocaleMap, lc.defaultLocale);
434
- const localesToLoad = Array.from(new Set([...(lc.preload ?? []), effectiveLocale]));
435
- await Promise.all(localesToLoad.map(l => this.lang.loadLocale(l)));
436
- await this.lang.setLocale(effectiveLocale);
437
- }
438
- }
439
- this._configVersion.update(v => v + 1);
440
- }
441
- /**
442
- * Resolve a configuration object for a component, optionally scoped to a section path
443
- * and optionally overridden by an instance id.
444
- */
445
- resolve(componentName, sectionPath = [], instanceId) {
446
- const baseConfig = isPlainObject(this._config?.defaults)
447
- ? (isPlainObject(this._config.defaults[componentName])
448
- ? { ...this._config.defaults[componentName] }
449
- : {})
450
- : {};
451
- const leaf = this.walkOverrides(this._config?.overrides ?? {}, sectionPath);
452
- let resolved = baseConfig;
453
- if (leaf && isPlainObject(leaf[componentName])) {
454
- resolved = this.deepMerge(resolved, leaf[componentName]);
455
- }
456
- if (instanceId) {
457
- const instKey = `#${instanceId}`;
458
- if (leaf && isPlainObject(leaf[instKey])) {
459
- resolved = this.deepMerge(resolved, leaf[instKey]);
460
- }
461
- }
462
- if (this._debugMode) {
463
- console.debug(`[MnConfig] Resolving for ${componentName}`, {
464
- sectionPath,
465
- instanceId,
466
- resolved,
467
- });
468
- }
469
- return this.resolveTranslatables(resolved);
470
- }
471
- /**
472
- * Walk the overrides nested object using the provided section path and return the leaf node.
473
- * If any segment is missing or the current node is not a plain object, returns undefined.
474
- */
475
- walkOverrides(overridesRoot, sectionPath) {
476
- let node = overridesRoot;
477
- for (const segment of sectionPath) {
478
- if (!isPlainObject(node))
479
- return undefined;
480
- node = node[segment];
481
- if (node === undefined)
482
- return undefined;
483
- }
484
- return node;
485
- }
486
- /**
487
- * Recursively walk a resolved config object and replace any `{ $translate: "key" }` markers
488
- * with their translated values from MnLanguageService.
489
- */
490
- resolveTranslatables(obj) {
491
- const out = {};
492
- for (const [key, value] of Object.entries(obj)) {
493
- if (isTranslatable(value)) {
494
- out[key] = this.lang.translate(value.$translate, value.params);
495
- }
496
- else if (Array.isArray(value)) {
497
- out[key] = value.map(item => {
498
- if (isTranslatable(item)) {
499
- return this.lang.translate(item.$translate, item.params);
500
- }
501
- else if (isPlainObject(item)) {
502
- return this.resolveTranslatables(item);
503
- }
504
- return item;
505
- });
506
- }
507
- else if (isPlainObject(value)) {
508
- out[key] = this.resolveTranslatables(value);
509
- }
510
- else {
511
- out[key] = value;
512
- }
513
- }
514
- return out;
515
- }
516
- /**
517
- * Deep merge two plain-object trees. Arrays and non-plain values are replaced by the patch.
518
- * Does not mutate inputs; returns a new object.
519
- */
520
- deepMerge(base, patch) {
521
- const out = { ...base };
522
- for (const key of Object.keys(patch)) {
523
- const bVal = base[key];
524
- const pVal = patch[key];
525
- if (isPlainObject(bVal) && isPlainObject(pVal)) {
526
- out[key] = this.deepMerge(bVal, pVal);
527
- }
528
- else {
529
- // replace for arrays, primitives, null, undefined, and non-plain objects
530
- out[key] = pVal;
531
- }
532
- }
533
- return out;
534
- }
535
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: MnConfigService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
536
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: MnConfigService, providedIn: 'root' });
196
+ try {
197
+ return JSON.parse(text);
198
+ } catch {
199
+ const { default: JSON5 } = await import("json5");
200
+ return JSON5.parse(text);
201
+ }
537
202
  }
538
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: MnConfigService, decorators: [{
539
- type: Injectable,
540
- args: [{ providedIn: 'root' }]
541
- }] });
542
-
543
- /**
544
- * Provides an APP_INITIALIZER that loads the mn-lib configuration from the given URL
545
- * during application bootstrap. The consuming application is responsible for providing
546
- * HttpClient (e.g., via HttpClientModule or provideHttpClient()).
547
- */
203
+ var MnConfigService = class MnConfigService {
204
+ http = inject(HttpClient);
205
+ _config = null;
206
+ _settings = {};
207
+ _debugMode = false;
208
+ _configVersion = signal(0, ...ngDevMode ? [{ debugName: "_configVersion" }] : /* istanbul ignore next */ []);
209
+ configVersion = this._configVersion.asReadonly();
210
+ lang = inject(MnLanguageService);
211
+ get settings() {
212
+ return this._settings;
213
+ }
214
+ async load(url, debugMode = false) {
215
+ this._debugMode = debugMode;
216
+ this.lang.setDebug(debugMode);
217
+ let text;
218
+ try {
219
+ text = await firstValueFrom(this.http.get(url, { responseType: "text" }));
220
+ } catch (err) {
221
+ console.warn(`[MnConfig] Failed to load config from ${url}`, err);
222
+ this._config = {
223
+ defaults: {},
224
+ overrides: {}
225
+ };
226
+ return;
227
+ }
228
+ let json;
229
+ try {
230
+ json = await parseConfigText(text);
231
+ } catch (err) {
232
+ console.warn(`[MnConfig] Failed to parse JSON5 from ${url}`, err, text);
233
+ json = {};
234
+ }
235
+ const cfg = isPlainObject(json) ? json : {};
236
+ const defaults = isPlainObject(cfg["defaults"]) ? cfg["defaults"] : {};
237
+ const overrides = isPlainObject(cfg["overrides"]) ? cfg["overrides"] : {};
238
+ const settings = isPlainObject(cfg["settings"]) ? cfg["settings"] : {};
239
+ this._config = {
240
+ settings,
241
+ defaults,
242
+ overrides
243
+ };
244
+ this._settings = settings;
245
+ const langCfg = cfg["language"];
246
+ if (isPlainObject(langCfg) && typeof langCfg["urlPattern"] === "string") {
247
+ const lc = langCfg;
248
+ if (this._debugMode) console.log(`[MnConfig] Applying language config from file`, lc);
249
+ this.lang.configure(lc.urlPattern);
250
+ const effectiveLocale = this.lang.resolveLocaleForDomain(lc.domainLocaleMap, lc.defaultLocale);
251
+ const localesToLoad = Array.from(/* @__PURE__ */ new Set([...lc.preload ?? [], effectiveLocale]));
252
+ await Promise.all(localesToLoad.map((l) => this.lang.loadLocale(l)));
253
+ await this.lang.setLocale(effectiveLocale);
254
+ }
255
+ this._configVersion.update((v) => v + 1);
256
+ }
257
+ async loadFromObject(config, bootstrapLanguage = false) {
258
+ const defaults = isPlainObject(config["defaults"]) ? config["defaults"] : {};
259
+ const overrides = isPlainObject(config["overrides"]) ? config["overrides"] : {};
260
+ const settings = isPlainObject(config["settings"]) ? config["settings"] : {};
261
+ this._config = {
262
+ settings,
263
+ defaults,
264
+ overrides
265
+ };
266
+ this._settings = settings;
267
+ if (bootstrapLanguage) {
268
+ const langCfg = config["language"];
269
+ if (isPlainObject(langCfg) && typeof langCfg["urlPattern"] === "string") {
270
+ const lc = langCfg;
271
+ if (this._debugMode) console.log(`[MnConfig] Applying language config from object`, lc);
272
+ this.lang.configure(lc.urlPattern);
273
+ const effectiveLocale = this.lang.resolveLocaleForDomain(lc.domainLocaleMap, lc.defaultLocale);
274
+ const localesToLoad = Array.from(/* @__PURE__ */ new Set([...lc.preload ?? [], effectiveLocale]));
275
+ await Promise.all(localesToLoad.map((l) => this.lang.loadLocale(l)));
276
+ await this.lang.setLocale(effectiveLocale);
277
+ }
278
+ }
279
+ this._configVersion.update((v) => v + 1);
280
+ }
281
+ resolve(componentName, sectionPath = [], instanceId) {
282
+ const baseConfig = isPlainObject(this._config?.defaults) ? isPlainObject(this._config.defaults[componentName]) ? { ...this._config.defaults[componentName] } : {} : {};
283
+ const leaf = this.walkOverrides(this._config?.overrides ?? {}, sectionPath);
284
+ let resolved = baseConfig;
285
+ if (leaf && isPlainObject(leaf[componentName])) resolved = this.deepMerge(resolved, leaf[componentName]);
286
+ if (instanceId) {
287
+ const instKey = `#${instanceId}`;
288
+ if (leaf && isPlainObject(leaf[instKey])) resolved = this.deepMerge(resolved, leaf[instKey]);
289
+ }
290
+ if (this._debugMode) console.debug(`[MnConfig] Resolving for ${componentName}`, {
291
+ sectionPath,
292
+ instanceId,
293
+ resolved
294
+ });
295
+ return this.resolveTranslatables(resolved);
296
+ }
297
+ walkOverrides(overridesRoot, sectionPath) {
298
+ let node = overridesRoot;
299
+ for (const segment of sectionPath) {
300
+ if (!isPlainObject(node)) return void 0;
301
+ node = node[segment];
302
+ if (node === void 0) return void 0;
303
+ }
304
+ return node;
305
+ }
306
+ resolveTranslatables(obj) {
307
+ const out = {};
308
+ for (const [key, value] of Object.entries(obj)) if (isTranslatable(value)) out[key] = this.lang.translate(value.$translate, value.params);
309
+ else if (Array.isArray(value)) out[key] = value.map((item) => {
310
+ if (isTranslatable(item)) return this.lang.translate(item.$translate, item.params);
311
+ else if (isPlainObject(item)) return this.resolveTranslatables(item);
312
+ return item;
313
+ });
314
+ else if (isPlainObject(value)) out[key] = this.resolveTranslatables(value);
315
+ else out[key] = value;
316
+ return out;
317
+ }
318
+ deepMerge(base, patch) {
319
+ const out = { ...base };
320
+ for (const key of Object.keys(patch)) {
321
+ const bVal = base[key];
322
+ const pVal = patch[key];
323
+ if (isPlainObject(bVal) && isPlainObject(pVal)) out[key] = this.deepMerge(bVal, pVal);
324
+ else out[key] = pVal;
325
+ }
326
+ return out;
327
+ }
328
+ static ɵfac = i0.ɵɵngDeclareFactory({
329
+ minVersion: "12.0.0",
330
+ version: "22.2.2",
331
+ ngImport: i0,
332
+ type: MnConfigService,
333
+ deps: [],
334
+ target: i0.ɵɵFactoryTarget.Injectable
335
+ });
336
+ static ɵprov = i0.ɵɵngDeclareInjectable({
337
+ minVersion: "12.0.0",
338
+ version: "22.2.2",
339
+ ngImport: i0,
340
+ type: MnConfigService,
341
+ providedIn: "root"
342
+ });
343
+ };
344
+ i0.ɵɵngDeclareClassMetadata({
345
+ minVersion: "12.0.0",
346
+ version: "22.2.2",
347
+ ngImport: i0,
348
+ type: MnConfigService,
349
+ decorators: [{
350
+ type: Injectable,
351
+ args: [{ providedIn: "root" }]
352
+ }]
353
+ });
548
354
  function provideMnConfig(url, debugMode = false) {
549
- return [
550
- {
551
- provide: APP_INITIALIZER,
552
- multi: true,
553
- useFactory: (svc) => () => svc.load(url, debugMode),
554
- deps: [MnConfigService],
555
- },
556
- ];
355
+ return [{
356
+ provide: APP_INITIALIZER,
357
+ multi: true,
358
+ useFactory: (svc) => () => svc.load(url, debugMode),
359
+ deps: [MnConfigService]
360
+ }];
557
361
  }
558
-
559
- /**
560
- * Represents the current section path based on nested mn-section directives.
561
- */
562
- const MN_SECTION_PATH = new InjectionToken('MN_SECTION_PATH', {
563
- providedIn: 'root',
564
- factory: () => [],
362
+ const MN_SECTION_PATH = new InjectionToken("MN_SECTION_PATH", {
363
+ providedIn: "root",
364
+ factory: () => []
565
365
  });
566
- /**
567
- * Whether the injecting component renders inside an mn modal. `MnModalShellComponent` provides
568
- * `true` for everything in its view, so a component deep in a modal body can tell without the
569
- * consumer passing anything: mn-table uses it to skip its own bottom sheet, because a sheet
570
- * opened over a modal that is already a sheet on a phone stacks two drawers on one screen.
571
- */
572
- const MN_IN_MODAL = new InjectionToken('MN_IN_MODAL', {
573
- providedIn: 'root',
574
- factory: () => false,
366
+ const MN_IN_MODAL = new InjectionToken("MN_IN_MODAL", {
367
+ providedIn: "root",
368
+ factory: () => false
575
369
  });
576
- /**
577
- * Whether the injecting component renders inside an `mn-bottom-sheet`. The sheet provides `true`
578
- * to its content. mn-select and mn-multi-select read it: on a phone they normally open their
579
- * options as a bottom sheet of their own, which inside a sheet stacks a second one on top and
580
- * hides the form around it, so there they open as an anchored dropdown instead.
581
- */
582
- const MN_IN_BOTTOM_SHEET = new InjectionToken('MN_IN_BOTTOM_SHEET', {
583
- providedIn: 'root',
584
- factory: () => false,
370
+ const MN_IN_BOTTOM_SHEET = new InjectionToken("MN_IN_BOTTOM_SHEET", {
371
+ providedIn: "root",
372
+ factory: () => false
585
373
  });
586
- /**
587
- * Represents the current component instance id provided by [mn-instance].
588
- */
589
- const MN_INSTANCE_ID = new InjectionToken('MN_INSTANCE_ID', {
590
- providedIn: 'root',
591
- factory: () => null,
374
+ const MN_INSTANCE_ID = new InjectionToken("MN_INSTANCE_ID", {
375
+ providedIn: "root",
376
+ factory: () => null
592
377
  });
593
-
594
- /**
595
- * Helper to provide a resolved, typed component config via DI.
596
- *
597
- * Usage in a component/module providers:
598
- * const MY_CFG = new InjectionToken<MyCfg>('MY_CFG');
599
- * providers: [ provideMnComponentConfig(MY_CFG, 'my-component') ]
600
- * Then in the component:
601
- * readonly cfg = inject(MY_CFG)
602
- *
603
- * The returned config object is **reactive**: when the active locale changes,
604
- * all translatable values are re-resolved in place so that templates using
605
- * `cfg.someLabel` automatically reflect the new language on the next change-detection cycle.
606
- */
607
378
  function provideMnComponentConfig(token, componentName, initial) {
608
- return {
609
- provide: token,
610
- deps: [
611
- MnConfigService,
612
- MnLanguageService,
613
- DestroyRef,
614
- [new Optional(), MN_SECTION_PATH],
615
- [new Optional(), MN_INSTANCE_ID],
616
- ],
617
- useFactory: (svc, lang, destroyRef, sectionPath, instanceId) => {
618
- const resolveConfig = () => {
619
- const resolved = svc.resolve(componentName, sectionPath ?? [], instanceId ?? undefined);
620
- return Object.assign({}, initial ?? {}, resolved);
621
- };
622
- // Create the initial config object that will be shared by reference.
623
- const cfg = resolveConfig();
624
- // Re-resolve translatable values whenever the locale changes.
625
- // skip(1) because the current locale was already used for the initial resolve.
626
- const sub = lang.locale$.subscribe(() => {
627
- const updated = resolveConfig();
628
- // Mutate the existing object in place so all template bindings pick up the new values.
629
- for (const key of Object.keys(updated)) {
630
- cfg[key] = updated[key];
631
- }
632
- });
633
- destroyRef.onDestroy(() => sub.unsubscribe());
634
- return cfg;
635
- },
636
- };
637
- }
638
-
639
- class MnSectionDirective {
640
- /** Section name contributed by this DOM node to the section path */
641
- mnSection;
642
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: MnSectionDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive });
643
- static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "22.1.7", type: MnSectionDirective, isStandalone: true, selector: "[mn-section]", inputs: { mnSection: ["mn-section", "mnSection"] }, providers: [
644
- {
645
- provide: MN_SECTION_PATH,
646
- // Read parent MN_SECTION_PATH from ancestor injector (skipSelf to avoid self-reference),
647
- // and read the attribute value using Attribute so it's available at provider creation time.
648
- deps: [[new Optional(), new SkipSelf(), MN_SECTION_PATH], new Attribute('mn-section')],
649
- useFactory: (parentPath, attr) => {
650
- const parent = Array.isArray(parentPath) ? parentPath : [];
651
- const name = (attr ?? '').trim();
652
- return name ? [...parent, name] : [...parent];
653
- },
654
- },
655
- ], ngImport: i0 });
379
+ return {
380
+ provide: token,
381
+ deps: [
382
+ MnConfigService,
383
+ MnLanguageService,
384
+ DestroyRef,
385
+ [new Optional(), MN_SECTION_PATH],
386
+ [new Optional(), MN_INSTANCE_ID]
387
+ ],
388
+ useFactory: (svc, lang, destroyRef, sectionPath, instanceId) => {
389
+ const resolveConfig = () => {
390
+ const resolved = svc.resolve(componentName, sectionPath ?? [], instanceId ?? void 0);
391
+ return Object.assign({}, initial ?? {}, resolved);
392
+ };
393
+ const cfg = resolveConfig();
394
+ const sub = lang.locale$.subscribe(() => {
395
+ const updated = resolveConfig();
396
+ for (const key of Object.keys(updated)) cfg[key] = updated[key];
397
+ });
398
+ destroyRef.onDestroy(() => sub.unsubscribe());
399
+ return cfg;
400
+ }
401
+ };
656
402
  }
657
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: MnSectionDirective, decorators: [{
658
- type: Directive,
659
- args: [{
660
- // eslint-disable-next-line @angular-eslint/directive-selector -- kebab-case is intentional: matches the Attribute() token and is stable public API
661
- selector: '[mn-section]',
662
- standalone: true,
663
- providers: [
664
- {
665
- provide: MN_SECTION_PATH,
666
- // Read parent MN_SECTION_PATH from ancestor injector (skipSelf to avoid self-reference),
667
- // and read the attribute value using Attribute so it's available at provider creation time.
668
- deps: [[new Optional(), new SkipSelf(), MN_SECTION_PATH], new Attribute('mn-section')],
669
- useFactory: (parentPath, attr) => {
670
- const parent = Array.isArray(parentPath) ? parentPath : [];
671
- const name = (attr ?? '').trim();
672
- return name ? [...parent, name] : [...parent];
673
- },
674
- },
675
- ],
676
- }]
677
- }], propDecorators: { mnSection: [{
678
- type: Input,
679
- args: ['mn-section']
680
- }] } });
681
-
682
- class MnInstanceDirective {
683
- /** Instance id for targeting per-component instance overrides */
684
- mnInstance;
685
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: MnInstanceDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive });
686
- static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "22.1.7", type: MnInstanceDirective, isStandalone: true, selector: "[mn-instance]", inputs: { mnInstance: ["mn-instance", "mnInstance"] }, providers: [
687
- {
688
- provide: MN_INSTANCE_ID,
689
- // Read the attribute at provider creation time using Attribute token; Inputs may not be set yet.
690
- deps: [new Attribute('mn-instance')],
691
- useFactory: (attr) => (attr ?? '').trim() || null,
692
- },
693
- ], ngImport: i0 });
694
- }
695
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: MnInstanceDirective, decorators: [{
696
- type: Directive,
697
- args: [{
698
- // eslint-disable-next-line @angular-eslint/directive-selector -- kebab-case is intentional: matches the Attribute() token and is stable public API
699
- selector: '[mn-instance]',
700
- standalone: true,
701
- providers: [
702
- {
703
- provide: MN_INSTANCE_ID,
704
- // Read the attribute at provider creation time using Attribute token; Inputs may not be set yet.
705
- deps: [new Attribute('mn-instance')],
706
- useFactory: (attr) => (attr ?? '').trim() || null,
707
- },
708
- ],
709
- }]
710
- }], propDecorators: { mnInstance: [{
711
- type: Input,
712
- args: ['mn-instance']
713
- }] } });
714
-
715
- /**
716
- * Injection token for the base URL used by all CRUD service requests.
717
- *
718
- * Provide this token at the application or module level to configure
719
- * the root API URL that `CrudService` prepends to every endpoint.
720
- */
721
- const API_BASE_URL = new InjectionToken('API_BASE_URL');
722
-
723
- /**
724
- * Abstract base class for CRUD services.
725
- * Provides standard HTTP operations with typed `Result<T>` responses.
726
- *
727
- * @template TEntity The entity type returned by single-item operations.
728
- * @template TListResponse The response type for list operations (defaults to `TEntity[]`).
729
- * @template TCreatePayload The payload type for create operations (defaults to `Partial<TEntity>`).
730
- * @template TUpdatePayload The payload type for update operations (defaults to `Partial<TEntity>`).
731
- * @template TId The type of the entity identifier (defaults to `number`).
732
- * @template TGetByIdResponse The response type for getById (defaults to `TEntity`).
733
- * @template TCreateResponse The response type for create (defaults to `TEntity`).
734
- * @template TUpdateResponse The response type for update and patch (defaults to `TEntity`).
735
- * @template TDeleteResponse The response type for delete (defaults to `void`).
736
- */
737
- class CrudService {
738
- http = inject(HttpClient);
739
- baseUrl = inject(API_BASE_URL);
740
- endpoint;
741
- constructor(config) {
742
- this.endpoint = `${this.baseUrl}${config.endpoint}`;
743
- }
744
- /**
745
- * Retrieves all entities from the configured endpoint.
746
- *
747
- * Sends a GET request to the base endpoint. Query values are
748
- * converted to `HttpParams` before the request is sent.
749
- *
750
- * @param query Optional query parameters appended to the request URL.
751
- * @returns An observable emitting a `Result` with the list response or a structured failure.
752
- */
753
- getAll(query) {
754
- return this.http
755
- .get(this.endpoint, {
756
- params: this.toHttpParams(query)
757
- })
758
- .pipe(map((data) => this.success(data)), catchError((error) => of(this.failure(this.mapHttpError(error)))));
759
- }
760
- /**
761
- * Retrieves a single entity by its identifier.
762
- *
763
- * Sends a GET request to `{endpoint}/{id}`.
764
- *
765
- * @param id The unique identifier of the entity to retrieve.
766
- * @returns An observable emitting a `Result` with the entity or a structured failure.
767
- */
768
- getById(id) {
769
- return this.http
770
- .get(this.itemUrl(id))
771
- .pipe(map((data) => this.success(data)), catchError((error) => of(this.failure(this.mapHttpError(error)))));
772
- }
773
- /**
774
- * Creates a new entity at the configured endpoint.
775
- *
776
- * Sends a POST request with the provided payload as the request body.
777
- *
778
- * @param payload The data used to create the entity.
779
- * @returns An observable emitting a `Result` with the created entity or a structured failure.
780
- */
781
- create(payload) {
782
- return this.http
783
- .post(this.endpoint, payload)
784
- .pipe(map((data) => this.success(data)), catchError((error) => of(this.failure(this.mapHttpError(error)))));
785
- }
786
- /**
787
- * Fully replaces an existing entity.
788
- *
789
- * Sends a PUT request to `{endpoint}/{id}` with the provided payload,
790
- * replacing the entire entity.
791
- *
792
- * @param id The unique identifier of the entity to update.
793
- * @param payload The complete data to replace the existing entity with.
794
- * @returns An observable emitting a `Result` with the updated entity or a structured failure.
795
- */
796
- update(id, payload) {
797
- return this.http
798
- .put(this.itemUrl(id), payload)
799
- .pipe(map((data) => this.success(data)), catchError((error) => of(this.failure(this.mapHttpError(error)))));
800
- }
801
- /**
802
- * Partially updates an existing entity.
803
- *
804
- * Sends a PATCH request to `{endpoint}/{id}` with the provided payload,
805
- * merging changes into the existing entity.
806
- *
807
- * @param id The unique identifier of the entity to patch.
808
- * @param payload A partial set of fields to update on the existing entity.
809
- * @returns An observable emitting a `Result` with the updated entity or a structured failure.
810
- */
811
- patch(id, payload) {
812
- return this.http
813
- .patch(this.itemUrl(id), payload)
814
- .pipe(map((data) => this.success(data)), catchError((error) => of(this.failure(this.mapHttpError(error)))));
815
- }
816
- /**
817
- * Deletes an entity by its identifier.
818
- *
819
- * Sends a DELETE request to `{endpoint}/{id}`.
820
- *
821
- * @param id The unique identifier of the entity to delete.
822
- * @returns An observable emitting a `Result` with the delete response or a structured failure.
823
- */
824
- delete(id) {
825
- return this.http
826
- .delete(this.itemUrl(id))
827
- .pipe(map((data) => this.success(data)), catchError((error) => of(this.failure(this.mapHttpError(error)))));
828
- }
829
- /**
830
- * Retrieves all entities with the full `HttpResponse` wrapper.
831
- *
832
- * Behaves like {@link getAll} but observes the complete HTTP response,
833
- * giving access to headers, status code, and URL alongside the body.
834
- *
835
- * @param query Optional query parameters appended to the request URL.
836
- * @returns An observable emitting a `Result` with the full HTTP response or a structured failure.
837
- */
838
- getAllResponse(query) {
839
- return this.http
840
- .get(this.endpoint, {
841
- params: this.toHttpParams(query),
842
- observe: 'response',
843
- })
844
- .pipe(map((response) => this.success(response, {
845
- statusCode: response.status,
846
- headers: response.headers,
847
- url: response.url ?? undefined,
848
- })), catchError((error) => of(this.failure(this.mapHttpError(error)))));
849
- }
850
- /**
851
- * Builds the URL for a single entity by appending the identifier to the endpoint.
852
- *
853
- * @param id The unique identifier to append.
854
- * @returns The full URL targeting the specific entity.
855
- */
856
- itemUrl(id) {
857
- return `${this.endpoint}/${id}`;
858
- }
859
- /**
860
- * Wraps a value in a `SuccessResult`.
861
- *
862
- * @template T The type of the response data.
863
- * @param data The response data to wrap.
864
- * @param meta Optional metadata (status code, headers, URL) to attach.
865
- * @returns A `SuccessResult` containing the provided data.
866
- */
867
- success(data, meta) {
868
- return { ok: true, data, meta };
869
- }
870
- /**
871
- * Wraps an error in a `FailureResult`.
872
- *
873
- * When no explicit metadata is provided, metadata is derived from
874
- * the `ApiError` itself (status code, headers, URL).
875
- *
876
- * @param error The structured API error.
877
- * @param meta Optional metadata to override the error-derived values.
878
- * @returns A `FailureResult` containing the error and metadata.
879
- */
880
- failure(error, meta) {
881
- return {
882
- ok: false,
883
- error,
884
- meta: meta ?? {
885
- statusCode: error.status ?? undefined,
886
- headers: error.headers,
887
- url: error.url ?? undefined,
888
- },
889
- };
890
- }
891
- /**
892
- * Maps an unknown error into a structured `ApiError`.
893
- *
894
- * Handles both `HttpErrorResponse` instances and unexpected error types.
895
- * Extracts backend messages, validation errors, and retry information
896
- * so callers receive a consistent error shape.
897
- *
898
- * @param error The raw error caught from the HTTP pipeline.
899
- * @returns A fully populated `ApiError` object.
900
- */
901
- mapHttpError(error) {
902
- const timestamp = new Date().toISOString();
903
- if (!(error instanceof HttpErrorResponse)) {
904
- return {
905
- status: null,
906
- message: 'Unknown error',
907
- original: error instanceof Error ? error : new Error(String(error)),
908
- retryable: false,
909
- timestamp,
910
- };
911
- }
912
- const status = this.normalizeStatus(error.status);
913
- const details = error.error;
914
- const backendMessage = this.extractBackendMessage(details);
915
- const validationErrors = this.extractValidationErrors(details);
916
- return {
917
- status,
918
- message: backendMessage ?? this.defaultMessage(status),
919
- details,
920
- backendMessage,
921
- validationErrors,
922
- url: error.url,
923
- headers: error.headers,
924
- original: error,
925
- retryable: this.isRetryable(status),
926
- timestamp,
927
- };
928
- }
929
- /**
930
- * Extracts a human-readable message from the error response body.
931
- *
932
- * Checks common keys (`message`, `title`, `detail`, `error`) on the
933
- * body object and returns the first non-empty string found.
934
- *
935
- * @param body The parsed error response body.
936
- * @returns The extracted message, or `undefined` if none was found.
937
- */
938
- extractBackendMessage(body) {
939
- if (typeof body === 'string' && body.trim()) {
940
- return body;
941
- }
942
- if (!body || typeof body !== 'object') {
943
- return undefined;
944
- }
945
- const obj = body;
946
- for (const key of ['message', 'title', 'detail', 'error']) {
947
- const value = obj[key];
948
- if (typeof value === 'string' && value.trim()) {
949
- return value;
950
- }
951
- }
952
- return undefined;
953
- }
954
- /**
955
- * Extracts field-level validation errors from the error response body.
956
- *
957
- * Expects an `errors` property on the body containing a record of
958
- * field names to error messages (string or string array).
959
- *
960
- * @param body The parsed error response body.
961
- * @returns A record mapping field names to their error messages, or `undefined` if none were found.
962
- */
963
- extractValidationErrors(body) {
964
- if (!body || typeof body !== 'object') {
965
- return undefined;
966
- }
967
- const obj = body;
968
- const errors = obj['errors'];
969
- if (!errors || typeof errors !== 'object') {
970
- return undefined;
971
- }
972
- const result = {};
973
- for (const [key, value] of Object.entries(errors)) {
974
- if (Array.isArray(value)) {
975
- result[key] = value.map(String);
976
- }
977
- else if (typeof value === 'string') {
978
- result[key] = [value];
979
- }
980
- }
981
- return Object.keys(result).length ? result : undefined;
982
- }
983
- /**
984
- * Returns a default user-facing message for the given HTTP status code.
985
- *
986
- * Provides human-readable messages for common HTTP status codes.
987
- * Override this method to customise messages.
988
- *
989
- * @param status The HTTP status code, or `null` when unknown.
990
- * @returns A descriptive error message.
991
- */
992
- defaultMessage(status) {
993
- switch (status) {
994
- case HttpStatusCode.BadRequest:
995
- return 'Bad request';
996
- case HttpStatusCode.Unauthorized:
997
- return 'Unauthorized';
998
- case HttpStatusCode.Forbidden:
999
- return 'Forbidden';
1000
- case HttpStatusCode.NotFound:
1001
- return 'Not found';
1002
- case HttpStatusCode.Conflict:
1003
- return 'Conflict';
1004
- case HttpStatusCode.UnprocessableEntity:
1005
- return 'Unprocessable entity';
1006
- case HttpStatusCode.InternalServerError:
1007
- return 'Internal server error';
1008
- case null:
1009
- return 'Unknown error';
1010
- default:
1011
- return `Request failed with status ${status}`;
1012
- }
1013
- }
1014
- /**
1015
- * Determines whether a request with the given status can be retried.
1016
- *
1017
- * Timeouts, rate-limiting responses, and server errors
1018
- * (5xx) are considered retryable by default.
1019
- *
1020
- * @param status The HTTP status code, or `null` when unknown.
1021
- * @returns `true` if the request is safe to retry.
1022
- */
1023
- isRetryable(status) {
1024
- if (status === HttpStatusCode.RequestTimeout)
1025
- return true;
1026
- if (status === HttpStatusCode.TooManyRequests)
1027
- return true;
1028
- if (typeof status === 'number' && status >= 500)
1029
- return true;
1030
- return false;
1031
- }
1032
- /**
1033
- * Normalises a raw HTTP status into an `HttpStatusCode | null` value.
1034
- *
1035
- * Converts `undefined`, `NaN`, and `0` (network error) to `null`
1036
- * so downstream code only needs to handle `HttpStatusCode | null`.
1037
- *
1038
- * @param status The raw status value from the HTTP response.
1039
- * @returns The normalised status code, or `null` when indeterminate.
1040
- */
1041
- normalizeStatus(status) {
1042
- if (status === null || status === undefined || status === 0 || Number.isNaN(status))
1043
- return null;
1044
- return status;
1045
- }
1046
- /**
1047
- * Converts query parameters into Angular `HttpParams`.
1048
- *
1049
- * `null` and `undefined` values are silently skipped.
1050
- * Array values are appended as multiple entries for the same key.
1051
- *
1052
- * @param query The query parameter record to convert.
1053
- * @returns An `HttpParams` instance, or `undefined` when no parameters are provided.
1054
- */
1055
- toHttpParams(query) {
1056
- if (!query)
1057
- return undefined;
1058
- let params = new HttpParams();
1059
- for (const [key, rawValue] of Object.entries(query)) {
1060
- if (rawValue === null || rawValue === undefined)
1061
- continue;
1062
- const values = Array.isArray(rawValue) ? rawValue : [rawValue];
1063
- for (const value of values) {
1064
- if (value === null || value === undefined)
1065
- continue;
1066
- params = params.append(key, String(value));
1067
- }
1068
- }
1069
- return params;
1070
- }
1071
- }
1072
-
1073
- /**
1074
- * Lightweight abstract HTTP base class that removes common boilerplate
1075
- * from API services.
1076
- *
1077
- * Provides typed `get`, `post`, `patch`, `put`, and `delete` methods
1078
- * that return Promises, automatic query-param building, and base-URL
1079
- * injection via the `API_BASE_URL` token.
1080
- *
1081
- * Subclass this directly for services with static or mixed endpoints.
1082
- * No CRUD structure is imposed — every method accepts a free-form path.
1083
- */
1084
- class MnHttpService {
1085
- /** Angular HTTP client injected automatically. */
1086
- http = inject(HttpClient);
1087
- /** Base API URL provided via the `API_BASE_URL` injection token. */
1088
- baseUrl = inject(API_BASE_URL);
1089
- /**
1090
- * Sends a typed GET request.
1091
- * @param path The path appended to the base URL.
1092
- * @param query Optional query parameters.
1093
- * @returns A promise resolving to the typed response body.
1094
- */
1095
- get(path, query) {
1096
- return firstValueFrom(this.http.get(`${this.baseUrl}${path}`, {
1097
- params: this.toHttpParams(query),
1098
- }));
1099
- }
1100
- /**
1101
- * Sends a typed POST request.
1102
- * @param path The path appended to the base URL.
1103
- * @param body Optional request body.
1104
- * @param query Optional query parameters.
1105
- * @returns A promise resolving to the typed response body.
1106
- */
1107
- post(path, body, query) {
1108
- return firstValueFrom(this.http.post(`${this.baseUrl}${path}`, body ?? {}, {
1109
- params: this.toHttpParams(query),
1110
- }));
1111
- }
1112
- /**
1113
- * Sends a typed PATCH request.
1114
- * @param path The path appended to the base URL.
1115
- * @param body Optional request body.
1116
- * @param query Optional query parameters.
1117
- * @returns A promise resolving to the typed response body.
1118
- */
1119
- patch(path, body, query) {
1120
- return firstValueFrom(this.http.patch(`${this.baseUrl}${path}`, body ?? {}, {
1121
- params: this.toHttpParams(query),
1122
- }));
1123
- }
1124
- /**
1125
- * Sends a typed PUT request.
1126
- * @param path The path appended to the base URL.
1127
- * @param body Optional request body.
1128
- * @param query Optional query parameters.
1129
- * @returns A promise resolving to the typed response body.
1130
- */
1131
- put(path, body, query) {
1132
- return firstValueFrom(this.http.put(`${this.baseUrl}${path}`, body ?? {}, {
1133
- params: this.toHttpParams(query),
1134
- }));
1135
- }
1136
- /**
1137
- * Sends a typed DELETE request.
1138
- * @param path The path appended to the base URL.
1139
- * @param query Optional query parameters.
1140
- * @returns A promise resolving to the typed response body.
1141
- */
1142
- delete(path, query) {
1143
- return firstValueFrom(this.http.delete(`${this.baseUrl}${path}`, {
1144
- params: this.toHttpParams(query),
1145
- }));
1146
- }
1147
- /**
1148
- * Converts a query-params record to Angular `HttpParams`.
1149
- * Null and undefined values are silently skipped.
1150
- * Array values are appended as multiple entries for the same key.
1151
- * @param query The query parameter record to convert.
1152
- * @returns An `HttpParams` instance, or `undefined` when no parameters are provided.
1153
- */
1154
- toHttpParams(query) {
1155
- if (!query)
1156
- return undefined;
1157
- let params = new HttpParams();
1158
- for (const [key, rawValue] of Object.entries(query)) {
1159
- if (rawValue === null || rawValue === undefined)
1160
- continue;
1161
- const values = Array.isArray(rawValue) ? rawValue : [rawValue];
1162
- for (const value of values) {
1163
- if (value === null || value === undefined)
1164
- continue;
1165
- params = params.append(key, String(value));
1166
- }
1167
- }
1168
- return params;
1169
- }
1170
- }
1171
-
1172
- /**
1173
- * Turns icon nodes from the vanilla `lucide` package into the icon data that
1174
- * `<svg [lucideIcon]>` (`LucideDynamicIcon`) and MnLib's icon inputs accept.
1175
- *
1176
- * Why not `@lucide/angular`'s per-icon components (`<svg lucideArrowLeft>`): that
1177
- * package is a single module, and the Angular linker compiles a full copy of the
1178
- * SVG template into every icon class, so each icon cost ~2.8 kB and all of them
1179
- * landed in the startup chunk. With `lucide` an icon is a few hundred bytes of data, and
1180
- * only the icons something imports are bundled. esbuild keeps all of them in one shared
1181
- * chunk (they hang off the package's re-export barrel), about 30 kB for the whole app.
1182
- *
1183
- * Import the namespace and name each icon, so an icon called `Component`, `Map`
1184
- * or `X` never shadows another import:
1185
- *
1186
- * ```ts
1187
- * import * as lucide from 'lucide';
1188
- * const ICONS = lucideIcons({ ArrowLeft: lucide.ArrowLeft, Trash2: lucide.Trash2 });
1189
- * // template: <svg [lucideIcon]="icons.ArrowLeft" [size]="16"></svg>
1190
- * ```
1191
- *
1192
- * @param nodes Icon nodes keyed by their PascalCase `lucide` export name.
1193
- * @returns Icon data under the same keys, named `arrow-left`-style for the
1194
- * `lucide-<name>` class the icon renders with.
1195
- */
403
+ var MnSectionDirective = class MnSectionDirective {
404
+ mnSection;
405
+ static ɵfac = i0.ɵɵngDeclareFactory({
406
+ minVersion: "12.0.0",
407
+ version: "22.2.2",
408
+ ngImport: i0,
409
+ type: MnSectionDirective,
410
+ deps: [],
411
+ target: i0.ɵɵFactoryTarget.Directive
412
+ });
413
+ static ɵdir = i0.ɵɵngDeclareDirective({
414
+ minVersion: "14.0.0",
415
+ version: "22.2.2",
416
+ type: MnSectionDirective,
417
+ isStandalone: true,
418
+ selector: "[mn-section]",
419
+ inputs: { mnSection: ["mn-section", "mnSection"] },
420
+ providers: [{
421
+ provide: MN_SECTION_PATH,
422
+ deps: [[
423
+ new Optional(),
424
+ new SkipSelf(),
425
+ MN_SECTION_PATH
426
+ ], new Attribute("mn-section")],
427
+ useFactory: (parentPath, attr) => {
428
+ const parent = Array.isArray(parentPath) ? parentPath : [];
429
+ const name = (attr ?? "").trim();
430
+ return name ? [...parent, name] : [...parent];
431
+ }
432
+ }],
433
+ ngImport: i0
434
+ });
435
+ };
436
+ i0.ɵɵngDeclareClassMetadata({
437
+ minVersion: "12.0.0",
438
+ version: "22.2.2",
439
+ ngImport: i0,
440
+ type: MnSectionDirective,
441
+ decorators: [{
442
+ type: Directive,
443
+ args: [{
444
+ selector: "[mn-section]",
445
+ standalone: true,
446
+ providers: [{
447
+ provide: MN_SECTION_PATH,
448
+ deps: [[
449
+ new Optional(),
450
+ new SkipSelf(),
451
+ MN_SECTION_PATH
452
+ ], new Attribute("mn-section")],
453
+ useFactory: (parentPath, attr) => {
454
+ const parent = Array.isArray(parentPath) ? parentPath : [];
455
+ const name = (attr ?? "").trim();
456
+ return name ? [...parent, name] : [...parent];
457
+ }
458
+ }]
459
+ }]
460
+ }],
461
+ propDecorators: { mnSection: [{
462
+ type: Input,
463
+ args: ["mn-section"]
464
+ }] }
465
+ });
466
+ var MnInstanceDirective = class MnInstanceDirective {
467
+ mnInstance;
468
+ static ɵfac = i0.ɵɵngDeclareFactory({
469
+ minVersion: "12.0.0",
470
+ version: "22.2.2",
471
+ ngImport: i0,
472
+ type: MnInstanceDirective,
473
+ deps: [],
474
+ target: i0.ɵɵFactoryTarget.Directive
475
+ });
476
+ static ɵdir = i0.ɵɵngDeclareDirective({
477
+ minVersion: "14.0.0",
478
+ version: "22.2.2",
479
+ type: MnInstanceDirective,
480
+ isStandalone: true,
481
+ selector: "[mn-instance]",
482
+ inputs: { mnInstance: ["mn-instance", "mnInstance"] },
483
+ providers: [{
484
+ provide: MN_INSTANCE_ID,
485
+ deps: [new Attribute("mn-instance")],
486
+ useFactory: (attr) => (attr ?? "").trim() || null
487
+ }],
488
+ ngImport: i0
489
+ });
490
+ };
491
+ i0.ɵɵngDeclareClassMetadata({
492
+ minVersion: "12.0.0",
493
+ version: "22.2.2",
494
+ ngImport: i0,
495
+ type: MnInstanceDirective,
496
+ decorators: [{
497
+ type: Directive,
498
+ args: [{
499
+ selector: "[mn-instance]",
500
+ standalone: true,
501
+ providers: [{
502
+ provide: MN_INSTANCE_ID,
503
+ deps: [new Attribute("mn-instance")],
504
+ useFactory: (attr) => (attr ?? "").trim() || null
505
+ }]
506
+ }]
507
+ }],
508
+ propDecorators: { mnInstance: [{
509
+ type: Input,
510
+ args: ["mn-instance"]
511
+ }] }
512
+ });
513
+ const API_BASE_URL = new InjectionToken("API_BASE_URL");
514
+ var CrudService = class {
515
+ http = inject(HttpClient);
516
+ baseUrl = inject(API_BASE_URL);
517
+ endpoint;
518
+ constructor(config) {
519
+ this.endpoint = `${this.baseUrl}${config.endpoint}`;
520
+ }
521
+ getAll(query) {
522
+ return this.http.get(this.endpoint, { params: this.toHttpParams(query) }).pipe(map((data) => this.success(data)), catchError((error) => of(this.failure(this.mapHttpError(error)))));
523
+ }
524
+ getById(id) {
525
+ return this.http.get(this.itemUrl(id)).pipe(map((data) => this.success(data)), catchError((error) => of(this.failure(this.mapHttpError(error)))));
526
+ }
527
+ create(payload) {
528
+ return this.http.post(this.endpoint, payload).pipe(map((data) => this.success(data)), catchError((error) => of(this.failure(this.mapHttpError(error)))));
529
+ }
530
+ update(id, payload) {
531
+ return this.http.put(this.itemUrl(id), payload).pipe(map((data) => this.success(data)), catchError((error) => of(this.failure(this.mapHttpError(error)))));
532
+ }
533
+ patch(id, payload) {
534
+ return this.http.patch(this.itemUrl(id), payload).pipe(map((data) => this.success(data)), catchError((error) => of(this.failure(this.mapHttpError(error)))));
535
+ }
536
+ delete(id) {
537
+ return this.http.delete(this.itemUrl(id)).pipe(map((data) => this.success(data)), catchError((error) => of(this.failure(this.mapHttpError(error)))));
538
+ }
539
+ getAllResponse(query) {
540
+ return this.http.get(this.endpoint, {
541
+ params: this.toHttpParams(query),
542
+ observe: "response"
543
+ }).pipe(map((response) => this.success(response, {
544
+ statusCode: response.status,
545
+ headers: response.headers,
546
+ url: response.url ?? void 0
547
+ })), catchError((error) => of(this.failure(this.mapHttpError(error)))));
548
+ }
549
+ itemUrl(id) {
550
+ return `${this.endpoint}/${id}`;
551
+ }
552
+ success(data, meta) {
553
+ return {
554
+ ok: true,
555
+ data,
556
+ meta
557
+ };
558
+ }
559
+ failure(error, meta) {
560
+ return {
561
+ ok: false,
562
+ error,
563
+ meta: meta ?? {
564
+ statusCode: error.status ?? void 0,
565
+ headers: error.headers,
566
+ url: error.url ?? void 0
567
+ }
568
+ };
569
+ }
570
+ mapHttpError(error) {
571
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
572
+ if (!(error instanceof HttpErrorResponse)) return {
573
+ status: null,
574
+ message: "Unknown error",
575
+ original: error instanceof Error ? error : new Error(String(error)),
576
+ retryable: false,
577
+ timestamp
578
+ };
579
+ const status = this.normalizeStatus(error.status);
580
+ const details = error.error;
581
+ const backendMessage = this.extractBackendMessage(details);
582
+ const validationErrors = this.extractValidationErrors(details);
583
+ return {
584
+ status,
585
+ message: backendMessage ?? this.defaultMessage(status),
586
+ details,
587
+ backendMessage,
588
+ validationErrors,
589
+ url: error.url,
590
+ headers: error.headers,
591
+ original: error,
592
+ retryable: this.isRetryable(status),
593
+ timestamp
594
+ };
595
+ }
596
+ extractBackendMessage(body) {
597
+ if (typeof body === "string" && body.trim()) return body;
598
+ if (!body || typeof body !== "object") return;
599
+ const obj = body;
600
+ for (const key of [
601
+ "message",
602
+ "title",
603
+ "detail",
604
+ "error"
605
+ ]) {
606
+ const value = obj[key];
607
+ if (typeof value === "string" && value.trim()) return value;
608
+ }
609
+ }
610
+ extractValidationErrors(body) {
611
+ if (!body || typeof body !== "object") return;
612
+ const errors = body["errors"];
613
+ if (!errors || typeof errors !== "object") return;
614
+ const result = {};
615
+ for (const [key, value] of Object.entries(errors)) if (Array.isArray(value)) result[key] = value.map(String);
616
+ else if (typeof value === "string") result[key] = [value];
617
+ return Object.keys(result).length ? result : void 0;
618
+ }
619
+ defaultMessage(status) {
620
+ switch (status) {
621
+ case HttpStatusCode.BadRequest: return "Bad request";
622
+ case HttpStatusCode.Unauthorized: return "Unauthorized";
623
+ case HttpStatusCode.Forbidden: return "Forbidden";
624
+ case HttpStatusCode.NotFound: return "Not found";
625
+ case HttpStatusCode.Conflict: return "Conflict";
626
+ case HttpStatusCode.UnprocessableEntity: return "Unprocessable entity";
627
+ case HttpStatusCode.InternalServerError: return "Internal server error";
628
+ case null: return "Unknown error";
629
+ default: return `Request failed with status ${status}`;
630
+ }
631
+ }
632
+ isRetryable(status) {
633
+ if (status === HttpStatusCode.RequestTimeout) return true;
634
+ if (status === HttpStatusCode.TooManyRequests) return true;
635
+ if (typeof status === "number" && status >= 500) return true;
636
+ return false;
637
+ }
638
+ normalizeStatus(status) {
639
+ if (status === null || status === void 0 || status === 0 || Number.isNaN(status)) return null;
640
+ return status;
641
+ }
642
+ toHttpParams(query) {
643
+ if (!query) return void 0;
644
+ let params = new HttpParams();
645
+ for (const [key, rawValue] of Object.entries(query)) {
646
+ if (rawValue === null || rawValue === void 0) continue;
647
+ const values = Array.isArray(rawValue) ? rawValue : [rawValue];
648
+ for (const value of values) {
649
+ if (value === null || value === void 0) continue;
650
+ params = params.append(key, String(value));
651
+ }
652
+ }
653
+ return params;
654
+ }
655
+ };
656
+ var MnHttpService = class {
657
+ http = inject(HttpClient);
658
+ baseUrl = inject(API_BASE_URL);
659
+ get(path, query) {
660
+ return firstValueFrom(this.http.get(`${this.baseUrl}${path}`, { params: this.toHttpParams(query) }));
661
+ }
662
+ post(path, body, query) {
663
+ return firstValueFrom(this.http.post(`${this.baseUrl}${path}`, body ?? {}, { params: this.toHttpParams(query) }));
664
+ }
665
+ patch(path, body, query) {
666
+ return firstValueFrom(this.http.patch(`${this.baseUrl}${path}`, body ?? {}, { params: this.toHttpParams(query) }));
667
+ }
668
+ put(path, body, query) {
669
+ return firstValueFrom(this.http.put(`${this.baseUrl}${path}`, body ?? {}, { params: this.toHttpParams(query) }));
670
+ }
671
+ delete(path, query) {
672
+ return firstValueFrom(this.http.delete(`${this.baseUrl}${path}`, { params: this.toHttpParams(query) }));
673
+ }
674
+ toHttpParams(query) {
675
+ if (!query) return void 0;
676
+ let params = new HttpParams();
677
+ for (const [key, rawValue] of Object.entries(query)) {
678
+ if (rawValue === null || rawValue === void 0) continue;
679
+ const values = Array.isArray(rawValue) ? rawValue : [rawValue];
680
+ for (const value of values) {
681
+ if (value === null || value === void 0) continue;
682
+ params = params.append(key, String(value));
683
+ }
684
+ }
685
+ return params;
686
+ }
687
+ };
1196
688
  function lucideIcons(nodes) {
1197
- const icons = {};
1198
- for (const key of Object.keys(nodes)) {
1199
- // `lucide` types attribute values as optional; its generated icon data never omits one.
1200
- icons[key] = { name: toKebabCase(key), node: nodes[key] };
1201
- }
1202
- return icons;
689
+ const icons = {};
690
+ for (const key of Object.keys(nodes)) icons[key] = {
691
+ name: toKebabCase(key),
692
+ node: nodes[key]
693
+ };
694
+ return icons;
1203
695
  }
1204
- /**
1205
- * Converts a PascalCase export name to Lucide's kebab-case icon name.
1206
- * @param name Export name, e.g. `CircleCheck` or `Trash2`.
1207
- * @returns The icon name, e.g. `circle-check` or `trash-2`.
1208
- */
1209
696
  function toKebabCase(name) {
1210
- return name
1211
- .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
1212
- .replace(/([a-zA-Z])(\d)/g, '$1-$2')
1213
- .toLowerCase();
697
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/([a-zA-Z])(\d)/g, "$1-$2").toLowerCase();
1214
698
  }
1215
-
1216
- /**
1217
- * Enable live preview mode. Listens for postMessage events from
1218
- * Mn Web Manager and hot-swaps config/translations at runtime.
1219
- *
1220
- * Call this once in your app's bootstrap (e.g., APP_INITIALIZER or root component).
1221
- *
1222
- * @param configService - The MnConfigService instance
1223
- * @param langService - The MnLanguageService instance
1224
- * @param allowedOrigins - Optional whitelist of allowed origins (security)
1225
- */
1226
699
  function enableMnPreviewMode(configService, langService, allowedOrigins) {
1227
- window.addEventListener('message', async (event) => {
1228
- if (allowedOrigins?.length && !allowedOrigins.includes(event.origin)) {
1229
- return;
1230
- }
1231
- const data = event.data;
1232
- if (!data?.type)
1233
- return;
1234
- switch (data.type) {
1235
- case 'mn-config-update':
1236
- if (data.config) {
1237
- await configService.loadFromObject(data.config);
1238
- }
1239
- break;
1240
- case 'mn-translations-update':
1241
- if (data.translations) {
1242
- for (const [locale, translations] of Object.entries(data.translations)) {
1243
- langService.registerTranslations(locale, translations);
1244
- }
1245
- await langService.setLocale(langService.locale);
1246
- }
1247
- break;
1248
- }
1249
- });
700
+ window.addEventListener("message", async (event) => {
701
+ if (allowedOrigins?.length && !allowedOrigins.includes(event.origin)) return;
702
+ const data = event.data;
703
+ if (!data?.type) return;
704
+ switch (data.type) {
705
+ case "mn-config-update":
706
+ if (data.config) await configService.loadFromObject(data.config);
707
+ break;
708
+ case "mn-translations-update": if (data.translations) {
709
+ for (const [locale, translations] of Object.entries(data.translations)) langService.registerTranslations(locale, translations);
710
+ await langService.setLocale(langService.locale);
711
+ }
712
+ }
713
+ });
1250
714
  }
1251
-
1252
- /**
1253
- * Public API of the `mn-angular-lib/core` entry point: config, context, language, preview, HTTP/CRUD services, shared types and icon helpers.
1254
- *
1255
- * Each entry point is its own module in the published package, so a consumer's bundler
1256
- * splits it into the chunk that uses it instead of loading the whole library at startup.
1257
- * The root `mn-angular-lib` entry re-exports every entry point.
1258
- */
1259
-
1260
- /**
1261
- * Generated bundle index. Do not edit.
1262
- */
1263
-
1264
715
  export { API_BASE_URL, CrudService, MN_INSTANCE_ID, MN_IN_BOTTOM_SHEET, MN_IN_MODAL, MN_SECTION_PATH, MnConfigService, MnHttpService, MnInstanceDirective, MnLanguageService, MnSectionDirective, MnTranslatePipe, enableMnPreviewMode, isTranslatable, lucideIcons, parseConfigText, provideMnComponentConfig, provideMnConfig, provideMnLanguage };
1265
- //# sourceMappingURL=mn-angular-lib-core.mjs.map
716
+
717
+ //# sourceMappingURL=mn-angular-lib-core.mjs.map