From 0ce7d04fd969f235e792388bfbfdb27cf7f55f91 Mon Sep 17 00:00:00 2001 From: Oleg Date: Fri, 31 Jul 2026 13:08:15 +0300 Subject: [PATCH 01/18] added schema --- README.md | 63 +++++++++-- projects/translate/src/__test__/proxy.spec.ts | 16 +-- .../translate/src/__test__/schema.spec.ts | 105 ++++++++++++++++++ projects/translate/src/public_api.ts | 1 + .../translate/src/translate/schema/index.ts | 4 + .../src/translate/schema/infer-schema-type.ts | 17 +++ .../src/translate/schema/schema-builders.ts | 17 +++ .../src/translate/schema/schema.types.ts | 18 +++ .../translate/schema/validate-dictionary.ts | 105 ++++++++++++++++++ .../src/translate/translate.proxy.ts | 8 +- src/app/translate.common.ts | 6 +- src/assets/translations/_.ts | 32 +++--- src/assets/translations/dynamic.ts | 10 +- 13 files changed, 358 insertions(+), 44 deletions(-) create mode 100644 projects/translate/src/__test__/schema.spec.ts create mode 100644 projects/translate/src/translate/schema/index.ts create mode 100644 projects/translate/src/translate/schema/infer-schema-type.ts create mode 100644 projects/translate/src/translate/schema/schema-builders.ts create mode 100644 projects/translate/src/translate/schema/schema.types.ts create mode 100644 projects/translate/src/translate/schema/validate-dictionary.ts diff --git a/README.md b/README.md index 67f8eca..77c16cb 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,10 @@ ### **Breaking changes** +#### (v0.21.10) +- `TranslateProxy` now takes a schema (`typeof yourSchema`) instead of a hand-written `Dictionary` interface — see [Use TranslateProxy](#Use-TranslateProxy). +- added schema-first dictionary definitions (`TranslateSchema`, `String`, `Value`, `Namespace`) and runtime validation (`validateDictionary`, `assertValidDictionary`) — see [Validating dictionaries with a schema](#validating-dictionaries-with-a-schema). + #### (v0.21.0) - upgraded to Angular 17. @@ -146,23 +150,26 @@ export class Component { ### Use TranslateProxy -For typed, autocompleted access to your dictionary keys (instead of passing string keys to `TranslateService`), extend `TranslateProxy` with an interface describing your dictionary shape. +For typed, autocompleted access to your dictionary keys, describe your dictionary shape with `TranslateSchema` and extend `TranslateProxy`. ```typescript import { Injectable } from '@angular/core'; -import { TranslateProxy } from 'simply-translate-angular'; - -interface AppDictionary { - hello_user: string; - namespace: { - hello_user: string; - }; -} +import { Namespace, String, TranslateProxy, TranslateSchema, Value } from 'simply-translate-angular'; + +const appSchema = TranslateSchema({ + hello_user: String(), + namespace: Namespace({ + hello_user: String(), + }), + with_plural_params: Value() +}); @Injectable() -export class AppTranslate extends TranslateProxy {} +export class AppTranslate extends TranslateProxy {} ``` +`TranslateProxy` takes the schema itself as its type parameter — the dictionary type is inferred from it via `InferTranslateSchemaType`. See [Validating dictionaries with a schema](#validating-dictionaries-with-a-schema) for the full builder API (`String`, `Value`, `Namespace`) and for validating your JSON dictionaries against the same schema at runtime. + Inject it like any other service and read keys off `object`. Every leaf key is callable (mirrors `translate`), and carries `.Signal()` / `.$()` companions that mirror `translateSignal` / `translateObservable`: ```typescript @@ -202,6 +209,42 @@ this.helloSignal = translate.object.hello_user.Signal({ user: 'Oleg' }); **Restriction:** `Signal` and `$` are reserved property names — `TranslateProxy` uses them on every key to expose the reactive accessors above. A dictionary key literally named `Signal` or `$` (at any nesting level) will be shadowed by these accessors and become unreachable through `object`. Avoid naming dictionary keys `Signal` or `$`. +### Validating dictionaries with a schema + +`TranslateSchema` describes a dictionary once and gives you both the static type (via `InferTranslateSchemaType`, used internally by `TranslateProxy`) and a runtime validator for your actual JSON dictionary files — so a language file that's missing a key, has an extra key, or has the wrong shape fails loudly instead of silently falling back at runtime. + +Build a schema with three node builders: + +- `String()` — a leaf that must be a plain string. +- `Value()` — a leaf that may be a string, a `DictionaryEntry` (`{ value, plural?, cases?, description? }`), or a nested dictionary. +- `Namespace({...})` — a nested dictionary with a fixed, known shape. + +```typescript +import { Namespace, String, TranslateSchema, Value } from 'simply-translate-angular'; + +export const appSchema = TranslateSchema({ + welcome_to_app: String(), + goodbye_world: Value(), // string, or { value, description } etc. + namespace: Namespace({ + hello_user: Value(), + }), +}); + +export type AppDictionary = InferTranslateSchemaType; +``` + +Validate a loaded dictionary (e.g. a parsed JSON file) against the schema: + +```typescript +import { assertValidDictionary, validateDictionary } from 'simply-translate-angular'; + +// returns a list of { path, message } issues, empty when valid +const errors = validateDictionary(appSchema, parsedJson); + +// or throw with a formatted message if invalid — handy in a startup check or a build/CI script +assertValidDictionary(appSchema, parsedJson, 'en-US.json'); +``` + ### Load dictionaries #### Root diff --git a/projects/translate/src/__test__/proxy.spec.ts b/projects/translate/src/__test__/proxy.spec.ts index 6415abf..5f7e453 100644 --- a/projects/translate/src/__test__/proxy.spec.ts +++ b/projects/translate/src/__test__/proxy.spec.ts @@ -3,18 +3,18 @@ import { TestBed } from '@angular/core/testing'; import { BehaviorSubject } from 'rxjs'; import { TranslateRootService } from '../public_api'; import { TranslateModule } from '../simply-translate.module'; +import { Namespace, String as Str, TranslateSchema } from '../translate/schema'; import { TranslateProxy } from '../translate/translate.proxy'; -interface TestDict { - [key: string]: any; - hello_user: string; - namespace: { - hello_user: string; - }; -} +const testSchema = TranslateSchema({ + hello_user: Str(), + namespace: Namespace({ + hello_user: Str(), + }), +}); @Injectable() -class TestTranslateProxy extends TranslateProxy {} +class TestTranslateProxy extends TranslateProxy {} const lang = 'lang'; const newLang = 'new'; diff --git a/projects/translate/src/__test__/schema.spec.ts b/projects/translate/src/__test__/schema.spec.ts new file mode 100644 index 0000000..f6a6e83 --- /dev/null +++ b/projects/translate/src/__test__/schema.spec.ts @@ -0,0 +1,105 @@ +import { Dictionary } from 'simply-translate'; +import { InferTranslateSchemaType, Namespace, String, TranslateSchema, Value, validateDictionary } from '../translate/schema'; + +const testSchema = TranslateSchema({ + welcome_to_app: String(), + hello_user: String(), + + hello_world: Value(), + goodbye_world: Value(), + + namespace: Namespace({ + value: String(), + hello_user: Value(), + user: Value(), + }), + + i_have_been_here_count: Value(), + day_since_new_year: Value(), + for_fallback: Value(), + same_key: Value(), +}); + +type TestDictionary = InferTranslateSchemaType; + +// Compile-time check: the inferred type must satisfy `Dictionary`, just like a hand-written interface. +function expectsDictionary(_dictionary: Dictionary): void {} +expectsDictionary({} as TestDictionary); + +const validDictionary = { + welcome_to_app: 'Welcome to Translation Testing Application', + hello_user: 'Hello ${user}!', + + hello_world: 'Hello World', + goodbye_world: { + value: 'Goodbye World', + description: 'When you want to say goodbye to the world', + }, + + namespace: { + value: 'Namespace translated', + hello_user: 'Hello again, ${user}!', + user: 'User', + }, + + i_have_been_here_count: { + value: '${count} ${days}', + cases: { count: [['!!', 'value']] }, + plural: { count: [['=0', 'value']], days: [['=0', 'value']] }, + }, + day_since_new_year: { value: '${days}', plural: { days: [['=1', 'value']] } }, + for_fallback: 'Fallback', + same_key: 'Same in the Root', +}; + +describe('schema', () => { + it('accepts a dictionary that matches the schema', () => { + expect(validateDictionary(testSchema, validDictionary)).toEqual([]); + }); + + it('reports a missing key', () => { + const { welcome_to_app, ...rest } = validDictionary; + expect(validateDictionary(testSchema, rest)).toEqual([{ path: ['welcome_to_app'], message: 'missing key' }]); + }); + + it('reports an unexpected key not declared in the schema', () => { + const errors = validateDictionary(testSchema, { ...validDictionary, only_root_key: 'Only in the Root' }); + expect(errors).toEqual([{ path: ['only_root_key'], message: 'unexpected key not declared in schema' }]); + }); + + it('reports a wrong type on a strict string leaf', () => { + const errors = validateDictionary(testSchema, { ...validDictionary, welcome_to_app: 42 }); + expect(errors).toEqual([{ path: ['welcome_to_app'], message: 'expected string, got number' }]); + }); + + it('reports a wrong type on a value leaf', () => { + const errors = validateDictionary(testSchema, { ...validDictionary, hello_world: 42 }); + expect(errors).toEqual([{ path: ['hello_world'], message: 'expected a string, entry, or nested dictionary, got number' }]); + }); + + it('validates entry shape on a value leaf (value/description/plural/cases)', () => { + const errors = validateDictionary(testSchema, { + ...validDictionary, + goodbye_world: { value: 42, description: 7, plural: 'nope', cases: 'nope' }, + }); + expect(errors).toEqual([ + { path: ['goodbye_world', 'value'], message: 'expected string, got number' }, + { path: ['goodbye_world', 'plural'], message: 'expected a plurals map, got string' }, + { path: ['goodbye_world', 'cases'], message: 'expected a cases map, got string' }, + { path: ['goodbye_world', 'description'], message: 'expected string, got number' }, + ]); + }); + + it('recurses into a namespace and reports nested errors with a full path', () => { + const errors = validateDictionary(testSchema, { + ...validDictionary, + namespace: { value: 'Namespace translated', hello_user: 'Hello again!' }, + }); + expect(errors).toEqual([{ path: ['namespace', 'user'], message: 'missing key' }]); + }); + + it('rejects a non-object dictionary', () => { + expect(validateDictionary(testSchema, null)).toEqual([{ path: [], message: 'expected a dictionary object, got null' }]); + expect(validateDictionary(testSchema, 'nope')).toEqual([{ path: [], message: 'expected a dictionary object, got string' }]); + }); +}); diff --git a/projects/translate/src/public_api.ts b/projects/translate/src/public_api.ts index 3dbd2b7..529a6e3 100644 --- a/projects/translate/src/public_api.ts +++ b/projects/translate/src/public_api.ts @@ -3,6 +3,7 @@ export * from './translate/translate.pipe'; export * from './translate/translate.resolver'; export * from './translate/translate.service'; export * from './translate/translate.proxy'; +export * from './translate/schema'; export * from './simply-translate.module'; export { TranslateChildConfig } from './translate/translate.service'; export { diff --git a/projects/translate/src/translate/schema/index.ts b/projects/translate/src/translate/schema/index.ts new file mode 100644 index 0000000..891c1aa --- /dev/null +++ b/projects/translate/src/translate/schema/index.ts @@ -0,0 +1,4 @@ +export * from './schema.types'; +export * from './schema-builders'; +export * from './infer-schema-type'; +export * from './validate-dictionary'; diff --git a/projects/translate/src/translate/schema/infer-schema-type.ts b/projects/translate/src/translate/schema/infer-schema-type.ts new file mode 100644 index 0000000..3407fd9 --- /dev/null +++ b/projects/translate/src/translate/schema/infer-schema-type.ts @@ -0,0 +1,17 @@ +import { Dictionary } from 'simply-translate'; +import { DictionaryValue } from '../translate.proxy'; +import { NamespaceNode, SchemaNode, SchemaShape, TranslateSchemaNode } from './schema.types'; + +type InferNode = Node extends { kind: 'string' } + ? string + : Node extends NamespaceNode + ? DictionaryValue> + : Node extends { kind: 'value' } + ? DictionaryValue + : never; + +type InferShape = { + [K in keyof Shape]: InferNode; +}; + +export type InferTranslateSchemaType = InferShape & Dictionary; diff --git a/projects/translate/src/translate/schema/schema-builders.ts b/projects/translate/src/translate/schema/schema-builders.ts new file mode 100644 index 0000000..577f8b2 --- /dev/null +++ b/projects/translate/src/translate/schema/schema-builders.ts @@ -0,0 +1,17 @@ +import { NamespaceNode, SchemaShape, StringNode, TranslateSchemaNode, ValueNode } from './schema.types'; + +export function String(): StringNode { + return { kind: 'string' }; +} + +export function Value(): ValueNode { + return { kind: 'value' }; +} + +export function Namespace(shape: Shape): NamespaceNode { + return { kind: 'namespace', shape }; +} + +export function TranslateSchema(shape: Shape): TranslateSchemaNode { + return { kind: 'namespace', shape }; +} diff --git a/projects/translate/src/translate/schema/schema.types.ts b/projects/translate/src/translate/schema/schema.types.ts new file mode 100644 index 0000000..e113cb1 --- /dev/null +++ b/projects/translate/src/translate/schema/schema.types.ts @@ -0,0 +1,18 @@ +export interface StringNode { + readonly kind: 'string'; +} + +export interface ValueNode { + readonly kind: 'value'; +} + +export interface NamespaceNode { + readonly kind: 'namespace'; + readonly shape: Shape; +} + +export type SchemaNode = StringNode | ValueNode | NamespaceNode; + +export type SchemaShape = Record; + +export type TranslateSchemaNode = NamespaceNode; diff --git a/projects/translate/src/translate/schema/validate-dictionary.ts b/projects/translate/src/translate/schema/validate-dictionary.ts new file mode 100644 index 0000000..aa696f2 --- /dev/null +++ b/projects/translate/src/translate/schema/validate-dictionary.ts @@ -0,0 +1,105 @@ +import { SchemaNode, SchemaShape, TranslateSchemaNode } from './schema.types'; + +export interface SchemaValidationError { + path: string[]; + message: string; +} + +export function validateDictionary(schema: TranslateSchemaNode, data: unknown): SchemaValidationError[] { + const errors: SchemaValidationError[] = []; + if (!isPlainObject(data)) { + return [{ path: [], message: `expected a dictionary object, got ${describe(data)}` }]; + } + validateShape(schema.shape, data, [], errors); + return errors; +} + +export function formatSchemaErrors(errors: SchemaValidationError[]): string { + return errors.map((e) => `${e.path.join('.') || ''}: ${e.message}`).join('\n'); +} + +export function assertValidDictionary(schema: TranslateSchemaNode, data: unknown, label?: string): void { + const errors = validateDictionary(schema, data); + if (errors.length) { + const prefix = label ? `Invalid dictionary "${label}":\n` : 'Invalid dictionary:\n'; + throw new Error(prefix + formatSchemaErrors(errors)); + } +} + +function validateShape(shape: SchemaShape, obj: Record, path: string[], errors: SchemaValidationError[]): void { + for (const key of Object.keys(shape)) { + const childPath = [...path, key]; + if (!(key in obj)) { + errors.push({ path: childPath, message: 'missing key' }); + continue; + } + validateNode(shape[key], obj[key], childPath, errors); + } + for (const key of Object.keys(obj)) { + if (!(key in shape)) { + errors.push({ path: [...path, key], message: 'unexpected key not declared in schema' }); + } + } +} + +function validateNode(node: SchemaNode, value: unknown, path: string[], errors: SchemaValidationError[]): void { + switch (node.kind) { + case 'string': + if (typeof value !== 'string') { + errors.push({ path, message: `expected string, got ${describe(value)}` }); + } + return; + case 'namespace': + if (!isPlainObject(value)) { + errors.push({ path, message: `expected a nested dictionary, got ${describe(value)}` }); + return; + } + validateShape(node.shape, value, path, errors); + return; + case 'value': + validateDictionaryValue(value, path, errors); + return; + } +} + +function validateDictionaryValue(value: unknown, path: string[], errors: SchemaValidationError[]): void { + if (typeof value === 'string') { + return; + } + if (isPlainObject(value)) { + if ('value' in value) { + validateDictionaryEntry(value, path, errors); + return; + } + for (const [key, child] of Object.entries(value)) { + validateDictionaryValue(child, [...path, key], errors); + } + return; + } + errors.push({ path, message: `expected a string, entry, or nested dictionary, got ${describe(value)}` }); +} + +function validateDictionaryEntry(entry: Record, path: string[], errors: SchemaValidationError[]): void { + if (typeof entry['value'] !== 'string') { + errors.push({ path: [...path, 'value'], message: `expected string, got ${describe(entry['value'])}` }); + } + if (entry['plural'] !== undefined && !isPlainObject(entry['plural'])) { + errors.push({ path: [...path, 'plural'], message: `expected a plurals map, got ${describe(entry['plural'])}` }); + } + if (entry['cases'] !== undefined && !isPlainObject(entry['cases'])) { + errors.push({ path: [...path, 'cases'], message: `expected a cases map, got ${describe(entry['cases'])}` }); + } + if (entry['description'] !== undefined && typeof entry['description'] !== 'string') { + errors.push({ path: [...path, 'description'], message: `expected string, got ${describe(entry['description'])}` }); + } +} + +function isPlainObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function describe(value: unknown): string { + if (value === null) return 'null'; + if (Array.isArray(value)) return 'array'; + return typeof value; +} diff --git a/projects/translate/src/translate/translate.proxy.ts b/projects/translate/src/translate/translate.proxy.ts index 8957907..705daed 100644 --- a/projects/translate/src/translate/translate.proxy.ts +++ b/projects/translate/src/translate/translate.proxy.ts @@ -1,6 +1,8 @@ import { inject, Injectable, Signal } from '@angular/core'; import { Observable } from 'rxjs'; import { Dictionary, DictionaryEntry, TranslateDynamicProps } from 'simply-translate'; +import { InferTranslateSchemaType } from './schema/infer-schema-type'; +import { TranslateSchemaNode } from './schema/schema.types'; import { TranslateService } from './translate.service'; type TranslationFunction = { @@ -16,13 +18,13 @@ export type ProxyDictionary = { export type DictionaryValue = T extends string ? string : T extends Dictionary ? T : DictionaryEntry; @Injectable() -export abstract class TranslateProxy { +export abstract class TranslateProxy { private _cache: any = {}; readonly service = inject(TranslateService); - readonly object: ProxyDictionary = this.createLazyProxy([], this._cache); + readonly object: ProxyDictionary> = this.createLazyProxy([], this._cache); - private createLazyProxy(fullPath: string[], cache: any): any { + private createLazyProxy(fullPath: string[], cache: any): any { if (cache.$$proxy) { return cache.$$proxy; } diff --git a/src/app/translate.common.ts b/src/app/translate.common.ts index a20ce38..a43ce41 100644 --- a/src/app/translate.common.ts +++ b/src/app/translate.common.ts @@ -1,6 +1,6 @@ import { Injectable } from '@angular/core'; import { TranslateProxy } from '../../projects/translate/src/translate/translate.proxy'; -import { TestDictionary } from 'src/assets/translations/_'; - +import type { testDictionary } from 'src/assets/translations/_'; + @Injectable({ providedIn: 'root' }) -export class TranslateProxyCommon extends TranslateProxy {} +export class TranslateProxyCommon extends TranslateProxy {} diff --git a/src/assets/translations/_.ts b/src/assets/translations/_.ts index 96b89c7..e7379aa 100644 --- a/src/assets/translations/_.ts +++ b/src/assets/translations/_.ts @@ -1,23 +1,23 @@ -import { Dictionary, DictionaryValue } from 'projects/translate/src/public_api'; +import { Namespace, String, TranslateSchema, Value } from 'projects/translate/src/public_api'; -export interface TestDictionary extends Dictionary { - welcome_to_app: DictionaryValue; - hello_user: DictionaryValue; +export const testDictionary = TranslateSchema({ + welcome_to_app: String(), + hello_user: String(), - hello_world: DictionaryValue; - goodbye_world: DictionaryValue; + hello_world: String(), + goodbye_world: String(), - namespace: DictionaryValue<{ - value: string; - hello_user: DictionaryValue; - user: DictionaryValue; - }>; + namespace: Namespace({ + value: String(), + hello_user: Value(), + user: Value(), + }), - i_have_been_here_count: DictionaryValue; + i_have_been_here_count: Value(), - day_since_new_year: DictionaryValue; + day_since_new_year: Value(), - for_fallback: DictionaryValue; + for_fallback: Value(), - same_key: DictionaryValue; -} + same_key: Value(), +}); diff --git a/src/assets/translations/dynamic.ts b/src/assets/translations/dynamic.ts index ec3d14e..e63f931 100644 --- a/src/assets/translations/dynamic.ts +++ b/src/assets/translations/dynamic.ts @@ -1,6 +1,8 @@ import { Dictionary, DictionaryEntry } from 'simply-translate'; -export interface TestDictionary extends Dictionary { - hello_user_dynamic: DictionaryEntry; - same_dyn: DictionaryEntry; -} +import { TranslateSchema, Value } from 'projects/translate/src/public_api'; + +export const testDictionary = TranslateSchema({ + hello_user_dynamic: Value(), + same_dyn: Value(), +}); From 1c87b926e927752e17c564ab7c30bb02e2ebb5ae Mon Sep 17 00:00:00 2001 From: Oleg Date: Fri, 31 Jul 2026 18:09:49 +0300 Subject: [PATCH 02/18] update schema builder --- README.md | 32 ++++++++--- angular.json | 1 - projects/translate/package.json | 2 +- .../translate/src/__test__/schema.spec.ts | 20 +++++++ .../translate/schema/validate-dictionary.ts | 53 +++++++++++++++---- .../src/translate/translate.proxy.ts | 3 +- src/app/translate.common.ts | 4 +- src/assets/translations/_.ts | 2 + 8 files changed, 94 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 77c16cb..f97f62d 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ ### **Breaking changes** #### (v0.21.10) -- `TranslateProxy` now takes a schema (`typeof yourSchema`) instead of a hand-written `Dictionary` interface — see [Use TranslateProxy](#Use-TranslateProxy). +- `TranslateProxy` now takes a schema type (`typeof yourSchema`) instead of a hand-written `Dictionary` interface — see [Use TranslateProxy](#Use-TranslateProxy). - added schema-first dictionary definitions (`TranslateSchema`, `String`, `Value`, `Namespace`) and runtime validation (`validateDictionary`, `assertValidDictionary`) — see [Validating dictionaries with a schema](#validating-dictionaries-with-a-schema). #### (v0.21.0) @@ -153,22 +153,31 @@ export class Component { For typed, autocompleted access to your dictionary keys, describe your dictionary shape with `TranslateSchema` and extend `TranslateProxy`. ```typescript -import { Injectable } from '@angular/core'; -import { Namespace, String, TranslateProxy, TranslateSchema, Value } from 'simply-translate-angular'; +// app.schema.ts +import { Namespace, String, TranslateSchema, Value } from 'simply-translate-angular'; -const appSchema = TranslateSchema({ +export const appSchema = TranslateSchema({ hello_user: String(), namespace: Namespace({ hello_user: String(), }), - with_plural_params: Value() + with_plural_params: Value(), }); +export type AppSchema = typeof appSchema; +``` + +```typescript +// app.translate.ts +import { Injectable } from '@angular/core'; +import { TranslateProxy } from 'simply-translate-angular'; +import type { AppSchema } from './app.schema'; + @Injectable() -export class AppTranslate extends TranslateProxy {} +export class AppTranslate extends TranslateProxy {} ``` -`TranslateProxy` takes the schema itself as its type parameter — the dictionary type is inferred from it via `InferTranslateSchemaType`. See [Validating dictionaries with a schema](#validating-dictionaries-with-a-schema) for the full builder API (`String`, `Value`, `Namespace`) and for validating your JSON dictionaries against the same schema at runtime. +`TranslateProxy` takes the schema itself as its type parameter — the dictionary type is inferred from it via `InferTranslateSchemaType`. `TranslateProxy` only ever needs `AppSchema`'s **type**, never `appSchema`'s runtime value, so import it with `import type`: TypeScript erases `import type` entirely at compile time, keeping the schema-building code (and everything it imports) out of your app's bundle unless something else in it also needs the actual schema object at runtime — e.g. to call `validateDictionary`. See [Validating dictionaries with a schema](#validating-dictionaries-with-a-schema) for the full builder API (`String`, `Value`, `Namespace`) and for validating your JSON dictionaries against the same schema at runtime. Inject it like any other service and read keys off `object`. Every leaf key is callable (mirrors `translate`), and carries `.Signal()` / `.$()` companions that mirror `translateSignal` / `translateObservable`: @@ -245,6 +254,15 @@ const errors = validateDictionary(appSchema, parsedJson); assertValidDictionary(appSchema, parsedJson, 'en-US.json'); ``` +Some keys are legitimately allowed to diverge between the schema and a given language file — a translation that isn't ready yet, or a root-only fallback key. Rather than silently ignoring every missing/extra key, list the exceptions explicitly (with a reason) via `allowedMissing` / `allowedOrphans`, keyed by the same dotted path shown in `SchemaValidationError.path`: + +```typescript +const errors = validateDictionary(appSchema, parsedJson, { + allowedMissing: { 'namespace.hello_user': 'translation pending, falls back to en-US' }, + allowedOrphans: { only_root_key: 'root-only fallback key, intentionally absent from other languages' }, +}); +``` + ### Load dictionaries #### Root diff --git a/angular.json b/angular.json index b15cd88..6da2c2e 100644 --- a/angular.json +++ b/angular.json @@ -48,7 +48,6 @@ "optimization": true, "outputHashing": "all", "sourceMap": false, - "extractCss": true, "namedChunks": false, "extractLicenses": true, "vendorChunk": false, diff --git a/projects/translate/package.json b/projects/translate/package.json index f3b106d..291e2eb 100644 --- a/projects/translate/package.json +++ b/projects/translate/package.json @@ -1,6 +1,6 @@ { "name": "simply-translate-angular", - "version": "0.21.7", + "version": "0.21.10", "type": "module", "dependencies": { "tslib": "^2.4.0", diff --git a/projects/translate/src/__test__/schema.spec.ts b/projects/translate/src/__test__/schema.spec.ts index f6a6e83..67b8151 100644 --- a/projects/translate/src/__test__/schema.spec.ts +++ b/projects/translate/src/__test__/schema.spec.ts @@ -67,6 +67,26 @@ describe('schema', () => { expect(errors).toEqual([{ path: ['only_root_key'], message: 'unexpected key not declared in schema' }]); }); + it('does not report a missing key allowed via allowedMissing', () => { + const { welcome_to_app, ...rest } = validDictionary; + expect(validateDictionary(testSchema, rest, { allowedMissing: { welcome_to_app: 'not translated yet' } })).toEqual([]); + }); + + it('does not report an orphan key allowed via allowedOrphans', () => { + const errors = validateDictionary(testSchema, { ...validDictionary, only_root_key: 'Only in the Root' }, { allowedOrphans: { only_root_key: true } }); + expect(errors).toEqual([]); + }); + + it('matches allowedMissing/allowedOrphans on the full dotted path, not just the leaf key', () => { + const { namespace, ...rest } = validDictionary; + const errors = validateDictionary( + testSchema, + { ...rest, namespace: { value: namespace.value, hello_user: namespace.hello_user } }, + { allowedMissing: { user: true } }, + ); + expect(errors).toEqual([{ path: ['namespace', 'user'], message: 'missing key' }]); + }); + it('reports a wrong type on a strict string leaf', () => { const errors = validateDictionary(testSchema, { ...validDictionary, welcome_to_app: 42 }); expect(errors).toEqual([{ path: ['welcome_to_app'], message: 'expected string, got number' }]); diff --git a/projects/translate/src/translate/schema/validate-dictionary.ts b/projects/translate/src/translate/schema/validate-dictionary.ts index aa696f2..baf3a81 100644 --- a/projects/translate/src/translate/schema/validate-dictionary.ts +++ b/projects/translate/src/translate/schema/validate-dictionary.ts @@ -5,12 +5,24 @@ export interface SchemaValidationError { message: string; } -export function validateDictionary(schema: TranslateSchemaNode, data: unknown): SchemaValidationError[] { +/** + * Dotted path (matching `SchemaValidationError.path.join('.')`) -> `true`, or a string documenting why it's allowed. + */ +export type SchemaAllowanceMap = Record; + +export interface ValidateDictionaryOptions { + /** Schema keys allowed to be missing from the dictionary, e.g. a translation not filled in yet for this language. */ + allowedMissing?: SchemaAllowanceMap; + /** Dictionary keys allowed to be absent from the schema, e.g. a root-only fallback key. */ + allowedOrphans?: SchemaAllowanceMap; +} + +export function validateDictionary(schema: TranslateSchemaNode, data: unknown, options?: ValidateDictionaryOptions): SchemaValidationError[] { const errors: SchemaValidationError[] = []; if (!isPlainObject(data)) { return [{ path: [], message: `expected a dictionary object, got ${describe(data)}` }]; } - validateShape(schema.shape, data, [], errors); + validateShape(schema.shape, data, [], errors, options ?? {}); return errors; } @@ -18,31 +30,52 @@ export function formatSchemaErrors(errors: SchemaValidationError[]): string { return errors.map((e) => `${e.path.join('.') || ''}: ${e.message}`).join('\n'); } -export function assertValidDictionary(schema: TranslateSchemaNode, data: unknown, label?: string): void { - const errors = validateDictionary(schema, data); +export function assertValidDictionary(schema: TranslateSchemaNode, data: unknown, label?: string, options?: ValidateDictionaryOptions): void { + const errors = validateDictionary(schema, data, options); if (errors.length) { const prefix = label ? `Invalid dictionary "${label}":\n` : 'Invalid dictionary:\n'; throw new Error(prefix + formatSchemaErrors(errors)); } } -function validateShape(shape: SchemaShape, obj: Record, path: string[], errors: SchemaValidationError[]): void { +function validateShape( + shape: SchemaShape, + obj: Record, + path: string[], + errors: SchemaValidationError[], + options: ValidateDictionaryOptions, +): void { for (const key of Object.keys(shape)) { const childPath = [...path, key]; if (!(key in obj)) { - errors.push({ path: childPath, message: 'missing key' }); + if (!isAllowed(options.allowedMissing, childPath)) { + errors.push({ path: childPath, message: 'missing key' }); + } continue; } - validateNode(shape[key], obj[key], childPath, errors); + validateNode(shape[key], obj[key], childPath, errors, options); } for (const key of Object.keys(obj)) { if (!(key in shape)) { - errors.push({ path: [...path, key], message: 'unexpected key not declared in schema' }); + const childPath = [...path, key]; + if (!isAllowed(options.allowedOrphans, childPath)) { + errors.push({ path: childPath, message: 'unexpected key not declared in schema' }); + } } } } -function validateNode(node: SchemaNode, value: unknown, path: string[], errors: SchemaValidationError[]): void { +function isAllowed(allowances: SchemaAllowanceMap | undefined, path: string[]): boolean { + return allowances !== undefined && path.join('.') in allowances; +} + +function validateNode( + node: SchemaNode, + value: unknown, + path: string[], + errors: SchemaValidationError[], + options: ValidateDictionaryOptions, +): void { switch (node.kind) { case 'string': if (typeof value !== 'string') { @@ -54,7 +87,7 @@ function validateNode(node: SchemaNode, value: unknown, path: string[], errors: errors.push({ path, message: `expected a nested dictionary, got ${describe(value)}` }); return; } - validateShape(node.shape, value, path, errors); + validateShape(node.shape, value, path, errors, options); return; case 'value': validateDictionaryValue(value, path, errors); diff --git a/projects/translate/src/translate/translate.proxy.ts b/projects/translate/src/translate/translate.proxy.ts index 705daed..de823af 100644 --- a/projects/translate/src/translate/translate.proxy.ts +++ b/projects/translate/src/translate/translate.proxy.ts @@ -1,9 +1,8 @@ import { inject, Injectable, Signal } from '@angular/core'; import { Observable } from 'rxjs'; import { Dictionary, DictionaryEntry, TranslateDynamicProps } from 'simply-translate'; -import { InferTranslateSchemaType } from './schema/infer-schema-type'; -import { TranslateSchemaNode } from './schema/schema.types'; import { TranslateService } from './translate.service'; +import type { TranslateSchemaNode, InferTranslateSchemaType } from './schema'; type TranslationFunction = { (dynamicProps?: TranslateDynamicProps): string; diff --git a/src/app/translate.common.ts b/src/app/translate.common.ts index a43ce41..96d70b0 100644 --- a/src/app/translate.common.ts +++ b/src/app/translate.common.ts @@ -1,6 +1,6 @@ import { Injectable } from '@angular/core'; import { TranslateProxy } from '../../projects/translate/src/translate/translate.proxy'; -import type { testDictionary } from 'src/assets/translations/_'; +import type { TestDictionary } from 'src/assets/translations/_'; @Injectable({ providedIn: 'root' }) -export class TranslateProxyCommon extends TranslateProxy {} +export class TranslateProxyCommon extends TranslateProxy {} diff --git a/src/assets/translations/_.ts b/src/assets/translations/_.ts index e7379aa..b75ad69 100644 --- a/src/assets/translations/_.ts +++ b/src/assets/translations/_.ts @@ -21,3 +21,5 @@ export const testDictionary = TranslateSchema({ same_key: Value(), }); + +export type TestDictionary = typeof testDictionary; From e93a29619bcbbb95850cdb6824ed761f5bfe3145 Mon Sep 17 00:00:00 2001 From: Oleg Date: Fri, 31 Jul 2026 20:37:12 +0300 Subject: [PATCH 03/18] add params --- projects/translate/.npmrc | 2 +- projects/translate/src/__test__/proxy.spec.ts | 45 ++++++++++++++++--- .../src/translate/schema/schema-builders.ts | 21 ++++++--- .../src/translate/schema/schema.types.ts | 19 ++++++-- .../src/translate/translate.proxy.ts | 29 ++++++++---- src/app/app.module.ts | 1 - src/app/try-proxy/try-proxy.component.ts | 24 +++++++--- src/assets/translations/_.ts | 8 ++-- src/assets/translations/en-US.json | 4 +- 9 files changed, 113 insertions(+), 40 deletions(-) diff --git a/projects/translate/.npmrc b/projects/translate/.npmrc index 73ed4c3..593f2f0 100644 --- a/projects/translate/.npmrc +++ b/projects/translate/.npmrc @@ -1 +1 @@ -//registry.npmjs.org/:_authToken= +//registry.npmjs.org/:_authToken=REDACTED_REVOKED_TOKEN diff --git a/projects/translate/src/__test__/proxy.spec.ts b/projects/translate/src/__test__/proxy.spec.ts index 5f7e453..de75a56 100644 --- a/projects/translate/src/__test__/proxy.spec.ts +++ b/projects/translate/src/__test__/proxy.spec.ts @@ -7,9 +7,11 @@ import { Namespace, String as Str, TranslateSchema } from '../translate/schema'; import { TranslateProxy } from '../translate/translate.proxy'; const testSchema = TranslateSchema({ - hello_user: Str(), + hello_user: Str<{ user: string }>(), + strict_user: Str<{ user: string }>(), + no_params: Str(), namespace: Namespace({ - hello_user: Str(), + hello_user: Str<{ user: string }>(), }), }); @@ -21,10 +23,14 @@ const newLang = 'new'; const dic = { [lang]: { hello_user: 'Hello ${user}', + strict_user: 'Strict ${user}', + no_params: 'No params needed', namespace: { hello_user: 'NS Hello ${user}' }, }, [newLang]: { hello_user: 'Hello New ${user}', + strict_user: 'Strict New ${user}', + no_params: 'No params needed (new)', namespace: { hello_user: 'NS Hello New ${user}' }, }, }; @@ -63,14 +69,14 @@ describe('TranslateProxy', () => { }); it('caches the observable returned by $()', () => { - const obs1 = proxy.object.hello_user.$(); - const obs2 = proxy.object.hello_user.$(); + const obs1 = proxy.object.no_params.$(); + const obs2 = proxy.object.no_params.$(); expect(obs1).toBe(obs2); }); it('caches the signal returned by Signal()', () => { - const sig1 = proxy.object.hello_user.Signal(); - const sig2 = proxy.object.hello_user.Signal(); + const sig1 = proxy.object.no_params.Signal(); + const sig2 = proxy.object.no_params.Signal(); expect(sig1).toBe(sig2); }); @@ -180,4 +186,31 @@ describe('TranslateProxy', () => { it('does not look like a thenable', () => { expect((proxy.object.hello_user as any).then).toBeUndefined(); }); + + it('narrows the call signature, .Signal(), and .$() to the params declared on the schema leaf', () => { + expect(proxy.object.strict_user({ user: 'Oleg' })).toBe('Strict Oleg'); + expect(proxy.object.strict_user.Signal({ user: 'Oleg' })()).toBe('Strict Oleg'); + expect(proxy.object.strict_user).toBeTruthy(); + + // @ts-expect-error strict_user requires { user: string } — a number isn't assignable to it + proxy.object.strict_user({ user: 42 }); + // @ts-expect-error same shape is enforced on .Signal(...) + proxy.object.strict_user.Signal({ user: 42 }); + // @ts-expect-error same shape is enforced on .$(...) + proxy.object.strict_user.$({ user: 42 }); + // @ts-expect-error { nope: true } doesn't satisfy the required { user: string } shape + proxy.object.strict_user({ nope: true }); + // @ts-expect-error omitting the argument entirely is not allowed once TParams is declared + proxy.object.strict_user(); + }); + + it('a leaf declared with a bare Str()/Value() takes no dynamic props at all', () => { + expect(proxy.object.no_params()).toBe('No params needed'); + expect(proxy.object.no_params.Signal()()).toBe('No params needed'); + + // @ts-expect-error no_params has no declared TParams, so it must not accept an argument + proxy.object.no_params({ user: 'Oleg' }); + // @ts-expect-error same restriction applies to .Signal(...) + proxy.object.no_params.Signal({ user: 'Oleg' }); + }); }); diff --git a/projects/translate/src/translate/schema/schema-builders.ts b/projects/translate/src/translate/schema/schema-builders.ts index 577f8b2..35a4163 100644 --- a/projects/translate/src/translate/schema/schema-builders.ts +++ b/projects/translate/src/translate/schema/schema-builders.ts @@ -1,15 +1,24 @@ import { NamespaceNode, SchemaShape, StringNode, TranslateSchemaNode, ValueNode } from './schema.types'; -export function String(): StringNode { - return { kind: 'string' }; +// Overloaded rather than a single `` signature: when this is called bare, as an +// argument inside `Namespace({...})`/`TranslateSchema({...})`, TypeScript uses that call's expected +// contextual type (`SchemaNode`) to help infer TParams — which silently overrides a *default* type +// parameter with whatever `SchemaNode`'s own default is, discarding `undefined`. A non-generic overload +// for the zero-argument call has no generic parameter for that contextual type to hijack. +export function String(options?: { description?: string }): StringNode; +export function String(options?: { description?: string }): StringNode; +export function String(options?: { description?: string }): StringNode { + return { kind: 'string', description: options?.description, params: (_: TParams) => {} }; } -export function Value(): ValueNode { - return { kind: 'value' }; +export function Value(options?: { description?: string }): ValueNode; +export function Value(options?: { description?: string }): ValueNode; +export function Value(options?: { description?: string }): ValueNode { + return { kind: 'value', description: options?.description, params: (_: TParams) => {} }; } -export function Namespace(shape: Shape): NamespaceNode { - return { kind: 'namespace', shape }; +export function Namespace(shape: Shape, options?: { description?: string }): NamespaceNode { + return { kind: 'namespace', shape, description: options?.description }; } export function TranslateSchema(shape: Shape): TranslateSchemaNode { diff --git a/projects/translate/src/translate/schema/schema.types.ts b/projects/translate/src/translate/schema/schema.types.ts index e113cb1..8c6de83 100644 --- a/projects/translate/src/translate/schema/schema.types.ts +++ b/projects/translate/src/translate/schema/schema.types.ts @@ -1,17 +1,28 @@ -export interface StringNode { +export interface BaseNode { + readonly kind: 'string' | 'value' | 'namespace'; + readonly description?: string; + /** Never actually called — a phantom marker so `TParams` can be recovered later via `extends BaseNode`. */ + readonly params?: (params: TParams) => void; +} + +export interface StringNode extends BaseNode { readonly kind: 'string'; } -export interface ValueNode { +export interface ValueNode extends BaseNode { readonly kind: 'value'; } -export interface NamespaceNode { +export interface NamespaceNode extends BaseNode { readonly kind: 'namespace'; readonly shape: Shape; } -export type SchemaNode = StringNode | ValueNode | NamespaceNode; +// `any` here (not `unknown`) is deliberate: `SchemaShape` uses `SchemaNode` as a container type that +// must accept a node with ANY concrete `TParams`, and `params` is a contravariant function-parameter +// position — a node with a specific `TParams` (e.g. `StringNode<{ user: string }>`) is not assignable +// to `StringNode`, only to `StringNode`. +export type SchemaNode = StringNode | ValueNode | NamespaceNode; export type SchemaShape = Record; diff --git a/projects/translate/src/translate/translate.proxy.ts b/projects/translate/src/translate/translate.proxy.ts index de823af..469b041 100644 --- a/projects/translate/src/translate/translate.proxy.ts +++ b/projects/translate/src/translate/translate.proxy.ts @@ -1,17 +1,28 @@ import { inject, Injectable, Signal } from '@angular/core'; import { Observable } from 'rxjs'; import { Dictionary, DictionaryEntry, TranslateDynamicProps } from 'simply-translate'; +import type { BaseNode, NamespaceNode, SchemaShape, TranslateSchemaNode } from './schema/schema.types'; import { TranslateService } from './translate.service'; -import type { TranslateSchemaNode, InferTranslateSchemaType } from './schema'; -type TranslationFunction = { - (dynamicProps?: TranslateDynamicProps): string; - Signal: (dynamicProps?: TranslateDynamicProps | Signal) => Signal; - $: (dynamicProps?: TranslateDynamicProps | Observable) => Observable; -} & string; +type TranslationFunction = (TParams extends undefined + ? { + (): string; + Signal: () => Signal; + $: () => Observable; + } + : { + (dynamicProps: TParams): string; + Signal: (dynamicProps: TParams | Signal) => Signal; + $: (dynamicProps: TParams | Observable) => Observable; + }) & + string; -export type ProxyDictionary = { - [K in keyof T]: T[K] extends Dictionary ? ProxyDictionary : TranslationFunction; +export type ProxyDictionary = { + [K in keyof Shape]: Shape[K] extends NamespaceNode + ? ProxyDictionary + : Shape[K] extends BaseNode + ? TranslationFunction + : never; }; export type DictionaryValue = T extends string ? string : T extends Dictionary ? T : DictionaryEntry; @@ -21,7 +32,7 @@ export abstract class TranslateProxy { private _cache: any = {}; readonly service = inject(TranslateService); - readonly object: ProxyDictionary> = this.createLazyProxy([], this._cache); + readonly object: ProxyDictionary = this.createLazyProxy([], this._cache); private createLazyProxy(fullPath: string[], cache: any): any { if (cache.$$proxy) { diff --git a/src/app/app.module.ts b/src/app/app.module.ts index 092f0e8..a2f45e6 100644 --- a/src/app/app.module.ts +++ b/src/app/app.module.ts @@ -45,7 +45,6 @@ function getDictionary(lang: string, client: HttpClient) { loadDictionaries: ({ lang, fallbackLang }, client: HttpClient) => { return forkJoin([getDictionary(lang, client), getDictionary('ru-RU', client)]).pipe( map(([current, fallback]) => { - debugger; return { [lang]: current, 'ru-RU': fallback }; }), ); diff --git a/src/app/try-proxy/try-proxy.component.ts b/src/app/try-proxy/try-proxy.component.ts index 727df65..02468f7 100644 --- a/src/app/try-proxy/try-proxy.component.ts +++ b/src/app/try-proxy/try-proxy.component.ts @@ -1,4 +1,4 @@ -import { Component } from '@angular/core'; +import { Component, computed, signal } from '@angular/core'; import { TranslateRootService } from 'src/_translate.imports'; import { TranslateProxyCommon } from '../translate.common'; @@ -9,20 +9,24 @@ import { TranslateProxyCommon } from '../translate.common'; -

Just Name

+

Signal

-
{{ t9nCommon.namespace.hello_user.Signal()()}}
+
{{ t9nCommon.welcome_to_app.Signal()() }}
+
{{ t9nCommon.namespace.hello_user.Signal({ user: 'John' })() }}
+
{{ t9nCommon.namespace.hello_user.Signal({ user: 'Jane' })() }}
+
{{ t9nCommon.i_have_been_here_count.Signal({ count: 1, days: 2 })() }}
+
{{ countDays() }}
-

Observable

+ `, }) export class TryProxyComponent { @@ -30,11 +34,17 @@ export class TryProxyComponent { selectedLang = this.root.lang; dynamicKey = 'hello_world'; protected t9nCommon = this.translateCommon.object; + countDaysValue = signal(0); + countDays = this.t9nCommon.day_since_new_year.Signal(computed(() => ({ days: this.countDaysValue() }))); constructor( private root: TranslateRootService, private translateCommon: TranslateProxyCommon, - ) {} + ) { + setInterval(() => { + this.countDaysValue.set(this.countDaysValue() + 1); + }, 3000); + } onLangChange(lang: string) { this.selectedLang = lang; diff --git a/src/assets/translations/_.ts b/src/assets/translations/_.ts index b75ad69..7837f01 100644 --- a/src/assets/translations/_.ts +++ b/src/assets/translations/_.ts @@ -2,20 +2,20 @@ import { Namespace, String, TranslateSchema, Value } from 'projects/translate/sr export const testDictionary = TranslateSchema({ welcome_to_app: String(), - hello_user: String(), + hello_user: String<{user?: string}>(), hello_world: String(), goodbye_world: String(), namespace: Namespace({ value: String(), - hello_user: Value(), + hello_user: Value<{user?: string}>(), user: Value(), }), - i_have_been_here_count: Value(), + i_have_been_here_count: Value<{count: number; days: number}>(), - day_since_new_year: Value(), + day_since_new_year: Value<{days: number}>(), for_fallback: Value(), diff --git a/src/assets/translations/en-US.json b/src/assets/translations/en-US.json index 4fd9194..92fa82d 100644 --- a/src/assets/translations/en-US.json +++ b/src/assets/translations/en-US.json @@ -45,12 +45,12 @@ "plural": { "days": [ ["=1", "one day since"], - ["<1", "day of"], + ["<1", "a first day of"], [">365", "more then year since that"], [">360", "almost an year"], [">181", "more then six months since"], [">93", "more then three months since"], - ["_", "$# days"] + ["_", "$# days since"] ] } }, From a3b79c11d94bc4d44b5f332db2768aac47f980ee Mon Sep 17 00:00:00 2001 From: Oleg Date: Fri, 31 Jul 2026 20:42:39 +0300 Subject: [PATCH 04/18] readme --- README.md | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index f97f62d..087e600 100644 --- a/README.md +++ b/README.md @@ -157,11 +157,12 @@ For typed, autocompleted access to your dictionary keys, describe your dictionar import { Namespace, String, TranslateSchema, Value } from 'simply-translate-angular'; export const appSchema = TranslateSchema({ - hello_user: String(), + hello_user: String<{ user: string }>(), + about: String(), namespace: Namespace({ - hello_user: String(), + hello_user: String<{ user: string }>(), }), - with_plural_params: Value(), + visit_count: Value<{ count: number }>(), }); export type AppSchema = typeof appSchema; @@ -179,7 +180,12 @@ export class AppTranslate extends TranslateProxy {} `TranslateProxy` takes the schema itself as its type parameter — the dictionary type is inferred from it via `InferTranslateSchemaType`. `TranslateProxy` only ever needs `AppSchema`'s **type**, never `appSchema`'s runtime value, so import it with `import type`: TypeScript erases `import type` entirely at compile time, keeping the schema-building code (and everything it imports) out of your app's bundle unless something else in it also needs the actual schema object at runtime — e.g. to call `validateDictionary`. See [Validating dictionaries with a schema](#validating-dictionaries-with-a-schema) for the full builder API (`String`, `Value`, `Namespace`) and for validating your JSON dictionaries against the same schema at runtime. -Inject it like any other service and read keys off `object`. Every leaf key is callable (mirrors `translate`), and carries `.Signal()` / `.$()` companions that mirror `translateSignal` / `translateObservable`: +Inject it like any other service and read keys off `object`. Every leaf key is callable (mirrors `translate`), and carries `.Signal()` / `.$()` companions that mirror `translateSignal` / `translateObservable`. + +**The params each of these accepts comes entirely from how the schema leaf was declared:** + +- `String()` / `Value()`, called with no type argument — the leaf takes **no dynamic props at all**. The call, `.Signal()`, and `.$()` all become zero-argument — passing anything is a compile error. +- `String()` / `Value()` — the leaf **requires** exactly `TParams`, everywhere. Omitting the argument, passing `undefined`, or passing the wrong shape are all compile errors. ```typescript @Component({ @@ -198,13 +204,18 @@ export class MyComponent { // nested keys work the same way this.nsHello = translate.object.namespace.hello_user({ user: 'Oleg' }); + + // `about` was declared with String() (no type argument) -> zero-argument call + this.about = translate.object.about(); + // translate.object.about({ user: 'Oleg' }); // compile error: `about` takes no params + // translate.object.hello_user(); // compile error: `hello_user` requires { user: string } } } ``` Each key also stringifies to its full dotted path — `` `${translate.object.namespace.hello_user}` === 'namespace.hello_user' `` — useful when you need the key itself (logging, passing to another API) rather than its translation. -**Warning — dynamic props with `.Signal()` / `.$()`:** the returned `Signal`/`Observable` is cached per `dynamicProps` reference (keyed by identity, not by value). A plain object always stays reactive to **language/dictionary** changes, but is a fixed snapshot of its own properties — it will never update if you mutate the object later, and passing a fresh object literal on every call (e.g. inline in a template) defeats the cache, allocating a new `Signal`/`Observable` each time. If the dynamic values themselves change over time, pass a `Signal` or `Observable` instead, and keep reusing the **same** reference so the cache can pick it up: +**Warning — dynamic props with `.Signal()` / `.$()`:** the returned `Signal`/`Observable` is cached per `dynamicProps` reference (keyed by identity, not by value). A plain object always stays reactive to **language/dictionary** changes, but is a fixed snapshot of its own properties — it will never update if you mutate the object later, and passing a fresh object literal on every call (e.g. inline in a template) defeats the cache, allocating a new `Signal`/`Observable` each time. If the dynamic values themselves change over time, pass a `Signal`/`Observable` of that same params shape instead, and keep reusing the **same** reference so the cache can pick it up: ```typescript // reactive to changing values — pass a stable Signal/Observable reference From 1977d8ad054beb6305a2ba8986805014e74bff3e Mon Sep 17 00:00:00 2001 From: Oleg Date: Sat, 1 Aug 2026 00:37:26 +0300 Subject: [PATCH 05/18] added loader --- README.md | 6 + .../translate/src/__test__/loader.spec.ts | 149 ++++++++++++++++++ .../translate/src/simply-translate.module.ts | 2 + .../loader/translate.loader-cache.ts | 24 +++ .../loader/translate.loader.resolver.ts | 19 +++ .../src/translate/loader/translate.loader.ts | 82 ++++++++++ .../src/translate/translate.proxy.ts | 32 +++- src/app/translate.common.ts | 6 - src/app/translate.proxy.ts | 17 ++ src/app/try-proxy/try-proxy.component.ts | 26 +-- src/assets/translations/_.ts | 25 --- src/assets/translations/dynamic.ts | 8 - src/assets/translations/en-US.json | 108 ++++++------- src/assets/translations/proxy/_.ts | 27 ++++ src/assets/translations/proxy/en-US.json | 64 ++++++++ src/assets/translations/proxy/ru-RU.json | 62 ++++++++ 16 files changed, 550 insertions(+), 107 deletions(-) create mode 100644 projects/translate/src/__test__/loader.spec.ts create mode 100644 projects/translate/src/translate/loader/translate.loader-cache.ts create mode 100644 projects/translate/src/translate/loader/translate.loader.resolver.ts create mode 100644 projects/translate/src/translate/loader/translate.loader.ts delete mode 100644 src/app/translate.common.ts create mode 100644 src/app/translate.proxy.ts delete mode 100644 src/assets/translations/_.ts delete mode 100644 src/assets/translations/dynamic.ts create mode 100644 src/assets/translations/proxy/_.ts create mode 100644 src/assets/translations/proxy/en-US.json create mode 100644 src/assets/translations/proxy/ru-RU.json diff --git a/README.md b/README.md index 087e600..8217443 100644 --- a/README.md +++ b/README.md @@ -408,6 +408,12 @@ For rare cases you may use `id` parameter for Lazy loaded module, that allows ha }) ``` +#### Per-proxy (`applyLoader`) + +A `TranslateProxy` subclass can load its own per-language dictionary by overriding `applyLoader()`, without any `forChild()`/`NgModule` wrapper — each language may be a plain object, a `Promise`, an `Observable`, or a URL string fetched via `HttpClient`, and only the *current* language loads eagerly; any other language loads on demand the first time you switch to it. + +**Caveat:** unlike `forChild()`'s `id`-based key prefixing, `applyLoader()` does not namespace keys — every proxy's dictionary is merged flat into the same per-language dictionary. If more than one proxy uses `applyLoader()`, wrap each one's own schema in a top-level `Namespace({...})` (named after that feature) to avoid colliding with another proxy's keys. + ### Pipeline **(experimental)** diff --git a/projects/translate/src/__test__/loader.spec.ts b/projects/translate/src/__test__/loader.spec.ts new file mode 100644 index 0000000..27be5f7 --- /dev/null +++ b/projects/translate/src/__test__/loader.spec.ts @@ -0,0 +1,149 @@ +import { HttpClient } from '@angular/common/http'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { TestBed } from '@angular/core/testing'; +import { Subject } from 'rxjs'; +import { TranslateRootService } from '../public_api'; +import { TranslateModule } from '../simply-translate.module'; +import { TranslateLoader, TranslateLoaderDictionaries } from '../translate/loader/translate.loader'; +import { TranslateLoaderCache } from '../translate/loader/translate.loader-cache'; +import { TranslateService } from '../translate/translate.service'; +import { tick } from './core/tick'; + +const lang = 'lang'; +const newLang = 'new'; + +describe('TranslateLoader', () => { + let root: TranslateRootService; + let httpMock: HttpTestingController; + + function createLoader(id: string, dictionaries: TranslateLoaderDictionaries): TranslateLoader { + const loader = new TranslateLoader(TestBed.inject(TranslateLoaderCache), TestBed.inject(HttpClient), TestBed.inject(TranslateService), id, dictionaries); + loader.init(); + return loader; + } + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule, TranslateModule.forRoot({ lang })], + }); + + root = TestBed.inject(TranslateRootService); + httpMock = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpMock.verify(); + }); + + it('grafts a plain-object dictionary onto the current language immediately', () => { + createLoader('id1', { [lang]: { hello_user: 'Hello ${user}' } }); + + expect(root.translate('hello_user', { user: 'Oleg' })).toBe('Hello Oleg'); + }); + + it('caches the resolved dictionary so getProcess returns it', () => { + const dict = { hello_user: 'Hello ${user}' }; + const loader = createLoader('id1', { [lang]: dict }); + + expect(loader.getProcess()).toBe(dict); + }); + + it('resolves a Promise source and grafts it once resolved', async () => { + createLoader('id1', { [lang]: Promise.resolve({ hello_user: 'Hello ${user}' }) }); + + await tick(0); + + expect(root.translate('hello_user', { user: 'Oleg' })).toBe('Hello Oleg'); + }); + + it('resolves an Observable source and grafts it once it emits', () => { + const dict$ = new Subject>(); + createLoader('id1', { [lang]: dict$ }); + + expect(root.translate('hello_user', { user: 'Oleg' })).toBe('hello_user'); + + dict$.next({ hello_user: 'Hello ${user}' }); + + expect(root.translate('hello_user', { user: 'Oleg' })).toBe('Hello Oleg'); + }); + + it('fetches a URL source via HttpClient and grafts the response', () => { + createLoader('id1', { [lang]: '/assets/id1.json' }); + + httpMock.expectOne('/assets/id1.json').flush({ hello_user: 'Hello ${user}' }); + + expect(root.translate('hello_user', { user: 'Oleg' })).toBe('Hello Oleg'); + }); + + it('does not start a second request while one is already cached/in-flight for the same id+lang', () => { + createLoader('id1', { [lang]: '/assets/id1.json' }); + createLoader('id1', { [lang]: '/assets/id1.json' }); + + const requests = httpMock.match('/assets/id1.json'); + expect(requests.length).toBe(1); + requests[0].flush({ hello_user: 'Hello ${user}' }); + }); + + it('merges distinct ids into the same shared per-language dictionary (no id namespacing)', () => { + createLoader('id1', { [lang]: { greeting_from_id1: 'From id1' } }); + createLoader('id2', { [lang]: { greeting_from_id2: 'From id2' } }); + + // Both land in the same flat dictionary for `lang` — unlike TranslateService.extendDictionary() + // for forChild(), TranslateLoader does not prefix keys by id, so distinct ids must use distinct keys. + expect(root.translate('greeting_from_id1')).toBe('From id1'); + expect(root.translate('greeting_from_id2')).toBe('From id2'); + }); + + it('loads the dictionary for the newly selected language on language change', () => { + createLoader('id1', { + [lang]: { hello_user: 'Hello ${user}' }, + [newLang]: { hello_user: 'Hello New ${user}' }, + }); + + root.lang = newLang; + + expect(root.translate('hello_user', { user: 'Oleg' })).toBe('Hello New Oleg'); + }); + + it('fetches the new language over HTTP only after switching to it', () => { + createLoader('id1', { + [lang]: { hello_user: 'Hello ${user}' }, + [newLang]: '/assets/id1.new.json', + }); + + httpMock.expectNone('/assets/id1.new.json'); + + root.lang = newLang; + + httpMock.expectOne('/assets/id1.new.json').flush({ hello_user: 'Hello New ${user}' }); + + expect(root.translate('hello_user', { user: 'Oleg' })).toBe('Hello New Oleg'); + }); + + it('stops reacting to language changes once removed', () => { + const loader = createLoader('id1', { + [lang]: { hello_user: 'Hello ${user}' }, + [newLang]: '/assets/id1.new.json', + }); + + loader.remove(); + root.lang = newLang; + + expect(httpMock.match('/assets/id1.new.json').length).toBe(0); + }); + + it('clears the cache on a failed load so a later attempt retries', () => { + const consoleError = spyOn(console, 'error'); + + const failed = createLoader('id1', { [lang]: '/assets/id1.json' }); + httpMock.expectOne('/assets/id1.json').error(new ProgressEvent('error')); + + expect(failed.getProcess()).toBeUndefined(); + + createLoader('id1', { [lang]: '/assets/id1.json' }); + httpMock.expectOne('/assets/id1.json').flush({ hello_user: 'Hello ${user}' }); + + expect(root.translate('hello_user', { user: 'Oleg' })).toBe('Hello Oleg'); + expect(consoleError).toHaveBeenCalled(); + }); +}); diff --git a/projects/translate/src/simply-translate.module.ts b/projects/translate/src/simply-translate.module.ts index 623d5b2..ddd18e1 100644 --- a/projects/translate/src/simply-translate.module.ts +++ b/projects/translate/src/simply-translate.module.ts @@ -14,6 +14,7 @@ import { import { TranslatePipe, TranslateToPipe, TranslatePipeDetect } from './translate/translate.pipe'; import { TranslateDirective } from './translate/translate.directive'; import { TranslateResolve } from './translate/translate.resolver'; +import { TranslateLoaderCache } from './translate/loader/translate.loader-cache'; export type AddMiddlewareFunc = (...any: any[]) => Array; export type LoadDictionariesFunc = ( @@ -146,6 +147,7 @@ export class TranslateModule { TranslateRootService, TranslateService, TranslateResolve, + TranslateLoaderCache, { provide: TRANSLATE_CHILD, useValue: {}, diff --git a/projects/translate/src/translate/loader/translate.loader-cache.ts b/projects/translate/src/translate/loader/translate.loader-cache.ts new file mode 100644 index 0000000..1cb9dd0 --- /dev/null +++ b/projects/translate/src/translate/loader/translate.loader-cache.ts @@ -0,0 +1,24 @@ +import { Injectable } from '@angular/core'; +import { Observable } from 'rxjs'; +import { Dictionary } from 'simply-translate'; + +@Injectable() +export class TranslateLoaderCache { + private readonly cache: Partial>> = {}; + + get(lang: string, id: string): Dictionary | Observable | undefined { + return this.cache[`${id}_${lang}`]; + } + + set>(lang: string, id: string, value: T): T { + this.cache[`${id}_${lang}`] = value; + + return value; + } + + clear(lang: string, id: string): void { + delete this.cache[`${id}_${lang}`]; + } +} + + diff --git a/projects/translate/src/translate/loader/translate.loader.resolver.ts b/projects/translate/src/translate/loader/translate.loader.resolver.ts new file mode 100644 index 0000000..950961a --- /dev/null +++ b/projects/translate/src/translate/loader/translate.loader.resolver.ts @@ -0,0 +1,19 @@ +import { inject } from '@angular/core'; +import { Dictionary } from 'simply-translate'; +import { TranslateLoaderCache } from './translate.loader-cache'; +import { TranslateService } from '../translate.service'; +import { ResolveFn } from '@angular/router'; + +export const translationsExtensionResolver: (id: string) => ResolveFn = (id: string) => { + return () => { + const provider = inject(TranslateLoaderCache); + const service = inject(TranslateService); + + const lang = service.lang; + if (!lang) { + return undefined; + } + + return provider.get(lang, id); + }; +}; diff --git a/projects/translate/src/translate/loader/translate.loader.ts b/projects/translate/src/translate/loader/translate.loader.ts new file mode 100644 index 0000000..9b37fbc --- /dev/null +++ b/projects/translate/src/translate/loader/translate.loader.ts @@ -0,0 +1,82 @@ +import { from, Observable, shareReplay, Subscription } from 'rxjs'; +import { Dictionary } from 'simply-translate'; +import { TranslateService } from '../translate.service'; +import { TranslateLoaderCache } from './translate.loader-cache'; +import { HttpClient } from '@angular/common/http'; + +export type TranslateLoaderDictionary = Dictionary | Promise | Observable | string; +export type TranslateLoaderDictionaries = Record; + +export class TranslateLoader { + constructor( + private cache: TranslateLoaderCache, + private httpClient: HttpClient, + private service: TranslateService, + readonly id: string, + readonly dictionaries: TranslateLoaderDictionaries, + ) {} + private _subs?: Subscription; + + init() { + if (!this._subs && this.service.lang && this.dictionaries[this.service.lang]) { + this.importLang(this.service.lang, this.id); + } + + this._subs = this.service.languageChange$.pipe().subscribe((_lang) => { + const lang = _lang.lang; + this.importLang(lang, this.id); + }); + } + + remove(){ + this._subs?.unsubscribe(); + this._subs = undefined; + } + + getProcess() { + const lang = this.service.lang; + if (!lang) { + return undefined; + } + + return this.cache.get(lang, this.id); + } + + private importLang(lang: string, id: string): void { + const dic = this.dictionaries[lang]; + const cached = this.cache.get(lang, this.id); + + // Already resolved to a dictionary, or a load is still in flight — either way, don't start another. + // (On error the entry is cleared below, so a later call retries.) + if (cached) { + return; + } + + // Synchronous inline dictionary — graft immediately. + if (!(typeof dic === 'string' || dic instanceof Promise || dic instanceof Observable)) { + this.cache.set(lang, this.id, dic); + this.service.extendDictionary(lang, dic); + + return; + } + + // Async source (URL string | Promise | Observable) — normalise to a single shared stream so + // concurrent consumers (and the resolver via getProcess()) don't trigger duplicate loads. + const source = typeof dic === 'string' ? this.httpClient.get(dic) : from(dic); + const load = this.cache.set(lang, this.id, source.pipe(shareReplay(1))); + + load.subscribe({ + next: (dictionary) => { + this.cache.set(lang, this.id, dictionary); + this.service.extendDictionary(lang, dictionary); + }, + error: (error) => { + // Clear the in-flight entry so a subsequent attempt (e.g. re-selecting the language) retries, + // instead of being permanently short-circuited by a cached failed load. + this.cache.clear(lang, this.id); + // eslint-disable-next-line no-console -- deliberate surfacing of a runtime dictionary-load failure + console.error(`[TranslateLoader] Failed to load dictionary '${this.id}' (${lang}):`, error); + }, + }); + } +} diff --git a/projects/translate/src/translate/translate.proxy.ts b/projects/translate/src/translate/translate.proxy.ts index 469b041..5af3c4f 100644 --- a/projects/translate/src/translate/translate.proxy.ts +++ b/projects/translate/src/translate/translate.proxy.ts @@ -1,8 +1,11 @@ -import { inject, Injectable, Signal } from '@angular/core'; +import { inject, Injectable, OnDestroy, Signal } from '@angular/core'; import { Observable } from 'rxjs'; import { Dictionary, DictionaryEntry, TranslateDynamicProps } from 'simply-translate'; import type { BaseNode, NamespaceNode, SchemaShape, TranslateSchemaNode } from './schema/schema.types'; import { TranslateService } from './translate.service'; +import { TranslateLoader, TranslateLoaderDictionaries } from './loader/translate.loader'; +import { TranslateLoaderCache } from './loader/translate.loader-cache'; +import { HttpClient } from '@angular/common/http'; type TranslationFunction = (TParams extends undefined ? { @@ -28,11 +31,32 @@ export type ProxyDictionary = { export type DictionaryValue = T extends string ? string : T extends Dictionary ? T : DictionaryEntry; @Injectable() -export abstract class TranslateProxy { +export abstract class TranslateProxy implements OnDestroy { private _cache: any = {}; readonly service = inject(TranslateService); readonly object: ProxyDictionary = this.createLazyProxy([], this._cache); + private _id?: string; + private _dictionaries?: Record | Observable | string>; + private _loader?: TranslateLoader; + + constructor() { + const loaderInfo = this.applyLoader?.(); + if (loaderInfo) { + this._load(loaderInfo.id, loaderInfo.dictionaries); + } + } + + protected applyLoader?(): { id: string; dictionaries: TranslateLoaderDictionaries }; + + private _load(id: string, dictionaries: TranslateLoaderDictionaries) { + this._id = id; + this._dictionaries = dictionaries ?? {}; + if (this._id) { + this._loader = new TranslateLoader(inject(TranslateLoaderCache), inject(HttpClient), this.service, this._id, this._dictionaries); + this._loader.init(); + } + } private createLazyProxy(fullPath: string[], cache: any): any { if (cache.$$proxy) { @@ -100,4 +124,8 @@ export abstract class TranslateProxy { return cached; }; } + + ngOnDestroy(): void { + this._loader?.remove(); + } } diff --git a/src/app/translate.common.ts b/src/app/translate.common.ts deleted file mode 100644 index 96d70b0..0000000 --- a/src/app/translate.common.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { Injectable } from '@angular/core'; -import { TranslateProxy } from '../../projects/translate/src/translate/translate.proxy'; -import type { TestDictionary } from 'src/assets/translations/_'; - -@Injectable({ providedIn: 'root' }) -export class TranslateProxyCommon extends TranslateProxy {} diff --git a/src/app/translate.proxy.ts b/src/app/translate.proxy.ts new file mode 100644 index 0000000..264843f --- /dev/null +++ b/src/app/translate.proxy.ts @@ -0,0 +1,17 @@ +import { Injectable } from '@angular/core'; +import { TranslateProxy } from '../../projects/translate/src/translate/translate.proxy'; +import type { TestDictionary } from 'src/assets/translations/proxy/_'; +import { Dictionary } from 'simply-translate'; + +@Injectable({ providedIn: 'root' }) +export class TranslateProxyCommon extends TranslateProxy { + applyLoader() { + return { + id: 'common', + dictionaries: { + 'en-US': import('src/assets/translations/proxy/en-US.json').then((module) => module.default as unknown as Dictionary), + 'ru-RU': '/assets/translations/proxy/ru-RU.json', + }, + }; + } +} diff --git a/src/app/try-proxy/try-proxy.component.ts b/src/app/try-proxy/try-proxy.component.ts index 02468f7..70cc09f 100644 --- a/src/app/try-proxy/try-proxy.component.ts +++ b/src/app/try-proxy/try-proxy.component.ts @@ -1,6 +1,6 @@ import { Component, computed, signal } from '@angular/core'; import { TranslateRootService } from 'src/_translate.imports'; -import { TranslateProxyCommon } from '../translate.common'; +import { TranslateProxyCommon } from '../translate.proxy'; @Component({ selector: 'app-try-proxy', @@ -9,33 +9,33 @@ import { TranslateProxyCommon } from '../translate.common'; - +
{{ t9nProxy.namespace.hello_user.$({user:'Me'}) | async}}

Signal

-
{{ t9nCommon.welcome_to_app.Signal()() }}
-
{{ t9nCommon.namespace.hello_user.Signal({ user: 'John' })() }}
-
{{ t9nCommon.namespace.hello_user.Signal({ user: 'Jane' })() }}
-
{{ t9nCommon.i_have_been_here_count.Signal({ count: 1, days: 2 })() }}
+
{{ t9nProxy.welcome_to_app.Signal()() }}
+
{{ t9nProxy.namespace.hello_user.Signal({ user: 'John' })() }}
+
{{ t9nProxy.namespace.hello_user.Signal({ user: 'Jane' })() }}
+
{{ t9nProxy.i_have_been_here_count.Signal({ count: 1, days: 2 })() }}
{{ countDays() }}
- +
{{ t9nProxy.hello_user.Signal({user:'Me'})()}}
`, }) export class TryProxyComponent { langs = ['en-US', 'ru-RU']; selectedLang = this.root.lang; dynamicKey = 'hello_world'; - protected t9nCommon = this.translateCommon.object; + protected t9nProxy = this.translateCommon.object.proxy; countDaysValue = signal(0); - countDays = this.t9nCommon.day_since_new_year.Signal(computed(() => ({ days: this.countDaysValue() }))); + countDays = this.t9nProxy.day_since_new_year.Signal(computed(() => ({ days: this.countDaysValue() }))); constructor( private root: TranslateRootService, diff --git a/src/assets/translations/_.ts b/src/assets/translations/_.ts deleted file mode 100644 index 7837f01..0000000 --- a/src/assets/translations/_.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { Namespace, String, TranslateSchema, Value } from 'projects/translate/src/public_api'; - -export const testDictionary = TranslateSchema({ - welcome_to_app: String(), - hello_user: String<{user?: string}>(), - - hello_world: String(), - goodbye_world: String(), - - namespace: Namespace({ - value: String(), - hello_user: Value<{user?: string}>(), - user: Value(), - }), - - i_have_been_here_count: Value<{count: number; days: number}>(), - - day_since_new_year: Value<{days: number}>(), - - for_fallback: Value(), - - same_key: Value(), -}); - -export type TestDictionary = typeof testDictionary; diff --git a/src/assets/translations/dynamic.ts b/src/assets/translations/dynamic.ts deleted file mode 100644 index e63f931..0000000 --- a/src/assets/translations/dynamic.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { Dictionary, DictionaryEntry } from 'simply-translate'; - -import { TranslateSchema, Value } from 'projects/translate/src/public_api'; - -export const testDictionary = TranslateSchema({ - hello_user_dynamic: Value(), - same_dyn: Value(), -}); diff --git a/src/assets/translations/en-US.json b/src/assets/translations/en-US.json index 92fa82d..232b195 100644 --- a/src/assets/translations/en-US.json +++ b/src/assets/translations/en-US.json @@ -1,62 +1,64 @@ { - "welcome_to_app": "Welcome to Translation Testing Application", - "hello_user": "Hello $&{user?namespace.user}!", + "proxy": { + "welcome_to_app": "Welcome to Translation Testing Application", + "hello_user": "Hello $&{user?namespace.user}!", - "hello_world": "Hello World", - "goodbye_world": { - "value": "Goodbye World", - "description": "When you want to say goodbye to the world" - }, + "hello_world": "Hello World", + "goodbye_world": { + "value": "Goodbye World", + "description": "When you want to say goodbye to the world" + }, - "namespace": { - "value": "Namespace translated", - "hello_user": "Hello again, $&{user?namespace.user}!", - "user": "User" - }, + "namespace": { + "value": "Namespace translated", + "hello_user": "Hello again, $&{user?namespace.user}!", + "user": "User" + }, - "i_have_been_here_count": { - "value": "$!{count} ${days}", - "cases": { - "count": [ - ["!!", "I've been here ${count}"], - ["!", "I've not been here"] - ] + "i_have_been_here_count": { + "value": "$!{count} ${days}", + "cases": { + "count": [ + ["!!", "I've been here ${count}"], + ["!", "I've not been here"] + ] + }, + "plural": { + "count": [ + ["=0", "... not even once"], + ["=1", "once"], + ["=2", "twice"], + ["in [3,4,5]", "few times"], + ["<100", "many times"], + ["_", "$# times"] + ], + "days": [ + ["=0", "today"], + ["=1", "last day"], + ["<4", "last few days"], + ["_", "for a while"] + ] + } }, - "plural": { - "count": [ - ["=0", "... not even once"], - ["=1", "once"], - ["=2", "twice"], - ["in [3,4,5]", "few times"], - ["<100", "many times"], - ["_", "$# times"] - ], - "days": [ - ["=0", "today"], - ["=1", "last day"], - ["<4", "last few days"], - ["_", "for a while"] - ] - } - }, - "day_since_new_year": { - "value": "It is ${days} New Year", - "plural": { - "days": [ - ["=1", "one day since"], - ["<1", "a first day of"], - [">365", "more then year since that"], - [">360", "almost an year"], - [">181", "more then six months since"], - [">93", "more then three months since"], - ["_", "$# days since"] - ] - } - }, + "day_since_new_year": { + "value": "It is ${days} New Year", + "plural": { + "days": [ + ["=1", "one day since"], + ["<1", "a first day of"], + [">365", "more then year since that"], + [">360", "almost an year"], + [">181", "more then six months since"], + [">93", "more then three months since"], + ["_", "$# days since"] + ] + } + }, - "for_fallback": "Fallback", + "for_fallback": "Fallback", - "same_key": "Same in the Root", - "only_root_key": "Only in the Root" + "same_key": "Same in the Root", + "only_root_key": "Only in the Root" + } } diff --git a/src/assets/translations/proxy/_.ts b/src/assets/translations/proxy/_.ts new file mode 100644 index 0000000..a27c05e --- /dev/null +++ b/src/assets/translations/proxy/_.ts @@ -0,0 +1,27 @@ +import { Namespace, String, TranslateSchema, Value } from 'projects/translate/src/public_api'; + +export const testDictionary = TranslateSchema({ + proxy: Namespace({ + welcome_to_app: String(), + hello_user: String<{ user?: string }>(), + + hello_world: String(), + goodbye_world: String(), + + namespace: Namespace({ + value: String(), + hello_user: Value<{ user?: string }>(), + user: Value(), + }), + + i_have_been_here_count: Value<{ count: number; days: number }>(), + + day_since_new_year: Value<{ days: number }>(), + + for_fallback: Value(), + + same_key: Value(), + }), +}); + +export type TestDictionary = typeof testDictionary; diff --git a/src/assets/translations/proxy/en-US.json b/src/assets/translations/proxy/en-US.json new file mode 100644 index 0000000..dbf01e6 --- /dev/null +++ b/src/assets/translations/proxy/en-US.json @@ -0,0 +1,64 @@ +{ + "proxy": { + "welcome_to_app": "[Proxy] Welcome to Translation Testing Application", + "hello_user": "[Proxy] Hello $&{user?namespace.user}!", + + "hello_world": "[Proxy] Hello World", + "goodbye_world": { + "value": "[Proxy] Goodbye World", + "description": "When you want to say goodbye to the world" + }, + + "namespace": { + "value": "[Proxy] Namespace translated", + "hello_user": "[Proxy] Hello again, $&{user?namespace.user}!", + "user": "[Proxy] User" + }, + + "i_have_been_here_count": { + "value": "[Proxy] $!{count} ${days}", + "cases": { + "count": [ + ["!!", "I've been here ${count}"], + ["!", "I've not been here"] + ] + }, + "plural": { + "count": [ + ["=0", "... not even once"], + ["=1", "once"], + ["=2", "twice"], + ["in [3,4,5]", "few times"], + ["<100", "many times"], + ["_", "$# times"] + ], + "days": [ + ["=0", "today"], + ["=1", "last day"], + ["<4", "last few days"], + ["_", "for a while"] + ] + } + }, + + "day_since_new_year": { + "value": "[Proxy] It is ${days} New Year", + "plural": { + "days": [ + ["=1", "one day since"], + ["<1", "a first day of"], + [">365", "more then year since that"], + [">360", "almost an year"], + [">181", "more then six months since"], + [">93", "more then three months since"], + ["_", "$# days since"] + ] + } + }, + + "for_fallback": "[Proxy] Fallback", + + "same_key": "[Proxy] Same in the Root", + "only_root_key": "[Proxy] Only in the Root" + } +} diff --git a/src/assets/translations/proxy/ru-RU.json b/src/assets/translations/proxy/ru-RU.json new file mode 100644 index 0000000..023aaa7 --- /dev/null +++ b/src/assets/translations/proxy/ru-RU.json @@ -0,0 +1,62 @@ +{ + "proxy": { + "welcome_to_app": "[Proxy] Добро пожаловть в Тестовое приложение", + "hello_user": "[Proxy] Привет, $&{user?namespace.user}!", + + "hello_world": "[Proxy] Привет мир!", + "goodbye_world": { + "value": "[Proxy] Пока мир", + "description": "тест" + }, + + "namespace": { + "value": "[Proxy] пространство имен", + "hello_user": "[Proxy] Снова здравствуй, $&{user?namespace.user}!", + "user": "[Proxy] Пользователь" + }, + + "i_have_been_here_count": { + "value": "[Proxy] $!{count} ${days}", + "cases": { + "count": [ + ["!!", "Я уже был здесь ${count}"], + ["!", "Я не был здесь"] + ] + }, + "plural": { + "count": [ + ["=0", "... ващет ни разу"], + ["=1", "раз"], + ["=2", "дважды"], + ["in [3,4,5]", "несколько раз"], + ["<100", "много раз"], + ["_", "$# раз(а)"] + ], + "days": [ + ["=0", "сегодня"], + ["=1", "за день"], + ["<4", "пару дней"], + ["_", "за долго"] + ] + } + }, + + "day_since_new_year": { + "value": "[Proxy] ${days}", + "plural": { + "days": [ + ["=1", "Прошел день с Нового Года"], + ["<1", "Это Новый Год"], + [">365", "Прошел уже год с начала того года"], + [">181", "Прошло уже полгода с начала года"], + [">93", "Более трех месяцев прошло с Нового Года"], + ["_", "Уже прошло $# дней с начала года"] + ] + } + }, + + "for_fallback": "[Proxy] для Фолбэка", + + "same_key": "[Proxy] Same in the Root" + } +} From 5673b8f68f080d38fa750d158ba7377191f09be3 Mon Sep 17 00:00:00 2001 From: Oleg Date: Sat, 1 Aug 2026 14:09:19 +0300 Subject: [PATCH 06/18] add loader error handler --- .../translate/src/__test__/loader.spec.ts | 9 +++++--- projects/translate/src/public_api.ts | 1 + .../src/translate/loader/translate.loader.ts | 22 +++++++++---------- .../src/translate/translate.proxy.ts | 12 ++++++---- src/app/{ => try-proxy}/translate.proxy.ts | 9 ++++++-- src/app/try-proxy/try-proxy.component.ts | 2 +- 6 files changed, 34 insertions(+), 21 deletions(-) rename src/app/{ => try-proxy}/translate.proxy.ts (56%) diff --git a/projects/translate/src/__test__/loader.spec.ts b/projects/translate/src/__test__/loader.spec.ts index 27be5f7..cd78cae 100644 --- a/projects/translate/src/__test__/loader.spec.ts +++ b/projects/translate/src/__test__/loader.spec.ts @@ -133,17 +133,20 @@ describe('TranslateLoader', () => { }); it('clears the cache on a failed load so a later attempt retries', () => { - const consoleError = spyOn(console, 'error'); - const failed = createLoader('id1', { [lang]: '/assets/id1.json' }); + const errors: { lang: string; id: string; error: unknown }[] = []; + failed.errors$.subscribe((e) => errors.push(e)); + httpMock.expectOne('/assets/id1.json').error(new ProgressEvent('error')); expect(failed.getProcess()).toBeUndefined(); + expect(errors.length).toBe(1); + expect(errors[0].lang).toBe(lang); + expect(errors[0].id).toBe('id1'); createLoader('id1', { [lang]: '/assets/id1.json' }); httpMock.expectOne('/assets/id1.json').flush({ hello_user: 'Hello ${user}' }); expect(root.translate('hello_user', { user: 'Oleg' })).toBe('Hello Oleg'); - expect(consoleError).toHaveBeenCalled(); }); }); diff --git a/projects/translate/src/public_api.ts b/projects/translate/src/public_api.ts index 529a6e3..05dca4d 100644 --- a/projects/translate/src/public_api.ts +++ b/projects/translate/src/public_api.ts @@ -4,6 +4,7 @@ export * from './translate/translate.resolver'; export * from './translate/translate.service'; export * from './translate/translate.proxy'; export * from './translate/schema'; +export { TranslateLoaderSupport, TranslateLoaderDictionaries, TranslateLoaderDictionary } from './translate/loader/translate.loader'; export * from './simply-translate.module'; export { TranslateChildConfig } from './translate/translate.service'; export { diff --git a/projects/translate/src/translate/loader/translate.loader.ts b/projects/translate/src/translate/loader/translate.loader.ts index 9b37fbc..d3664d0 100644 --- a/projects/translate/src/translate/loader/translate.loader.ts +++ b/projects/translate/src/translate/loader/translate.loader.ts @@ -1,4 +1,4 @@ -import { from, Observable, shareReplay, Subscription } from 'rxjs'; +import { from, Observable, shareReplay, Subject, Subscription } from 'rxjs'; import { Dictionary } from 'simply-translate'; import { TranslateService } from '../translate.service'; import { TranslateLoaderCache } from './translate.loader-cache'; @@ -7,6 +7,11 @@ import { HttpClient } from '@angular/common/http'; export type TranslateLoaderDictionary = Dictionary | Promise | Observable | string; export type TranslateLoaderDictionaries = Record; +export interface TranslateLoaderSupport{ + applyLoader(): { id: string; dictionaries: TranslateLoaderDictionaries }; + onLoaderError?(args: { lang: string; id: string; error: any }): void; +} + export class TranslateLoader { constructor( private cache: TranslateLoaderCache, @@ -15,7 +20,10 @@ export class TranslateLoader { readonly id: string, readonly dictionaries: TranslateLoaderDictionaries, ) {} + private _subs?: Subscription; + readonly _errorsSub = new Subject<{ lang: string; id: string; error: any }>(); + readonly errors$ = this._errorsSub.asObservable(); init() { if (!this._subs && this.service.lang && this.dictionaries[this.service.lang]) { @@ -28,7 +36,7 @@ export class TranslateLoader { }); } - remove(){ + remove() { this._subs?.unsubscribe(); this._subs = undefined; } @@ -46,13 +54,10 @@ export class TranslateLoader { const dic = this.dictionaries[lang]; const cached = this.cache.get(lang, this.id); - // Already resolved to a dictionary, or a load is still in flight — either way, don't start another. - // (On error the entry is cleared below, so a later call retries.) if (cached) { return; } - // Synchronous inline dictionary — graft immediately. if (!(typeof dic === 'string' || dic instanceof Promise || dic instanceof Observable)) { this.cache.set(lang, this.id, dic); this.service.extendDictionary(lang, dic); @@ -60,8 +65,6 @@ export class TranslateLoader { return; } - // Async source (URL string | Promise | Observable) — normalise to a single shared stream so - // concurrent consumers (and the resolver via getProcess()) don't trigger duplicate loads. const source = typeof dic === 'string' ? this.httpClient.get(dic) : from(dic); const load = this.cache.set(lang, this.id, source.pipe(shareReplay(1))); @@ -71,11 +74,8 @@ export class TranslateLoader { this.service.extendDictionary(lang, dictionary); }, error: (error) => { - // Clear the in-flight entry so a subsequent attempt (e.g. re-selecting the language) retries, - // instead of being permanently short-circuited by a cached failed load. this.cache.clear(lang, this.id); - // eslint-disable-next-line no-console -- deliberate surfacing of a runtime dictionary-load failure - console.error(`[TranslateLoader] Failed to load dictionary '${this.id}' (${lang}):`, error); + this._errorsSub.next({ lang, id, error }); }, }); } diff --git a/projects/translate/src/translate/translate.proxy.ts b/projects/translate/src/translate/translate.proxy.ts index 5af3c4f..c8f2252 100644 --- a/projects/translate/src/translate/translate.proxy.ts +++ b/projects/translate/src/translate/translate.proxy.ts @@ -3,7 +3,7 @@ import { Observable } from 'rxjs'; import { Dictionary, DictionaryEntry, TranslateDynamicProps } from 'simply-translate'; import type { BaseNode, NamespaceNode, SchemaShape, TranslateSchemaNode } from './schema/schema.types'; import { TranslateService } from './translate.service'; -import { TranslateLoader, TranslateLoaderDictionaries } from './loader/translate.loader'; +import { TranslateLoader, TranslateLoaderDictionaries, TranslateLoaderSupport } from './loader/translate.loader'; import { TranslateLoaderCache } from './loader/translate.loader-cache'; import { HttpClient } from '@angular/common/http'; @@ -31,7 +31,7 @@ export type ProxyDictionary = { export type DictionaryValue = T extends string ? string : T extends Dictionary ? T : DictionaryEntry; @Injectable() -export abstract class TranslateProxy implements OnDestroy { +export abstract class TranslateProxy implements OnDestroy, Partial { private _cache: any = {}; readonly service = inject(TranslateService); @@ -47,7 +47,8 @@ export abstract class TranslateProxy implements O } } - protected applyLoader?(): { id: string; dictionaries: TranslateLoaderDictionaries }; + applyLoader?(): { id: string; dictionaries: TranslateLoaderDictionaries }; + onLoaderError?(args: { lang: string; id: string; error: any }): void; private _load(id: string, dictionaries: TranslateLoaderDictionaries) { this._id = id; @@ -55,6 +56,9 @@ export abstract class TranslateProxy implements O if (this._id) { this._loader = new TranslateLoader(inject(TranslateLoaderCache), inject(HttpClient), this.service, this._id, this._dictionaries); this._loader.init(); + this._loader.errors$.subscribe((error) => { + this.onLoaderError?.(error); + }); } } @@ -124,7 +128,7 @@ export abstract class TranslateProxy implements O return cached; }; } - + ngOnDestroy(): void { this._loader?.remove(); } diff --git a/src/app/translate.proxy.ts b/src/app/try-proxy/translate.proxy.ts similarity index 56% rename from src/app/translate.proxy.ts rename to src/app/try-proxy/translate.proxy.ts index 264843f..bcf4200 100644 --- a/src/app/translate.proxy.ts +++ b/src/app/try-proxy/translate.proxy.ts @@ -1,10 +1,11 @@ import { Injectable } from '@angular/core'; -import { TranslateProxy } from '../../projects/translate/src/translate/translate.proxy'; +import { TranslateProxy } from '../../../projects/translate/src/translate/translate.proxy'; import type { TestDictionary } from 'src/assets/translations/proxy/_'; import { Dictionary } from 'simply-translate'; +import { TranslateLoaderSupport } from 'projects/translate/src/translate/loader/translate.loader'; @Injectable({ providedIn: 'root' }) -export class TranslateProxyCommon extends TranslateProxy { +export class TranslateProxyCommon extends TranslateProxy implements TranslateLoaderSupport { applyLoader() { return { id: 'common', @@ -14,4 +15,8 @@ export class TranslateProxyCommon extends TranslateProxy { }, }; } + + onLoaderError(args: { lang: string; id: string; error: any }): void { + console.error(`Error loading translation for lang=${args.lang}, id=${args.id}`, args.error); + } } diff --git a/src/app/try-proxy/try-proxy.component.ts b/src/app/try-proxy/try-proxy.component.ts index 70cc09f..b1e0659 100644 --- a/src/app/try-proxy/try-proxy.component.ts +++ b/src/app/try-proxy/try-proxy.component.ts @@ -1,6 +1,6 @@ import { Component, computed, signal } from '@angular/core'; import { TranslateRootService } from 'src/_translate.imports'; -import { TranslateProxyCommon } from '../translate.proxy'; +import { TranslateProxyCommon } from './translate.proxy'; @Component({ selector: 'app-try-proxy', From abe48dd8a65d05f8c260953cc69842f47379f17a Mon Sep 17 00:00:00 2001 From: Oleg Date: Sat, 1 Aug 2026 14:20:50 +0300 Subject: [PATCH 07/18] fix directive --- .../src/translate/translate.directive.ts | 54 +++------ src/app/app.component.html | 5 +- .../try-directive/try-directive.component.ts | 4 +- src/assets/translations/en-US.json | 109 +++++++++--------- 4 files changed, 74 insertions(+), 98 deletions(-) diff --git a/projects/translate/src/translate/translate.directive.ts b/projects/translate/src/translate/translate.directive.ts index a98b9b4..0b08516 100644 --- a/projects/translate/src/translate/translate.directive.ts +++ b/projects/translate/src/translate/translate.directive.ts @@ -1,17 +1,17 @@ -import { computed, Directive, effect, ElementRef, inject, input, OnDestroy, OnInit, signal } from '@angular/core'; +import { computed, Directive, effect, ElementRef, inject, input, OnInit, signal } from '@angular/core'; import { DictionaryEntry, TranslateKey } from 'simply-translate'; import { TranslateService } from './translate.service'; @Directive({ selector: '[translate]', }) -export class TranslateDirective implements OnInit, OnDestroy { +export class TranslateDirective implements OnInit { private _element: ElementRef = inject(ElementRef); private _service: TranslateService = inject(TranslateService); private domContent = signal(''); - private observer: MutationObserver | null = null; private _textNode: Text | null = null; + private _lastOutput: string | null = null; fallback = input(undefined); key = input(undefined, { alias: 'translate' }); @@ -28,39 +28,36 @@ export class TranslateDirective implements OnInit, OnDestroy { }); const translatedText = computed(() => { + const lang = this.to(); + this._service.stateVersion(); + const activeKey = finalKey(); - if (!activeKey) return ''; + const fallbackValue = this.fallback(); - const fallbackValue = this.fallback() ?? (this.domContent() || undefined); - const lang = this.to(); + const values = this.values(); + + if (!activeKey) return ''; if (lang) { - this._service.stateVersion(); - return this._service.translateTo(lang, activeKey, this.values() as any, fallbackValue); + return this._service.translateTo(lang, activeKey, values as any, fallbackValue); } - return this._service.translateSignal(activeKey, this.values() as any, fallbackValue)(); + return this._service.translate(activeKey, values as any, fallbackValue); }); effect(() => { const output = translatedText(); - - this.observer?.disconnect(); - this._textNode!.data = output; - - this.observer?.observe(this._element.nativeElement, { - childList: true, - characterData: true, - subtree: true, - }); + this._lastOutput = output; }); } ngAfterViewChecked(): void { if (this._textNode) { const currentText = this._textNode.data.trim(); - if (currentText !== this.domContent()) { + // Skip a DOM read that's just our own last translated output reflected back — + // otherwise the implicit key/fallback gets contaminated with a stale translation. + if (currentText !== this.domContent() && currentText !== this._lastOutput) { this.domContent.set(currentText); } } @@ -69,25 +66,6 @@ export class TranslateDirective implements OnInit, OnDestroy { ngOnInit(): void { this._textNode = this._resolveTextNode(); this.domContent.set(this._textNode.data.trim()); - - this.observer = new MutationObserver(() => { - const currentText = this._textNode!.data.trim(); - if (currentText !== this.domContent()) { - this.domContent.set(currentText); - } - }); - - this.observer.observe(this._element.nativeElement, { - childList: true, - characterData: true, - subtree: true, - }); - } - - ngOnDestroy(): void { - if (this.observer) { - this.observer.disconnect(); - } } private _resolveTextNode(): Text { diff --git a/src/app/app.component.html b/src/app/app.component.html index 242672c..e42f0c6 100644 --- a/src/app/app.component.html +++ b/src/app/app.component.html @@ -13,8 +13,8 @@
-

-

+

{{ 'welcome_to_app' | translate }}

+

{{ 'hello_user' | translate$: { user: nameInput.value } }}

@@ -27,4 +27,3 @@

Same key:
- diff --git a/src/app/try-directive/try-directive.component.ts b/src/app/try-directive/try-directive.component.ts index baf30c4..80391ee 100644 --- a/src/app/try-directive/try-directive.component.ts +++ b/src/app/try-directive/try-directive.component.ts @@ -8,7 +8,7 @@ import { TranslateRootService } from 'src/_translate.imports'; - +
---

Dynamic content

diff --git a/src/assets/translations/en-US.json b/src/assets/translations/en-US.json index 232b195..a68fc5b 100644 --- a/src/assets/translations/en-US.json +++ b/src/assets/translations/en-US.json @@ -1,64 +1,63 @@ { - "proxy": { - "welcome_to_app": "Welcome to Translation Testing Application", - "hello_user": "Hello $&{user?namespace.user}!", - "hello_world": "Hello World", - "goodbye_world": { - "value": "Goodbye World", - "description": "When you want to say goodbye to the world" - }, + "welcome_to_app": "Welcome to Translation Testing Application", + "hello_user": "Hello $&{user?namespace.user}!", - "namespace": { - "value": "Namespace translated", - "hello_user": "Hello again, $&{user?namespace.user}!", - "user": "User" - }, + "hello_world": "Hello World", + "goodbye_world": { + "value": "Goodbye World", + "description": "When you want to say goodbye to the world" + }, - "i_have_been_here_count": { - "value": "$!{count} ${days}", - "cases": { - "count": [ - ["!!", "I've been here ${count}"], - ["!", "I've not been here"] - ] - }, - "plural": { - "count": [ - ["=0", "... not even once"], - ["=1", "once"], - ["=2", "twice"], - ["in [3,4,5]", "few times"], - ["<100", "many times"], - ["_", "$# times"] - ], - "days": [ - ["=0", "today"], - ["=1", "last day"], - ["<4", "last few days"], - ["_", "for a while"] - ] - } - }, + "namespace": { + "value": "Namespace translated", + "hello_user": "Hello again, $&{user?namespace.user}!", + "user": "User" + }, - "day_since_new_year": { - "value": "It is ${days} New Year", - "plural": { - "days": [ - ["=1", "one day since"], - ["<1", "a first day of"], - [">365", "more then year since that"], - [">360", "almost an year"], - [">181", "more then six months since"], - [">93", "more then three months since"], - ["_", "$# days since"] - ] - } + "i_have_been_here_count": { + "value": "$!{count} ${days}", + "cases": { + "count": [ + ["!!", "I've been here ${count}"], + ["!", "I've not been here"] + ] }, + "plural": { + "count": [ + ["=0", "... not even once"], + ["=1", "once"], + ["=2", "twice"], + ["in [3,4,5]", "few times"], + ["<100", "many times"], + ["_", "$# times"] + ], + "days": [ + ["=0", "today"], + ["=1", "last day"], + ["<4", "last few days"], + ["_", "for a while"] + ] + } + }, + + "day_since_new_year": { + "value": "It is ${days} New Year", + "plural": { + "days": [ + ["=1", "one day since"], + ["<1", "a first day of"], + [">365", "more then year since that"], + [">360", "almost an year"], + [">181", "more then six months since"], + [">93", "more then three months since"], + ["_", "$# days since"] + ] + } + }, - "for_fallback": "Fallback", + "for_fallback": "Fallback", - "same_key": "Same in the Root", - "only_root_key": "Only in the Root" - } + "same_key": "Same in the Root", + "only_root_key": "Only in the Root" } From 92ec1932c6d4897ab12ef05c4533669e9a3634a9 Mon Sep 17 00:00:00 2001 From: Oleg Date: Sat, 1 Aug 2026 14:29:15 +0300 Subject: [PATCH 08/18] fix directive --- projects/translate/src/translate/translate.directive.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/projects/translate/src/translate/translate.directive.ts b/projects/translate/src/translate/translate.directive.ts index 0b08516..3f95578 100644 --- a/projects/translate/src/translate/translate.directive.ts +++ b/projects/translate/src/translate/translate.directive.ts @@ -12,6 +12,7 @@ export class TranslateDirective implements OnInit { private domContent = signal(''); private _textNode: Text | null = null; private _lastOutput: string | null = null; + private _initialContent = ''; fallback = input(undefined); key = input(undefined, { alias: 'translate' }); @@ -32,7 +33,7 @@ export class TranslateDirective implements OnInit { this._service.stateVersion(); const activeKey = finalKey(); - const fallbackValue = this.fallback(); + const fallbackValue = this.fallback() ?? (this._initialContent || undefined); const values = this.values(); @@ -65,7 +66,8 @@ export class TranslateDirective implements OnInit { ngOnInit(): void { this._textNode = this._resolveTextNode(); - this.domContent.set(this._textNode.data.trim()); + this._initialContent = this._textNode.data.trim(); + this.domContent.set(this._initialContent); } private _resolveTextNode(): Text { From 7985050c24da847a66bb5231eb8873340a77fe83 Mon Sep 17 00:00:00 2001 From: Oleg Date: Sat, 1 Aug 2026 14:29:30 +0300 Subject: [PATCH 09/18] readme loader --- README.md | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 8217443..35cc9d1 100644 --- a/README.md +++ b/README.md @@ -410,7 +410,36 @@ For rare cases you may use `id` parameter for Lazy loaded module, that allows ha #### Per-proxy (`applyLoader`) -A `TranslateProxy` subclass can load its own per-language dictionary by overriding `applyLoader()`, without any `forChild()`/`NgModule` wrapper — each language may be a plain object, a `Promise`, an `Observable`, or a URL string fetched via `HttpClient`, and only the *current* language loads eagerly; any other language loads on demand the first time you switch to it. +A `TranslateProxy` subclass can load its own per-language dictionary by overriding `applyLoader()`, without any `forChild()`/`NgModule` wrapper — each language may be a plain object, a `Promise`, an `Observable`, or a URL string fetched via `HttpClient`, and only the *current* language loads eagerly; any other language loads on demand the first time you switch to it. Implement the `TranslateLoaderSupport` interface to get both `applyLoader()` and the optional `onLoaderError()` hook typed: + +```typescript +import { Injectable } from '@angular/core'; +import { Dictionary } from 'simply-translate'; +import { TranslateLoaderSupport, TranslateProxy } from 'simply-translate-angular'; +import type { AppSchema } from './app.schema'; + +@Injectable({ providedIn: 'root' }) +export class AppTranslate extends TranslateProxy implements TranslateLoaderSupport { + applyLoader() { + return { + id: 'app', + dictionaries: { + // dynamic import() — code-split into its own lazy chunk, fetched when this proxy is first constructed + 'en-US': import('./translations/en-US.json').then((m) => m.default as unknown as Dictionary), + // URL string — fetched via HttpClient the first time this language becomes active + 'ru-RU': '/assets/translations/ru-RU.json', + }, + }; + } + + // optional — called whenever a language fails to load; omit it and failures stay silent + onLoaderError({ lang, id, error }: { lang: string; id: string; error: unknown }): void { + console.error(`Failed to load '${id}' (${lang})`, error); + } +} +``` + +`onLoaderError` is the only thing the library ever surfaces on a failed load — there's no default `console.error` of its own, so implement it if you want failures to be visible at all. **Caveat:** unlike `forChild()`'s `id`-based key prefixing, `applyLoader()` does not namespace keys — every proxy's dictionary is merged flat into the same per-language dictionary. If more than one proxy uses `applyLoader()`, wrap each one's own schema in a top-level `Namespace({...})` (named after that feature) to avoid colliding with another proxy's keys. From db010b01ec7bdb31a20cbdfdd40aa716ab3ecf6c Mon Sep 17 00:00:00 2001 From: Oleg Date: Sat, 1 Aug 2026 18:23:18 +0300 Subject: [PATCH 10/18] added param validation --- README.md | 59 +++++++--- package.json | 2 +- projects/translate/package.json | 2 +- .../translate/src/__test__/loader.spec.ts | 5 +- projects/translate/src/__test__/proxy.spec.ts | 10 +- .../translate/src/__test__/schema.spec.ts | 52 ++++++--- projects/translate/src/public_api.ts | 8 +- .../translate/src/simply-translate.module.ts | 2 +- .../loader/translate.loader-cache.ts | 0 .../loader/translate.loader.resolver.ts | 4 +- .../{ => proxy}/loader/translate.loader.ts | 2 +- .../src/translate/{ => proxy}/schema/index.ts | 0 .../{ => proxy}/schema/infer-schema-type.ts | 3 +- .../translate/proxy/schema/schema-builders.ts | 38 +++++++ .../{ => proxy}/schema/schema.types.ts | 30 ++++++ .../{ => proxy}/schema/validate-dictionary.ts | 101 ++++++++++++++++-- .../translate/{ => proxy}/translate.proxy.ts | 4 +- .../src/translate/schema/schema-builders.ts | 26 ----- src/app/try-proxy/schema.ts | 27 +++++ src/app/try-proxy/translate.proxy.ts | 5 +- src/app/try-proxy/try-proxy.component.ts | 2 +- src/assets/translations/proxy/_.ts | 27 ----- tsconfig.json | 2 +- 23 files changed, 294 insertions(+), 117 deletions(-) rename projects/translate/src/translate/{ => proxy}/loader/translate.loader-cache.ts (100%) rename projects/translate/src/translate/{ => proxy}/loader/translate.loader.resolver.ts (71%) rename projects/translate/src/translate/{ => proxy}/loader/translate.loader.ts (97%) rename projects/translate/src/translate/{ => proxy}/schema/index.ts (100%) rename projects/translate/src/translate/{ => proxy}/schema/infer-schema-type.ts (77%) create mode 100644 projects/translate/src/translate/proxy/schema/schema-builders.ts rename projects/translate/src/translate/{ => proxy}/schema/schema.types.ts (51%) rename projects/translate/src/translate/{ => proxy}/schema/validate-dictionary.ts (54%) rename projects/translate/src/translate/{ => proxy}/translate.proxy.ts (96%) delete mode 100644 projects/translate/src/translate/schema/schema-builders.ts create mode 100644 src/app/try-proxy/schema.ts delete mode 100644 src/assets/translations/proxy/_.ts diff --git a/README.md b/README.md index 35cc9d1..61ba580 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ #### (v0.21.10) - `TranslateProxy` now takes a schema type (`typeof yourSchema`) instead of a hand-written `Dictionary` interface — see [Use TranslateProxy](#Use-TranslateProxy). -- added schema-first dictionary definitions (`TranslateSchema`, `String`, `Value`, `Namespace`) and runtime validation (`validateDictionary`, `assertValidDictionary`) — see [Validating dictionaries with a schema](#validating-dictionaries-with-a-schema). +- added schema-first dictionary definitions (`TranslateSchema`, `StringProp`, `ValueProp`, `Namespace`) and runtime validation (`validateDictionary`, `assertValidDictionary`), including placeholder-usage checks against each leaf's declared `params` — see [Validating dictionaries with a schema](#validating-dictionaries-with-a-schema). #### (v0.21.0) @@ -154,20 +154,22 @@ For typed, autocompleted access to your dictionary keys, describe your dictionar ```typescript // app.schema.ts -import { Namespace, String, TranslateSchema, Value } from 'simply-translate-angular'; +import { Namespace, NumberParam, StringParam, StringProp, TranslateSchema, ValueProp } from 'simply-translate-angular'; export const appSchema = TranslateSchema({ - hello_user: String<{ user: string }>(), - about: String(), + hello_user: StringProp({ params: { user: StringParam } }), + about: StringProp(), namespace: Namespace({ - hello_user: String<{ user: string }>(), + hello_user: StringProp({ params: { user: StringParam } }), }), - visit_count: Value<{ count: number }>(), + visit_count: ValueProp({ params: { count: NumberParam } }), }); export type AppSchema = typeof appSchema; ``` +(Named `StringProp`/`ValueProp` rather than `String`/`Value` to avoid shadowing the globals of the same name.) + ```typescript // app.translate.ts import { Injectable } from '@angular/core'; @@ -178,14 +180,16 @@ import type { AppSchema } from './app.schema'; export class AppTranslate extends TranslateProxy {} ``` -`TranslateProxy` takes the schema itself as its type parameter — the dictionary type is inferred from it via `InferTranslateSchemaType`. `TranslateProxy` only ever needs `AppSchema`'s **type**, never `appSchema`'s runtime value, so import it with `import type`: TypeScript erases `import type` entirely at compile time, keeping the schema-building code (and everything it imports) out of your app's bundle unless something else in it also needs the actual schema object at runtime — e.g. to call `validateDictionary`. See [Validating dictionaries with a schema](#validating-dictionaries-with-a-schema) for the full builder API (`String`, `Value`, `Namespace`) and for validating your JSON dictionaries against the same schema at runtime. +`TranslateProxy` takes the schema itself as its type parameter — the dictionary type is inferred from it via `InferTranslateSchemaType`. `TranslateProxy` only ever needs `AppSchema`'s **type**, never `appSchema`'s runtime value, so import it with `import type`: TypeScript erases `import type` entirely at compile time, keeping the schema-building code (and everything it imports) out of your app's bundle unless something else in it also needs the actual schema object at runtime — e.g. to call `validateDictionary`. See [Validating dictionaries with a schema](#validating-dictionaries-with-a-schema) for the full builder API (`StringProp`, `ValueProp`, `Namespace`) and for validating your JSON dictionaries against the same schema at runtime. Inject it like any other service and read keys off `object`. Every leaf key is callable (mirrors `translate`), and carries `.Signal()` / `.$()` companions that mirror `translateSignal` / `translateObservable`. **The params each of these accepts comes entirely from how the schema leaf was declared:** -- `String()` / `Value()`, called with no type argument — the leaf takes **no dynamic props at all**. The call, `.Signal()`, and `.$()` all become zero-argument — passing anything is a compile error. -- `String()` / `Value()` — the leaf **requires** exactly `TParams`, everywhere. Omitting the argument, passing `undefined`, or passing the wrong shape are all compile errors. +- `StringProp()` / `ValueProp()`, called with no `params` — the leaf takes **no dynamic props at all**. The call, `.Signal()`, and `.$()` all become zero-argument — passing anything is a compile error. +- `StringProp({ params: {...} })` / `ValueProp({ params: {...} })` — the leaf **requires** exactly the shape described by `params`, everywhere. Omitting the argument, passing `undefined`, or passing the wrong shape are all compile errors. + +`params` is a flat map of prop name → either an actual default value (e.g. `user: 'Guest'`, `count: 0`) or, when there's no natural default, the `StringParam` / `NumberParam` markers. Either way the value is only ever used to infer that prop's type (`string`/`number`) and to read its name — nothing about it is used at runtime beyond that. Params are intentionally flat (`string`/`number` only, no nesting) to match what dynamic props can actually be. ```typescript @Component({ @@ -205,7 +209,7 @@ export class MyComponent { // nested keys work the same way this.nsHello = translate.object.namespace.hello_user({ user: 'Oleg' }); - // `about` was declared with String() (no type argument) -> zero-argument call + // `about` was declared with StringProp() (no params) -> zero-argument call this.about = translate.object.about(); // translate.object.about({ user: 'Oleg' }); // compile error: `about` takes no params // translate.object.hello_user(); // compile error: `hello_user` requires { user: string } @@ -235,18 +239,18 @@ this.helloSignal = translate.object.hello_user.Signal({ user: 'Oleg' }); Build a schema with three node builders: -- `String()` — a leaf that must be a plain string. -- `Value()` — a leaf that may be a string, a `DictionaryEntry` (`{ value, plural?, cases?, description? }`), or a nested dictionary. +- `StringProp()` — a leaf that must be a plain string. +- `ValueProp()` — a leaf that may be a string, a `DictionaryEntry` (`{ value, plural?, cases?, description? }`), or a nested dictionary. - `Namespace({...})` — a nested dictionary with a fixed, known shape. ```typescript -import { Namespace, String, TranslateSchema, Value } from 'simply-translate-angular'; +import { Namespace, StringProp, TranslateSchema, ValueProp } from 'simply-translate-angular'; export const appSchema = TranslateSchema({ - welcome_to_app: String(), - goodbye_world: Value(), // string, or { value, description } etc. + welcome_to_app: StringProp(), + goodbye_world: ValueProp(), // string, or { value, description } etc. namespace: Namespace({ - hello_user: Value(), + hello_user: ValueProp(), }), }); @@ -274,6 +278,29 @@ const errors = validateDictionary(appSchema, parsedJson, { }); ``` +#### Placeholder validation + +When a leaf declares `params` (see [Use TranslateProxy](#Use-TranslateProxy)), `validateDictionary` also checks that every declared param actually shows up as a `${name}` placeholder somewhere in the translation — and flags any placeholder that *isn't* declared. "Somewhere" covers the leaf's `value` as well as every `plural`/`cases` result string, since `simply-translate` re-scans a chosen plural/case result for further placeholders: + +```typescript +const appSchema = TranslateSchema({ + hello_user: StringProp({ params: { user: StringParam } }), + about: StringProp(), +}); + +validateDictionary(appSchema, { hello_user: 'Hello there', about: 'Welcome' }); +// [{ path: ['hello_user'], message: 'missing placeholder for param "user"' }] + +validateDictionary(appSchema, { hello_user: 'Hello ${user}!', about: 'Welcome, ${name}!' }); +// [{ path: ['about'], message: 'unexpected placeholder "name", not declared in schema params' }] +``` + +If your app uses a non-default `placeholder` style (`'single'` `{user}` / `'double'` `{{user}}`, see [`TranslateModule.forRoot`](#Initialize)), pass the same value so the checks recognize the right syntax: + +```typescript +validateDictionary(appSchema, parsedJson, { placeholder: 'single' }); +``` + ### Load dictionaries #### Root diff --git a/package.json b/package.json index c73d556..9663e02 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "publish:prod:patch": "npm run build:prod:patch && cd dist/translate && npm publish && cd ../..", "build:demo:dev": "ng build --configuration development", "build:demo:prod": "node --max-old-space-size=8192 ./node_modules/@angular/cli/bin/ng build --configuration production --aot", - "start:demo": "ng serve --port 4801 --live-reload false", + "start:demo": "ng serve --port 4800 --live-reload false", "restart:all": "npm run build:library:prod && npm run start:demo", "test": "ng test translate", "e2e": "ng e2e", diff --git a/projects/translate/package.json b/projects/translate/package.json index 291e2eb..c189f1b 100644 --- a/projects/translate/package.json +++ b/projects/translate/package.json @@ -1,6 +1,6 @@ { "name": "simply-translate-angular", - "version": "0.21.10", + "version": "0.21.12", "type": "module", "dependencies": { "tslib": "^2.4.0", diff --git a/projects/translate/src/__test__/loader.spec.ts b/projects/translate/src/__test__/loader.spec.ts index cd78cae..386f224 100644 --- a/projects/translate/src/__test__/loader.spec.ts +++ b/projects/translate/src/__test__/loader.spec.ts @@ -2,12 +2,11 @@ import { HttpClient } from '@angular/common/http'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { Subject } from 'rxjs'; -import { TranslateRootService } from '../public_api'; +import { TranslateLoaderCache, TranslateLoaderDictionaries, TranslateRootService } from '../public_api'; import { TranslateModule } from '../simply-translate.module'; -import { TranslateLoader, TranslateLoaderDictionaries } from '../translate/loader/translate.loader'; -import { TranslateLoaderCache } from '../translate/loader/translate.loader-cache'; import { TranslateService } from '../translate/translate.service'; import { tick } from './core/tick'; +import { TranslateLoader } from '../translate/proxy/loader/translate.loader'; const lang = 'lang'; const newLang = 'new'; diff --git a/projects/translate/src/__test__/proxy.spec.ts b/projects/translate/src/__test__/proxy.spec.ts index de75a56..31dff22 100644 --- a/projects/translate/src/__test__/proxy.spec.ts +++ b/projects/translate/src/__test__/proxy.spec.ts @@ -3,15 +3,15 @@ import { TestBed } from '@angular/core/testing'; import { BehaviorSubject } from 'rxjs'; import { TranslateRootService } from '../public_api'; import { TranslateModule } from '../simply-translate.module'; -import { Namespace, String as Str, TranslateSchema } from '../translate/schema'; -import { TranslateProxy } from '../translate/translate.proxy'; +import { Namespace, StringProp as Str, StringParam, TranslateSchema } from '../translate/proxy/schema'; +import { TranslateProxy } from '../translate/proxy/translate.proxy'; const testSchema = TranslateSchema({ - hello_user: Str<{ user: string }>(), - strict_user: Str<{ user: string }>(), + hello_user: Str({ params: { user: StringParam } }), + strict_user: Str({ params: { user: StringParam } }), no_params: Str(), namespace: Namespace({ - hello_user: Str<{ user: string }>(), + hello_user: Str({ params: { user: StringParam } }), }), }); diff --git a/projects/translate/src/__test__/schema.spec.ts b/projects/translate/src/__test__/schema.spec.ts index 67b8151..37ebd28 100644 --- a/projects/translate/src/__test__/schema.spec.ts +++ b/projects/translate/src/__test__/schema.spec.ts @@ -1,23 +1,23 @@ import { Dictionary } from 'simply-translate'; -import { InferTranslateSchemaType, Namespace, String, TranslateSchema, Value, validateDictionary } from '../translate/schema'; +import { InferTranslateSchemaType, Namespace, NumberParam, StringProp, StringParam, TranslateSchema, ValueProp, validateDictionary } from '../translate/proxy/schema'; const testSchema = TranslateSchema({ - welcome_to_app: String(), - hello_user: String(), + welcome_to_app: StringProp(), + hello_user: StringProp({ params: { user: StringParam } }), - hello_world: Value(), - goodbye_world: Value(), + hello_world: ValueProp(), + goodbye_world: ValueProp(), namespace: Namespace({ - value: String(), - hello_user: Value(), - user: Value(), + value: StringProp(), + hello_user: ValueProp({ params: { user: StringParam } }), + user: ValueProp(), }), - i_have_been_here_count: Value(), - day_since_new_year: Value(), - for_fallback: Value(), - same_key: Value(), + i_have_been_here_count: ValueProp({ params: { count: NumberParam, days: NumberParam } }), + day_since_new_year: ValueProp({ params: { days: NumberParam } }), + for_fallback: ValueProp(), + same_key: ValueProp(), }); type TestDictionary = InferTranslateSchemaType; @@ -113,7 +113,7 @@ describe('schema', () => { it('recurses into a namespace and reports nested errors with a full path', () => { const errors = validateDictionary(testSchema, { ...validDictionary, - namespace: { value: 'Namespace translated', hello_user: 'Hello again!' }, + namespace: { value: 'Namespace translated', hello_user: 'Hello again, ${user}!' }, }); expect(errors).toEqual([{ path: ['namespace', 'user'], message: 'missing key' }]); }); @@ -122,4 +122,30 @@ describe('schema', () => { expect(validateDictionary(testSchema, null)).toEqual([{ path: [], message: 'expected a dictionary object, got null' }]); expect(validateDictionary(testSchema, 'nope')).toEqual([{ path: [], message: 'expected a dictionary object, got string' }]); }); + + it('reports a missing placeholder for a declared param', () => { + const errors = validateDictionary(testSchema, { ...validDictionary, hello_user: 'Hello there' }); + expect(errors).toEqual([{ path: ['hello_user'], message: 'missing placeholder for param "user"' }]); + }); + + it('reports an unexpected placeholder when the node declares no params', () => { + const errors = validateDictionary(testSchema, { ...validDictionary, welcome_to_app: 'Welcome, ${name}!' }); + expect(errors).toEqual([{ path: ['welcome_to_app'], message: 'unexpected placeholder "name", not declared in schema params' }]); + }); + + it('accepts a required placeholder that only appears inside a plural/cases result string', () => { + const errors = validateDictionary(testSchema, { + ...validDictionary, + day_since_new_year: { value: 'x', plural: { count: [['=1', 'Just ${days} day']] } }, + }); + expect(errors).toEqual([]); + }); + + it('supports the "single" placeholder syntax via the `placeholder` option', () => { + const singleSchema = TranslateSchema({ greeting: StringProp({ params: { user: StringParam } }) }); + expect(validateDictionary(singleSchema, { greeting: 'Hello {user}!' }, { placeholder: 'single' })).toEqual([]); + expect(validateDictionary(singleSchema, { greeting: 'Hello {user}!' })).toEqual([ + { path: ['greeting'], message: 'missing placeholder for param "user"' }, + ]); + }); }); diff --git a/projects/translate/src/public_api.ts b/projects/translate/src/public_api.ts index 05dca4d..99cdb72 100644 --- a/projects/translate/src/public_api.ts +++ b/projects/translate/src/public_api.ts @@ -2,9 +2,11 @@ export * from './translate/translate.directive'; export * from './translate/translate.pipe'; export * from './translate/translate.resolver'; export * from './translate/translate.service'; -export * from './translate/translate.proxy'; -export * from './translate/schema'; -export { TranslateLoaderSupport, TranslateLoaderDictionaries, TranslateLoaderDictionary } from './translate/loader/translate.loader'; +export * from './translate/proxy/translate.proxy'; +export * from './translate/proxy/schema'; +export { TranslateLoaderSupport, TranslateLoaderDictionaries, TranslateLoaderDictionary } from './translate/proxy/loader/translate.loader'; +export { TranslateLoaderCache } from './translate/proxy/loader/translate.loader-cache'; +export { translateLoaderResolver } from './translate/proxy/loader/translate.loader.resolver'; export * from './simply-translate.module'; export { TranslateChildConfig } from './translate/translate.service'; export { diff --git a/projects/translate/src/simply-translate.module.ts b/projects/translate/src/simply-translate.module.ts index ddd18e1..5564176 100644 --- a/projects/translate/src/simply-translate.module.ts +++ b/projects/translate/src/simply-translate.module.ts @@ -14,7 +14,7 @@ import { import { TranslatePipe, TranslateToPipe, TranslatePipeDetect } from './translate/translate.pipe'; import { TranslateDirective } from './translate/translate.directive'; import { TranslateResolve } from './translate/translate.resolver'; -import { TranslateLoaderCache } from './translate/loader/translate.loader-cache'; +import { TranslateLoaderCache } from './translate/proxy/loader/translate.loader-cache'; export type AddMiddlewareFunc = (...any: any[]) => Array; export type LoadDictionariesFunc = ( diff --git a/projects/translate/src/translate/loader/translate.loader-cache.ts b/projects/translate/src/translate/proxy/loader/translate.loader-cache.ts similarity index 100% rename from projects/translate/src/translate/loader/translate.loader-cache.ts rename to projects/translate/src/translate/proxy/loader/translate.loader-cache.ts diff --git a/projects/translate/src/translate/loader/translate.loader.resolver.ts b/projects/translate/src/translate/proxy/loader/translate.loader.resolver.ts similarity index 71% rename from projects/translate/src/translate/loader/translate.loader.resolver.ts rename to projects/translate/src/translate/proxy/loader/translate.loader.resolver.ts index 950961a..dbc3903 100644 --- a/projects/translate/src/translate/loader/translate.loader.resolver.ts +++ b/projects/translate/src/translate/proxy/loader/translate.loader.resolver.ts @@ -1,10 +1,10 @@ import { inject } from '@angular/core'; import { Dictionary } from 'simply-translate'; import { TranslateLoaderCache } from './translate.loader-cache'; -import { TranslateService } from '../translate.service'; +import { TranslateService } from '../../translate.service'; import { ResolveFn } from '@angular/router'; -export const translationsExtensionResolver: (id: string) => ResolveFn = (id: string) => { +export const translateLoaderResolver: (id: string) => ResolveFn = (id: string) => { return () => { const provider = inject(TranslateLoaderCache); const service = inject(TranslateService); diff --git a/projects/translate/src/translate/loader/translate.loader.ts b/projects/translate/src/translate/proxy/loader/translate.loader.ts similarity index 97% rename from projects/translate/src/translate/loader/translate.loader.ts rename to projects/translate/src/translate/proxy/loader/translate.loader.ts index d3664d0..fa9e47f 100644 --- a/projects/translate/src/translate/loader/translate.loader.ts +++ b/projects/translate/src/translate/proxy/loader/translate.loader.ts @@ -1,6 +1,6 @@ import { from, Observable, shareReplay, Subject, Subscription } from 'rxjs'; import { Dictionary } from 'simply-translate'; -import { TranslateService } from '../translate.service'; +import { TranslateService } from '../../translate.service'; import { TranslateLoaderCache } from './translate.loader-cache'; import { HttpClient } from '@angular/common/http'; diff --git a/projects/translate/src/translate/schema/index.ts b/projects/translate/src/translate/proxy/schema/index.ts similarity index 100% rename from projects/translate/src/translate/schema/index.ts rename to projects/translate/src/translate/proxy/schema/index.ts diff --git a/projects/translate/src/translate/schema/infer-schema-type.ts b/projects/translate/src/translate/proxy/schema/infer-schema-type.ts similarity index 77% rename from projects/translate/src/translate/schema/infer-schema-type.ts rename to projects/translate/src/translate/proxy/schema/infer-schema-type.ts index 3407fd9..4a5e802 100644 --- a/projects/translate/src/translate/schema/infer-schema-type.ts +++ b/projects/translate/src/translate/proxy/schema/infer-schema-type.ts @@ -1,6 +1,5 @@ import { Dictionary } from 'simply-translate'; -import { DictionaryValue } from '../translate.proxy'; -import { NamespaceNode, SchemaNode, SchemaShape, TranslateSchemaNode } from './schema.types'; +import { DictionaryValue, NamespaceNode, SchemaNode, SchemaShape, TranslateSchemaNode } from './schema.types'; type InferNode = Node extends { kind: 'string' } ? string diff --git a/projects/translate/src/translate/proxy/schema/schema-builders.ts b/projects/translate/src/translate/proxy/schema/schema-builders.ts new file mode 100644 index 0000000..d438a33 --- /dev/null +++ b/projects/translate/src/translate/proxy/schema/schema-builders.ts @@ -0,0 +1,38 @@ +import { InferParams, NamespaceNode, Params, SchemaShape, StringNode, TranslateSchemaNode, ValueNode } from './schema.types'; + +// Overloaded rather than a single `` signature: when this is called bare, as an +// argument inside `Namespace({...})`/`TranslateSchema({...})`, TypeScript uses that call's expected +// contextual type (`SchemaNode`) to help infer TParams — which silently overrides a *default* type +// parameter with whatever `SchemaNode`'s own default is, discarding `undefined`. A non-generic overload +// for the zero-argument call has no generic parameter for that contextual type to hijack. +// `TParams` is inferred from `params` itself (an example value per key, or `StringParam`/`NumberParam` +// when there's no natural default) rather than passed explicitly — generics are erased at runtime, so +// without this witness `validateDictionary` would have no way to know which placeholders a translation +// is supposed to contain, and declaring the shape twice (as a type argument AND at runtime) would be redundant. +export function StringProp(options?: { description?: string }): StringNode; +export function StringProp

(options: { description?: string; params: P }): StringNode>; +export function StringProp(options?: { description?: string; params?: Params }): StringNode { + return { + kind: 'string', + description: options?.description, + paramNames: options?.params ? Object.keys(options.params) : undefined, + }; +} + +export function ValueProp(options?: { description?: string }): ValueNode; +export function ValueProp

(options: { description?: string; params: P }): ValueNode>; +export function ValueProp(options?: { description?: string; params?: Params }): ValueNode { + return { + kind: 'value', + description: options?.description, + paramNames: options?.params ? Object.keys(options.params) : undefined, + }; +} + +export function Namespace(shape: Shape, options?: { description?: string }): NamespaceNode { + return { kind: 'namespace', shape, description: options?.description }; +} + +export function TranslateSchema(shape: Shape): TranslateSchemaNode { + return { kind: 'namespace', shape }; +} diff --git a/projects/translate/src/translate/schema/schema.types.ts b/projects/translate/src/translate/proxy/schema/schema.types.ts similarity index 51% rename from projects/translate/src/translate/schema/schema.types.ts rename to projects/translate/src/translate/proxy/schema/schema.types.ts index 8c6de83..1c80efc 100644 --- a/projects/translate/src/translate/schema/schema.types.ts +++ b/projects/translate/src/translate/proxy/schema/schema.types.ts @@ -1,8 +1,12 @@ +import { Dictionary, DictionaryEntry } from "simply-translate"; + export interface BaseNode { readonly kind: 'string' | 'value' | 'namespace'; readonly description?: string; /** Never actually called — a phantom marker so `TParams` can be recovered later via `extends BaseNode`. */ readonly params?: (params: TParams) => void; + /** Runtime witness of `TParams`' keys — generics are erased at runtime, so `validateDictionary` needs this to check placeholder usage. */ + readonly paramNames?: readonly string[]; } export interface StringNode extends BaseNode { @@ -27,3 +31,29 @@ export type SchemaNode = StringNode | ValueNode export type SchemaShape = Record; export type TranslateSchemaNode = NamespaceNode; + +export type DictionaryValue = T extends string ? string : T extends Dictionary ? T : DictionaryEntry; + +// Sentinels for declaring a param's type when it has no natural default value. Params are kept flat +// (string | number only, no nesting) to match `TranslateDynamicProps` and keep placeholder validation simple. +export const StringParam: unique symbol = Symbol('StringParam'); +export const NumberParam: unique symbol = Symbol('NumberParam'); + +export type ParamMarker = typeof StringParam | typeof NumberParam; + +/** A param's declared value: an actual default (`string`/`number`), or a marker when there's no sensible default. */ +export type ParamValue = string | number | ParamMarker; + +export type Params = Record; + +type InferParamValue = V extends typeof StringParam + ? string + : V extends typeof NumberParam + ? number + : V extends string + ? string + : V extends number + ? number + : never; + +export type InferParams

= { [K in keyof P]: InferParamValue }; diff --git a/projects/translate/src/translate/schema/validate-dictionary.ts b/projects/translate/src/translate/proxy/schema/validate-dictionary.ts similarity index 54% rename from projects/translate/src/translate/schema/validate-dictionary.ts rename to projects/translate/src/translate/proxy/schema/validate-dictionary.ts index baf3a81..b21ceed 100644 --- a/projects/translate/src/translate/schema/validate-dictionary.ts +++ b/projects/translate/src/translate/proxy/schema/validate-dictionary.ts @@ -1,3 +1,4 @@ +import { PlaceholderType } from 'simply-translate'; import { SchemaNode, SchemaShape, TranslateSchemaNode } from './schema.types'; export interface SchemaValidationError { @@ -15,6 +16,59 @@ export interface ValidateDictionaryOptions { allowedMissing?: SchemaAllowanceMap; /** Dictionary keys allowed to be absent from the schema, e.g. a root-only fallback key. */ allowedOrphans?: SchemaAllowanceMap; + /** Placeholder syntax the dictionaries use — must match the `placeholder` passed to `TranslateModule.forRoot`. */ + placeholder?: PlaceholderType; +} + +// Mirrors the prefix rules `simply-translate` uses to decide a `{...}` is actually a placeholder (see +// `prepare-regular-expressions-middleware`): 'default' requires a `$`/`&`/`!` right before the brace, +// 'single'/'double' don't. The captured group is always the placeholder's prop name. +const PLACEHOLDER_PATTERNS: Record = { + default: /(?:\$[&!]?|[&!])\{([\w.-]+)(?:\?[^}]*)?\}/g, + single: /[&!]?\{([\w.-]+)(?:\?[^}]*)?\}/g, + double: /[&!]?\{\{([\w.-]+)(?:\?[^}]*)?\}\}/g, +}; + +function findPlaceholders(value: string, pattern: RegExp, found: Set): void { + pattern.lastIndex = 0; + let match: RegExpExecArray | null; + while ((match = pattern.exec(value))) { + found.add(match[1]); + } +} + +function collectPlaceholders(value: string, pattern: RegExp): Set { + const found = new Set(); + findPlaceholders(value, pattern, found); + return found; +} + +// `plural`/`cases` maps are keyed by prop name, each holding `[matcher, resultText, testFn?]` options — +// `resultText` (index 1) can itself reference placeholders (including other params), since +// `simply-translate` re-scans a chosen plural/case result for further `{...}` substitutions. +function collectMapPlaceholders(map: Record, pattern: RegExp, found: Set): void { + for (const options of Object.values(map)) { + if (!Array.isArray(options)) continue; + for (const option of options) { + if (Array.isArray(option) && typeof option[1] === 'string') { + findPlaceholders(option[1], pattern, found); + } + } + } +} + +function checkParams(found: Set, required: readonly string[] | undefined, path: string[], errors: SchemaValidationError[]): void { + const requiredSet = new Set(required ?? []); + for (const name of requiredSet) { + if (!found.has(name)) { + errors.push({ path, message: `missing placeholder for param "${name}"` }); + } + } + for (const name of found) { + if (!requiredSet.has(name)) { + errors.push({ path, message: `unexpected placeholder "${name}", not declared in schema params` }); + } + } } export function validateDictionary(schema: TranslateSchemaNode, data: unknown, options?: ValidateDictionaryOptions): SchemaValidationError[] { @@ -22,7 +76,8 @@ export function validateDictionary(schema: TranslateSchemaNode, data: unknown, o if (!isPlainObject(data)) { return [{ path: [], message: `expected a dictionary object, got ${describe(data)}` }]; } - validateShape(schema.shape, data, [], errors, options ?? {}); + const pattern = PLACEHOLDER_PATTERNS[options?.placeholder ?? 'default']; + validateShape(schema.shape, data, [], errors, options ?? {}, pattern); return errors; } @@ -44,6 +99,7 @@ function validateShape( path: string[], errors: SchemaValidationError[], options: ValidateDictionaryOptions, + pattern: RegExp, ): void { for (const key of Object.keys(shape)) { const childPath = [...path, key]; @@ -53,7 +109,7 @@ function validateShape( } continue; } - validateNode(shape[key], obj[key], childPath, errors, options); + validateNode(shape[key], obj[key], childPath, errors, options, pattern); } for (const key of Object.keys(obj)) { if (!(key in shape)) { @@ -75,56 +131,85 @@ function validateNode( path: string[], errors: SchemaValidationError[], options: ValidateDictionaryOptions, + pattern: RegExp, ): void { switch (node.kind) { case 'string': if (typeof value !== 'string') { errors.push({ path, message: `expected string, got ${describe(value)}` }); + return; } + checkParams(collectPlaceholders(value, pattern), node.paramNames, path, errors); return; case 'namespace': if (!isPlainObject(value)) { errors.push({ path, message: `expected a nested dictionary, got ${describe(value)}` }); return; } - validateShape(node.shape, value, path, errors, options); + validateShape(node.shape, value, path, errors, options, pattern); return; case 'value': - validateDictionaryValue(value, path, errors); + validateDictionaryValue(value, node.paramNames, pattern, path, errors); return; } } -function validateDictionaryValue(value: unknown, path: string[], errors: SchemaValidationError[]): void { +function validateDictionaryValue( + value: unknown, + paramNames: readonly string[] | undefined, + pattern: RegExp, + path: string[], + errors: SchemaValidationError[], +): void { if (typeof value === 'string') { + checkParams(collectPlaceholders(value, pattern), paramNames, path, errors); return; } if (isPlainObject(value)) { if ('value' in value) { - validateDictionaryEntry(value, path, errors); + validateDictionaryEntry(value, paramNames, pattern, path, errors); return; } for (const [key, child] of Object.entries(value)) { - validateDictionaryValue(child, [...path, key], errors); + validateDictionaryValue(child, paramNames, pattern, [...path, key], errors); } return; } errors.push({ path, message: `expected a string, entry, or nested dictionary, got ${describe(value)}` }); } -function validateDictionaryEntry(entry: Record, path: string[], errors: SchemaValidationError[]): void { +function validateDictionaryEntry( + entry: Record, + paramNames: readonly string[] | undefined, + pattern: RegExp, + path: string[], + errors: SchemaValidationError[], +): void { + const found = new Set(); + if (typeof entry['value'] !== 'string') { errors.push({ path: [...path, 'value'], message: `expected string, got ${describe(entry['value'])}` }); + } else { + findPlaceholders(entry['value'], pattern, found); } + if (entry['plural'] !== undefined && !isPlainObject(entry['plural'])) { errors.push({ path: [...path, 'plural'], message: `expected a plurals map, got ${describe(entry['plural'])}` }); + } else if (isPlainObject(entry['plural'])) { + collectMapPlaceholders(entry['plural'], pattern, found); } + if (entry['cases'] !== undefined && !isPlainObject(entry['cases'])) { errors.push({ path: [...path, 'cases'], message: `expected a cases map, got ${describe(entry['cases'])}` }); + } else if (isPlainObject(entry['cases'])) { + collectMapPlaceholders(entry['cases'], pattern, found); } + if (entry['description'] !== undefined && typeof entry['description'] !== 'string') { errors.push({ path: [...path, 'description'], message: `expected string, got ${describe(entry['description'])}` }); } + + checkParams(found, paramNames, path, errors); } function isPlainObject(value: unknown): value is Record { diff --git a/projects/translate/src/translate/translate.proxy.ts b/projects/translate/src/translate/proxy/translate.proxy.ts similarity index 96% rename from projects/translate/src/translate/translate.proxy.ts rename to projects/translate/src/translate/proxy/translate.proxy.ts index c8f2252..1ae1947 100644 --- a/projects/translate/src/translate/translate.proxy.ts +++ b/projects/translate/src/translate/proxy/translate.proxy.ts @@ -2,7 +2,7 @@ import { inject, Injectable, OnDestroy, Signal } from '@angular/core'; import { Observable } from 'rxjs'; import { Dictionary, DictionaryEntry, TranslateDynamicProps } from 'simply-translate'; import type { BaseNode, NamespaceNode, SchemaShape, TranslateSchemaNode } from './schema/schema.types'; -import { TranslateService } from './translate.service'; +import { TranslateService } from '../translate.service'; import { TranslateLoader, TranslateLoaderDictionaries, TranslateLoaderSupport } from './loader/translate.loader'; import { TranslateLoaderCache } from './loader/translate.loader-cache'; import { HttpClient } from '@angular/common/http'; @@ -28,8 +28,6 @@ export type ProxyDictionary = { : never; }; -export type DictionaryValue = T extends string ? string : T extends Dictionary ? T : DictionaryEntry; - @Injectable() export abstract class TranslateProxy implements OnDestroy, Partial { private _cache: any = {}; diff --git a/projects/translate/src/translate/schema/schema-builders.ts b/projects/translate/src/translate/schema/schema-builders.ts deleted file mode 100644 index 35a4163..0000000 --- a/projects/translate/src/translate/schema/schema-builders.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { NamespaceNode, SchemaShape, StringNode, TranslateSchemaNode, ValueNode } from './schema.types'; - -// Overloaded rather than a single `` signature: when this is called bare, as an -// argument inside `Namespace({...})`/`TranslateSchema({...})`, TypeScript uses that call's expected -// contextual type (`SchemaNode`) to help infer TParams — which silently overrides a *default* type -// parameter with whatever `SchemaNode`'s own default is, discarding `undefined`. A non-generic overload -// for the zero-argument call has no generic parameter for that contextual type to hijack. -export function String(options?: { description?: string }): StringNode; -export function String(options?: { description?: string }): StringNode; -export function String(options?: { description?: string }): StringNode { - return { kind: 'string', description: options?.description, params: (_: TParams) => {} }; -} - -export function Value(options?: { description?: string }): ValueNode; -export function Value(options?: { description?: string }): ValueNode; -export function Value(options?: { description?: string }): ValueNode { - return { kind: 'value', description: options?.description, params: (_: TParams) => {} }; -} - -export function Namespace(shape: Shape, options?: { description?: string }): NamespaceNode { - return { kind: 'namespace', shape, description: options?.description }; -} - -export function TranslateSchema(shape: Shape): TranslateSchemaNode { - return { kind: 'namespace', shape }; -} diff --git a/src/app/try-proxy/schema.ts b/src/app/try-proxy/schema.ts new file mode 100644 index 0000000..8a24c38 --- /dev/null +++ b/src/app/try-proxy/schema.ts @@ -0,0 +1,27 @@ +import { Namespace, NumberParam, StringProp, StringParam, TranslateSchema, ValueProp } from 'projects/translate/src/public_api'; + +export const testDictionary = TranslateSchema({ + proxy: Namespace({ + welcome_to_app: StringProp(), + hello_user: StringProp({ params: { user: StringParam } }), + + hello_world: StringProp(), + goodbye_world: StringProp(), + + namespace: Namespace({ + value: StringProp(), + hello_user: ValueProp({params: { user: StringParam }}), + user: ValueProp(), + }), + + i_have_been_here_count: ValueProp({params: { count: NumberParam, days: NumberParam }}), + + day_since_new_year: ValueProp({params: { days: 100 }}), + + for_fallback: ValueProp(), + + same_key: ValueProp(), + }), +}); + +export type TestDictionary = typeof testDictionary; diff --git a/src/app/try-proxy/translate.proxy.ts b/src/app/try-proxy/translate.proxy.ts index bcf4200..63e661f 100644 --- a/src/app/try-proxy/translate.proxy.ts +++ b/src/app/try-proxy/translate.proxy.ts @@ -1,8 +1,7 @@ import { Injectable } from '@angular/core'; -import { TranslateProxy } from '../../../projects/translate/src/translate/translate.proxy'; -import type { TestDictionary } from 'src/assets/translations/proxy/_'; +import type { TestDictionary } from 'src/app/try-proxy/schema'; import { Dictionary } from 'simply-translate'; -import { TranslateLoaderSupport } from 'projects/translate/src/translate/loader/translate.loader'; +import { TranslateLoaderSupport, TranslateProxy } from 'projects/translate/src/public_api'; @Injectable({ providedIn: 'root' }) export class TranslateProxyCommon extends TranslateProxy implements TranslateLoaderSupport { diff --git a/src/app/try-proxy/try-proxy.component.ts b/src/app/try-proxy/try-proxy.component.ts index b1e0659..7d7c969 100644 --- a/src/app/try-proxy/try-proxy.component.ts +++ b/src/app/try-proxy/try-proxy.component.ts @@ -34,7 +34,7 @@ export class TryProxyComponent { selectedLang = this.root.lang; dynamicKey = 'hello_world'; protected t9nProxy = this.translateCommon.object.proxy; - countDaysValue = signal(0); + countDaysValue = signal(undefined as unknown as number); countDays = this.t9nProxy.day_since_new_year.Signal(computed(() => ({ days: this.countDaysValue() }))); constructor( diff --git a/src/assets/translations/proxy/_.ts b/src/assets/translations/proxy/_.ts deleted file mode 100644 index a27c05e..0000000 --- a/src/assets/translations/proxy/_.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { Namespace, String, TranslateSchema, Value } from 'projects/translate/src/public_api'; - -export const testDictionary = TranslateSchema({ - proxy: Namespace({ - welcome_to_app: String(), - hello_user: String<{ user?: string }>(), - - hello_world: String(), - goodbye_world: String(), - - namespace: Namespace({ - value: String(), - hello_user: Value<{ user?: string }>(), - user: Value(), - }), - - i_have_been_here_count: Value<{ count: number; days: number }>(), - - day_since_new_year: Value<{ days: number }>(), - - for_fallback: Value(), - - same_key: Value(), - }), -}); - -export type TestDictionary = typeof testDictionary; diff --git a/tsconfig.json b/tsconfig.json index 5e3f808..da5111c 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -24,7 +24,7 @@ "include": [ "src/**/*.ts", "src/**/*.spec.ts", - "projects/translate/src/translate/translate.proxy.ts" + "projects/translate/src/translate/proxy/translate.proxy.ts" ], "angularCompilerOptions": { "enableI18nLegacyMessageIdFormat": false, From a94c56e28cfab08f0f9a432acfae871a2ddcf972 Mon Sep 17 00:00:00 2001 From: Oleg Date: Sat, 1 Aug 2026 19:40:42 +0300 Subject: [PATCH 11/18] fix the cache --- .../src/translate/proxy/loader/translate.loader-cache.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/projects/translate/src/translate/proxy/loader/translate.loader-cache.ts b/projects/translate/src/translate/proxy/loader/translate.loader-cache.ts index 1cb9dd0..ea7cbfd 100644 --- a/projects/translate/src/translate/proxy/loader/translate.loader-cache.ts +++ b/projects/translate/src/translate/proxy/loader/translate.loader-cache.ts @@ -2,7 +2,7 @@ import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { Dictionary } from 'simply-translate'; -@Injectable() +@Injectable({providedIn: 'root'}) export class TranslateLoaderCache { private readonly cache: Partial>> = {}; From 4c3a708c9b1d3cfb4765514dfa3675abeb09ffef Mon Sep 17 00:00:00 2001 From: Oleg Date: Tue, 4 Aug 2026 12:25:54 +0300 Subject: [PATCH 12/18] changed the error accepting and added onready cb --- README.md | 27 ++++- .../translate/src/__test__/loader.spec.ts | 110 +++++++++++++++++- .../translate/src/__test__/schema.spec.ts | 66 +++++++++-- .../proxy/loader/translate.loader.ts | 27 ++++- .../proxy/schema/validate-dictionary.ts | 49 +++++--- .../src/translate/proxy/translate.proxy.ts | 28 ++++- 6 files changed, 264 insertions(+), 43 deletions(-) diff --git a/README.md b/README.md index 61ba580..dcbcff8 100644 --- a/README.md +++ b/README.md @@ -269,15 +269,19 @@ const errors = validateDictionary(appSchema, parsedJson); assertValidDictionary(appSchema, parsedJson, 'en-US.json'); ``` -Some keys are legitimately allowed to diverge between the schema and a given language file — a translation that isn't ready yet, or a root-only fallback key. Rather than silently ignoring every missing/extra key, list the exceptions explicitly (with a reason) via `allowedMissing` / `allowedOrphans`, keyed by the same dotted path shown in `SchemaValidationError.path`: +Some keys are legitimately allowed to diverge between the schema and a given language file — a translation that isn't ready yet, or a root-only fallback key. Rather than silently ignoring every missing/extra key, list the exceptions explicitly via `allowedErrors`, keyed by the same dotted path shown in `SchemaValidationError.path`. Each entry names the kind of error tolerated there — `'missing'`, `'orphan'`, `'params'`, or `'any'` (whichever check applies) — either as a bare string, or as `{ kind, reason? }` if you want to document why: ```typescript const errors = validateDictionary(appSchema, parsedJson, { - allowedMissing: { 'namespace.hello_user': 'translation pending, falls back to en-US' }, - allowedOrphans: { only_root_key: 'root-only fallback key, intentionally absent from other languages' }, + allowedErrors: { + 'namespace.hello_user': { kind: 'missing', reason: 'translation pending, falls back to en-US' }, + only_root_key: 'orphan', // root-only fallback key, intentionally absent from other languages + }, }); ``` +The kind has to match the check that would otherwise fire at that path — allowing `'orphan'` on a path that's actually reported as `'missing'` still errors. `'params'` is blanket per-path: it silences every placeholder mismatch at that key (see [Placeholder validation](#placeholder-validation)), not individual param names. + #### Placeholder validation When a leaf declares `params` (see [Use TranslateProxy](#Use-TranslateProxy)), `validateDictionary` also checks that every declared param actually shows up as a `${name}` placeholder somewhere in the translation — and flags any placeholder that *isn't* declared. "Somewhere" covers the leaf's `value` as well as every `plural`/`cases` result string, since `simply-translate` re-scans a chosen plural/case result for further placeholders: @@ -437,7 +441,7 @@ For rare cases you may use `id` parameter for Lazy loaded module, that allows ha #### Per-proxy (`applyLoader`) -A `TranslateProxy` subclass can load its own per-language dictionary by overriding `applyLoader()`, without any `forChild()`/`NgModule` wrapper — each language may be a plain object, a `Promise`, an `Observable`, or a URL string fetched via `HttpClient`, and only the *current* language loads eagerly; any other language loads on demand the first time you switch to it. Implement the `TranslateLoaderSupport` interface to get both `applyLoader()` and the optional `onLoaderError()` hook typed: +A `TranslateProxy` subclass can load its own per-language dictionary by overriding `applyLoader()`, without any `forChild()`/`NgModule` wrapper — each language may be a plain object, a `Promise`, an `Observable`, or a URL string fetched via `HttpClient`. Only the *active* language loads eagerly by default; anything else loads on demand the first time you switch to it — unless you ask for it upfront, either declaratively via `preloadLangs`, or on demand via `preloadLang()`. Implement the `TranslateLoaderSupport` interface to get `applyLoader()` and the optional `onLoaderReady()` / `onLoaderError()` hooks typed: ```typescript import { Injectable } from '@angular/core'; @@ -456,9 +460,16 @@ export class AppTranslate extends TranslateProxy implements Translate // URL string — fetched via HttpClient the first time this language becomes active 'ru-RU': '/assets/translations/ru-RU.json', }, + // loaded immediately alongside the active language, not lazily on switch — e.g. your fallback language + preloadLangs: [this.service.fallbackLang].filter((lang): lang is string => !!lang), }; } + // optional — called whenever a language finishes loading successfully + onLoaderReady({ lang, id }: { lang: string; id: string }): void { + console.log(`Loaded '${id}' (${lang})`); + } + // optional — called whenever a language fails to load; omit it and failures stay silent onLoaderError({ lang, id, error }: { lang: string; id: string; error: unknown }): void { console.error(`Failed to load '${id}' (${lang})`, error); @@ -466,7 +477,13 @@ export class AppTranslate extends TranslateProxy implements Translate } ``` -`onLoaderError` is the only thing the library ever surfaces on a failed load — there's no default `console.error` of its own, so implement it if you want failures to be visible at all. +Both hooks are opt-in — there's no default `console.log`/`console.error` of its own, so implement `onLoaderError` if you want failures to be visible at all. + +Beyond `preloadLangs`, call the proxy's own `preloadLang(lang)` whenever you want a language warmed up ahead of time for some other reason (e.g. a language the user is likely to switch to next) — it's a no-op if the proxy has no dictionary entry for `lang`: + +```typescript +appTranslate.preloadLang('de-DE'); +``` **Caveat:** unlike `forChild()`'s `id`-based key prefixing, `applyLoader()` does not namespace keys — every proxy's dictionary is merged flat into the same per-language dictionary. If more than one proxy uses `applyLoader()`, wrap each one's own schema in a top-level `Namespace({...})` (named after that feature) to avoid colliding with another proxy's keys. diff --git a/projects/translate/src/__test__/loader.spec.ts b/projects/translate/src/__test__/loader.spec.ts index 386f224..3361b50 100644 --- a/projects/translate/src/__test__/loader.spec.ts +++ b/projects/translate/src/__test__/loader.spec.ts @@ -15,8 +15,15 @@ describe('TranslateLoader', () => { let root: TranslateRootService; let httpMock: HttpTestingController; - function createLoader(id: string, dictionaries: TranslateLoaderDictionaries): TranslateLoader { - const loader = new TranslateLoader(TestBed.inject(TranslateLoaderCache), TestBed.inject(HttpClient), TestBed.inject(TranslateService), id, dictionaries); + function createLoader(id: string, dictionaries: TranslateLoaderDictionaries, preloadLangs?: string[]): TranslateLoader { + const loader = new TranslateLoader( + TestBed.inject(TranslateLoaderCache), + TestBed.inject(HttpClient), + TestBed.inject(TranslateService), + id, + dictionaries, + preloadLangs, + ); loader.init(); return loader; } @@ -131,6 +138,105 @@ describe('TranslateLoader', () => { expect(httpMock.match('/assets/id1.new.json').length).toBe(0); }); + it('does not load any other language on its own — only the active one', () => { + createLoader('id1', { + [lang]: { hello_user: 'Hello ${user}' }, + [newLang]: '/assets/id1.new.json', + }); + + expect(httpMock.match('/assets/id1.new.json').length).toBe(0); + }); + + describe('preloadLangs (declared upfront via applyLoader)', () => { + it('loads every declared language immediately, not just the active one', () => { + createLoader( + 'id1', + { + [lang]: { hello_user: 'Hello ${user}' }, + [newLang]: { hello_user: 'Hello Preloaded ${user}' }, + }, + [newLang], + ); + + // `newLang` is available immediately, without switching to it. + expect(root.translateTo(newLang, 'hello_user', { user: 'Oleg' })).toBe('Hello Preloaded Oleg'); + }); + + it('fetches every declared language over HTTP upfront, alongside the active language', () => { + createLoader( + 'id1', + { + [lang]: '/assets/id1.json', + [newLang]: '/assets/id1.preload.json', + }, + [newLang], + ); + + httpMock.expectOne('/assets/id1.json').flush({ hello_user: 'Hello ${user}' }); + httpMock.expectOne('/assets/id1.preload.json').flush({ hello_user: 'Hello Preloaded ${user}' }); + + expect(root.translateTo(newLang, 'hello_user', { user: 'Oleg' })).toBe('Hello Preloaded Oleg'); + }); + + it('does not try to load a declared language the proxy has no dictionary for', () => { + createLoader('id1', { [lang]: { hello_user: 'Hello ${user}' } }, [newLang]); + + expect(httpMock.match('/assets/id1.preload.json').length).toBe(0); + }); + }); + + describe('preloadLang() (ad hoc, called explicitly)', () => { + it('loads a language on demand without switching to it', () => { + const loader = createLoader('id1', { + [lang]: { hello_user: 'Hello ${user}' }, + [newLang]: { hello_user: 'Hello Preloaded ${user}' }, + }); + + loader.preloadLang(newLang); + + expect(root.translateTo(newLang, 'hello_user', { user: 'Oleg' })).toBe('Hello Preloaded Oleg'); + }); + + it('is a no-op for a language the loader has no dictionary for', () => { + const loader = createLoader('id1', { [lang]: { hello_user: 'Hello ${user}' } }); + + loader.preloadLang(newLang); + + expect(httpMock.match('/assets/id1.new.json').length).toBe(0); + }); + }); + + describe('ready$', () => { + it('emits once a language is grafted synchronously', () => { + // Constructed but not init()'d yet, so we can subscribe before the synchronous initial load fires. + const loader = new TranslateLoader( + TestBed.inject(TranslateLoaderCache), + TestBed.inject(HttpClient), + TestBed.inject(TranslateService), + 'id1', + { [lang]: { hello_user: 'Hello ${user}' } }, + ); + const ready: { lang: string; id: string }[] = []; + loader.ready$.subscribe((e) => ready.push(e)); + + loader.init(); + loader.preloadLang(newLang); + // Nothing to report for `newLang` — no dictionary declared for it — only the initial load fires. + + expect(ready).toEqual([{ lang, id: 'id1' }]); + }); + + it('emits once an async source resolves', () => { + const loader = createLoader('id1', { [lang]: '/assets/id1.json' }); + const ready: { lang: string; id: string }[] = []; + loader.ready$.subscribe((e) => ready.push(e)); + + httpMock.expectOne('/assets/id1.json').flush({ hello_user: 'Hello ${user}' }); + + expect(ready).toEqual([{ lang, id: 'id1' }]); + }); + }); + it('clears the cache on a failed load so a later attempt retries', () => { const failed = createLoader('id1', { [lang]: '/assets/id1.json' }); const errors: { lang: string; id: string; error: unknown }[] = []; diff --git a/projects/translate/src/__test__/schema.spec.ts b/projects/translate/src/__test__/schema.spec.ts index 37ebd28..1f20d33 100644 --- a/projects/translate/src/__test__/schema.spec.ts +++ b/projects/translate/src/__test__/schema.spec.ts @@ -1,5 +1,14 @@ import { Dictionary } from 'simply-translate'; -import { InferTranslateSchemaType, Namespace, NumberParam, StringProp, StringParam, TranslateSchema, ValueProp, validateDictionary } from '../translate/proxy/schema'; +import { + InferTranslateSchemaType, + Namespace, + NumberParam, + StringProp, + StringParam, + TranslateSchema, + ValueProp, + validateDictionary, +} from '../translate/proxy/schema'; const testSchema = TranslateSchema({ welcome_to_app: StringProp(), @@ -62,31 +71,70 @@ describe('schema', () => { expect(validateDictionary(testSchema, rest)).toEqual([{ path: ['welcome_to_app'], message: 'missing key' }]); }); + it('pass cases', () => { + const dict = { + ...validDictionary, + i_have_been_here_count: { value: '${days}', cases: { count: [['!!', 'value']] }, plural: { count: [['=0', 'value']] } }, + }; + expect(validateDictionary(testSchema, dict)).toEqual([]); + }); + it('reports an unexpected key not declared in the schema', () => { const errors = validateDictionary(testSchema, { ...validDictionary, only_root_key: 'Only in the Root' }); expect(errors).toEqual([{ path: ['only_root_key'], message: 'unexpected key not declared in schema' }]); }); - it('does not report a missing key allowed via allowedMissing', () => { + it('does not report a missing key allowed via allowedErrors', () => { + const { welcome_to_app, ...rest } = validDictionary; + expect(validateDictionary(testSchema, rest, { allowedErrors: { welcome_to_app: 'missing' } })).toEqual([]); + }); + + it('does not report a missing key allowed via allowedErrors with a documented reason', () => { const { welcome_to_app, ...rest } = validDictionary; - expect(validateDictionary(testSchema, rest, { allowedMissing: { welcome_to_app: 'not translated yet' } })).toEqual([]); + expect(validateDictionary(testSchema, rest, { allowedErrors: { welcome_to_app: { kind: 'missing', reason: 'not translated yet' } } })).toEqual([]); }); - it('does not report an orphan key allowed via allowedOrphans', () => { - const errors = validateDictionary(testSchema, { ...validDictionary, only_root_key: 'Only in the Root' }, { allowedOrphans: { only_root_key: true } }); + it('does not report an orphan key allowed via allowedErrors', () => { + const errors = validateDictionary(testSchema, { ...validDictionary, only_root_key: 'Only in the Root' }, { allowedErrors: { only_root_key: 'orphan' } }); expect(errors).toEqual([]); }); - it('matches allowedMissing/allowedOrphans on the full dotted path, not just the leaf key', () => { + it('matches allowedErrors on the full dotted path, not just the leaf key', () => { const { namespace, ...rest } = validDictionary; const errors = validateDictionary( testSchema, { ...rest, namespace: { value: namespace.value, hello_user: namespace.hello_user } }, - { allowedMissing: { user: true } }, + { allowedErrors: { user: 'missing' } }, ); expect(errors).toEqual([{ path: ['namespace', 'user'], message: 'missing key' }]); }); + it('suppresses the error once allowed via the full dotted path', () => { + const { namespace, ...rest } = validDictionary; + const errors = validateDictionary( + testSchema, + { ...rest, namespace: { value: namespace.value, hello_user: namespace.hello_user } }, + { allowedErrors: { 'namespace.user': 'missing' } }, + ); + expect(errors).toEqual([]); + }); + + it('does not allow a path whose error kind does not match the allowed kind', () => { + const { welcome_to_app, ...rest } = validDictionary; + const errors = validateDictionary(testSchema, rest, { allowedErrors: { welcome_to_app: 'orphan' } }); + expect(errors).toEqual([{ path: ['welcome_to_app'], message: 'missing key' }]); + }); + + it('"any" tolerates whichever check applies at that path', () => { + const { welcome_to_app, ...rest } = validDictionary; + expect(validateDictionary(testSchema, rest, { allowedErrors: { welcome_to_app: 'any' } })).toEqual([]); + }); + + it('"params" blanket-allows every placeholder mismatch at that path', () => { + const errors = validateDictionary(testSchema, { ...validDictionary, hello_user: 'Hello there ${extra}' }, { allowedErrors: { hello_user: 'params' } }); + expect(errors).toEqual([]); + }); + it('reports a wrong type on a strict string leaf', () => { const errors = validateDictionary(testSchema, { ...validDictionary, welcome_to_app: 42 }); expect(errors).toEqual([{ path: ['welcome_to_app'], message: 'expected string, got number' }]); @@ -144,8 +192,6 @@ describe('schema', () => { it('supports the "single" placeholder syntax via the `placeholder` option', () => { const singleSchema = TranslateSchema({ greeting: StringProp({ params: { user: StringParam } }) }); expect(validateDictionary(singleSchema, { greeting: 'Hello {user}!' }, { placeholder: 'single' })).toEqual([]); - expect(validateDictionary(singleSchema, { greeting: 'Hello {user}!' })).toEqual([ - { path: ['greeting'], message: 'missing placeholder for param "user"' }, - ]); + expect(validateDictionary(singleSchema, { greeting: 'Hello {user}!' })).toEqual([{ path: ['greeting'], message: 'missing placeholder for param "user"' }]); }); }); diff --git a/projects/translate/src/translate/proxy/loader/translate.loader.ts b/projects/translate/src/translate/proxy/loader/translate.loader.ts index fa9e47f..b8bddf5 100644 --- a/projects/translate/src/translate/proxy/loader/translate.loader.ts +++ b/projects/translate/src/translate/proxy/loader/translate.loader.ts @@ -8,7 +8,8 @@ export type TranslateLoaderDictionary = Dictionary | Promise | Obser export type TranslateLoaderDictionaries = Record; export interface TranslateLoaderSupport{ - applyLoader(): { id: string; dictionaries: TranslateLoaderDictionaries }; + applyLoader(): { id: string; dictionaries: TranslateLoaderDictionaries; preloadLangs?: string[] }; + onLoaderReady?(args: { lang: string; id: string }): void; onLoaderError?(args: { lang: string; id: string; error: any }): void; } @@ -19,23 +20,37 @@ export class TranslateLoader { private service: TranslateService, readonly id: string, readonly dictionaries: TranslateLoaderDictionaries, + readonly preloadLangs: readonly string[] = [], ) {} private _subs?: Subscription; + readonly _readySub = new Subject<{ lang: string; id: string }>(); + readonly ready$ = this._readySub.asObservable(); readonly _errorsSub = new Subject<{ lang: string; id: string; error: any }>(); readonly errors$ = this._errorsSub.asObservable(); init() { - if (!this._subs && this.service.lang && this.dictionaries[this.service.lang]) { - this.importLang(this.service.lang, this.id); + if (!this._subs) { + this.preloadLang(this.service.lang); + this.preloadLangs.forEach((lang) => this.preloadLang(lang)); } this._subs = this.service.languageChange$.pipe().subscribe((_lang) => { - const lang = _lang.lang; - this.importLang(lang, this.id); + this.preloadLang(_lang.lang); }); } + /** + * Loads this loader's dictionary for `lang` right away, without waiting for the app to switch to it — + * e.g. the fallback language, or any other language you want warmed up ahead of time. A no-op if this + * loader has no dictionary declared for `lang`, or it's already loaded/in-flight. + */ + preloadLang(lang: string | undefined): void { + if (lang && this.dictionaries[lang]) { + this.importLang(lang, this.id); + } + } + remove() { this._subs?.unsubscribe(); this._subs = undefined; @@ -61,6 +76,7 @@ export class TranslateLoader { if (!(typeof dic === 'string' || dic instanceof Promise || dic instanceof Observable)) { this.cache.set(lang, this.id, dic); this.service.extendDictionary(lang, dic); + this._readySub.next({ lang, id }); return; } @@ -72,6 +88,7 @@ export class TranslateLoader { next: (dictionary) => { this.cache.set(lang, this.id, dictionary); this.service.extendDictionary(lang, dictionary); + this._readySub.next({ lang, id }); }, error: (error) => { this.cache.clear(lang, this.id); diff --git a/projects/translate/src/translate/proxy/schema/validate-dictionary.ts b/projects/translate/src/translate/proxy/schema/validate-dictionary.ts index b21ceed..4bf295a 100644 --- a/projects/translate/src/translate/proxy/schema/validate-dictionary.ts +++ b/projects/translate/src/translate/proxy/schema/validate-dictionary.ts @@ -6,16 +6,17 @@ export interface SchemaValidationError { message: string; } +export type SchemaAllowedKind = 'missing' | 'orphan' | 'params' | 'any'; + /** - * Dotted path (matching `SchemaValidationError.path.join('.')`) -> `true`, or a string documenting why it's allowed. + * Dotted path (matching `SchemaValidationError.path.join('.')`) -> the kind of error tolerated there + * (`'any'` tolerates whichever check applies), optionally with a `reason` documenting why. + * `'params'` is blanket per-path: it silences every placeholder mismatch at that path, not individual names. */ -export type SchemaAllowanceMap = Record; +export type SchemaAllowanceMap = Record; export interface ValidateDictionaryOptions { - /** Schema keys allowed to be missing from the dictionary, e.g. a translation not filled in yet for this language. */ - allowedMissing?: SchemaAllowanceMap; - /** Dictionary keys allowed to be absent from the schema, e.g. a root-only fallback key. */ - allowedOrphans?: SchemaAllowanceMap; + allowedErrors?: SchemaAllowanceMap; /** Placeholder syntax the dictionaries use — must match the `placeholder` passed to `TranslateModule.forRoot`. */ placeholder?: PlaceholderType; } @@ -57,7 +58,15 @@ function collectMapPlaceholders(map: Record, pattern: RegExp, f } } -function checkParams(found: Set, required: readonly string[] | undefined, path: string[], errors: SchemaValidationError[]): void { +function checkParams( + found: Set, + required: readonly string[] | undefined, + path: string[], + errors: SchemaValidationError[], + allowedErrors: SchemaAllowanceMap | undefined, +): void { + if (isAllowed(allowedErrors, path, 'params')) return; + const requiredSet = new Set(required ?? []); for (const name of requiredSet) { if (!found.has(name)) { @@ -104,7 +113,7 @@ function validateShape( for (const key of Object.keys(shape)) { const childPath = [...path, key]; if (!(key in obj)) { - if (!isAllowed(options.allowedMissing, childPath)) { + if (!isAllowed(options.allowedErrors, childPath, 'missing')) { errors.push({ path: childPath, message: 'missing key' }); } continue; @@ -114,15 +123,19 @@ function validateShape( for (const key of Object.keys(obj)) { if (!(key in shape)) { const childPath = [...path, key]; - if (!isAllowed(options.allowedOrphans, childPath)) { + if (!isAllowed(options.allowedErrors, childPath, 'orphan')) { errors.push({ path: childPath, message: 'unexpected key not declared in schema' }); } } } } -function isAllowed(allowances: SchemaAllowanceMap | undefined, path: string[]): boolean { - return allowances !== undefined && path.join('.') in allowances; +function isAllowed(allowances: SchemaAllowanceMap | undefined, path: string[], kind: SchemaAllowedKind): boolean { + if (!allowances) return false; + const entry = allowances[path.join('.')]; + if (entry === undefined) return false; + const allowedKind = typeof entry === 'string' ? entry : entry.kind; + return allowedKind === kind || allowedKind === 'any'; } function validateNode( @@ -139,7 +152,7 @@ function validateNode( errors.push({ path, message: `expected string, got ${describe(value)}` }); return; } - checkParams(collectPlaceholders(value, pattern), node.paramNames, path, errors); + checkParams(collectPlaceholders(value, pattern), node.paramNames, path, errors, options.allowedErrors); return; case 'namespace': if (!isPlainObject(value)) { @@ -149,7 +162,7 @@ function validateNode( validateShape(node.shape, value, path, errors, options, pattern); return; case 'value': - validateDictionaryValue(value, node.paramNames, pattern, path, errors); + validateDictionaryValue(value, node.paramNames, pattern, path, errors, options.allowedErrors); return; } } @@ -160,18 +173,19 @@ function validateDictionaryValue( pattern: RegExp, path: string[], errors: SchemaValidationError[], + allowedErrors: SchemaAllowanceMap | undefined, ): void { if (typeof value === 'string') { - checkParams(collectPlaceholders(value, pattern), paramNames, path, errors); + checkParams(collectPlaceholders(value, pattern), paramNames, path, errors, allowedErrors); return; } if (isPlainObject(value)) { if ('value' in value) { - validateDictionaryEntry(value, paramNames, pattern, path, errors); + validateDictionaryEntry(value, paramNames, pattern, path, errors, allowedErrors); return; } for (const [key, child] of Object.entries(value)) { - validateDictionaryValue(child, paramNames, pattern, [...path, key], errors); + validateDictionaryValue(child, paramNames, pattern, [...path, key], errors, allowedErrors); } return; } @@ -184,6 +198,7 @@ function validateDictionaryEntry( pattern: RegExp, path: string[], errors: SchemaValidationError[], + allowedErrors: SchemaAllowanceMap | undefined, ): void { const found = new Set(); @@ -209,7 +224,7 @@ function validateDictionaryEntry( errors.push({ path: [...path, 'description'], message: `expected string, got ${describe(entry['description'])}` }); } - checkParams(found, paramNames, path, errors); + checkParams(found, paramNames, path, errors, allowedErrors); } function isPlainObject(value: unknown): value is Record { diff --git a/projects/translate/src/translate/proxy/translate.proxy.ts b/projects/translate/src/translate/proxy/translate.proxy.ts index 1ae1947..fcf37e6 100644 --- a/projects/translate/src/translate/proxy/translate.proxy.ts +++ b/projects/translate/src/translate/proxy/translate.proxy.ts @@ -41,19 +41,39 @@ export abstract class TranslateProxy implements O constructor() { const loaderInfo = this.applyLoader?.(); if (loaderInfo) { - this._load(loaderInfo.id, loaderInfo.dictionaries); + this._load(loaderInfo.id, loaderInfo.dictionaries, loaderInfo.preloadLangs); } } - applyLoader?(): { id: string; dictionaries: TranslateLoaderDictionaries }; + applyLoader?(): { id: string; dictionaries: TranslateLoaderDictionaries; preloadLangs?: string[] }; + onLoaderReady?(args: { lang: string; id: string }): void; onLoaderError?(args: { lang: string; id: string; error: any }): void; - private _load(id: string, dictionaries: TranslateLoaderDictionaries) { + /** + * Loads this proxy's dictionary for `lang` right away, without waiting for the app to switch to it. + * Nothing is preloaded automatically — declare known languages upfront via `applyLoader()`'s + * `preloadLangs`, and call this for anything ad hoc. A no-op if this proxy has no loader. + */ + preloadLang(lang: string | undefined): void { + this._loader?.preloadLang(lang); + } + + private _load(id: string, dictionaries: TranslateLoaderDictionaries, preloadLangs?: string[]) { this._id = id; this._dictionaries = dictionaries ?? {}; if (this._id) { - this._loader = new TranslateLoader(inject(TranslateLoaderCache), inject(HttpClient), this.service, this._id, this._dictionaries); + this._loader = new TranslateLoader( + inject(TranslateLoaderCache), + inject(HttpClient), + this.service, + this._id, + this._dictionaries, + preloadLangs ?? [], + ); this._loader.init(); + this._loader.ready$.subscribe((info) => { + this.onLoaderReady?.(info); + }); this._loader.errors$.subscribe((error) => { this.onLoaderError?.(error); }); From 77c0dafa9ef061ade314f9b63da95c3c00e26a61 Mon Sep 17 00:00:00 2001 From: Oleg Date: Tue, 4 Aug 2026 20:58:45 +0300 Subject: [PATCH 13/18] add nullable params --- .../translate/proxy/schema/schema.types.ts | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/projects/translate/src/translate/proxy/schema/schema.types.ts b/projects/translate/src/translate/proxy/schema/schema.types.ts index 1c80efc..a0487d8 100644 --- a/projects/translate/src/translate/proxy/schema/schema.types.ts +++ b/projects/translate/src/translate/proxy/schema/schema.types.ts @@ -38,8 +38,11 @@ export type DictionaryValue = T extends string ? string : T extends // (string | number only, no nesting) to match `TranslateDynamicProps` and keep placeholder validation simple. export const StringParam: unique symbol = Symbol('StringParam'); export const NumberParam: unique symbol = Symbol('NumberParam'); +// Nullable variants — same as above, but the param's inferred type also accepts `null`. +export const StringNullableParam: unique symbol = Symbol('StringNullableParam'); +export const NumberNullableParam: unique symbol = Symbol('NumberNullableParam'); -export type ParamMarker = typeof StringParam | typeof NumberParam; +export type ParamMarker = typeof StringParam | typeof NumberParam | typeof StringNullableParam | typeof NumberNullableParam; /** A param's declared value: an actual default (`string`/`number`), or a marker when there's no sensible default. */ export type ParamValue = string | number | ParamMarker; @@ -50,10 +53,14 @@ type InferParamValue = V extends typeof StringParam ? string : V extends typeof NumberParam ? number - : V extends string - ? string - : V extends number - ? number - : never; + : V extends typeof StringNullableParam + ? string | null + : V extends typeof NumberNullableParam + ? number | null + : V extends string + ? string + : V extends number + ? number + : never; export type InferParams

= { [K in keyof P]: InferParamValue }; From e500e6103a7ccf206c68dd9f6e43d45403dd7d86 Mon Sep 17 00:00:00 2001 From: Oleg Date: Wed, 5 Aug 2026 15:52:47 +0300 Subject: [PATCH 14/18] added decorator and more --- README.md | 90 ++++++++---- projects/translate/package.json | 2 +- .../__test__/proxy-loader-decorator.spec.ts | 59 ++++++++ .../translate/src/__test__/schema.spec.ts | 46 +++++- projects/translate/src/public_api.ts | 1 + .../loader/translate.loader-cache.ts | 24 --- .../loader/translate.loader.resolver.ts | 19 --- .../src/translate/loader/translate.loader.ts | 82 ----------- .../translate-proxy-loader.decorator.ts | 44 ++++++ .../proxy/loader/translate.loader.ts | 10 +- .../proxy/schema/validate-dictionary.ts | 26 +++- .../src/translate/proxy/translate.proxy.ts | 7 +- .../translate/src/translate/schema/index.ts | 4 - .../src/translate/schema/infer-schema-type.ts | 17 --- .../src/translate/schema/schema-builders.ts | 26 ---- .../src/translate/schema/schema.types.ts | 29 ---- .../translate/schema/validate-dictionary.ts | 138 ------------------ src/app/try-proxy/schema.ts | 22 ++- src/app/try-proxy/translate.proxy.ts | 41 ++++-- src/app/try-proxy/try-proxy.component.ts | 18 ++- src/assets/translations/proxy/_.ts | 27 ---- src/assets/translations/proxy/more/en-US.json | 5 + src/assets/translations/proxy/more/ru-RU.json | 3 + 23 files changed, 312 insertions(+), 428 deletions(-) create mode 100644 projects/translate/src/__test__/proxy-loader-decorator.spec.ts delete mode 100644 projects/translate/src/translate/loader/translate.loader-cache.ts delete mode 100644 projects/translate/src/translate/loader/translate.loader.resolver.ts delete mode 100644 projects/translate/src/translate/loader/translate.loader.ts create mode 100644 projects/translate/src/translate/proxy/loader/translate-proxy-loader.decorator.ts delete mode 100644 projects/translate/src/translate/schema/index.ts delete mode 100644 projects/translate/src/translate/schema/infer-schema-type.ts delete mode 100644 projects/translate/src/translate/schema/schema-builders.ts delete mode 100644 projects/translate/src/translate/schema/schema.types.ts delete mode 100644 projects/translate/src/translate/schema/validate-dictionary.ts delete mode 100644 src/assets/translations/proxy/_.ts create mode 100644 src/assets/translations/proxy/more/en-US.json create mode 100644 src/assets/translations/proxy/more/ru-RU.json diff --git a/README.md b/README.md index dcbcff8..4d7d31a 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,11 @@ ### **Breaking changes** +#### (v0.21.20) +- per-proxy loading is now configured with the `@TranslateProxyLoader` decorator instead of implementing the `TranslateLoaderSupport` interface by hand — see [Per-proxy (`TranslateProxyLoader`)](#per-proxy-loader). +- added `onLoaderReady?(args: { lang, id })` alongside `onLoaderError?()` — fires whenever a language finishes loading successfully. +- `TranslateProxyLoader` gained a public `preloadLangs` and `preloadFallbackLang`. + #### (v0.21.10) - `TranslateProxy` now takes a schema type (`typeof yourSchema`) instead of a hand-written `Dictionary` interface — see [Use TranslateProxy](#Use-TranslateProxy). - added schema-first dictionary definitions (`TranslateSchema`, `StringProp`, `ValueProp`, `Namespace`) and runtime validation (`validateDictionary`, `assertValidDictionary`), including placeholder-usage checks against each leaf's declared `params` — see [Validating dictionaries with a schema](#validating-dictionaries-with-a-schema). @@ -225,7 +230,7 @@ Each key also stringifies to its full dotted path — `` `${translate.object.nam // reactive to changing values — pass a stable Signal/Observable reference const params = signal({ user: 'Oleg' }); this.helloSignal = translate.object.hello_user.Signal(params); -params.set({ user: 'Dana' }); // helloSignal updates automatically +params.set({ user: 'John' }); // helloSignal updates automatically // static values, but still reactive to language/dictionary changes this.helloSignal = translate.object.hello_user.Signal({ user: 'Oleg' }); @@ -282,6 +287,14 @@ const errors = validateDictionary(appSchema, parsedJson, { The kind has to match the check that would otherwise fire at that path — allowing `'orphan'` on a path that's actually reported as `'missing'` still errors. `'params'` is blanket per-path: it silences every placeholder mismatch at that key (see [Placeholder validation](#placeholder-validation)), not individual param names. +A key ending in `.*` allows a whole namespace at once, instead of enumerating every leaf under it — `'namespace.*'` matches `namespace` itself and everything nested under it: + +```typescript +validateDictionary(appSchema, parsedJson, { + allowedErrors: { 'namespace.*': 'missing' }, // an entire namespace not translated yet for this language +}); +``` + #### Placeholder validation When a leaf declares `params` (see [Use TranslateProxy](#Use-TranslateProxy)), `validateDictionary` also checks that every declared param actually shows up as a `${name}` placeholder somewhere in the translation — and flags any placeholder that *isn't* declared. "Somewhere" covers the leaf's `value` as well as every `plural`/`cases` result string, since `simply-translate` re-scans a chosen plural/case result for further placeholders: @@ -409,7 +422,7 @@ const routes: Routes = [{ path: '', component: DynamicComponent, resolve: { tran export class DynamicRoutingModule {} ``` -For rare cases you may use `id` parameter for Lazy loaded module, that allows having different values with same key. +**Deprecated: Under consideration of removing**: For rare cases you may use `id` parameter for Lazy loaded module, that allows having different values with same key. "Lazy" values will be available only for lazy modules with that special `id`. ```javascript @@ -439,53 +452,76 @@ For rare cases you may use `id` parameter for Lazy loaded module, that allows ha }) ``` -#### Per-proxy (`applyLoader`) +#### Per-proxy (`per-proxy-loader`) -A `TranslateProxy` subclass can load its own per-language dictionary by overriding `applyLoader()`, without any `forChild()`/`NgModule` wrapper — each language may be a plain object, a `Promise`, an `Observable`, or a URL string fetched via `HttpClient`. Only the *active* language loads eagerly by default; anything else loads on demand the first time you switch to it — unless you ask for it upfront, either declaratively via `preloadLangs`, or on demand via `preloadLang()`. Implement the `TranslateLoaderSupport` interface to get `applyLoader()` and the optional `onLoaderReady()` / `onLoaderError()` hooks typed: +A `TranslateProxy` subclass can load its own per-language dictionary, without any `forChild()`/`NgModule` wrapper — each language may be a plain object, a `Promise`, an `Observable`, or a URL string fetched via `HttpClient`. Only the *active* language loads eagerly by default; anything else loads on demand the first time you switch to it, unless you ask for it upfront via `preloadLangs`/`preloadFallbackLang`, or on demand via `preloadLang()`. Configure it with the `@TranslateProxyLoader(config)` decorator: ```typescript import { Injectable } from '@angular/core'; -import { Dictionary } from 'simply-translate'; -import { TranslateLoaderSupport, TranslateProxy } from 'simply-translate-angular'; +import { TranslateProxy, TranslateProxyLoader } from 'simply-translate-angular'; import type { AppSchema } from './app.schema'; @Injectable({ providedIn: 'root' }) -export class AppTranslate extends TranslateProxy implements TranslateLoaderSupport { - applyLoader() { - return { - id: 'app', - dictionaries: { - // dynamic import() — code-split into its own lazy chunk, fetched when this proxy is first constructed - 'en-US': import('./translations/en-US.json').then((m) => m.default as unknown as Dictionary), - // URL string — fetched via HttpClient the first time this language becomes active - 'ru-RU': '/assets/translations/ru-RU.json', - }, - // loaded immediately alongside the active language, not lazily on switch — e.g. your fallback language - preloadLangs: [this.service.fallbackLang].filter((lang): lang is string => !!lang), - }; - } - - // optional — called whenever a language finishes loading successfully +@TranslateProxyLoader({ + id: 'app', + dictionaries: { + // dynamic import() — code-split into its own lazy chunk, fetched when this proxy is first constructed + 'en-US': import('./translations/en-US.json').then((m) => m.default), + // URL string — fetched via HttpClient the first time this language becomes active + 'ru-RU': '/assets/translations/ru-RU.json', + }, + preloadFallbackLang: true, // also load `service.fallbackLang` upfront, not just the active language +}) +export class AppTranslate extends TranslateProxy { + // optional — fires whenever a language finishes loading successfully onLoaderReady({ lang, id }: { lang: string; id: string }): void { console.log(`Loaded '${id}' (${lang})`); } - // optional — called whenever a language fails to load; omit it and failures stay silent + // optional — fires whenever a language fails to load; omit it and failures stay silent onLoaderError({ lang, id, error }: { lang: string; id: string; error: unknown }): void { console.error(`Failed to load '${id}' (${lang})`, error); } } ``` -Both hooks are opt-in — there's no default `console.log`/`console.error` of its own, so implement `onLoaderError` if you want failures to be visible at all. - -Beyond `preloadLangs`, call the proxy's own `preloadLang(lang)` whenever you want a language warmed up ahead of time for some other reason (e.g. a language the user is likely to switch to next) — it's a no-op if the proxy has no dictionary entry for `lang`: +Beyond `preloadLangs`/`preloadFallbackLang`, call the proxy's own `preloadLang(lang)` whenever you want a language warmed up ad hoc (e.g. a language the user is likely to switch to next) — it's a no-op if the proxy has no dictionary entry for `lang`: ```typescript appTranslate.preloadLang('de-DE'); ``` -**Caveat:** unlike `forChild()`'s `id`-based key prefixing, `applyLoader()` does not namespace keys — every proxy's dictionary is merged flat into the same per-language dictionary. If more than one proxy uses `applyLoader()`, wrap each one's own schema in a top-level `Namespace({...})` (named after that feature) to avoid colliding with another proxy's keys. +**Caveat:** unlike `forChild()`'s `id`-based key prefixing, this does not namespace keys — every proxy's dictionary is merged flat into the same per-language dictionary. If more than one proxy loads its own dictionary, wrap each one's own schema in a top-level `Namespace({...})` (named after that feature) to avoid colliding with another proxy's keys. + +##### Sharing a dictionary between proxies (`extends`) + +`@TranslateProxyLoader`'s real value beyond being declarative is `extends` — sharing one proxy's dictionary with another, so common strings (`ok`, `no`, generic labels, ...) don't have to be redeclared and reloaded by every feature that needs them: + +```typescript +import { StringProp, TranslateSchema } from 'simply-translate-angular'; + +const commonSchema = TranslateSchema({ ok: StringProp(), no: StringProp() }); + +@Injectable({ providedIn: 'root' }) +@TranslateProxyLoader({ id: 'common', dictionaries: { 'en-US': { ok: 'Ok', no: 'No' } } }) +export class CommonTranslate extends TranslateProxy {} + +// spread the shared shape in — schemas are plain objects, so this is ordinary composition (see +// [Validating dictionaries with a schema](#validating-dictionaries-with-a-schema)), nothing `extends`-specific +const featureSchema = TranslateSchema({ ...commonSchema.shape, title: StringProp() }); + +@Injectable({ providedIn: 'root' }) +@TranslateProxyLoader({ + id: 'feature', + extends: [CommonTranslate], + dictionaries: { 'en-US': { title: 'Title' } }, +}) +export class FeatureTranslate extends TranslateProxy {} +``` + +Injecting `FeatureTranslate` alone is enough — `feature.object.ok` and `feature.object.title` both resolve, without ever injecting `CommonTranslate` anywhere. `extends` takes **class references**, forces to actually `inject` that class. + +Two things `extends` does *not* do: it doesn't derive `FeatureTranslate`'s schema type for you (spread the shape in by hand, as above — `extends` only affects runtime loading), and it doesn't forward `CommonTranslate`'s own `onLoaderReady`/`onLoaderError` to `FeatureTranslate`, `extends` never constructs a `CommonTranslate` instance of its own beyond what DI already gives you. ### Pipeline diff --git a/projects/translate/package.json b/projects/translate/package.json index c189f1b..ffa4b57 100644 --- a/projects/translate/package.json +++ b/projects/translate/package.json @@ -1,6 +1,6 @@ { "name": "simply-translate-angular", - "version": "0.21.12", + "version": "0.21.20", "type": "module", "dependencies": { "tslib": "^2.4.0", diff --git a/projects/translate/src/__test__/proxy-loader-decorator.spec.ts b/projects/translate/src/__test__/proxy-loader-decorator.spec.ts new file mode 100644 index 0000000..af2510a --- /dev/null +++ b/projects/translate/src/__test__/proxy-loader-decorator.spec.ts @@ -0,0 +1,59 @@ +import { Injectable } from '@angular/core'; +import { HttpClientTestingModule } from '@angular/common/http/testing'; +import { TestBed } from '@angular/core/testing'; +import { StringProp, TranslateSchema } from '../translate/proxy/schema'; +import { TranslateProxy } from '../translate/proxy/translate.proxy'; +import { TranslateProxyLoader } from '../translate/proxy/loader/translate-proxy-loader.decorator'; +import { TranslateModule } from '../simply-translate.module'; +import { TranslateRootService } from '../public_api'; + +const lang = 'lang'; + +const commonSchema = TranslateSchema({ ok: StringProp() }); + +@Injectable({ providedIn: 'root' }) +@TranslateProxyLoader({ + id: 'common', + dictionaries: { [lang]: { ok: 'Ok' } }, +}) +class CommonTranslate extends TranslateProxy {} + +const featureSchema = TranslateSchema({ ok: StringProp(), title: StringProp() }); + +@Injectable({ providedIn: 'root' }) +@TranslateProxyLoader({ + id: 'feature', + extends: [CommonTranslate], + dictionaries: { [lang]: { title: 'Title' } }, +}) +class FeatureTranslate extends TranslateProxy {} + +describe('TranslateProxyLoader decorator', () => { + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule, TranslateModule.forRoot({ lang })], + }); + }); + + it('loads its own dictionary without being injected directly anywhere', () => { + const feature = TestBed.inject(FeatureTranslate); + + expect(feature.object.title()).toBe('Title'); + }); + + it('also loads an `extends`-listed proxy dictionary, without that proxy ever being injected directly', () => { + const feature = TestBed.inject(FeatureTranslate); + + expect(feature.object.ok()).toBe('Ok'); + }); + + it('does not require the extended proxy to be injected/used anywhere else first', () => { + const root = TestBed.inject(TranslateRootService); + + // No `TestBed.inject(CommonTranslate)` anywhere in this spec — only FeatureTranslate is ever asked for. + const feature = TestBed.inject(FeatureTranslate); + + expect(root.translate('ok')).toBe('Ok'); + expect(feature.object.ok()).toBe('Ok'); + }); +}); diff --git a/projects/translate/src/__test__/schema.spec.ts b/projects/translate/src/__test__/schema.spec.ts index 1f20d33..6ac9856 100644 --- a/projects/translate/src/__test__/schema.spec.ts +++ b/projects/translate/src/__test__/schema.spec.ts @@ -184,11 +184,55 @@ describe('schema', () => { it('accepts a required placeholder that only appears inside a plural/cases result string', () => { const errors = validateDictionary(testSchema, { ...validDictionary, - day_since_new_year: { value: 'x', plural: { count: [['=1', 'Just ${days} day']] } }, + day_since_new_year: { value: 'x', plural: { days: [['=1', 'Just ${days} day']] } }, }); expect(errors).toEqual([]); }); + it('credits a plural/cases map key itself as a used param, even with no literal placeholder', () => { + // `cases`/`plural` are keyed by the param name they switch on — selecting a bucket "uses" that param + // just as reading `dynamicProps[name]` does, even if no branch's result text ever interpolates it. + const errors = validateDictionary(testSchema, { + ...validDictionary, + i_have_been_here_count: { value: '${days}', cases: { count: [['!!', 'value']] }, plural: { count: [['=0', 'value']] } }, + }); + expect(errors).toEqual([]); + }); + + it('still flags a plural/cases map key that is not declared in schema params', () => { + const errors = validateDictionary(testSchema, { + ...validDictionary, + day_since_new_year: { value: '${days}', plural: { days: [['=1', 'value']], bogus: [['=1', 'value']] } }, + }); + expect(errors).toEqual([{ path: ['day_since_new_year'], message: 'unexpected placeholder "bogus", not declared in schema params' }]); + }); + + it('allows every error under a namespace via a "namespace.*" wildcard', () => { + const errors = validateDictionary(testSchema, { ...validDictionary, namespace: {} }, { allowedErrors: { 'namespace.*': 'missing' } }); + expect(errors).toEqual([]); + }); + + it('a namespace wildcard also covers the namespace key itself, not just its children', () => { + const { namespace, ...rest } = validDictionary; + const errors = validateDictionary(testSchema, rest, { allowedErrors: { 'namespace.*': 'missing' } }); + expect(errors).toEqual([]); + }); + + it('a namespace wildcard does not leak outside that namespace', () => { + const { namespace, welcome_to_app, ...rest } = validDictionary; + const errors = validateDictionary(testSchema, { ...rest, namespace: {} }, { allowedErrors: { 'namespace.*': 'missing' } }); + expect(errors).toEqual([{ path: ['welcome_to_app'], message: 'missing key' }]); + }); + + it('a namespace wildcard still requires the matching kind', () => { + const errors = validateDictionary(testSchema, { ...validDictionary, namespace: {} }, { allowedErrors: { 'namespace.*': 'orphan' } }); + expect(errors).toEqual([ + { path: ['namespace', 'value'], message: 'missing key' }, + { path: ['namespace', 'hello_user'], message: 'missing key' }, + { path: ['namespace', 'user'], message: 'missing key' }, + ]); + }); + it('supports the "single" placeholder syntax via the `placeholder` option', () => { const singleSchema = TranslateSchema({ greeting: StringProp({ params: { user: StringParam } }) }); expect(validateDictionary(singleSchema, { greeting: 'Hello {user}!' }, { placeholder: 'single' })).toEqual([]); diff --git a/projects/translate/src/public_api.ts b/projects/translate/src/public_api.ts index 99cdb72..b743cbe 100644 --- a/projects/translate/src/public_api.ts +++ b/projects/translate/src/public_api.ts @@ -7,6 +7,7 @@ export * from './translate/proxy/schema'; export { TranslateLoaderSupport, TranslateLoaderDictionaries, TranslateLoaderDictionary } from './translate/proxy/loader/translate.loader'; export { TranslateLoaderCache } from './translate/proxy/loader/translate.loader-cache'; export { translateLoaderResolver } from './translate/proxy/loader/translate.loader.resolver'; +export { TranslateProxyLoader, TranslateProxyLoaderConfig } from './translate/proxy/loader/translate-proxy-loader.decorator'; export * from './simply-translate.module'; export { TranslateChildConfig } from './translate/translate.service'; export { diff --git a/projects/translate/src/translate/loader/translate.loader-cache.ts b/projects/translate/src/translate/loader/translate.loader-cache.ts deleted file mode 100644 index 1cb9dd0..0000000 --- a/projects/translate/src/translate/loader/translate.loader-cache.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { Injectable } from '@angular/core'; -import { Observable } from 'rxjs'; -import { Dictionary } from 'simply-translate'; - -@Injectable() -export class TranslateLoaderCache { - private readonly cache: Partial>> = {}; - - get(lang: string, id: string): Dictionary | Observable | undefined { - return this.cache[`${id}_${lang}`]; - } - - set>(lang: string, id: string, value: T): T { - this.cache[`${id}_${lang}`] = value; - - return value; - } - - clear(lang: string, id: string): void { - delete this.cache[`${id}_${lang}`]; - } -} - - diff --git a/projects/translate/src/translate/loader/translate.loader.resolver.ts b/projects/translate/src/translate/loader/translate.loader.resolver.ts deleted file mode 100644 index 950961a..0000000 --- a/projects/translate/src/translate/loader/translate.loader.resolver.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { inject } from '@angular/core'; -import { Dictionary } from 'simply-translate'; -import { TranslateLoaderCache } from './translate.loader-cache'; -import { TranslateService } from '../translate.service'; -import { ResolveFn } from '@angular/router'; - -export const translationsExtensionResolver: (id: string) => ResolveFn = (id: string) => { - return () => { - const provider = inject(TranslateLoaderCache); - const service = inject(TranslateService); - - const lang = service.lang; - if (!lang) { - return undefined; - } - - return provider.get(lang, id); - }; -}; diff --git a/projects/translate/src/translate/loader/translate.loader.ts b/projects/translate/src/translate/loader/translate.loader.ts deleted file mode 100644 index d3664d0..0000000 --- a/projects/translate/src/translate/loader/translate.loader.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { from, Observable, shareReplay, Subject, Subscription } from 'rxjs'; -import { Dictionary } from 'simply-translate'; -import { TranslateService } from '../translate.service'; -import { TranslateLoaderCache } from './translate.loader-cache'; -import { HttpClient } from '@angular/common/http'; - -export type TranslateLoaderDictionary = Dictionary | Promise | Observable | string; -export type TranslateLoaderDictionaries = Record; - -export interface TranslateLoaderSupport{ - applyLoader(): { id: string; dictionaries: TranslateLoaderDictionaries }; - onLoaderError?(args: { lang: string; id: string; error: any }): void; -} - -export class TranslateLoader { - constructor( - private cache: TranslateLoaderCache, - private httpClient: HttpClient, - private service: TranslateService, - readonly id: string, - readonly dictionaries: TranslateLoaderDictionaries, - ) {} - - private _subs?: Subscription; - readonly _errorsSub = new Subject<{ lang: string; id: string; error: any }>(); - readonly errors$ = this._errorsSub.asObservable(); - - init() { - if (!this._subs && this.service.lang && this.dictionaries[this.service.lang]) { - this.importLang(this.service.lang, this.id); - } - - this._subs = this.service.languageChange$.pipe().subscribe((_lang) => { - const lang = _lang.lang; - this.importLang(lang, this.id); - }); - } - - remove() { - this._subs?.unsubscribe(); - this._subs = undefined; - } - - getProcess() { - const lang = this.service.lang; - if (!lang) { - return undefined; - } - - return this.cache.get(lang, this.id); - } - - private importLang(lang: string, id: string): void { - const dic = this.dictionaries[lang]; - const cached = this.cache.get(lang, this.id); - - if (cached) { - return; - } - - if (!(typeof dic === 'string' || dic instanceof Promise || dic instanceof Observable)) { - this.cache.set(lang, this.id, dic); - this.service.extendDictionary(lang, dic); - - return; - } - - const source = typeof dic === 'string' ? this.httpClient.get(dic) : from(dic); - const load = this.cache.set(lang, this.id, source.pipe(shareReplay(1))); - - load.subscribe({ - next: (dictionary) => { - this.cache.set(lang, this.id, dictionary); - this.service.extendDictionary(lang, dictionary); - }, - error: (error) => { - this.cache.clear(lang, this.id); - this._errorsSub.next({ lang, id, error }); - }, - }); - } -} diff --git a/projects/translate/src/translate/proxy/loader/translate-proxy-loader.decorator.ts b/projects/translate/src/translate/proxy/loader/translate-proxy-loader.decorator.ts new file mode 100644 index 0000000..c42e6ac --- /dev/null +++ b/projects/translate/src/translate/proxy/loader/translate-proxy-loader.decorator.ts @@ -0,0 +1,44 @@ +import { inject, Type } from '@angular/core'; +import { TranslateProxy } from '../translate.proxy'; +import { APPLY_LOADER, TranslateLoaderDictionaries } from './translate.loader'; + +export interface TranslateProxyLoaderConfig { + id: string; + dictionaries: TranslateLoaderDictionaries; + preloadLangs?: string[]; + /** Also preload `TranslateService.fallbackLang`, if one is configured — resolved per instance, not at decoration time. */ + preloadFallbackLang?: boolean; + /** + * Other `TranslateProxy` classes this one depends on. Listed as class references (not string ids) so that + * referencing them here forces a real import — and, more importantly, so this decorator can `inject()` each + * one to force Angular to actually construct it. That's what makes the dependency reliable: the depended-on + * proxy loads its own dictionary via its own `applyLoader()`, the moment *this* class is constructed, with no + * requirement that anything else in the app separately inject it (as long as it's reachable from this + * injector — e.g. `providedIn: 'root'`). + */ + extends?: Type>[]; +} + +/** + * Declaratively configures a `TranslateProxy` subclass's loader, instead of implementing `applyLoader()` by hand. + * Synthesizes `applyLoader()` on the class prototype — do not also implement `applyLoader()` yourself. + */ +export function TranslateProxyLoader(config: TranslateProxyLoaderConfig) { + return function (target: Type>): void { + target.prototype[APPLY_LOADER] = function (this: TranslateProxy) { + // Runs inside the base class's constructor, which is itself running as part of this instance's DI + // construction — so `inject()` here is called within a valid, active injection context. + config.extends?.forEach((ext) => inject(ext)); + + const preloadLangs = [...(config.preloadLangs ?? [])]; + if (config.preloadFallbackLang) { + const fallbackLang = this.service.fallbackLang; + if (fallbackLang && !preloadLangs.includes(fallbackLang)) { + preloadLangs.push(fallbackLang); + } + } + + return { id: config.id, dictionaries: config.dictionaries, preloadLangs }; + }; + }; +} diff --git a/projects/translate/src/translate/proxy/loader/translate.loader.ts b/projects/translate/src/translate/proxy/loader/translate.loader.ts index b8bddf5..3c662e3 100644 --- a/projects/translate/src/translate/proxy/loader/translate.loader.ts +++ b/projects/translate/src/translate/proxy/loader/translate.loader.ts @@ -8,11 +8,19 @@ export type TranslateLoaderDictionary = Dictionary | Promise | Obser export type TranslateLoaderDictionaries = Record; export interface TranslateLoaderSupport{ - applyLoader(): { id: string; dictionaries: TranslateLoaderDictionaries; preloadLangs?: string[] }; onLoaderReady?(args: { lang: string; id: string }): void; onLoaderError?(args: { lang: string; id: string; error: any }): void; } +/** + * Internal protocol between `TranslateProxy` and `@TranslateProxyLoader`. Not part of the public API — + * loader config is only ever meant to be supplied via the decorator, so this is a symbol rather than a + * named method, to keep it off `TranslateLoaderSupport` and out of reach of anything but the decorator. + */ +export const APPLY_LOADER: unique symbol = Symbol('applyLoader'); + +export type ApplyLoaderFn = () => { id: string; dictionaries: TranslateLoaderDictionaries; preloadLangs?: string[] }; + export class TranslateLoader { constructor( private cache: TranslateLoaderCache, diff --git a/projects/translate/src/translate/proxy/schema/validate-dictionary.ts b/projects/translate/src/translate/proxy/schema/validate-dictionary.ts index 4bf295a..6f09bf4 100644 --- a/projects/translate/src/translate/proxy/schema/validate-dictionary.ts +++ b/projects/translate/src/translate/proxy/schema/validate-dictionary.ts @@ -12,6 +12,9 @@ export type SchemaAllowedKind = 'missing' | 'orphan' | 'params' | 'any'; * Dotted path (matching `SchemaValidationError.path.join('.')`) -> the kind of error tolerated there * (`'any'` tolerates whichever check applies), optionally with a `reason` documenting why. * `'params'` is blanket per-path: it silences every placeholder mismatch at that path, not individual names. + * + * A key ending in `.*` (e.g. `'namespace.*'`) allows the whole namespace: it matches that path itself and + * everything nested under it, instead of enumerating every leaf individually. */ export type SchemaAllowanceMap = Record; @@ -46,9 +49,12 @@ function collectPlaceholders(value: string, pattern: RegExp): Set { // `plural`/`cases` maps are keyed by prop name, each holding `[matcher, resultText, testFn?]` options — // `resultText` (index 1) can itself reference placeholders (including other params), since -// `simply-translate` re-scans a chosen plural/case result for further `{...}` substitutions. +// `simply-translate` re-scans a chosen plural/case result for further `{...}` substitutions. The map's own +// keys count too: picking a plural/case bucket reads `dynamicProps[key]` at runtime, so that param is "used" +// even when no branch's result text ever literally interpolates `${key}`. function collectMapPlaceholders(map: Record, pattern: RegExp, found: Set): void { - for (const options of Object.values(map)) { + for (const [key, options] of Object.entries(map)) { + found.add(key); if (!Array.isArray(options)) continue; for (const option of options) { if (Array.isArray(option) && typeof option[1] === 'string') { @@ -132,12 +138,26 @@ function validateShape( function isAllowed(allowances: SchemaAllowanceMap | undefined, path: string[], kind: SchemaAllowedKind): boolean { if (!allowances) return false; - const entry = allowances[path.join('.')]; + const dotted = path.join('.'); + const entry = allowances[dotted] ?? findNamespaceAllowance(allowances, dotted); if (entry === undefined) return false; const allowedKind = typeof entry === 'string' ? entry : entry.kind; return allowedKind === kind || allowedKind === 'any'; } +// Matches a `'namespace.*'` entry against `dotted` itself or anything nested under it — e.g. `'namespace.*'` +// covers both `namespace` and `namespace.child`, without listing every leaf. +function findNamespaceAllowance(allowances: SchemaAllowanceMap, dotted: string): SchemaAllowanceMap[string] | undefined { + for (const key of Object.keys(allowances)) { + if (!key.endsWith('.*')) continue; + const prefix = key.slice(0, -2); + if (dotted === prefix || dotted.startsWith(`${prefix}.`)) { + return allowances[key]; + } + } + return undefined; +} + function validateNode( node: SchemaNode, value: unknown, diff --git a/projects/translate/src/translate/proxy/translate.proxy.ts b/projects/translate/src/translate/proxy/translate.proxy.ts index fcf37e6..441d6cc 100644 --- a/projects/translate/src/translate/proxy/translate.proxy.ts +++ b/projects/translate/src/translate/proxy/translate.proxy.ts @@ -3,7 +3,7 @@ import { Observable } from 'rxjs'; import { Dictionary, DictionaryEntry, TranslateDynamicProps } from 'simply-translate'; import type { BaseNode, NamespaceNode, SchemaShape, TranslateSchemaNode } from './schema/schema.types'; import { TranslateService } from '../translate.service'; -import { TranslateLoader, TranslateLoaderDictionaries, TranslateLoaderSupport } from './loader/translate.loader'; +import { APPLY_LOADER, ApplyLoaderFn, TranslateLoader, TranslateLoaderDictionaries, TranslateLoaderSupport } from './loader/translate.loader'; import { TranslateLoaderCache } from './loader/translate.loader-cache'; import { HttpClient } from '@angular/common/http'; @@ -39,13 +39,14 @@ export abstract class TranslateProxy implements O private _loader?: TranslateLoader; constructor() { - const loaderInfo = this.applyLoader?.(); + const loaderInfo = this[APPLY_LOADER]?.(); if (loaderInfo) { this._load(loaderInfo.id, loaderInfo.dictionaries, loaderInfo.preloadLangs); } } - applyLoader?(): { id: string; dictionaries: TranslateLoaderDictionaries; preloadLangs?: string[] }; + /** Set by `@TranslateProxyLoader` — not meant to be implemented directly. */ + [APPLY_LOADER]?: ApplyLoaderFn; onLoaderReady?(args: { lang: string; id: string }): void; onLoaderError?(args: { lang: string; id: string; error: any }): void; diff --git a/projects/translate/src/translate/schema/index.ts b/projects/translate/src/translate/schema/index.ts deleted file mode 100644 index 891c1aa..0000000 --- a/projects/translate/src/translate/schema/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -export * from './schema.types'; -export * from './schema-builders'; -export * from './infer-schema-type'; -export * from './validate-dictionary'; diff --git a/projects/translate/src/translate/schema/infer-schema-type.ts b/projects/translate/src/translate/schema/infer-schema-type.ts deleted file mode 100644 index 3407fd9..0000000 --- a/projects/translate/src/translate/schema/infer-schema-type.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { Dictionary } from 'simply-translate'; -import { DictionaryValue } from '../translate.proxy'; -import { NamespaceNode, SchemaNode, SchemaShape, TranslateSchemaNode } from './schema.types'; - -type InferNode = Node extends { kind: 'string' } - ? string - : Node extends NamespaceNode - ? DictionaryValue> - : Node extends { kind: 'value' } - ? DictionaryValue - : never; - -type InferShape = { - [K in keyof Shape]: InferNode; -}; - -export type InferTranslateSchemaType = InferShape & Dictionary; diff --git a/projects/translate/src/translate/schema/schema-builders.ts b/projects/translate/src/translate/schema/schema-builders.ts deleted file mode 100644 index 35a4163..0000000 --- a/projects/translate/src/translate/schema/schema-builders.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { NamespaceNode, SchemaShape, StringNode, TranslateSchemaNode, ValueNode } from './schema.types'; - -// Overloaded rather than a single `` signature: when this is called bare, as an -// argument inside `Namespace({...})`/`TranslateSchema({...})`, TypeScript uses that call's expected -// contextual type (`SchemaNode`) to help infer TParams — which silently overrides a *default* type -// parameter with whatever `SchemaNode`'s own default is, discarding `undefined`. A non-generic overload -// for the zero-argument call has no generic parameter for that contextual type to hijack. -export function String(options?: { description?: string }): StringNode; -export function String(options?: { description?: string }): StringNode; -export function String(options?: { description?: string }): StringNode { - return { kind: 'string', description: options?.description, params: (_: TParams) => {} }; -} - -export function Value(options?: { description?: string }): ValueNode; -export function Value(options?: { description?: string }): ValueNode; -export function Value(options?: { description?: string }): ValueNode { - return { kind: 'value', description: options?.description, params: (_: TParams) => {} }; -} - -export function Namespace(shape: Shape, options?: { description?: string }): NamespaceNode { - return { kind: 'namespace', shape, description: options?.description }; -} - -export function TranslateSchema(shape: Shape): TranslateSchemaNode { - return { kind: 'namespace', shape }; -} diff --git a/projects/translate/src/translate/schema/schema.types.ts b/projects/translate/src/translate/schema/schema.types.ts deleted file mode 100644 index 8c6de83..0000000 --- a/projects/translate/src/translate/schema/schema.types.ts +++ /dev/null @@ -1,29 +0,0 @@ -export interface BaseNode { - readonly kind: 'string' | 'value' | 'namespace'; - readonly description?: string; - /** Never actually called — a phantom marker so `TParams` can be recovered later via `extends BaseNode`. */ - readonly params?: (params: TParams) => void; -} - -export interface StringNode extends BaseNode { - readonly kind: 'string'; -} - -export interface ValueNode extends BaseNode { - readonly kind: 'value'; -} - -export interface NamespaceNode extends BaseNode { - readonly kind: 'namespace'; - readonly shape: Shape; -} - -// `any` here (not `unknown`) is deliberate: `SchemaShape` uses `SchemaNode` as a container type that -// must accept a node with ANY concrete `TParams`, and `params` is a contravariant function-parameter -// position — a node with a specific `TParams` (e.g. `StringNode<{ user: string }>`) is not assignable -// to `StringNode`, only to `StringNode`. -export type SchemaNode = StringNode | ValueNode | NamespaceNode; - -export type SchemaShape = Record; - -export type TranslateSchemaNode = NamespaceNode; diff --git a/projects/translate/src/translate/schema/validate-dictionary.ts b/projects/translate/src/translate/schema/validate-dictionary.ts deleted file mode 100644 index baf3a81..0000000 --- a/projects/translate/src/translate/schema/validate-dictionary.ts +++ /dev/null @@ -1,138 +0,0 @@ -import { SchemaNode, SchemaShape, TranslateSchemaNode } from './schema.types'; - -export interface SchemaValidationError { - path: string[]; - message: string; -} - -/** - * Dotted path (matching `SchemaValidationError.path.join('.')`) -> `true`, or a string documenting why it's allowed. - */ -export type SchemaAllowanceMap = Record; - -export interface ValidateDictionaryOptions { - /** Schema keys allowed to be missing from the dictionary, e.g. a translation not filled in yet for this language. */ - allowedMissing?: SchemaAllowanceMap; - /** Dictionary keys allowed to be absent from the schema, e.g. a root-only fallback key. */ - allowedOrphans?: SchemaAllowanceMap; -} - -export function validateDictionary(schema: TranslateSchemaNode, data: unknown, options?: ValidateDictionaryOptions): SchemaValidationError[] { - const errors: SchemaValidationError[] = []; - if (!isPlainObject(data)) { - return [{ path: [], message: `expected a dictionary object, got ${describe(data)}` }]; - } - validateShape(schema.shape, data, [], errors, options ?? {}); - return errors; -} - -export function formatSchemaErrors(errors: SchemaValidationError[]): string { - return errors.map((e) => `${e.path.join('.') || ''}: ${e.message}`).join('\n'); -} - -export function assertValidDictionary(schema: TranslateSchemaNode, data: unknown, label?: string, options?: ValidateDictionaryOptions): void { - const errors = validateDictionary(schema, data, options); - if (errors.length) { - const prefix = label ? `Invalid dictionary "${label}":\n` : 'Invalid dictionary:\n'; - throw new Error(prefix + formatSchemaErrors(errors)); - } -} - -function validateShape( - shape: SchemaShape, - obj: Record, - path: string[], - errors: SchemaValidationError[], - options: ValidateDictionaryOptions, -): void { - for (const key of Object.keys(shape)) { - const childPath = [...path, key]; - if (!(key in obj)) { - if (!isAllowed(options.allowedMissing, childPath)) { - errors.push({ path: childPath, message: 'missing key' }); - } - continue; - } - validateNode(shape[key], obj[key], childPath, errors, options); - } - for (const key of Object.keys(obj)) { - if (!(key in shape)) { - const childPath = [...path, key]; - if (!isAllowed(options.allowedOrphans, childPath)) { - errors.push({ path: childPath, message: 'unexpected key not declared in schema' }); - } - } - } -} - -function isAllowed(allowances: SchemaAllowanceMap | undefined, path: string[]): boolean { - return allowances !== undefined && path.join('.') in allowances; -} - -function validateNode( - node: SchemaNode, - value: unknown, - path: string[], - errors: SchemaValidationError[], - options: ValidateDictionaryOptions, -): void { - switch (node.kind) { - case 'string': - if (typeof value !== 'string') { - errors.push({ path, message: `expected string, got ${describe(value)}` }); - } - return; - case 'namespace': - if (!isPlainObject(value)) { - errors.push({ path, message: `expected a nested dictionary, got ${describe(value)}` }); - return; - } - validateShape(node.shape, value, path, errors, options); - return; - case 'value': - validateDictionaryValue(value, path, errors); - return; - } -} - -function validateDictionaryValue(value: unknown, path: string[], errors: SchemaValidationError[]): void { - if (typeof value === 'string') { - return; - } - if (isPlainObject(value)) { - if ('value' in value) { - validateDictionaryEntry(value, path, errors); - return; - } - for (const [key, child] of Object.entries(value)) { - validateDictionaryValue(child, [...path, key], errors); - } - return; - } - errors.push({ path, message: `expected a string, entry, or nested dictionary, got ${describe(value)}` }); -} - -function validateDictionaryEntry(entry: Record, path: string[], errors: SchemaValidationError[]): void { - if (typeof entry['value'] !== 'string') { - errors.push({ path: [...path, 'value'], message: `expected string, got ${describe(entry['value'])}` }); - } - if (entry['plural'] !== undefined && !isPlainObject(entry['plural'])) { - errors.push({ path: [...path, 'plural'], message: `expected a plurals map, got ${describe(entry['plural'])}` }); - } - if (entry['cases'] !== undefined && !isPlainObject(entry['cases'])) { - errors.push({ path: [...path, 'cases'], message: `expected a cases map, got ${describe(entry['cases'])}` }); - } - if (entry['description'] !== undefined && typeof entry['description'] !== 'string') { - errors.push({ path: [...path, 'description'], message: `expected string, got ${describe(entry['description'])}` }); - } -} - -function isPlainObject(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value); -} - -function describe(value: unknown): string { - if (value === null) return 'null'; - if (Array.isArray(value)) return 'array'; - return typeof value; -} diff --git a/src/app/try-proxy/schema.ts b/src/app/try-proxy/schema.ts index 8a24c38..1461194 100644 --- a/src/app/try-proxy/schema.ts +++ b/src/app/try-proxy/schema.ts @@ -1,6 +1,6 @@ -import { Namespace, NumberParam, StringProp, StringParam, TranslateSchema, ValueProp } from 'projects/translate/src/public_api'; +import { Namespace, NumberParam, NumberNullableParam, StringProp, StringParam, TranslateSchema, ValueProp } from 'projects/translate/src/public_api'; -export const testDictionary = TranslateSchema({ +export const commonDictionary = TranslateSchema({ proxy: Namespace({ welcome_to_app: StringProp(), hello_user: StringProp({ params: { user: StringParam } }), @@ -10,13 +10,13 @@ export const testDictionary = TranslateSchema({ namespace: Namespace({ value: StringProp(), - hello_user: ValueProp({params: { user: StringParam }}), + hello_user: ValueProp({ params: { user: StringParam } }), user: ValueProp(), }), - i_have_been_here_count: ValueProp({params: { count: NumberParam, days: NumberParam }}), + i_have_been_here_count: ValueProp({ params: { count: NumberNullableParam, days: NumberParam } }), - day_since_new_year: ValueProp({params: { days: 100 }}), + day_since_new_year: ValueProp({ params: { days: NumberParam } }), for_fallback: ValueProp(), @@ -24,4 +24,14 @@ export const testDictionary = TranslateSchema({ }), }); -export type TestDictionary = typeof testDictionary; +export type CommonDictionary = typeof commonDictionary; + +export const moreDictionary = TranslateSchema({ + proxy: Namespace({ + more: Namespace({ + more_translate: StringProp(), + }), + }), +}); + +export type MoreDictionary = typeof moreDictionary; diff --git a/src/app/try-proxy/translate.proxy.ts b/src/app/try-proxy/translate.proxy.ts index 63e661f..cf400c0 100644 --- a/src/app/try-proxy/translate.proxy.ts +++ b/src/app/try-proxy/translate.proxy.ts @@ -1,21 +1,36 @@ import { Injectable } from '@angular/core'; -import type { TestDictionary } from 'src/app/try-proxy/schema'; +import type { CommonDictionary, MoreDictionary } from 'src/app/try-proxy/schema'; import { Dictionary } from 'simply-translate'; -import { TranslateLoaderSupport, TranslateProxy } from 'projects/translate/src/public_api'; +import { TranslateProxy, TranslateProxyLoader } from 'projects/translate/src/public_api'; @Injectable({ providedIn: 'root' }) -export class TranslateProxyCommon extends TranslateProxy implements TranslateLoaderSupport { - applyLoader() { - return { - id: 'common', - dictionaries: { - 'en-US': import('src/assets/translations/proxy/en-US.json').then((module) => module.default as unknown as Dictionary), - 'ru-RU': '/assets/translations/proxy/ru-RU.json', - }, - }; - } - +@TranslateProxyLoader({ + id: 'common', + dictionaries: { + 'en-US': import('src/assets/translations/proxy/en-US.json').then((module) => module.default as unknown as Dictionary), + 'ru-RU': '/assets/translations/proxy/ru-RU.json', + }, + preloadFallbackLang: true, + preloadLangs: ['en-US', 'ru-RU'], +}) +export class TranslateProxyCommon extends TranslateProxy { onLoaderError(args: { lang: string; id: string; error: any }): void { console.error(`Error loading translation for lang=${args.lang}, id=${args.id}`, args.error); } } + +@Injectable({ providedIn: 'root' }) +@TranslateProxyLoader({ + id: 'more', + extends: [TranslateProxyCommon], + dictionaries: { + 'en-US': '/assets/translations/proxy/more/en-US.json', + 'ru-RU': '/assets/translations/proxy/more/ru-RU.json', + }, + preloadFallbackLang: false, +}) +export class TranslateProxyMore extends TranslateProxy { + onLoaderError(args: { lang: string; id: string; error: any }): void { + console.error(`Error loading more translations for lang=${args.lang}, id=${args.id}`, args.error); + } +} diff --git a/src/app/try-proxy/try-proxy.component.ts b/src/app/try-proxy/try-proxy.component.ts index 7d7c969..f99d4bf 100644 --- a/src/app/try-proxy/try-proxy.component.ts +++ b/src/app/try-proxy/try-proxy.component.ts @@ -1,6 +1,6 @@ import { Component, computed, signal } from '@angular/core'; import { TranslateRootService } from 'src/_translate.imports'; -import { TranslateProxyCommon } from './translate.proxy'; +import { TranslateProxyCommon, TranslateProxyMore } from './translate.proxy'; @Component({ selector: 'app-try-proxy', @@ -13,7 +13,7 @@ import { TranslateProxyCommon } from './translate.proxy';

{{ t9nProxy.namespace.hello_user | translate$ }}

Observable

-
{{ t9nProxy.namespace.hello_user.$({user:'Me'}) | async}}
+
{{ t9nProxy.namespace.hello_user.$({ user: 'Me' }) | async }}

Signal

{{ t9nProxy.welcome_to_app.Signal()() }}
@@ -23,23 +23,27 @@ import { TranslateProxyCommon } from './translate.proxy';
{{ countDays() }}

Observable

-
{{ t9nProxy.hello_user.$({user:'Me'}) | async }}
+
{{ t9nProxy.hello_user.$({ user: 'Me' }) | async }}
-

Signal

-
{{ t9nProxy.hello_user.Signal({user:'Me'})()}}
+

Signal Again

+
{{ t9nProxy.hello_user.Signal({ user: 'Me' })() }}
+
{{ t9nProxy.namespace.hello_user.Signal({ user: 'John' })() }}
+ +
More Proxy
+
{{ t9nProxy.more.more_translate.Signal()() }}
`, }) export class TryProxyComponent { langs = ['en-US', 'ru-RU']; selectedLang = this.root.lang; dynamicKey = 'hello_world'; - protected t9nProxy = this.translateCommon.object.proxy; + protected t9nProxy = this.translateMore.object.proxy; countDaysValue = signal(undefined as unknown as number); countDays = this.t9nProxy.day_since_new_year.Signal(computed(() => ({ days: this.countDaysValue() }))); constructor( private root: TranslateRootService, - private translateCommon: TranslateProxyCommon, + private translateMore: TranslateProxyMore, ) { setInterval(() => { this.countDaysValue.set(this.countDaysValue() + 1); diff --git a/src/assets/translations/proxy/_.ts b/src/assets/translations/proxy/_.ts deleted file mode 100644 index a27c05e..0000000 --- a/src/assets/translations/proxy/_.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { Namespace, String, TranslateSchema, Value } from 'projects/translate/src/public_api'; - -export const testDictionary = TranslateSchema({ - proxy: Namespace({ - welcome_to_app: String(), - hello_user: String<{ user?: string }>(), - - hello_world: String(), - goodbye_world: String(), - - namespace: Namespace({ - value: String(), - hello_user: Value<{ user?: string }>(), - user: Value(), - }), - - i_have_been_here_count: Value<{ count: number; days: number }>(), - - day_since_new_year: Value<{ days: number }>(), - - for_fallback: Value(), - - same_key: Value(), - }), -}); - -export type TestDictionary = typeof testDictionary; diff --git a/src/assets/translations/proxy/more/en-US.json b/src/assets/translations/proxy/more/en-US.json new file mode 100644 index 0000000..a4a350a --- /dev/null +++ b/src/assets/translations/proxy/more/en-US.json @@ -0,0 +1,5 @@ +{ + "proxy": { + "more": { "more_translate": "More Translate" } + } +} diff --git a/src/assets/translations/proxy/more/ru-RU.json b/src/assets/translations/proxy/more/ru-RU.json new file mode 100644 index 0000000..ff6c9ad --- /dev/null +++ b/src/assets/translations/proxy/more/ru-RU.json @@ -0,0 +1,3 @@ +{ + "more": { "more_translate": "Больше перевести" } +} From 02b3f40adf9252abbbd50fb0bd53e560cf36df2a Mon Sep 17 00:00:00 2001 From: Oleg Date: Fri, 9 Oct 2026 16:44:38 +0300 Subject: [PATCH 15/18] Split TranslateProxy into its own package and prepare v1.0.0 - Move TranslateProxy, schema API and per-proxy loader to the new simply-translate-angular-proxy library (projects/proxy) - Bump simply-translate-angular to 1.0.0 and require simply-translate 1.0.0 - Fix deep import of simply-translate internals blocked by its v1 exports map - Move release notes from READMEs into per-package CHANGELOG.md files - Fix and update the translate, proxy and root READMEs - Add per-package build/test/publish scripts - Add Test and Publish GitHub workflows (npm trusted publishing, tag @ selects the package) Co-Authored-By: Claude Opus 5.5 --- .github/workflows/publish.yml | 68 +++ .github/workflows/test.yml | 32 + README.md | 558 +----------------- angular.json | 36 ++ package-lock.json | 262 ++++++-- package.json | 32 +- projects/proxy/CHANGELOG.md | 12 + projects/proxy/README.md | 269 +++++++++ projects/proxy/ng-package.json | 12 + projects/proxy/package.json | 37 ++ projects/proxy/src/__test__/core/tick.ts | 7 + .../src/__test__/loader.spec.ts | 7 +- .../__test__/proxy-loader-decorator.spec.ts | 9 +- .../src/__test__/proxy.spec.ts | 7 +- .../src/__test__/schema.spec.ts | 26 +- .../translate-proxy-loader.decorator.ts | 0 .../src/lib}/loader/translate.loader-cache.ts | 0 .../lib}/loader/translate.loader.resolver.ts | 2 +- .../src/lib}/loader/translate.loader.ts | 2 +- .../proxy => proxy/src/lib}/schema/index.ts | 0 .../src/lib}/schema/infer-schema-type.ts | 0 .../src/lib}/schema/schema-builders.ts | 0 .../src/lib}/schema/schema.types.ts | 0 .../src/lib}/schema/validate-dictionary.ts | 10 +- .../src/lib}/translate.proxy.ts | 2 +- projects/proxy/src/public-api.ts | 10 + projects/proxy/tsconfig.lib.json | 14 + projects/proxy/tsconfig.lib.prod.json | 10 + projects/proxy/tsconfig.spec.json | 14 + projects/translate/CHANGELOG.md | 82 +++ projects/translate/README.md | 287 +++++++++ projects/translate/package.json | 10 +- projects/translate/src/public_api.ts | 6 - .../translate/src/simply-translate.module.ts | 2 - .../src/translate/translate.service.ts | 2 +- src/app/app.module.ts | 3 +- src/app/try-proxy/schema.ts | 12 +- src/app/try-proxy/translate.proxy.ts | 22 +- src/app/try-proxy/try-proxy.component.ts | 5 +- .../translations/proxy/one-more/en-US.json | 5 + .../translations/proxy/one-more/ru-RU.json | 3 + tsconfig.json | 7 +- 42 files changed, 1239 insertions(+), 645 deletions(-) create mode 100644 .github/workflows/publish.yml create mode 100644 .github/workflows/test.yml create mode 100644 projects/proxy/CHANGELOG.md create mode 100644 projects/proxy/README.md create mode 100644 projects/proxy/ng-package.json create mode 100644 projects/proxy/package.json create mode 100644 projects/proxy/src/__test__/core/tick.ts rename projects/{translate => proxy}/src/__test__/loader.spec.ts (96%) rename projects/{translate => proxy}/src/__test__/proxy-loader-decorator.spec.ts (83%) rename projects/{translate => proxy}/src/__test__/proxy.spec.ts (97%) rename projects/{translate => proxy}/src/__test__/schema.spec.ts (89%) rename projects/{translate/src/translate/proxy => proxy/src/lib}/loader/translate-proxy-loader.decorator.ts (100%) rename projects/{translate/src/translate/proxy => proxy/src/lib}/loader/translate.loader-cache.ts (100%) rename projects/{translate/src/translate/proxy => proxy/src/lib}/loader/translate.loader.resolver.ts (89%) rename projects/{translate/src/translate/proxy => proxy/src/lib}/loader/translate.loader.ts (98%) rename projects/{translate/src/translate/proxy => proxy/src/lib}/schema/index.ts (100%) rename projects/{translate/src/translate/proxy => proxy/src/lib}/schema/infer-schema-type.ts (100%) rename projects/{translate/src/translate/proxy => proxy/src/lib}/schema/schema-builders.ts (100%) rename projects/{translate/src/translate/proxy => proxy/src/lib}/schema/schema.types.ts (100%) rename projects/{translate/src/translate/proxy => proxy/src/lib}/schema/validate-dictionary.ts (97%) rename projects/{translate/src/translate/proxy => proxy/src/lib}/translate.proxy.ts (98%) create mode 100644 projects/proxy/src/public-api.ts create mode 100644 projects/proxy/tsconfig.lib.json create mode 100644 projects/proxy/tsconfig.lib.prod.json create mode 100644 projects/proxy/tsconfig.spec.json create mode 100644 projects/translate/CHANGELOG.md create mode 100644 projects/translate/README.md create mode 100644 src/assets/translations/proxy/one-more/en-US.json create mode 100644 src/assets/translations/proxy/one-more/ru-RU.json diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..39669ea --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,68 @@ +name: Publish + +# Publishes one package to npm when a GitHub Release is published. The release tag picks the +# package and must be `@`: +# simply-translate-angular@1.0.0 -> projects/translate +# simply-translate-angular-proxy@1.0.0 -> projects/proxy +# Authentication uses npm trusted publishing (OIDC), so no npm token is stored in the repo. The +# trusted publisher configured on npmjs.com for each package must name this repository and this +# workflow file (publish.yml). +on: + release: + types: [published] + +permissions: + contents: read + id-token: write + +jobs: + publish: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + # Node 24 bundles npm 11.5.1+, the minimum for trusted publishing. + - uses: actions/setup-node@v4 + with: + node-version: 24 + registry-url: https://registry.npmjs.org + cache: npm + + - name: Resolve package from release tag + id: pkg + run: | + NAME="${GITHUB_REF_NAME%@*}" + TAG_VERSION="${GITHUB_REF_NAME##*@}" + case "$NAME" in + simply-translate-angular) PROJECT=translate ;; + simply-translate-angular-proxy) PROJECT=proxy ;; + *) + echo "::error::Release tag $GITHUB_REF_NAME must be simply-translate-angular@ or simply-translate-angular-proxy@" + exit 1 + ;; + esac + VERSION="$(node -p "require('./projects/$PROJECT/package.json').version")" + if [ "$TAG_VERSION" != "$VERSION" ]; then + echo "::error::Release tag $GITHUB_REF_NAME does not match projects/$PROJECT/package.json version $VERSION" + exit 1 + fi + echo "project=$PROJECT" >> "$GITHUB_OUTPUT" + + - run: npm ci + + - run: npm test + + # Builds both: the proxy compiles against dist/translate. + - run: npm run build:prod + + # Pre-releases (e.g. 1.1.0-beta.1) go to the "next" dist-tag so they don't become "latest". + - name: Publish + working-directory: dist/${{ steps.pkg.outputs.project }} + run: | + VERSION="$(node -p "require('./package.json').version")" + if [[ "$VERSION" == *-* ]]; then + npm publish --tag next + else + npm publish + fi diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..ec45774 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,32 @@ +name: Test + +on: + push: + branches: [master] + pull_request: + workflow_dispatch: + +jobs: + test: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + node-version: [20, 22, 24] + + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node-version }} + cache: npm + + - run: npm ci + + # Tests both libraries. The proxy resolves simply-translate-angular from dist/translate, + # so this also builds the translate library in between. + - run: npm test + + - name: Build + run: npm run build:prod diff --git a/README.md b/README.md index 4d7d31a..36c27b3 100644 --- a/README.md +++ b/README.md @@ -1,555 +1,31 @@ # Simply Translate for Angular -[Simplest translations](https://www.npmjs.com/package/simply-translate) for Angular _(tested for v10+)_. +[![Test](https://github.com/oleg-wx/translate-angular/actions/workflows/test.yml/badge.svg)](https://github.com/oleg-wx/translate-angular/actions/workflows/test.yml) -### **Breaking changes** +Monorepo for [simply-translate](https://www.npmjs.com/package/simply-translate) Angular bindings. Two independently published libraries: -#### (v0.21.20) -- per-proxy loading is now configured with the `@TranslateProxyLoader` decorator instead of implementing the `TranslateLoaderSupport` interface by hand — see [Per-proxy (`TranslateProxyLoader`)](#per-proxy-loader). -- added `onLoaderReady?(args: { lang, id })` alongside `onLoaderError?()` — fires whenever a language finishes loading successfully. -- `TranslateProxyLoader` gained a public `preloadLangs` and `preloadFallbackLang`. +### [simply-translate-angular](projects/translate/README.md) -#### (v0.21.10) -- `TranslateProxy` now takes a schema type (`typeof yourSchema`) instead of a hand-written `Dictionary` interface — see [Use TranslateProxy](#Use-TranslateProxy). -- added schema-first dictionary definitions (`TranslateSchema`, `StringProp`, `ValueProp`, `Namespace`) and runtime validation (`validateDictionary`, `assertValidDictionary`), including placeholder-usage checks against each leaf's declared `params` — see [Validating dictionaries with a schema](#validating-dictionaries-with-a-schema). +The core translation library — `TranslateModule`, directive, pipes, `TranslateService`, and dictionary loading (root/lazy). See [projects/translate/README.md](projects/translate/README.md) for setup and usage, and its [changelog](projects/translate/CHANGELOG.md). -#### (v0.21.0) +### [simply-translate-angular-proxy](projects/proxy/README.md) -- upgraded to Angular 17. -- introduced new [`TranslateProxy`](#Use-TranslateProxy) for typed, autocompleted dictionary access. -- directive now **always** reacts to language/dictionary changes; removed the `detect` opt-in property. -- directive can infer its key from static inner text when `translate` has no value. -- fixed directive writing translated output to a fresh text node instead of updating the existing one, which broke content bound elsewhere in the same element (e.g. Angular interpolation). -- added `translateSignal` and `translateObservable` to `TranslateService`. +Optional add-on built on top of `simply-translate-angular` — `TranslateProxy` for typed, autocompleted access to dictionary keys, schema-based dictionary validation, and per-proxy dictionary loading. See [projects/proxy/README.md](projects/proxy/README.md) for setup and usage, and its [changelog](projects/proxy/CHANGELOG.md). -#### (v0.20.0) +## Development -- see [plain JS library changes](https://www.npmjs.com/package/simply-translate#Breaking-changes). -- deprecated `init` method in root import. Instead use `addMiddleware`, `loadDictionaries` and `final` methods instead. -- `lang` and `fallbackLang` now in the root import. -- added **middleware pipeline** _(see [Pipeline](#Pipeline))_. -- removed `$less` property. Instead of `$less` use `placeholder = 'single'`. -- added `fallback` property to directive. -- `defaultLang` renamed to `lang`. -- `extend` in `forChild` initialization changed to `loadDictionaries`. -- added language detection change for directives and pipes -- after initialization `lang` and `fallbackLang` can be changed only from `TranslateRootService`. -- removed **dynamic cache**. - -### Basics - -Please use link above to learn more about **basic interaction**, dictionaries, pluralization, cases, etc. - -### Install - -```javascript -npm i simply-translate-angular -``` - -### Import - -```javascript -import { TranslateModule, TranslateService } from 'simply-translate-angular'; -``` - -### Initialize - -```javascript -@NgModule({ - declarations: [AppComponent, AppViewComponent], - imports: [ - TranslateModule.forRoot({ - // dependencies - deps: [ HttpClient ], - // language - lang: window.navigator.language, - fallbackLang: 'ru-RU', - // static dictionaries - dictionaries:{'ru-RU':{...}} - // load dictionaries - loadDictionaries:({lang, fallbackLang}, client /* params are injected dependencies received in the same order as they are in deps */) =>{ - return { - [lang]: {...} - } - } - }) - ] -}); -``` - -See [Load dictionaries](#Load-dictionaries) - -### Use Directive - -```html - -

- -

- -

Hello user

- -

Hello ${user}

- -

-``` - -Directives always react to language and dictionary changes automatically, no opt-in needed. - -Directive can also use inner text as an implicit key (when `translate` has no value) or as a fallback (when the key is missing) — but only for **static** content; dynamic keys must be bound with `[translate]="expr"`. - -### Use Pipe - -```html -

{{ 'hello_user' | translate: { user: 'Oleg' } }}

- -

{{ 'hello_user' | translateTo: 'ru-RU': { user: 'Oleg' } }}

- -

{{ 'hello_user_not_there' | translate: { user: 'Oleg' } : 'Hello ${user}'}}

-``` - -Pipes are pure by default. However if application has dynamic language change you may use special _impure_ pipe (it has internal dirty check), it will detect language changes as well as pipe parameters. - -```html -

{{ 'hello_user' | translate$: { user: 'Oleg' } }}

-``` - -`translate$` is cheap despite being impure: it caches the last language/dictionary version and arguments, and only re-translates when one of them actually changed — not on every check. - -### Use Service - -```javascript -@Component({ - ... -}) -export class Component { - hello: string; - constructor(private translate: TranslateService) { - // use default language - this.hello = translate.translate('hello_user', { user: 'Oleg' }) - // use other language - this.hello = translate.translateTo('ru-RU','hello_user', { user: 'Oleg' }) - // use fallback - this.hello = translate.translateTo('ru-RU','hello_user_not_there', { user: 'Oleg' }, 'Hello ${user}') - } -} -``` - -`translateSignal` and `translateObservable` mirror `translate`'s overloads but return a reactive `Signal` / `Observable` that updates on language or dictionary changes. - -```javascript -helloSignal = translate.translateSignal('hello_user', { user: 'Oleg' }); // Signal -hello$ = translate.translateObservable('hello_user', { user: 'Oleg' }); // Observable -``` - -To change language use `TranslateRootService` `lang` property. -To detect changes subscribe on `languageChange$` and `dictionaryChange$`. **Note** that `loadDictionaries` method in root settings will not execute when language changes. - -```javascript -export class Component { - constructor(private rootTranslate: TranslateRootService){ - rootTranslate.lang = "en-US"; - } -} -``` - -### Use TranslateProxy - -For typed, autocompleted access to your dictionary keys, describe your dictionary shape with `TranslateSchema` and extend `TranslateProxy`. - -```typescript -// app.schema.ts -import { Namespace, NumberParam, StringParam, StringProp, TranslateSchema, ValueProp } from 'simply-translate-angular'; - -export const appSchema = TranslateSchema({ - hello_user: StringProp({ params: { user: StringParam } }), - about: StringProp(), - namespace: Namespace({ - hello_user: StringProp({ params: { user: StringParam } }), - }), - visit_count: ValueProp({ params: { count: NumberParam } }), -}); - -export type AppSchema = typeof appSchema; -``` - -(Named `StringProp`/`ValueProp` rather than `String`/`Value` to avoid shadowing the globals of the same name.) - -```typescript -// app.translate.ts -import { Injectable } from '@angular/core'; -import { TranslateProxy } from 'simply-translate-angular'; -import type { AppSchema } from './app.schema'; - -@Injectable() -export class AppTranslate extends TranslateProxy {} -``` - -`TranslateProxy` takes the schema itself as its type parameter — the dictionary type is inferred from it via `InferTranslateSchemaType`. `TranslateProxy` only ever needs `AppSchema`'s **type**, never `appSchema`'s runtime value, so import it with `import type`: TypeScript erases `import type` entirely at compile time, keeping the schema-building code (and everything it imports) out of your app's bundle unless something else in it also needs the actual schema object at runtime — e.g. to call `validateDictionary`. See [Validating dictionaries with a schema](#validating-dictionaries-with-a-schema) for the full builder API (`StringProp`, `ValueProp`, `Namespace`) and for validating your JSON dictionaries against the same schema at runtime. - -Inject it like any other service and read keys off `object`. Every leaf key is callable (mirrors `translate`), and carries `.Signal()` / `.$()` companions that mirror `translateSignal` / `translateObservable`. - -**The params each of these accepts comes entirely from how the schema leaf was declared:** - -- `StringProp()` / `ValueProp()`, called with no `params` — the leaf takes **no dynamic props at all**. The call, `.Signal()`, and `.$()` all become zero-argument — passing anything is a compile error. -- `StringProp({ params: {...} })` / `ValueProp({ params: {...} })` — the leaf **requires** exactly the shape described by `params`, everywhere. Omitting the argument, passing `undefined`, or passing the wrong shape are all compile errors. - -`params` is a flat map of prop name → either an actual default value (e.g. `user: 'Guest'`, `count: 0`) or, when there's no natural default, the `StringParam` / `NumberParam` markers. Either way the value is only ever used to infer that prop's type (`string`/`number`) and to read its name — nothing about it is used at runtime beyond that. Params are intentionally flat (`string`/`number` only, no nesting) to match what dynamic props can actually be. - -```typescript -@Component({ - ... -}) -export class MyComponent { - constructor(private translate: AppTranslate) { - // like translate.translate('hello_user', { user: 'Oleg' }) - this.hello = translate.object.hello_user({ user: 'Oleg' }); - - // reactive Signal, like translate.translateSignal(...) - this.helloSignal = translate.object.hello_user.Signal({ user: 'Oleg' }); - - // reactive Observable, like translate.translateObservable(...) - this.hello$ = translate.object.hello_user.$({ user: 'Oleg' }); - - // nested keys work the same way - this.nsHello = translate.object.namespace.hello_user({ user: 'Oleg' }); - - // `about` was declared with StringProp() (no params) -> zero-argument call - this.about = translate.object.about(); - // translate.object.about({ user: 'Oleg' }); // compile error: `about` takes no params - // translate.object.hello_user(); // compile error: `hello_user` requires { user: string } - } -} -``` - -Each key also stringifies to its full dotted path — `` `${translate.object.namespace.hello_user}` === 'namespace.hello_user' `` — useful when you need the key itself (logging, passing to another API) rather than its translation. - -**Warning — dynamic props with `.Signal()` / `.$()`:** the returned `Signal`/`Observable` is cached per `dynamicProps` reference (keyed by identity, not by value). A plain object always stays reactive to **language/dictionary** changes, but is a fixed snapshot of its own properties — it will never update if you mutate the object later, and passing a fresh object literal on every call (e.g. inline in a template) defeats the cache, allocating a new `Signal`/`Observable` each time. If the dynamic values themselves change over time, pass a `Signal`/`Observable` of that same params shape instead, and keep reusing the **same** reference so the cache can pick it up: - -```typescript -// reactive to changing values — pass a stable Signal/Observable reference -const params = signal({ user: 'Oleg' }); -this.helloSignal = translate.object.hello_user.Signal(params); -params.set({ user: 'John' }); // helloSignal updates automatically - -// static values, but still reactive to language/dictionary changes -this.helloSignal = translate.object.hello_user.Signal({ user: 'Oleg' }); -``` - -**Restriction:** `Signal` and `$` are reserved property names — `TranslateProxy` uses them on every key to expose the reactive accessors above. A dictionary key literally named `Signal` or `$` (at any nesting level) will be shadowed by these accessors and become unreachable through `object`. Avoid naming dictionary keys `Signal` or `$`. - -### Validating dictionaries with a schema - -`TranslateSchema` describes a dictionary once and gives you both the static type (via `InferTranslateSchemaType`, used internally by `TranslateProxy`) and a runtime validator for your actual JSON dictionary files — so a language file that's missing a key, has an extra key, or has the wrong shape fails loudly instead of silently falling back at runtime. - -Build a schema with three node builders: - -- `StringProp()` — a leaf that must be a plain string. -- `ValueProp()` — a leaf that may be a string, a `DictionaryEntry` (`{ value, plural?, cases?, description? }`), or a nested dictionary. -- `Namespace({...})` — a nested dictionary with a fixed, known shape. - -```typescript -import { Namespace, StringProp, TranslateSchema, ValueProp } from 'simply-translate-angular'; - -export const appSchema = TranslateSchema({ - welcome_to_app: StringProp(), - goodbye_world: ValueProp(), // string, or { value, description } etc. - namespace: Namespace({ - hello_user: ValueProp(), - }), -}); - -export type AppDictionary = InferTranslateSchemaType; -``` - -Validate a loaded dictionary (e.g. a parsed JSON file) against the schema: - -```typescript -import { assertValidDictionary, validateDictionary } from 'simply-translate-angular'; - -// returns a list of { path, message } issues, empty when valid -const errors = validateDictionary(appSchema, parsedJson); - -// or throw with a formatted message if invalid — handy in a startup check or a build/CI script -assertValidDictionary(appSchema, parsedJson, 'en-US.json'); -``` - -Some keys are legitimately allowed to diverge between the schema and a given language file — a translation that isn't ready yet, or a root-only fallback key. Rather than silently ignoring every missing/extra key, list the exceptions explicitly via `allowedErrors`, keyed by the same dotted path shown in `SchemaValidationError.path`. Each entry names the kind of error tolerated there — `'missing'`, `'orphan'`, `'params'`, or `'any'` (whichever check applies) — either as a bare string, or as `{ kind, reason? }` if you want to document why: - -```typescript -const errors = validateDictionary(appSchema, parsedJson, { - allowedErrors: { - 'namespace.hello_user': { kind: 'missing', reason: 'translation pending, falls back to en-US' }, - only_root_key: 'orphan', // root-only fallback key, intentionally absent from other languages - }, -}); -``` - -The kind has to match the check that would otherwise fire at that path — allowing `'orphan'` on a path that's actually reported as `'missing'` still errors. `'params'` is blanket per-path: it silences every placeholder mismatch at that key (see [Placeholder validation](#placeholder-validation)), not individual param names. - -A key ending in `.*` allows a whole namespace at once, instead of enumerating every leaf under it — `'namespace.*'` matches `namespace` itself and everything nested under it: - -```typescript -validateDictionary(appSchema, parsedJson, { - allowedErrors: { 'namespace.*': 'missing' }, // an entire namespace not translated yet for this language -}); +```bash +npm ci +npm test # tests both libraries once in headless Chrome +npm run build:prod # builds dist/translate and dist/proxy +npm run start:demo # demo app on http://localhost:4800 (run build:prod first) ``` -#### Placeholder validation - -When a leaf declares `params` (see [Use TranslateProxy](#Use-TranslateProxy)), `validateDictionary` also checks that every declared param actually shows up as a `${name}` placeholder somewhere in the translation — and flags any placeholder that *isn't* declared. "Somewhere" covers the leaf's `value` as well as every `plural`/`cases` result string, since `simply-translate` re-scans a chosen plural/case result for further placeholders: - -```typescript -const appSchema = TranslateSchema({ - hello_user: StringProp({ params: { user: StringParam } }), - about: StringProp(), -}); - -validateDictionary(appSchema, { hello_user: 'Hello there', about: 'Welcome' }); -// [{ path: ['hello_user'], message: 'missing placeholder for param "user"' }] - -validateDictionary(appSchema, { hello_user: 'Hello ${user}!', about: 'Welcome, ${name}!' }); -// [{ path: ['about'], message: 'unexpected placeholder "name", not declared in schema params' }] -``` - -If your app uses a non-default `placeholder` style (`'single'` `{user}` / `'double'` `{{user}}`, see [`TranslateModule.forRoot`](#Initialize)), pass the same value so the checks recognize the right syntax: - -```typescript -validateDictionary(appSchema, parsedJson, { placeholder: 'single' }); -``` - -### Load dictionaries - -#### Root - -Default `forRoot` initialization allows to use injected dependencies (e.g. `HttpClient`) to fetch dictionaries. It returns `Observable` that contains set of dictionaries - -```javascript -export function getDictionary(lang: string, client: HttpClient) { - return client.get(`/assets/translations/${lang}.json`); -} - -@NgModule({ - declarations: [...], - imports: [ - ... - TranslateModule.forRoot({ - // dependencies - deps: [ HttpClient ], - - lang: window.navigator.language, - fallbackLang: 'ru-RU', - - loadDictionaries: ({lang, fallbackLang}, client /* params are injected dependencies received in the same order as they are in deps */) => { - - const res$ = forkJoin([getDictionary(lang, client), getDictionary(fbLang, client)]).pipe( - map((res) => { - return { [lang]: res[0], fbLang: res[1] }; - }) - ); - - return res$; - }, - }), - ... - ], - ... -}) -``` - -**Note**: it is might be useful to **hardcode** _fallback dictionary_ in .ts or .json file then import it rather then use http client to download. - -```javascript -import fallback from './translations/fallback'; - -TranslateModule.forRoot({ - lang: window.navigator.language, - fallbackLang: env.fallbackLanguage, - dictionaries: { - [env.fallbackLanguage]: fallback, - }, - - deps: [ HttpClient ], - loadDictionaries: ({lang, fallbackLang}, client /* params are injected dependencies received in the same order as they are in deps */) => { - return getDictionary(lang, client).pipe( - map((res) => { - return { [lang]: res }; - }) - ); - }, -}), -``` - -**Note**: For more complex scenarios you may use initialization functions with `APP_INITIALIZER` token. - -#### Lazy +The proxy library and the demo app import `simply-translate-angular` from `dist/translate`, so build the translate library before working on them. -Load dictionaries for **Lazy** modules a bit trickier. +## Releasing -```javascript -export function getDictionary(lang: string, client: HttpClient) { - return client.get(`/assets/translations/${lang}.dynamic.json`); -} +1. Bump `version` in `projects//package.json` and move the `(unreleased)` heading in that project's `CHANGELOG.md` to the new version. +2. Publish a GitHub Release whose tag is `@`, for example `simply-translate-angular@1.0.0` or `simply-translate-angular-proxy@1.0.0`. -@NgModule({ - declarations: [...], - imports: [ - TranslateModule.forChild({ - deps: [ HttpClient ], - loadDictionaries: ({ lang, fallbackLang }, client: HttpClient) => { - return forkJoin([getDictionary(lang, client), getDictionary(fallbackLang, client)]).pipe( - map((res) => { - return { [lang]: res[0], [fallbackLang]: res[1] }; - }) - ); - }, - }), - ... - ] -}) -export class DynamicModule {} -``` - -Then you **must** use resolver `TranslateResolve` to every lazy component to wait for child `loadDictionaries`. - -```javascript -const routes: Routes = [{ path: '', component: DynamicComponent, resolve: { translate: TranslateResolve } }]; - -@NgModule({ - imports: [RouterModule.forChild(routes)], - exports: [RouterModule], -}) -export class DynamicRoutingModule {} -``` - -**Deprecated: Under consideration of removing**: For rare cases you may use `id` parameter for Lazy loaded module, that allows having different values with same key. -"Lazy" values will be available only for lazy modules with that special `id`. - -```javascript -@NgModule({ - declarations: [...], - imports: [ - TranslateModule.forRoot({ - dictionaries: {'en-US':{ - 'key':'Value' - }} - }) - ] -}) -``` - -```javascript -@NgModule({ - declarations: [...], - imports: [ - TranslateModule.forChild({ - id: 'lazy' - dictionaries: {'en-US':{ - 'key':'Value for Lazy' - }} - }) - ] -}) -``` - -#### Per-proxy (`per-proxy-loader`) - -A `TranslateProxy` subclass can load its own per-language dictionary, without any `forChild()`/`NgModule` wrapper — each language may be a plain object, a `Promise`, an `Observable`, or a URL string fetched via `HttpClient`. Only the *active* language loads eagerly by default; anything else loads on demand the first time you switch to it, unless you ask for it upfront via `preloadLangs`/`preloadFallbackLang`, or on demand via `preloadLang()`. Configure it with the `@TranslateProxyLoader(config)` decorator: - -```typescript -import { Injectable } from '@angular/core'; -import { TranslateProxy, TranslateProxyLoader } from 'simply-translate-angular'; -import type { AppSchema } from './app.schema'; - -@Injectable({ providedIn: 'root' }) -@TranslateProxyLoader({ - id: 'app', - dictionaries: { - // dynamic import() — code-split into its own lazy chunk, fetched when this proxy is first constructed - 'en-US': import('./translations/en-US.json').then((m) => m.default), - // URL string — fetched via HttpClient the first time this language becomes active - 'ru-RU': '/assets/translations/ru-RU.json', - }, - preloadFallbackLang: true, // also load `service.fallbackLang` upfront, not just the active language -}) -export class AppTranslate extends TranslateProxy { - // optional — fires whenever a language finishes loading successfully - onLoaderReady({ lang, id }: { lang: string; id: string }): void { - console.log(`Loaded '${id}' (${lang})`); - } - - // optional — fires whenever a language fails to load; omit it and failures stay silent - onLoaderError({ lang, id, error }: { lang: string; id: string; error: unknown }): void { - console.error(`Failed to load '${id}' (${lang})`, error); - } -} -``` - -Beyond `preloadLangs`/`preloadFallbackLang`, call the proxy's own `preloadLang(lang)` whenever you want a language warmed up ad hoc (e.g. a language the user is likely to switch to next) — it's a no-op if the proxy has no dictionary entry for `lang`: - -```typescript -appTranslate.preloadLang('de-DE'); -``` - -**Caveat:** unlike `forChild()`'s `id`-based key prefixing, this does not namespace keys — every proxy's dictionary is merged flat into the same per-language dictionary. If more than one proxy loads its own dictionary, wrap each one's own schema in a top-level `Namespace({...})` (named after that feature) to avoid colliding with another proxy's keys. - -##### Sharing a dictionary between proxies (`extends`) - -`@TranslateProxyLoader`'s real value beyond being declarative is `extends` — sharing one proxy's dictionary with another, so common strings (`ok`, `no`, generic labels, ...) don't have to be redeclared and reloaded by every feature that needs them: - -```typescript -import { StringProp, TranslateSchema } from 'simply-translate-angular'; - -const commonSchema = TranslateSchema({ ok: StringProp(), no: StringProp() }); - -@Injectable({ providedIn: 'root' }) -@TranslateProxyLoader({ id: 'common', dictionaries: { 'en-US': { ok: 'Ok', no: 'No' } } }) -export class CommonTranslate extends TranslateProxy {} - -// spread the shared shape in — schemas are plain objects, so this is ordinary composition (see -// [Validating dictionaries with a schema](#validating-dictionaries-with-a-schema)), nothing `extends`-specific -const featureSchema = TranslateSchema({ ...commonSchema.shape, title: StringProp() }); - -@Injectable({ providedIn: 'root' }) -@TranslateProxyLoader({ - id: 'feature', - extends: [CommonTranslate], - dictionaries: { 'en-US': { title: 'Title' } }, -}) -export class FeatureTranslate extends TranslateProxy {} -``` - -Injecting `FeatureTranslate` alone is enough — `feature.object.ok` and `feature.object.title` both resolve, without ever injecting `CommonTranslate` anywhere. `extends` takes **class references**, forces to actually `inject` that class. - -Two things `extends` does *not* do: it doesn't derive `FeatureTranslate`'s schema type for you (spread the shape in by hand, as above — `extends` only affects runtime loading), and it doesn't forward `CommonTranslate`'s own `onLoaderReady`/`onLoaderError` to `FeatureTranslate`, `extends` never constructs a `CommonTranslate` instance of its own beyond what DI already gives you. - -### Pipeline - -**(experimental)** -Currently it is possible to **append** middleware to the end of translation pipeline. -It might be specially useful to add **logger** or rarely fine-tune translation result. - -```javascript -@NgModule({ - declarations: [...], - imports: [ - ... - TranslateModule.forRoot({ - // dependencies - deps: [ Logger ], - addMiddleware: (logger /* injected dependencies */) => { - return [ - ({params, result}, next) => { - if (result.fallingBack) { - logger.log(`Translation absent [${params.lang}:${params.key}]`); - } - next(); - }, - ]; - }, - }), - ... - ], - ... -}) -``` +The [Publish workflow](.github/workflows/publish.yml) checks that the tag matches the package version, runs the tests, and publishes that package to npm. Versions with a pre-release suffix (`1.1.0-beta.1`) go to the `next` dist-tag. diff --git a/angular.json b/angular.json index 6da2c2e..d915929 100644 --- a/angular.json +++ b/angular.json @@ -182,6 +182,42 @@ } } } + }, + "proxy": { + "projectType": "library", + "root": "projects/proxy", + "sourceRoot": "projects/proxy/src", + "prefix": "lib", + "architect": { + "build": { + "builder": "@angular-devkit/build-angular:ng-packagr", + "options": { + "project": "projects/proxy/ng-package.json" + }, + "configurations": { + "production": { + "tsConfig": "projects/proxy/tsconfig.lib.prod.json" + }, + "development": { + "tsConfig": "projects/proxy/tsconfig.lib.json" + } + }, + "defaultConfiguration": "production" + }, + "test": { + "builder": "@angular-devkit/build-angular:karma", + "options": { + "tsConfig": "projects/proxy/tsconfig.spec.json", + "polyfills": [ + "zone.js", + "zone.js/testing" + ] + } + } + } } + }, + "cli": { + "analytics": false } } diff --git a/package-lock.json b/package-lock.json index 60f5beb..fe7f312 100644 --- a/package-lock.json +++ b/package-lock.json @@ -22,13 +22,14 @@ "@angular/platform-browser-dynamic": "^17.3.12", "@angular/router": "^17.3.12", "rxjs": "^7.3.0", - "simply-translate": "^0.20.0", + "simply-translate": "^1.0.0", "tslib": "^2.3.1", "typescript": "5.4.5", "zone.js": "~0.14.10" }, "devDependencies": { "@angular-devkit/build-angular": "^17.3.17", + "@angular/compiler-cli": "^17.3.0", "@types/jasmine": "~6.0.0", "@types/jasminewd2": "~2.0.10", "@types/node": "~18.11.7", @@ -38,18 +39,21 @@ "jasmine-spec-reporter": "~7.0.0", "karma": "~6.4.2", "karma-chrome-launcher": "~3.1.0", + "karma-coverage": "^2.2.1", "karma-coverage-istanbul-reporter": "~3.0.3", "karma-jasmine": "~5.1.0", "karma-jasmine-html-reporter": "^2.2.0", "ng-packagr": "^17.3.0", "protractor": "~7.0.0", - "tslint": "~6.1.3" + "tslint": "~6.1.3", + "typescript": "~5.4.2" } }, "node_modules/@ampproject/remapping": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.3.0.tgz", "integrity": "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==", + "dev": true, "license": "Apache-2.0", "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", @@ -568,6 +572,7 @@ "version": "17.3.12", "resolved": "https://registry.npmjs.org/@angular/compiler-cli/-/compiler-cli-17.3.12.tgz", "integrity": "sha512-1F8M7nWfChzurb7obbvuE7mJXlHtY1UG58pcwcomVtpPb+kPavgAO8OEvJHYBMV+bzSxkXt5UIwL9lt9jHUxZA==", + "dev": true, "license": "MIT", "dependencies": { "@babel/core": "7.23.9", @@ -762,6 +767,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "dev": true, "license": "MIT", "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", @@ -776,6 +782,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", + "dev": true, "license": "MIT", "engines": { "node": ">=6.9.0" @@ -785,6 +792,7 @@ "version": "7.23.9", "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.23.9.tgz", "integrity": "sha512-5q0175NOjddqpvvzU+kDiSOAk4PfdO6FvwCWoQ6RO7rTzEe8vlo+4HVfcnAREhD4npMs0e9uZypjTwzZPCf/cw==", + "dev": true, "license": "MIT", "dependencies": { "@ampproject/remapping": "^2.2.0", @@ -815,6 +823,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.7.tgz", "integrity": "sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ==", + "dev": true, "license": "MIT", "dependencies": { "@babel/parser": "^7.29.7", @@ -831,12 +840,14 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, "license": "MIT" }, "node_modules/@babel/core/node_modules/semver": { "version": "6.3.1", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, "license": "ISC", "bin": { "semver": "bin/semver.js" @@ -876,6 +887,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz", "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==", + "dev": true, "license": "MIT", "dependencies": { "@babel/compat-data": "^7.29.7", @@ -892,6 +904,7 @@ "version": "5.1.1", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, "license": "ISC", "dependencies": { "yallist": "^3.0.2" @@ -901,6 +914,7 @@ "version": "6.3.1", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, "license": "ISC", "bin": { "semver": "bin/semver.js" @@ -910,6 +924,7 @@ "version": "3.1.1", "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, "license": "ISC" }, "node_modules/@babel/helper-create-class-features-plugin": { @@ -1041,6 +1056,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", + "dev": true, "license": "MIT", "engines": { "node": ">=6.9.0" @@ -1064,6 +1080,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", + "dev": true, "license": "MIT", "dependencies": { "@babel/traverse": "^7.29.7", @@ -1077,6 +1094,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz", "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==", + "dev": true, "license": "MIT", "dependencies": { "@babel/helper-module-imports": "^7.29.7", @@ -1193,6 +1211,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", + "dev": true, "license": "MIT", "engines": { "node": ">=6.9.0" @@ -1202,6 +1221,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true, "license": "MIT", "engines": { "node": ">=6.9.0" @@ -1211,6 +1231,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", + "dev": true, "license": "MIT", "engines": { "node": ">=6.9.0" @@ -1235,6 +1256,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz", "integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==", + "dev": true, "license": "MIT", "dependencies": { "@babel/template": "^7.29.7", @@ -1248,6 +1270,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.7.tgz", "integrity": "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg==", + "dev": true, "license": "MIT", "dependencies": { "@babel/types": "^7.29.7" @@ -2427,6 +2450,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", + "dev": true, "license": "MIT", "dependencies": { "@babel/code-frame": "^7.29.7", @@ -2441,6 +2465,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.7.tgz", "integrity": "sha512-EhlfNQtZ+NK22w5BM61ciuiq1m58ed33Wr1Xan//ZRTy6hgjnwyCffRYwzsGXdASJSUJ1guZILsErh1eQcl+zw==", + "dev": true, "license": "MIT", "dependencies": { "@babel/code-frame": "^7.29.7", @@ -2459,6 +2484,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.7.tgz", "integrity": "sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ==", + "dev": true, "license": "MIT", "dependencies": { "@babel/parser": "^7.29.7", @@ -2475,6 +2501,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.7.tgz", "integrity": "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==", + "dev": true, "license": "MIT", "dependencies": { "@babel/helper-string-parser": "^7.29.7", @@ -3016,6 +3043,7 @@ "version": "0.3.13", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, "license": "MIT", "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", @@ -3026,6 +3054,7 @@ "version": "3.1.2", "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, "license": "MIT", "engines": { "node": ">=6.0.0" @@ -3052,6 +3081,7 @@ "version": "0.3.31", "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, "license": "MIT", "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", @@ -5530,6 +5560,7 @@ }, "node_modules/anymatch": { "version": "3.1.2", + "devOptional": true, "license": "ISC", "dependencies": { "normalize-path": "^3.0.0", @@ -5763,6 +5794,7 @@ "version": "2.11.1", "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.1.tgz", "integrity": "sha512-HYXq73DDpCtNzOmrFsm9eSwCvWCql0RzqjpDzXN9EadiLJ4DNat0nsZ/Bzmy+Ud12mb4/zKDY0cQ805ZzN+i0A==", + "dev": true, "license": "Apache-2.0", "bin": { "baseline-browser-mapping": "dist/cli.cjs" @@ -5797,6 +5829,7 @@ }, "node_modules/binary-extensions": { "version": "2.2.0", + "devOptional": true, "license": "MIT", "engines": { "node": ">=8" @@ -5904,6 +5937,7 @@ }, "node_modules/braces": { "version": "3.0.2", + "devOptional": true, "license": "MIT", "dependencies": { "fill-range": "^7.0.1" @@ -5916,6 +5950,7 @@ "version": "4.28.7", "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.7.tgz", "integrity": "sha512-JxV13hNrFxqjOc8alRbq9dK1MM79NEXYpma2B2J4wAtpWS5zIEIKqWPGCl7N4o7Uc7B7itylh7SuDujATRyyTw==", + "dev": true, "funding": [ { "type": "opencollective", @@ -6164,6 +6199,7 @@ "version": "1.0.30001806", "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001806.tgz", "integrity": "sha512-72Cuvd95zbSYPKq6Fhg8eDJRlzgWDf7/mtoZv6Qe/DYNCEBdNxoA3+rZAU2ZhGCpZlns3EssFavaZomckT5Uuw==", + "dev": true, "funding": [ { "type": "opencollective", @@ -6208,6 +6244,7 @@ "version": "3.5.3", "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz", "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==", + "devOptional": true, "funding": [ { "type": "individual", @@ -6548,6 +6585,7 @@ }, "node_modules/convert-source-map": { "version": "1.8.0", + "dev": true, "license": "MIT", "dependencies": { "safe-buffer": "~5.1.1" @@ -7322,6 +7360,7 @@ "version": "1.5.396", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.396.tgz", "integrity": "sha512-yHiw2Y3C3H9U6TMbOfoWK/BPreiOPXRfTWPBwQBoZG6/8TB6eOPnsy5oaRYuatR7Fw2SJ4kKforgufeo7fq0EQ==", + "dev": true, "license": "ISC" }, "node_modules/emoji-regex": { @@ -7952,6 +7991,7 @@ }, "node_modules/fill-range": { "version": "7.0.1", + "devOptional": true, "license": "MIT", "dependencies": { "to-regex-range": "^5.0.1" @@ -8201,6 +8241,7 @@ }, "node_modules/gensync": { "version": "1.0.0-beta.2", + "dev": true, "license": "MIT", "engines": { "node": ">=6.9.0" @@ -8300,6 +8341,7 @@ }, "node_modules/glob-parent": { "version": "5.1.2", + "devOptional": true, "license": "ISC", "dependencies": { "is-glob": "^4.0.1" @@ -9002,6 +9044,7 @@ }, "node_modules/is-binary-path": { "version": "2.1.0", + "devOptional": true, "license": "MIT", "dependencies": { "binary-extensions": "^2.0.0" @@ -9042,6 +9085,7 @@ }, "node_modules/is-extglob": { "version": "2.1.1", + "devOptional": true, "license": "MIT", "engines": { "node": ">=0.10.0" @@ -9056,6 +9100,7 @@ }, "node_modules/is-glob": { "version": "4.0.3", + "devOptional": true, "license": "MIT", "dependencies": { "is-extglob": "^2.1.1" @@ -9086,6 +9131,7 @@ }, "node_modules/is-number": { "version": "7.0.0", + "devOptional": true, "license": "MIT", "engines": { "node": ">=0.12.0" @@ -9485,6 +9531,7 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, "license": "MIT" }, "node_modules/js-yaml": { @@ -9508,6 +9555,7 @@ "version": "3.1.0", "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, "license": "MIT", "bin": { "jsesc": "bin/jsesc" @@ -9540,6 +9588,7 @@ "version": "2.2.3", "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, "license": "MIT", "bin": { "json5": "lib/cli.js" @@ -9670,6 +9719,24 @@ "which": "^1.2.1" } }, + "node_modules/karma-coverage": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/karma-coverage/-/karma-coverage-2.2.1.tgz", + "integrity": "sha512-yj7hbequkQP2qOSb20GuNSIyE//PgJWHwC2IydLE6XRtsnaflv+/OSGNssPjobYUlhVVagy99TQpqUt3vAUG7A==", + "dev": true, + "license": "MIT", + "dependencies": { + "istanbul-lib-coverage": "^3.2.0", + "istanbul-lib-instrument": "^5.1.0", + "istanbul-lib-report": "^3.0.0", + "istanbul-lib-source-maps": "^4.0.1", + "istanbul-reports": "^3.0.5", + "minimatch": "^3.0.4" + }, + "engines": { + "node": ">=10.0.0" + } + }, "node_modules/karma-coverage-istanbul-reporter": { "version": "3.0.3", "dev": true, @@ -9685,6 +9752,31 @@ "url": "https://github.com/sponsors/mattlewis92" } }, + "node_modules/karma-coverage/node_modules/istanbul-lib-source-maps": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz", + "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "debug": "^4.1.1", + "istanbul-lib-coverage": "^3.0.0", + "source-map": "^0.6.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/karma-coverage/node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/karma-jasmine": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/karma-jasmine/-/karma-jasmine-5.1.0.tgz", @@ -10840,6 +10932,7 @@ "version": "2.0.51", "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.51.tgz", "integrity": "sha512-wRNIrw4DmVLKQlbgOMdkMx27Wrpzes2hh5Jtbi2bjPd+4wJstWIqP5A+lscnqbm0xxmT5Bpg8Lec5ItEBwx6BQ==", + "dev": true, "license": "MIT", "engines": { "node": ">=18" @@ -10910,6 +11003,7 @@ }, "node_modules/normalize-path": { "version": "3.0.0", + "devOptional": true, "license": "MIT", "engines": { "node": ">=0.10.0" @@ -11535,10 +11629,12 @@ "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, "license": "ISC" }, "node_modules/picomatch": { "version": "2.3.1", + "devOptional": true, "license": "MIT", "engines": { "node": ">=8.6" @@ -12320,6 +12416,7 @@ }, "node_modules/readdirp": { "version": "3.6.0", + "devOptional": true, "license": "MIT", "dependencies": { "picomatch": "^2.2.1" @@ -12332,6 +12429,7 @@ "version": "0.2.2", "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz", "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==", + "dev": true, "license": "Apache-2.0" }, "node_modules/regenerate": { @@ -12669,6 +12767,7 @@ }, "node_modules/safe-buffer": { "version": "5.1.2", + "dev": true, "license": "MIT" }, "node_modules/safer-buffer": { @@ -13245,9 +13344,10 @@ } }, "node_modules/simply-translate": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/simply-translate/-/simply-translate-0.20.0.tgz", - "integrity": "sha512-A44qZNkix0OU/48oA5qa3fdvZZIUhztJZjDAjd6pMIsc0ZPjgbvM9ORmZQQ5KLxETBa23b8MRFfV9aHhyOGOnQ==" + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/simply-translate/-/simply-translate-1.0.0.tgz", + "integrity": "sha512-FXeKImdHZtge4FqY3PksJDP3UUCbfISSYGbtJP8o+EtZryurY2xrE6BcFuon+W0zkc5UBOD4J6W8pchs9e14Vw==", + "license": "MIT" }, "node_modules/slash": { "version": "4.0.0", @@ -13923,6 +14023,7 @@ }, "node_modules/to-regex-range": { "version": "5.0.1", + "devOptional": true, "license": "MIT", "dependencies": { "is-number": "^7.0.0" @@ -14112,6 +14213,7 @@ "version": "5.4.5", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz", "integrity": "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==", + "dev": true, "license": "Apache-2.0", "bin": { "tsc": "bin/tsc", @@ -14237,6 +14339,7 @@ "version": "1.2.3", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", + "dev": true, "funding": [ { "type": "opencollective", @@ -15499,6 +15602,7 @@ "version": "2.3.0", "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.3.0.tgz", "integrity": "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==", + "dev": true, "requires": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" @@ -15821,6 +15925,7 @@ "version": "17.3.12", "resolved": "https://registry.npmjs.org/@angular/compiler-cli/-/compiler-cli-17.3.12.tgz", "integrity": "sha512-1F8M7nWfChzurb7obbvuE7mJXlHtY1UG58pcwcomVtpPb+kPavgAO8OEvJHYBMV+bzSxkXt5UIwL9lt9jHUxZA==", + "dev": true, "requires": { "@babel/core": "7.23.9", "@jridgewell/sourcemap-codec": "^1.4.14", @@ -15936,6 +16041,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "dev": true, "requires": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", @@ -15945,12 +16051,14 @@ "@babel/compat-data": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", - "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==" + "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", + "dev": true }, "@babel/core": { "version": "7.23.9", "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.23.9.tgz", "integrity": "sha512-5q0175NOjddqpvvzU+kDiSOAk4PfdO6FvwCWoQ6RO7rTzEe8vlo+4HVfcnAREhD4npMs0e9uZypjTwzZPCf/cw==", + "dev": true, "requires": { "@ampproject/remapping": "^2.2.0", "@babel/code-frame": "^7.23.5", @@ -15973,6 +16081,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.7.tgz", "integrity": "sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ==", + "dev": true, "requires": { "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7", @@ -15984,12 +16093,14 @@ "convert-source-map": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", - "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==" + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true }, "semver": { "version": "6.3.1", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==" + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true } } }, @@ -16019,6 +16130,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz", "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==", + "dev": true, "requires": { "@babel/compat-data": "^7.29.7", "@babel/helper-validator-option": "^7.29.7", @@ -16031,6 +16143,7 @@ "version": "5.1.1", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, "requires": { "yallist": "^3.0.2" } @@ -16038,12 +16151,14 @@ "semver": { "version": "6.3.1", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==" + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true }, "yallist": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", - "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==" + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true } } }, @@ -16137,7 +16252,8 @@ "@babel/helper-globals": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", - "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==" + "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", + "dev": true }, "@babel/helper-member-expression-to-functions": { "version": "7.29.7", @@ -16153,6 +16269,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", + "dev": true, "requires": { "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7" @@ -16162,6 +16279,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz", "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==", + "dev": true, "requires": { "@babel/helper-module-imports": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7", @@ -16238,17 +16356,20 @@ "@babel/helper-string-parser": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", - "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==" + "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", + "dev": true }, "@babel/helper-validator-identifier": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", - "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==" + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true }, "@babel/helper-validator-option": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", - "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==" + "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", + "dev": true }, "@babel/helper-wrap-function": { "version": "7.29.7", @@ -16265,6 +16386,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz", "integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==", + "dev": true, "requires": { "@babel/template": "^7.29.7", "@babel/types": "^7.29.7" @@ -16274,6 +16396,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.7.tgz", "integrity": "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg==", + "dev": true, "requires": { "@babel/types": "^7.29.7" } @@ -17004,6 +17127,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", + "dev": true, "requires": { "@babel/code-frame": "^7.29.7", "@babel/parser": "^7.29.7", @@ -17014,6 +17138,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.7.tgz", "integrity": "sha512-EhlfNQtZ+NK22w5BM61ciuiq1m58ed33Wr1Xan//ZRTy6hgjnwyCffRYwzsGXdASJSUJ1guZILsErh1eQcl+zw==", + "dev": true, "requires": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.7", @@ -17028,6 +17153,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.7.tgz", "integrity": "sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ==", + "dev": true, "requires": { "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7", @@ -17042,6 +17168,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.7.tgz", "integrity": "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==", + "dev": true, "requires": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" @@ -17297,6 +17424,7 @@ "version": "0.3.13", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, "requires": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" @@ -17305,7 +17433,8 @@ "@jridgewell/resolve-uri": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", - "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==" + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true }, "@jridgewell/source-map": { "version": "0.3.11", @@ -17326,6 +17455,7 @@ "version": "0.3.31", "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, "requires": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" @@ -19195,6 +19325,7 @@ }, "anymatch": { "version": "3.1.2", + "devOptional": true, "requires": { "normalize-path": "^3.0.0", "picomatch": "^2.0.4" @@ -19332,7 +19463,8 @@ "baseline-browser-mapping": { "version": "2.11.1", "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.1.tgz", - "integrity": "sha512-HYXq73DDpCtNzOmrFsm9eSwCvWCql0RzqjpDzXN9EadiLJ4DNat0nsZ/Bzmy+Ud12mb4/zKDY0cQ805ZzN+i0A==" + "integrity": "sha512-HYXq73DDpCtNzOmrFsm9eSwCvWCql0RzqjpDzXN9EadiLJ4DNat0nsZ/Bzmy+Ud12mb4/zKDY0cQ805ZzN+i0A==", + "dev": true }, "batch": { "version": "0.6.1", @@ -19354,7 +19486,8 @@ "dev": true }, "binary-extensions": { - "version": "2.2.0" + "version": "2.2.0", + "devOptional": true }, "bl": { "version": "4.1.0", @@ -19439,6 +19572,7 @@ }, "braces": { "version": "3.0.2", + "devOptional": true, "requires": { "fill-range": "^7.0.1" } @@ -19447,6 +19581,7 @@ "version": "4.28.7", "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.7.tgz", "integrity": "sha512-JxV13hNrFxqjOc8alRbq9dK1MM79NEXYpma2B2J4wAtpWS5zIEIKqWPGCl7N4o7Uc7B7itylh7SuDujATRyyTw==", + "dev": true, "requires": { "baseline-browser-mapping": "^2.10.44", "caniuse-lite": "^1.0.30001806", @@ -19601,7 +19736,8 @@ "caniuse-lite": { "version": "1.0.30001806", "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001806.tgz", - "integrity": "sha512-72Cuvd95zbSYPKq6Fhg8eDJRlzgWDf7/mtoZv6Qe/DYNCEBdNxoA3+rZAU2ZhGCpZlns3EssFavaZomckT5Uuw==" + "integrity": "sha512-72Cuvd95zbSYPKq6Fhg8eDJRlzgWDf7/mtoZv6Qe/DYNCEBdNxoA3+rZAU2ZhGCpZlns3EssFavaZomckT5Uuw==", + "dev": true }, "caseless": { "version": "0.12.0", @@ -19625,6 +19761,7 @@ "version": "3.5.3", "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz", "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==", + "devOptional": true, "requires": { "anymatch": "~3.1.2", "braces": "~3.0.2", @@ -19844,6 +19981,7 @@ }, "convert-source-map": { "version": "1.8.0", + "dev": true, "requires": { "safe-buffer": "~5.1.1" } @@ -20354,7 +20492,8 @@ "electron-to-chromium": { "version": "1.5.396", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.396.tgz", - "integrity": "sha512-yHiw2Y3C3H9U6TMbOfoWK/BPreiOPXRfTWPBwQBoZG6/8TB6eOPnsy5oaRYuatR7Fw2SJ4kKforgufeo7fq0EQ==" + "integrity": "sha512-yHiw2Y3C3H9U6TMbOfoWK/BPreiOPXRfTWPBwQBoZG6/8TB6eOPnsy5oaRYuatR7Fw2SJ4kKforgufeo7fq0EQ==", + "dev": true }, "emoji-regex": { "version": "8.0.0" @@ -20792,6 +20931,7 @@ }, "fill-range": { "version": "7.0.1", + "devOptional": true, "requires": { "to-regex-range": "^5.0.1" } @@ -20946,7 +21086,8 @@ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==" }, "gensync": { - "version": "1.0.0-beta.2" + "version": "1.0.0-beta.2", + "dev": true }, "get-caller-file": { "version": "2.0.5" @@ -21008,6 +21149,7 @@ }, "glob-parent": { "version": "5.1.2", + "devOptional": true, "requires": { "is-glob": "^4.0.1" } @@ -21478,6 +21620,7 @@ }, "is-binary-path": { "version": "2.1.0", + "devOptional": true, "requires": { "binary-extensions": "^2.0.0" } @@ -21496,13 +21639,15 @@ "integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==" }, "is-extglob": { - "version": "2.1.1" + "version": "2.1.1", + "devOptional": true }, "is-fullwidth-code-point": { "version": "3.0.0" }, "is-glob": { "version": "4.0.3", + "devOptional": true, "requires": { "is-extglob": "^2.1.1" } @@ -21522,7 +21667,8 @@ "dev": true }, "is-number": { - "version": "7.0.0" + "version": "7.0.0", + "devOptional": true }, "is-path-cwd": { "version": "1.0.0", @@ -21778,7 +21924,8 @@ "js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true }, "js-yaml": { "version": "3.14.1", @@ -21795,7 +21942,8 @@ "jsesc": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", - "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==" + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true }, "json-parse-even-better-errors": { "version": "2.3.1", @@ -21817,7 +21965,8 @@ "json5": { "version": "2.2.3", "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", - "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==" + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true }, "jsonc-parser": { "version": "3.2.1", @@ -21961,6 +22110,39 @@ "which": "^1.2.1" } }, + "karma-coverage": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/karma-coverage/-/karma-coverage-2.2.1.tgz", + "integrity": "sha512-yj7hbequkQP2qOSb20GuNSIyE//PgJWHwC2IydLE6XRtsnaflv+/OSGNssPjobYUlhVVagy99TQpqUt3vAUG7A==", + "dev": true, + "requires": { + "istanbul-lib-coverage": "^3.2.0", + "istanbul-lib-instrument": "^5.1.0", + "istanbul-lib-report": "^3.0.0", + "istanbul-lib-source-maps": "^4.0.1", + "istanbul-reports": "^3.0.5", + "minimatch": "^3.0.4" + }, + "dependencies": { + "istanbul-lib-source-maps": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz", + "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==", + "dev": true, + "requires": { + "debug": "^4.1.1", + "istanbul-lib-coverage": "^3.0.0", + "source-map": "^0.6.1" + } + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, "karma-coverage-istanbul-reporter": { "version": "3.0.3", "dev": true, @@ -22695,7 +22877,8 @@ "node-releases": { "version": "2.0.51", "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.51.tgz", - "integrity": "sha512-wRNIrw4DmVLKQlbgOMdkMx27Wrpzes2hh5Jtbi2bjPd+4wJstWIqP5A+lscnqbm0xxmT5Bpg8Lec5ItEBwx6BQ==" + "integrity": "sha512-wRNIrw4DmVLKQlbgOMdkMx27Wrpzes2hh5Jtbi2bjPd+4wJstWIqP5A+lscnqbm0xxmT5Bpg8Lec5ItEBwx6BQ==", + "dev": true }, "noms": { "version": "0.0.0", @@ -22752,7 +22935,8 @@ } }, "normalize-path": { - "version": "3.0.0" + "version": "3.0.0", + "devOptional": true }, "normalize-range": { "version": "0.1.2", @@ -23158,10 +23342,12 @@ "picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", - "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==" + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true }, "picomatch": { - "version": "2.3.1" + "version": "2.3.1", + "devOptional": true }, "pify": { "version": "2.3.0", @@ -23651,6 +23837,7 @@ }, "readdirp": { "version": "3.6.0", + "devOptional": true, "requires": { "picomatch": "^2.2.1" } @@ -23658,7 +23845,8 @@ "reflect-metadata": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz", - "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==" + "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==", + "dev": true }, "regenerate": { "version": "1.4.2", @@ -23897,7 +24085,8 @@ } }, "safe-buffer": { - "version": "5.1.2" + "version": "5.1.2", + "dev": true }, "safer-buffer": { "version": "2.1.2" @@ -24286,9 +24475,9 @@ } }, "simply-translate": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/simply-translate/-/simply-translate-0.20.0.tgz", - "integrity": "sha512-A44qZNkix0OU/48oA5qa3fdvZZIUhztJZjDAjd6pMIsc0ZPjgbvM9ORmZQQ5KLxETBa23b8MRFfV9aHhyOGOnQ==" + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/simply-translate/-/simply-translate-1.0.0.tgz", + "integrity": "sha512-FXeKImdHZtge4FqY3PksJDP3UUCbfISSYGbtJP8o+EtZryurY2xrE6BcFuon+W0zkc5UBOD4J6W8pchs9e14Vw==" }, "slash": { "version": "4.0.0", @@ -24738,6 +24927,7 @@ }, "to-regex-range": { "version": "5.0.1", + "devOptional": true, "requires": { "is-number": "^7.0.0" } @@ -24865,7 +25055,8 @@ "typescript": { "version": "5.4.5", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz", - "integrity": "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==" + "integrity": "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==", + "dev": true }, "ua-parser-js": { "version": "0.7.31", @@ -24935,6 +25126,7 @@ "version": "1.2.3", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", + "dev": true, "requires": { "escalade": "^3.2.0", "picocolors": "^1.1.1" diff --git a/package.json b/package.json index 9663e02..3ca1b42 100644 --- a/package.json +++ b/package.json @@ -1,21 +1,24 @@ { "name": "simply-translate-angular", "version": "0.0.0", + "private": true, "type": "module", "scripts": { - "build:dev": "ng build translate --configuration development && npm run copy_readme && npm run copy_npmrc", - "build:prod": "ng build translate --configuration production && npm run copy_readme && npm run copy_npmrc", - "build:prod:patch": "cd ./projects/translate && npm --no-git-tag-version version patch && cd ../.. && npm run build:prod", - "publish:prod": "npm run build:prod && cd dist/translate && npm publish && cd ../..", - "publish:prod:patch": "npm run build:prod:patch && cd dist/translate && npm publish && cd ../..", + "build:translate": "ng build translate --configuration production && copyfiles -f projects/translate/CHANGELOG.md LICENSE dist/translate", + "build:proxy": "ng build proxy --configuration production && copyfiles -f projects/proxy/CHANGELOG.md LICENSE dist/proxy", + "build:prod": "npm run build:translate && npm run build:proxy", + "build:dev": "ng build translate && ng build proxy --configuration development", + "publish:translate": "npm run build:translate && npm publish ./dist/translate", + "publish:proxy": "npm run build:prod && npm publish ./dist/proxy", "build:demo:dev": "ng build --configuration development", "build:demo:prod": "node --max-old-space-size=8192 ./node_modules/@angular/cli/bin/ng build --configuration production --aot", "start:demo": "ng serve --port 4800 --live-reload false", - "restart:all": "npm run build:library:prod && npm run start:demo", - "test": "ng test translate", - "e2e": "ng e2e", - "copy_readme": "copyfiles ./README.md dist/translate", - "copy_npmrc": "copyfiles -f ./projects/translate/.npmrc dist/translate" + "restart:all": "npm run build:prod && npm run start:demo", + "test": "npm run test:translate && npm run build:translate && npm run test:proxy", + "test:translate": "ng test translate --watch=false --browsers=ChromeHeadless", + "test:proxy": "ng test proxy --watch=false --browsers=ChromeHeadless", + "test:watch": "ng test translate", + "e2e": "ng e2e" }, "dependencies": { "@angular/animations": "^17.3.12", @@ -32,27 +35,30 @@ "@angular/platform-browser-dynamic": "^17.3.12", "@angular/router": "^17.3.12", "rxjs": "^7.3.0", - "simply-translate": "^0.20.0", + "simply-translate": "^1.0.0", "tslib": "^2.3.1", "typescript": "5.4.5", "zone.js": "~0.14.10" }, "devDependencies": { "@angular-devkit/build-angular": "^17.3.17", + "@angular/compiler-cli": "^17.3.0", "@types/jasmine": "~6.0.0", "@types/jasminewd2": "~2.0.10", "@types/node": "~18.11.7", + "copyfiles": "^2.4.1", + "core-js": "^3.26.0", "jasmine-core": "~6.0.0", "jasmine-spec-reporter": "~7.0.0", "karma": "~6.4.2", "karma-chrome-launcher": "~3.1.0", + "karma-coverage": "^2.2.1", "karma-coverage-istanbul-reporter": "~3.0.3", "karma-jasmine": "~5.1.0", "karma-jasmine-html-reporter": "^2.2.0", "ng-packagr": "^17.3.0", "protractor": "~7.0.0", "tslint": "~6.1.3", - "core-js": "^3.26.0", - "copyfiles": "^2.4.1" + "typescript": "~5.4.2" } } diff --git a/projects/proxy/CHANGELOG.md b/projects/proxy/CHANGELOG.md new file mode 100644 index 0000000..51e9999 --- /dev/null +++ b/projects/proxy/CHANGELOG.md @@ -0,0 +1,12 @@ +# Changelog + +All notable changes to `simply-translate-angular-proxy` are listed here. + +## 1.0.0 (unreleased) + +First release as a separate package. The API moved here unchanged from `simply-translate-angular` 0.21.20. For earlier history see the [`simply-translate-angular` changelog](https://github.com/oleg-wx/translate-angular/blob/master/projects/translate/CHANGELOG.md). + +### Upgrading from simply-translate-angular 0.21.x + +1. `npm i simply-translate-angular-proxy` +2. Change imports of `TranslateProxy`, `TranslateProxyLoader`, `TranslateSchema`, `StringProp`, `ValueProp`, `Namespace`, `StringParam`, `NumberParam`, `StringNullableParam`, `NumberNullableParam`, `translateLoaderResolver`, `InferTranslateSchemaType`, `validateDictionary` and `assertValidDictionary` from `simply-translate-angular` to `simply-translate-angular-proxy`. diff --git a/projects/proxy/README.md b/projects/proxy/README.md new file mode 100644 index 0000000..831a580 --- /dev/null +++ b/projects/proxy/README.md @@ -0,0 +1,269 @@ +# Simply Translate Proxy for Angular + +Typed, autocompleted access to [simply-translate-angular](https://www.npmjs.com/package/simply-translate-angular) dictionaries, schema-based dictionary validation, and per-proxy dictionary loading. + +See the [changelog](CHANGELOG.md) for release notes. Before 1.0.0 this API shipped inside `simply-translate-angular`. + +### Install + +```bash +npm i simply-translate-angular simply-translate-angular-proxy +``` + +`TranslateProxy` uses `TranslateService` from `simply-translate-angular`, so set up `TranslateModule.forRoot(...)` as described in the [simply-translate-angular README](https://www.npmjs.com/package/simply-translate-angular#initialize) first. + +### Use TranslateProxy + +For typed, autocompleted access to your dictionary keys, describe your dictionary shape with `TranslateSchema` and extend `TranslateProxy`. + +```typescript +// app.schema.ts +import { Namespace, NumberParam, StringParam, StringProp, TranslateSchema, ValueProp } from 'simply-translate-angular-proxy'; + +export const appSchema = TranslateSchema({ + hello_user: StringProp({ params: { user: StringParam } }), + about: StringProp(), + namespace: Namespace({ + hello_user: StringProp({ params: { user: StringParam } }), + }), + visit_count: ValueProp({ params: { count: NumberParam } }), +}); + +export type AppSchema = typeof appSchema; +``` + +(Named `StringProp`/`ValueProp` rather than `String`/`Value` to avoid shadowing the globals of the same name.) + +```typescript +// app.translate.ts +import { Injectable } from '@angular/core'; +import { TranslateProxy } from 'simply-translate-angular-proxy'; +import type { AppSchema } from './app.schema'; + +@Injectable() +export class AppTranslate extends TranslateProxy {} +``` + +`TranslateProxy` takes the schema itself as its type parameter — the dictionary type is inferred from it via `InferTranslateSchemaType`. `TranslateProxy` only ever needs `AppSchema`'s **type**, never `appSchema`'s runtime value, so import it with `import type`: TypeScript erases `import type` entirely at compile time, keeping the schema-building code (and everything it imports) out of your app's bundle unless something else in it also needs the actual schema object at runtime — e.g. to call `validateDictionary`. See [Validating dictionaries with a schema](#validating-dictionaries-with-a-schema) for the full builder API (`StringProp`, `ValueProp`, `Namespace`) and for validating your JSON dictionaries against the same schema at runtime. + +Inject it like any other service and read keys off `object`. Every leaf key is callable (mirrors `translate`), and carries `.Signal()` / `.$()` companions that mirror `translateSignal` / `translateObservable`. + +**The params each of these accepts comes entirely from how the schema leaf was declared:** + +- `StringProp()` / `ValueProp()`, called with no `params` — the leaf takes **no dynamic props at all**. The call, `.Signal()`, and `.$()` all become zero-argument — passing anything is a compile error. +- `StringProp({ params: {...} })` / `ValueProp({ params: {...} })` — the leaf **requires** exactly the shape described by `params`, everywhere. Omitting the argument, passing `undefined`, or passing the wrong shape are all compile errors. + +`params` is a flat map of prop name → either an actual default value (e.g. `user: 'Guest'`, `count: 0`) or, when there's no natural default, the `StringParam` / `NumberParam` markers (`StringNullableParam` / `NumberNullableParam` also accept `null`). Either way the value is only ever used to infer that prop's type (`string`/`number`) and to read its name — nothing about it is used at runtime beyond that. Params are intentionally flat (`string`/`number` only, no nesting) to match what dynamic props can actually be. + +```typescript +@Component({ + ... +}) +export class MyComponent { + constructor(protected translate: AppTranslate) { + // like translate.translate('hello_user', { user: 'Oleg' }) + this.hello = translate.object.hello_user({ user: 'Oleg' }); + + // reactive Signal, like translate.translateSignal(...) + this.helloSignal = translate.object.hello_user.Signal({ user: 'Oleg' }); + + // reactive Observable, like translate.translateObservable(...) + this.hello$ = translate.object.hello_user.$({ user: 'Oleg' }); + + // nested keys work the same way + this.nsHello = translate.object.namespace.hello_user({ user: 'Oleg' }); + + // `about` was declared with StringProp() (no params) -> zero-argument call + this.about = translate.object.about(); + // translate.object.about({ user: 'Oleg' }); // compile error: `about` takes no params + // translate.object.hello_user(); // compile error: `hello_user` requires { user: string } + this.userData = signal({ user: 'Oleg' }); + } +} +``` + +```html +
{{ helloSignal() }}
+
{{ translate.object.hello_user.Signal(userData)() }}
+``` + +Each key also stringifies to its full dotted path — `` `${translate.object.namespace.hello_user}` === 'namespace.hello_user' `` — useful when you need the key itself (logging, passing to another API) rather than its translation. + +**Warning — dynamic props with `.Signal()` / `.$()`:** the returned `Signal`/`Observable` is cached per `dynamicProps` reference (keyed by identity, not by value). A plain object always stays reactive to **language/dictionary** changes, but is a fixed snapshot of its own properties — it will never update if you mutate the object later, and passing a fresh object literal on every call (e.g. inline in a template) defeats the cache, allocating a new `Signal`/`Observable` each time. If the dynamic values themselves change over time, pass a `Signal`/`Observable` of that same params shape instead, and keep reusing the **same** reference so the cache can pick it up: + +```typescript +// reactive to changing values — pass a stable Signal/Observable reference +const params = signal({ user: 'Oleg' }); +this.helloSignal = translate.object.hello_user.Signal(params); +params.set({ user: 'John' }); // helloSignal updates automatically + +// static values, but still reactive to language/dictionary changes +this.helloSignal = translate.object.hello_user.Signal({ user: 'Oleg' }); +``` + +**Restriction:** `Signal` and `$` are reserved property names — `TranslateProxy` uses them on every key to expose the reactive accessors above. A dictionary key literally named `Signal` or `$` (at any nesting level) will be shadowed by these accessors and become unreachable through `object`. Avoid naming dictionary keys `Signal` or `$`. + +### Validating dictionaries with a schema + +`TranslateSchema` describes a dictionary once and gives you both the static type (via `InferTranslateSchemaType`, used internally by `TranslateProxy`) and a runtime validator for your actual JSON dictionary files — so a language file that's missing a key, has an extra key, or has the wrong shape fails loudly instead of silently falling back at runtime. + +Build a schema with three node builders: + +- `StringProp()` — a leaf that must be a plain string. +- `ValueProp()` — a leaf that may be a string, a `DictionaryEntry` (`{ value, plural?, cases?, description? }`), or a nested dictionary. +- `Namespace({...})` — a nested dictionary with a fixed, known shape. + +```typescript +import { InferTranslateSchemaType, Namespace, StringProp, TranslateSchema, ValueProp } from 'simply-translate-angular-proxy'; + +export const appSchema = TranslateSchema({ + welcome_to_app: StringProp(), + goodbye_world: ValueProp(), // string, or { value, description } etc. + namespace: Namespace({ + hello_user: ValueProp(), + }), +}); + +export type AppDictionary = InferTranslateSchemaType; +``` + +Validate a loaded dictionary (e.g. a parsed JSON file) against the schema: + +```typescript +import { assertValidDictionary, validateDictionary } from 'simply-translate-angular-proxy'; + +// returns a list of { path, message } issues, empty when valid +const errors = validateDictionary(appSchema, parsedJson); + +// or throw with a formatted message if invalid — handy in a startup check or a build/CI script +assertValidDictionary(appSchema, parsedJson, 'en-US.json'); +``` + +Some keys are legitimately allowed to diverge between the schema and a given language file — a translation that isn't ready yet, or a root-only fallback key. Rather than silently ignoring every missing/extra key, list the exceptions explicitly via `allowedErrors`, keyed by the same dotted path shown in `SchemaValidationError.path`. Each entry names the kind of error tolerated there — `'missing'`, `'orphan'`, `'params'`, or `'any'` (whichever check applies) — either as a bare string, or as `{ kind, reason? }` if you want to document why: + +```typescript +const errors = validateDictionary(appSchema, parsedJson, { + allowedErrors: { + 'namespace.hello_user': { kind: 'missing', reason: 'translation pending, falls back to en-US' }, + only_root_key: 'orphan', // root-only fallback key, intentionally absent from other languages + }, +}); +``` + +The kind has to match the check that would otherwise fire at that path — allowing `'orphan'` on a path that's actually reported as `'missing'` still errors. `'params'` is blanket per-path: it silences every placeholder mismatch at that key (see [Placeholder validation](#placeholder-validation)), not individual param names. + +A key ending in `.*` allows a whole namespace at once, instead of enumerating every leaf under it — `'namespace.*'` matches `namespace` itself and everything nested under it: + +```typescript +validateDictionary(appSchema, parsedJson, { + allowedErrors: { 'namespace.*': 'missing' }, // an entire namespace not translated yet for this language +}); +``` + +#### Placeholder validation + +When a leaf declares `params` (see [Use TranslateProxy](#use-translateproxy)), `validateDictionary` also checks that every declared param actually shows up as a `${name}` placeholder somewhere in the translation — and flags any placeholder that *isn't* declared. "Somewhere" covers the leaf's `value` as well as every `plural`/`cases` result string, since `simply-translate` re-scans a chosen plural/case result for further placeholders: + +```typescript +const appSchema = TranslateSchema({ + hello_user: StringProp({ params: { user: StringParam } }), + about: StringProp(), +}); + +validateDictionary(appSchema, { hello_user: 'Hello there', about: 'Welcome' }); +// [{ path: ['hello_user'], message: 'missing placeholder for param "user"' }] + +validateDictionary(appSchema, { hello_user: 'Hello ${user}!', about: 'Welcome, ${name}!' }); +// [{ path: ['about'], message: 'unexpected placeholder "name", not declared in schema params' }] +``` + +If your app uses a non-default `placeholder` style (`'single'` `{user}` / `'double'` `{{user}}`, see [`TranslateModule.forRoot`](https://www.npmjs.com/package/simply-translate-angular#initialize)), pass the same value so the checks recognize the right syntax: + +```typescript +validateDictionary(appSchema, parsedJson, { placeholder: 'single' }); +``` +### Per-proxy dictionary loading + +A `TranslateProxy` subclass can load its own per-language dictionary, without any `forChild()`/`NgModule` wrapper — each language may be a plain object, a `Promise`, an `Observable`, or a URL string fetched via `HttpClient`. Only the *active* language loads eagerly by default; anything else loads on demand the first time you switch to it, unless you ask for it upfront via `preloadLangs`/`preloadFallbackLang`, or on demand via `preloadLang()`. Configure it with the `@TranslateProxyLoader(config)` decorator: + +```typescript +import { Injectable } from '@angular/core'; +import { TranslateProxy, TranslateProxyLoader } from 'simply-translate-angular-proxy'; +import type { AppSchema } from './app.schema'; + +@Injectable({ providedIn: 'root' }) +@TranslateProxyLoader({ + id: 'app', + dictionaries: { + // dynamic import() — code-split into its own chunk; decorator arguments run when the class is defined, + // so the chunk starts loading as soon as this file is loaded, not when the proxy is first injected + 'en-US': import('./translations/en-US.json').then((m) => m.default), + // URL string — fetched via HttpClient the first time this language becomes active + 'ru-RU': '/assets/translations/ru-RU.json', + }, + preloadFallbackLang: true, // also load `service.fallbackLang` upfront, not just the active language +}) +export class AppTranslate extends TranslateProxy { + // optional — fires whenever a language finishes loading successfully + onLoaderReady({ lang, id }: { lang: string; id: string }): void { + console.log(`Loaded '${id}' (${lang})`); + } + + // optional — fires whenever a language fails to load; omit it and failures stay silent + onLoaderError({ lang, id, error }: { lang: string; id: string; error: unknown }): void { + console.error(`Failed to load '${id}' (${lang})`, error); + } +} +``` + +Beyond `preloadLangs`/`preloadFallbackLang`, call the proxy's own `preloadLang(lang)` whenever you want a language warmed up ad hoc (e.g. a language the user is likely to switch to next) — it's a no-op if the proxy has no dictionary entry for `lang`: + +```typescript +appTranslate.preloadLang('de-DE'); +``` + +**Caveat:** unlike `forChild()`'s `id`-based key prefixing, this does not namespace keys — every proxy's dictionary is merged flat into the same per-language dictionary. If more than one proxy loads its own dictionary, wrap each one's own schema in a top-level `Namespace({...})` (named after that feature) to avoid colliding with another proxy's keys. + +#### Sharing a dictionary between proxies (`extends`) + +`@TranslateProxyLoader`'s real value beyond being declarative is `extends` — sharing one proxy's dictionary with another, so common strings (`ok`, `no`, generic labels, ...) don't have to be redeclared and reloaded by every feature that needs them: + +```typescript +import { StringProp, TranslateSchema } from 'simply-translate-angular-proxy'; + +const commonSchema = TranslateSchema({ ok: StringProp(), no: StringProp() }); + +@Injectable({ providedIn: 'root' }) +@TranslateProxyLoader({ id: 'common', dictionaries: { 'en-US': { ok: 'Ok', no: 'No' } } }) +export class CommonTranslate extends TranslateProxy {} + +// spread the shared shape in — schemas are plain objects, so this is ordinary composition (see +// [Validating dictionaries with a schema](#validating-dictionaries-with-a-schema)), nothing `extends`-specific +const featureSchema = TranslateSchema({ ...commonSchema.shape, title: StringProp() }); + +@Injectable({ providedIn: 'root' }) +@TranslateProxyLoader({ + id: 'feature', + extends: [CommonTranslate], + dictionaries: { 'en-US': { title: 'Title' } }, +}) +export class FeatureTranslate extends TranslateProxy {} +``` + +Injecting `FeatureTranslate` alone is enough — `feature.object.ok` and `feature.object.title` both resolve, without ever injecting `CommonTranslate` anywhere. `extends` takes **class references**, and the decorator `inject`s each one, so it is constructed and loads its dictionary. + +Two things `extends` does *not* do: it doesn't derive `FeatureTranslate`'s schema type for you (spread the shape in by hand, as above — `extends` only affects runtime loading), and it doesn't forward `CommonTranslate`'s own `onLoaderReady`/`onLoaderError` to `FeatureTranslate`, `extends` never constructs a `CommonTranslate` instance of its own beyond what DI already gives you. + +#### Waiting for a dictionary in a route (`translateLoaderResolver`) + +Per-proxy loading is asynchronous, so a component may render before its proxy's dictionary for the current language has arrived. To hold the route until it has, add `translateLoaderResolver(id)` with the same `id` as the proxy's `@TranslateProxyLoader` config: + +```typescript +import { translateLoaderResolver } from 'simply-translate-angular-proxy'; + +const routes: Routes = [ + { path: 'feature', component: FeatureComponent, resolve: { translate: translateLoaderResolver('feature') } }, +]; +``` + +The resolver only waits for a load that has already started, so the proxy must have been constructed before navigation (e.g. `providedIn: 'root'` and injected by a parent component or service). If nothing has started loading, it resolves immediately. diff --git a/projects/proxy/ng-package.json b/projects/proxy/ng-package.json new file mode 100644 index 0000000..f95e61a --- /dev/null +++ b/projects/proxy/ng-package.json @@ -0,0 +1,12 @@ +{ + "$schema": "../../node_modules/ng-packagr/ng-package.schema.json", + "dest": "../../dist/proxy", + "lib": { + "entryFile": "src/public-api.ts" + }, + "allowedNonPeerDependencies": [ + "simply-translate", + "simply-translate-angular", + "rxjs" + ] +} \ No newline at end of file diff --git a/projects/proxy/package.json b/projects/proxy/package.json new file mode 100644 index 0000000..217b332 --- /dev/null +++ b/projects/proxy/package.json @@ -0,0 +1,37 @@ +{ + "name": "simply-translate-angular-proxy", + "version": "1.0.0", + "description": "Typed, schema-validated dictionary access for simply-translate-angular", + "peerDependencies": { + "@angular/common": ">=17.0.0", + "@angular/core": ">=17.0.0", + "@angular/compiler": ">=17.0.0", + "typescript": ">=5.0.0" + }, + "dependencies": { + "tslib": ">=2.3.0", + "simply-translate": "^1.0.0", + "simply-translate-angular": "^1.0.0", + "rxjs": ">=7.5.7" + }, + "sideEffects": false, + "repository": { + "type": "git", + "url": "git+https://github.com/oleg-wx/translate-angular.git", + "directory": "projects/proxy" + }, + "keywords": [ + "angular", + "translate", + "translation", + "i18n", + "typed", + "schema" + ], + "author": "Oleg Volovikov", + "license": "MIT", + "bugs": { + "url": "https://github.com/oleg-wx/translate-angular/issues" + }, + "homepage": "https://github.com/oleg-wx/translate-angular/tree/master/projects/proxy#readme" +} diff --git a/projects/proxy/src/__test__/core/tick.ts b/projects/proxy/src/__test__/core/tick.ts new file mode 100644 index 0000000..70ecd3e --- /dev/null +++ b/projects/proxy/src/__test__/core/tick.ts @@ -0,0 +1,7 @@ +export function tick(time: number): Promise { + return new Promise((res) => { + setTimeout(() => { + res(); + }, time); + }); +} diff --git a/projects/translate/src/__test__/loader.spec.ts b/projects/proxy/src/__test__/loader.spec.ts similarity index 96% rename from projects/translate/src/__test__/loader.spec.ts rename to projects/proxy/src/__test__/loader.spec.ts index 3361b50..b5d72ab 100644 --- a/projects/translate/src/__test__/loader.spec.ts +++ b/projects/proxy/src/__test__/loader.spec.ts @@ -2,11 +2,10 @@ import { HttpClient } from '@angular/common/http'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { Subject } from 'rxjs'; -import { TranslateLoaderCache, TranslateLoaderDictionaries, TranslateRootService } from '../public_api'; -import { TranslateModule } from '../simply-translate.module'; -import { TranslateService } from '../translate/translate.service'; +import { TranslateModule, TranslateRootService, TranslateService } from 'simply-translate-angular'; +import { TranslateLoaderCache } from '../lib/loader/translate.loader-cache'; import { tick } from './core/tick'; -import { TranslateLoader } from '../translate/proxy/loader/translate.loader'; +import { TranslateLoader, TranslateLoaderDictionaries } from '../lib/loader/translate.loader'; const lang = 'lang'; const newLang = 'new'; diff --git a/projects/translate/src/__test__/proxy-loader-decorator.spec.ts b/projects/proxy/src/__test__/proxy-loader-decorator.spec.ts similarity index 83% rename from projects/translate/src/__test__/proxy-loader-decorator.spec.ts rename to projects/proxy/src/__test__/proxy-loader-decorator.spec.ts index af2510a..348d1c9 100644 --- a/projects/translate/src/__test__/proxy-loader-decorator.spec.ts +++ b/projects/proxy/src/__test__/proxy-loader-decorator.spec.ts @@ -1,11 +1,10 @@ import { Injectable } from '@angular/core'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; -import { StringProp, TranslateSchema } from '../translate/proxy/schema'; -import { TranslateProxy } from '../translate/proxy/translate.proxy'; -import { TranslateProxyLoader } from '../translate/proxy/loader/translate-proxy-loader.decorator'; -import { TranslateModule } from '../simply-translate.module'; -import { TranslateRootService } from '../public_api'; +import { StringProp, TranslateSchema } from '../lib/schema'; +import { TranslateProxy } from '../lib/translate.proxy'; +import { TranslateProxyLoader } from '../lib/loader/translate-proxy-loader.decorator'; +import { TranslateModule, TranslateRootService } from 'simply-translate-angular'; const lang = 'lang'; diff --git a/projects/translate/src/__test__/proxy.spec.ts b/projects/proxy/src/__test__/proxy.spec.ts similarity index 97% rename from projects/translate/src/__test__/proxy.spec.ts rename to projects/proxy/src/__test__/proxy.spec.ts index 31dff22..cc33316 100644 --- a/projects/translate/src/__test__/proxy.spec.ts +++ b/projects/proxy/src/__test__/proxy.spec.ts @@ -1,10 +1,9 @@ import { Injectable, signal } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { BehaviorSubject } from 'rxjs'; -import { TranslateRootService } from '../public_api'; -import { TranslateModule } from '../simply-translate.module'; -import { Namespace, StringProp as Str, StringParam, TranslateSchema } from '../translate/proxy/schema'; -import { TranslateProxy } from '../translate/proxy/translate.proxy'; +import { TranslateModule, TranslateRootService } from 'simply-translate-angular'; +import { Namespace, StringProp as Str, StringParam, TranslateSchema } from '../lib/schema'; +import { TranslateProxy } from '../lib/translate.proxy'; const testSchema = TranslateSchema({ hello_user: Str({ params: { user: StringParam } }), diff --git a/projects/translate/src/__test__/schema.spec.ts b/projects/proxy/src/__test__/schema.spec.ts similarity index 89% rename from projects/translate/src/__test__/schema.spec.ts rename to projects/proxy/src/__test__/schema.spec.ts index 6ac9856..12eb273 100644 --- a/projects/translate/src/__test__/schema.spec.ts +++ b/projects/proxy/src/__test__/schema.spec.ts @@ -8,7 +8,7 @@ import { TranslateSchema, ValueProp, validateDictionary, -} from '../translate/proxy/schema'; +} from '../lib/schema'; const testSchema = TranslateSchema({ welcome_to_app: StringProp(), @@ -86,16 +86,16 @@ describe('schema', () => { it('does not report a missing key allowed via allowedErrors', () => { const { welcome_to_app, ...rest } = validDictionary; - expect(validateDictionary(testSchema, rest, { allowedErrors: { welcome_to_app: 'missing' } })).toEqual([]); + expect(validateDictionary(testSchema, rest, { knownIssues: { welcome_to_app: 'missing' } })).toEqual([]); }); it('does not report a missing key allowed via allowedErrors with a documented reason', () => { const { welcome_to_app, ...rest } = validDictionary; - expect(validateDictionary(testSchema, rest, { allowedErrors: { welcome_to_app: { kind: 'missing', reason: 'not translated yet' } } })).toEqual([]); + expect(validateDictionary(testSchema, rest, { knownIssues: { welcome_to_app: { kind: 'missing', reason: 'not translated yet' } } })).toEqual([]); }); it('does not report an orphan key allowed via allowedErrors', () => { - const errors = validateDictionary(testSchema, { ...validDictionary, only_root_key: 'Only in the Root' }, { allowedErrors: { only_root_key: 'orphan' } }); + const errors = validateDictionary(testSchema, { ...validDictionary, only_root_key: 'Only in the Root' }, { knownIssues: { only_root_key: 'orphan' } }); expect(errors).toEqual([]); }); @@ -104,7 +104,7 @@ describe('schema', () => { const errors = validateDictionary( testSchema, { ...rest, namespace: { value: namespace.value, hello_user: namespace.hello_user } }, - { allowedErrors: { user: 'missing' } }, + { knownIssues: { user: 'missing' } }, ); expect(errors).toEqual([{ path: ['namespace', 'user'], message: 'missing key' }]); }); @@ -114,24 +114,24 @@ describe('schema', () => { const errors = validateDictionary( testSchema, { ...rest, namespace: { value: namespace.value, hello_user: namespace.hello_user } }, - { allowedErrors: { 'namespace.user': 'missing' } }, + { knownIssues: { 'namespace.user': 'missing' } }, ); expect(errors).toEqual([]); }); it('does not allow a path whose error kind does not match the allowed kind', () => { const { welcome_to_app, ...rest } = validDictionary; - const errors = validateDictionary(testSchema, rest, { allowedErrors: { welcome_to_app: 'orphan' } }); + const errors = validateDictionary(testSchema, rest, { knownIssues: { welcome_to_app: 'orphan' } }); expect(errors).toEqual([{ path: ['welcome_to_app'], message: 'missing key' }]); }); it('"any" tolerates whichever check applies at that path', () => { const { welcome_to_app, ...rest } = validDictionary; - expect(validateDictionary(testSchema, rest, { allowedErrors: { welcome_to_app: 'any' } })).toEqual([]); + expect(validateDictionary(testSchema, rest, { knownIssues: { welcome_to_app: 'any' } })).toEqual([]); }); it('"params" blanket-allows every placeholder mismatch at that path', () => { - const errors = validateDictionary(testSchema, { ...validDictionary, hello_user: 'Hello there ${extra}' }, { allowedErrors: { hello_user: 'params' } }); + const errors = validateDictionary(testSchema, { ...validDictionary, hello_user: 'Hello there ${extra}' }, { knownIssues: { hello_user: 'params' } }); expect(errors).toEqual([]); }); @@ -208,24 +208,24 @@ describe('schema', () => { }); it('allows every error under a namespace via a "namespace.*" wildcard', () => { - const errors = validateDictionary(testSchema, { ...validDictionary, namespace: {} }, { allowedErrors: { 'namespace.*': 'missing' } }); + const errors = validateDictionary(testSchema, { ...validDictionary, namespace: {} }, { knownIssues: { 'namespace.*': 'missing' } }); expect(errors).toEqual([]); }); it('a namespace wildcard also covers the namespace key itself, not just its children', () => { const { namespace, ...rest } = validDictionary; - const errors = validateDictionary(testSchema, rest, { allowedErrors: { 'namespace.*': 'missing' } }); + const errors = validateDictionary(testSchema, rest, { knownIssues: { 'namespace.*': 'missing' } }); expect(errors).toEqual([]); }); it('a namespace wildcard does not leak outside that namespace', () => { const { namespace, welcome_to_app, ...rest } = validDictionary; - const errors = validateDictionary(testSchema, { ...rest, namespace: {} }, { allowedErrors: { 'namespace.*': 'missing' } }); + const errors = validateDictionary(testSchema, { ...rest, namespace: {} }, { knownIssues: { 'namespace.*': 'missing' } }); expect(errors).toEqual([{ path: ['welcome_to_app'], message: 'missing key' }]); }); it('a namespace wildcard still requires the matching kind', () => { - const errors = validateDictionary(testSchema, { ...validDictionary, namespace: {} }, { allowedErrors: { 'namespace.*': 'orphan' } }); + const errors = validateDictionary(testSchema, { ...validDictionary, namespace: {} }, { knownIssues: { 'namespace.*': 'orphan' } }); expect(errors).toEqual([ { path: ['namespace', 'value'], message: 'missing key' }, { path: ['namespace', 'hello_user'], message: 'missing key' }, diff --git a/projects/translate/src/translate/proxy/loader/translate-proxy-loader.decorator.ts b/projects/proxy/src/lib/loader/translate-proxy-loader.decorator.ts similarity index 100% rename from projects/translate/src/translate/proxy/loader/translate-proxy-loader.decorator.ts rename to projects/proxy/src/lib/loader/translate-proxy-loader.decorator.ts diff --git a/projects/translate/src/translate/proxy/loader/translate.loader-cache.ts b/projects/proxy/src/lib/loader/translate.loader-cache.ts similarity index 100% rename from projects/translate/src/translate/proxy/loader/translate.loader-cache.ts rename to projects/proxy/src/lib/loader/translate.loader-cache.ts diff --git a/projects/translate/src/translate/proxy/loader/translate.loader.resolver.ts b/projects/proxy/src/lib/loader/translate.loader.resolver.ts similarity index 89% rename from projects/translate/src/translate/proxy/loader/translate.loader.resolver.ts rename to projects/proxy/src/lib/loader/translate.loader.resolver.ts index dbc3903..0df69ae 100644 --- a/projects/translate/src/translate/proxy/loader/translate.loader.resolver.ts +++ b/projects/proxy/src/lib/loader/translate.loader.resolver.ts @@ -1,7 +1,7 @@ import { inject } from '@angular/core'; import { Dictionary } from 'simply-translate'; import { TranslateLoaderCache } from './translate.loader-cache'; -import { TranslateService } from '../../translate.service'; +import { TranslateService } from 'simply-translate-angular'; import { ResolveFn } from '@angular/router'; export const translateLoaderResolver: (id: string) => ResolveFn = (id: string) => { diff --git a/projects/translate/src/translate/proxy/loader/translate.loader.ts b/projects/proxy/src/lib/loader/translate.loader.ts similarity index 98% rename from projects/translate/src/translate/proxy/loader/translate.loader.ts rename to projects/proxy/src/lib/loader/translate.loader.ts index 3c662e3..020849b 100644 --- a/projects/translate/src/translate/proxy/loader/translate.loader.ts +++ b/projects/proxy/src/lib/loader/translate.loader.ts @@ -1,6 +1,6 @@ import { from, Observable, shareReplay, Subject, Subscription } from 'rxjs'; import { Dictionary } from 'simply-translate'; -import { TranslateService } from '../../translate.service'; +import { TranslateService } from 'simply-translate-angular'; import { TranslateLoaderCache } from './translate.loader-cache'; import { HttpClient } from '@angular/common/http'; diff --git a/projects/translate/src/translate/proxy/schema/index.ts b/projects/proxy/src/lib/schema/index.ts similarity index 100% rename from projects/translate/src/translate/proxy/schema/index.ts rename to projects/proxy/src/lib/schema/index.ts diff --git a/projects/translate/src/translate/proxy/schema/infer-schema-type.ts b/projects/proxy/src/lib/schema/infer-schema-type.ts similarity index 100% rename from projects/translate/src/translate/proxy/schema/infer-schema-type.ts rename to projects/proxy/src/lib/schema/infer-schema-type.ts diff --git a/projects/translate/src/translate/proxy/schema/schema-builders.ts b/projects/proxy/src/lib/schema/schema-builders.ts similarity index 100% rename from projects/translate/src/translate/proxy/schema/schema-builders.ts rename to projects/proxy/src/lib/schema/schema-builders.ts diff --git a/projects/translate/src/translate/proxy/schema/schema.types.ts b/projects/proxy/src/lib/schema/schema.types.ts similarity index 100% rename from projects/translate/src/translate/proxy/schema/schema.types.ts rename to projects/proxy/src/lib/schema/schema.types.ts diff --git a/projects/translate/src/translate/proxy/schema/validate-dictionary.ts b/projects/proxy/src/lib/schema/validate-dictionary.ts similarity index 97% rename from projects/translate/src/translate/proxy/schema/validate-dictionary.ts rename to projects/proxy/src/lib/schema/validate-dictionary.ts index 6f09bf4..fb18933 100644 --- a/projects/translate/src/translate/proxy/schema/validate-dictionary.ts +++ b/projects/proxy/src/lib/schema/validate-dictionary.ts @@ -19,7 +19,7 @@ export type SchemaAllowedKind = 'missing' | 'orphan' | 'params' | 'any'; export type SchemaAllowanceMap = Record; export interface ValidateDictionaryOptions { - allowedErrors?: SchemaAllowanceMap; + knownIssues?: SchemaAllowanceMap; /** Placeholder syntax the dictionaries use — must match the `placeholder` passed to `TranslateModule.forRoot`. */ placeholder?: PlaceholderType; } @@ -119,7 +119,7 @@ function validateShape( for (const key of Object.keys(shape)) { const childPath = [...path, key]; if (!(key in obj)) { - if (!isAllowed(options.allowedErrors, childPath, 'missing')) { + if (!isAllowed(options.knownIssues, childPath, 'missing')) { errors.push({ path: childPath, message: 'missing key' }); } continue; @@ -129,7 +129,7 @@ function validateShape( for (const key of Object.keys(obj)) { if (!(key in shape)) { const childPath = [...path, key]; - if (!isAllowed(options.allowedErrors, childPath, 'orphan')) { + if (!isAllowed(options.knownIssues, childPath, 'orphan')) { errors.push({ path: childPath, message: 'unexpected key not declared in schema' }); } } @@ -172,7 +172,7 @@ function validateNode( errors.push({ path, message: `expected string, got ${describe(value)}` }); return; } - checkParams(collectPlaceholders(value, pattern), node.paramNames, path, errors, options.allowedErrors); + checkParams(collectPlaceholders(value, pattern), node.paramNames, path, errors, options.knownIssues); return; case 'namespace': if (!isPlainObject(value)) { @@ -182,7 +182,7 @@ function validateNode( validateShape(node.shape, value, path, errors, options, pattern); return; case 'value': - validateDictionaryValue(value, node.paramNames, pattern, path, errors, options.allowedErrors); + validateDictionaryValue(value, node.paramNames, pattern, path, errors, options.knownIssues); return; } } diff --git a/projects/translate/src/translate/proxy/translate.proxy.ts b/projects/proxy/src/lib/translate.proxy.ts similarity index 98% rename from projects/translate/src/translate/proxy/translate.proxy.ts rename to projects/proxy/src/lib/translate.proxy.ts index 441d6cc..a64ad64 100644 --- a/projects/translate/src/translate/proxy/translate.proxy.ts +++ b/projects/proxy/src/lib/translate.proxy.ts @@ -2,7 +2,7 @@ import { inject, Injectable, OnDestroy, Signal } from '@angular/core'; import { Observable } from 'rxjs'; import { Dictionary, DictionaryEntry, TranslateDynamicProps } from 'simply-translate'; import type { BaseNode, NamespaceNode, SchemaShape, TranslateSchemaNode } from './schema/schema.types'; -import { TranslateService } from '../translate.service'; +import { TranslateService } from 'simply-translate-angular'; import { APPLY_LOADER, ApplyLoaderFn, TranslateLoader, TranslateLoaderDictionaries, TranslateLoaderSupport } from './loader/translate.loader'; import { TranslateLoaderCache } from './loader/translate.loader-cache'; import { HttpClient } from '@angular/common/http'; diff --git a/projects/proxy/src/public-api.ts b/projects/proxy/src/public-api.ts new file mode 100644 index 0000000..cfa49f4 --- /dev/null +++ b/projects/proxy/src/public-api.ts @@ -0,0 +1,10 @@ +/* + * Public API Surface of simply-translate-angular-proxy + */ + +export * from './lib/translate.proxy'; +export * from './lib/schema'; +export { TranslateLoaderSupport, TranslateLoaderDictionaries, TranslateLoaderDictionary } from './lib/loader/translate.loader'; +export { TranslateLoaderCache } from './lib/loader/translate.loader-cache'; +export { translateLoaderResolver } from './lib/loader/translate.loader.resolver'; +export { TranslateProxyLoader, TranslateProxyLoaderConfig } from './lib/loader/translate-proxy-loader.decorator'; diff --git a/projects/proxy/tsconfig.lib.json b/projects/proxy/tsconfig.lib.json new file mode 100644 index 0000000..543fd47 --- /dev/null +++ b/projects/proxy/tsconfig.lib.json @@ -0,0 +1,14 @@ +/* To learn more about this file see: https://angular.io/config/tsconfig. */ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "outDir": "../../out-tsc/lib", + "declaration": true, + "declarationMap": true, + "inlineSources": true, + "types": [] + }, + "exclude": [ + "**/*.spec.ts" + ] +} diff --git a/projects/proxy/tsconfig.lib.prod.json b/projects/proxy/tsconfig.lib.prod.json new file mode 100644 index 0000000..06de549 --- /dev/null +++ b/projects/proxy/tsconfig.lib.prod.json @@ -0,0 +1,10 @@ +/* To learn more about this file see: https://angular.io/config/tsconfig. */ +{ + "extends": "./tsconfig.lib.json", + "compilerOptions": { + "declarationMap": false + }, + "angularCompilerOptions": { + "compilationMode": "partial" + } +} diff --git a/projects/proxy/tsconfig.spec.json b/projects/proxy/tsconfig.spec.json new file mode 100644 index 0000000..ce7048b --- /dev/null +++ b/projects/proxy/tsconfig.spec.json @@ -0,0 +1,14 @@ +/* To learn more about this file see: https://angular.io/config/tsconfig. */ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "outDir": "../../out-tsc/spec", + "types": [ + "jasmine" + ] + }, + "include": [ + "**/*.spec.ts", + "**/*.d.ts" + ] +} diff --git a/projects/translate/CHANGELOG.md b/projects/translate/CHANGELOG.md new file mode 100644 index 0000000..3d51c41 --- /dev/null +++ b/projects/translate/CHANGELOG.md @@ -0,0 +1,82 @@ +# Changelog + +All notable changes to `simply-translate-angular` are listed here. + +## 1.0.0 (unreleased) + +### Upgrading from 0.21.x + +1. If you use `TranslateProxy`, `TranslateSchema`, the schema builders, `validateDictionary`/`assertValidDictionary` or `@TranslateProxyLoader`, install [`simply-translate-angular-proxy`](https://www.npmjs.com/package/simply-translate-angular-proxy) and import them from there instead of `simply-translate-angular`. +2. Apply the [simply-translate 1.0.0 upgrade steps](https://github.com/oleg-wx/translate/blob/master/CHANGELOG.md): `defaultLang` → `lang`, `$less: true` → `placeholder: 'single'`, and no deep imports such as `simply-translate/es/...`. + +### Breaking + +- `TranslateProxy`, the schema API (`TranslateSchema`, `StringProp`, `ValueProp`, `Namespace`, param markers, `InferTranslateSchemaType`), dictionary validation, the per-proxy loader and `translateLoaderResolver` moved to the separate [`simply-translate-angular-proxy`](https://www.npmjs.com/package/simply-translate-angular-proxy) package. +- Requires `simply-translate` 1.0.0. + +### Fixed + +- The library no longer deep-imports `simply-translate` internals, which the `exports` map of `simply-translate` 1.0.0 blocks. + +## 0.21.20 + +### Changed + +- Per-proxy loading is configured with the `@TranslateProxyLoader` decorator instead of implementing the `TranslateLoaderSupport` interface by hand. +- `TranslateProxyLoader` gained `preloadLangs` and `preloadFallbackLang`. + +### Added + +- `onLoaderReady?(args: { lang, id })` alongside `onLoaderError?()`. It fires whenever a language finishes loading. +- `StringNullableParam` and `NumberNullableParam` param markers, which infer `string | null` and `number | null`. +- `translateLoaderResolver(id)` route resolver that waits for a proxy's dictionary for the current language. + +## 0.21.10 + +### Breaking + +- `TranslateProxy` takes a schema type (`typeof yourSchema`) instead of a hand-written `Dictionary` interface. + +### Added + +- Schema-first dictionary definitions (`TranslateSchema`, `StringProp`, `ValueProp`, `Namespace`). +- Runtime validation (`validateDictionary`, `assertValidDictionary`), including placeholder checks against each leaf's declared `params`. + +## 0.21.0 + +### Breaking + +- Requires Angular 17. +- The directive always reacts to language and dictionary changes; the `detect` opt-in property is removed. + +### Added + +- `TranslateProxy` for typed, autocompleted dictionary access. +- The directive infers its key from static inner text when `translate` has no value. +- `translateSignal` and `translateObservable` on `TranslateService`. + +### Fixed + +- The directive updates the existing text node instead of writing to a new one, which broke content bound elsewhere in the same element (for example Angular interpolation). + +## 0.20.0 + +See also the [simply-translate 0.20.0 changes](https://github.com/oleg-wx/translate/blob/master/CHANGELOG.md#0200). + +### Added + +- [Middleware pipeline](README.md#pipeline). +- `fallback` property on the directive. +- Directives and pipes detect language changes. + +### Deprecated + +- The `init` method in the root import. Use `addMiddleware`, `loadDictionaries` and `final` instead. + +### Breaking + +- `lang` and `fallbackLang` moved to the root import, and after initialization they can be changed only through `TranslateRootService`. +- `defaultLang` renamed to `lang`. +- Removed `$less`. Use `placeholder: 'single'`. +- `extend` in `forChild` renamed to `loadDictionaries`. +- Removed the dynamic cache. diff --git a/projects/translate/README.md b/projects/translate/README.md new file mode 100644 index 0000000..9a9d39d --- /dev/null +++ b/projects/translate/README.md @@ -0,0 +1,287 @@ +# Simply Translate for Angular + +[Simplest translations](https://www.npmjs.com/package/simply-translate) for Angular 17+. + +Upgrading or looking for what changed? See the [changelog](CHANGELOG.md). Version 1.0.0 moved `TranslateProxy` and the schema API to [simply-translate-angular-proxy](https://www.npmjs.com/package/simply-translate-angular-proxy). + +### Basics + +Please use the [simply-translate](https://www.npmjs.com/package/simply-translate) docs to learn more about **basic interaction**, dictionaries, pluralization, cases, etc. + +### Install + +```javascript +npm i simply-translate-angular +``` + +### Import + +```javascript +import { TranslateModule, TranslateService } from 'simply-translate-angular'; +``` + +### Initialize + +```javascript +@NgModule({ + declarations: [AppComponent, AppViewComponent], + imports: [ + TranslateModule.forRoot({ + // dependencies + deps: [ HttpClient ], + // language + lang: window.navigator.language, + fallbackLang: 'ru-RU', + // static dictionaries + dictionaries:{'ru-RU':{...}}, + // load dictionaries + loadDictionaries:({lang, fallbackLang}, client /* params are injected dependencies received in the same order as they are in deps */) =>{ + return of({ + [lang]: {...} + }); + } + }) + ] +}); +``` + +See [Load dictionaries](#load-dictionaries) + +### Use Directive + +```html + +

+ +

+ +

Hello user

+ +

Hello ${user}

+ +

+``` + +Directives always react to language and dictionary changes automatically, no opt-in needed. + +Directive can also use inner text as an implicit key (when `translate` has no value) or as a fallback (when the key is missing) — but only for **static** content; dynamic keys must be bound with `[translate]="expr"`. + +### Use Pipe + +```html +

{{ 'hello_user' | translate: { user: 'Oleg' } }}

+ +

{{ 'hello_user' | translateTo: 'ru-RU': { user: 'Oleg' } }}

+ +

{{ 'hello_user_not_there' | translate: { user: 'Oleg' } : 'Hello ${user}'}}

+``` + +Pipes are pure by default. However, if the application changes language at runtime you may use the special _impure_ pipe (it has internal dirty check), it will detect language changes as well as pipe parameters. + +```html +

{{ 'hello_user' | translate$: { user: 'Oleg' } }}

+``` + +`translate$` is cheap despite being impure: it caches the last language/dictionary version and arguments, and only re-translates when one of them actually changed — not on every check. + +### Use Service + +```javascript +@Component({ + ... +}) +export class Component { + hello: string; + constructor(private translate: TranslateService) { + // use default language + this.hello = translate.translate('hello_user', { user: 'Oleg' }) + // use other language + this.hello = translate.translateTo('ru-RU','hello_user', { user: 'Oleg' }) + // use fallback + this.hello = translate.translateTo('ru-RU','hello_user_not_there', { user: 'Oleg' }, 'Hello ${user}') + } +} +``` + +`translateSignal` and `translateObservable` mirror `translate`'s overloads but return a reactive `Signal` / `Observable` that updates on language or dictionary changes. + +```javascript +helloSignal = translate.translateSignal('hello_user', { user: 'Oleg' }); // Signal +hello$ = translate.translateObservable('hello_user', { user: 'Oleg' }); // Observable +``` + +To change language, use `TranslateRootService` `lang` property. +To detect changes, subscribe to `languageChange$` and `dictionaryChange$`. **Note** that `loadDictionaries` method in root settings will not execute when language changes. + +```javascript +export class Component { + constructor(private rootTranslate: TranslateRootService){ + rootTranslate.lang = "en-US"; + } +} +``` + +### Load dictionaries + +#### Root + +Default `forRoot` initialization can use injected dependencies (e.g. `HttpClient`) to fetch dictionaries. `loadDictionaries` returns an `Observable` of a set of dictionaries + +```javascript +export function getDictionary(lang: string, client: HttpClient) { + return client.get(`/assets/translations/${lang}.json`); +} + +@NgModule({ + declarations: [...], + imports: [ + ... + TranslateModule.forRoot({ + // dependencies + deps: [ HttpClient ], + + lang: window.navigator.language, + fallbackLang: 'ru-RU', + + loadDictionaries: ({lang, fallbackLang}, client /* params are injected dependencies received in the same order as they are in deps */) => { + + const res$ = forkJoin([getDictionary(lang, client), getDictionary(fallbackLang, client)]).pipe( + map((res) => { + return { [lang]: res[0], [fallbackLang]: res[1] }; + }) + ); + + return res$; + }, + }), + ... + ], + ... +}) +``` + +**Note**: it might be useful to **hardcode** _fallback dictionary_ in .ts or .json file then import it rather than use http client to download. + +```javascript +import fallback from './translations/fallback'; + +TranslateModule.forRoot({ + lang: window.navigator.language, + fallbackLang: env.fallbackLanguage, + dictionaries: { + [env.fallbackLanguage]: fallback, + }, + + deps: [ HttpClient ], + loadDictionaries: ({lang, fallbackLang}, client /* params are injected dependencies received in the same order as they are in deps */) => { + return getDictionary(lang, client).pipe( + map((res) => { + return { [lang]: res }; + }) + ); + }, +}), +``` + +**Note**: For more complex scenarios you may use initialization functions with `APP_INITIALIZER` token. + +#### Lazy + +Loading dictionaries for **Lazy** modules is a bit trickier. + +```javascript +export function getDictionary(lang: string, client: HttpClient) { + return client.get(`/assets/translations/${lang}.dynamic.json`); +} + +@NgModule({ + declarations: [...], + imports: [ + TranslateModule.forChild({ + deps: [ HttpClient ], + loadDictionaries: ({ lang, fallbackLang }, client: HttpClient) => { + return forkJoin([getDictionary(lang, client), getDictionary(fallbackLang, client)]).pipe( + map((res) => { + return { [lang]: res[0], [fallbackLang]: res[1] }; + }) + ); + }, + }), + ... + ] +}) +export class DynamicModule {} +``` + +Then you **must** add the `TranslateResolve` resolver to every lazy route to wait for child `loadDictionaries`. + +```javascript +const routes: Routes = [{ path: '', component: DynamicComponent, resolve: { translate: TranslateResolve } }]; + +@NgModule({ + imports: [RouterModule.forChild(routes)], + exports: [RouterModule], +}) +export class DynamicRoutingModule {} +``` + +**Deprecated: Under consideration of removing**: For rare cases you may use `id` parameter for Lazy loaded module, that allows having different values with same key. +"Lazy" values will be available only for lazy modules with that special `id`. + +```javascript +@NgModule({ + declarations: [...], + imports: [ + TranslateModule.forRoot({ + dictionaries: {'en-US':{ + 'key':'Value' + }} + }) + ] +}) +``` + +```javascript +@NgModule({ + declarations: [...], + imports: [ + TranslateModule.forChild({ + id: 'lazy', + dictionaries: {'en-US':{ + 'key':'Value for Lazy' + }} + }) + ] +}) +``` + +### Pipeline + +**(experimental)** +Currently it is possible to **append** middleware to the end of translation pipeline. +It might be specially useful to add **logger** or rarely fine-tune translation result. + +```javascript +@NgModule({ + declarations: [...], + imports: [ + ... + TranslateModule.forRoot({ + // dependencies + deps: [ Logger ], + addMiddleware: (logger /* injected dependencies */) => { + return [ + ({params, result}, next) => { + if (result.fallingBack) { + logger.log(`Translation absent [${params.lang}:${params.key}]`); + } + next(); + }, + ]; + }, + }), + ... + ], + ... +}) +``` diff --git a/projects/translate/package.json b/projects/translate/package.json index ffa4b57..88bfbc7 100644 --- a/projects/translate/package.json +++ b/projects/translate/package.json @@ -1,10 +1,11 @@ { "name": "simply-translate-angular", - "version": "0.21.20", + "version": "1.0.0", + "description": "Angular bindings for simply-translate: module, directive, pipes and service", "type": "module", "dependencies": { "tslib": "^2.4.0", - "simply-translate": "0.20.0", + "simply-translate": "^1.0.0", "rxjs": "^7.5.7" }, "peerDependencies": { @@ -20,7 +21,8 @@ }, "repository": { "type": "git", - "url": "git+https://github.com/oleg-wx/translate-angular.git" + "url": "git+https://github.com/oleg-wx/translate-angular.git", + "directory": "projects/translate" }, "keywords": [ "angular", @@ -35,5 +37,5 @@ "bugs": { "url": "https://github.com/oleg-wx/translate-angular/issues" }, - "homepage": "https://github.com/oleg-wx/translate-angular#readme" + "homepage": "https://github.com/oleg-wx/translate-angular/tree/master/projects/translate#readme" } diff --git a/projects/translate/src/public_api.ts b/projects/translate/src/public_api.ts index b743cbe..f457bd2 100644 --- a/projects/translate/src/public_api.ts +++ b/projects/translate/src/public_api.ts @@ -2,12 +2,6 @@ export * from './translate/translate.directive'; export * from './translate/translate.pipe'; export * from './translate/translate.resolver'; export * from './translate/translate.service'; -export * from './translate/proxy/translate.proxy'; -export * from './translate/proxy/schema'; -export { TranslateLoaderSupport, TranslateLoaderDictionaries, TranslateLoaderDictionary } from './translate/proxy/loader/translate.loader'; -export { TranslateLoaderCache } from './translate/proxy/loader/translate.loader-cache'; -export { translateLoaderResolver } from './translate/proxy/loader/translate.loader.resolver'; -export { TranslateProxyLoader, TranslateProxyLoaderConfig } from './translate/proxy/loader/translate-proxy-loader.decorator'; export * from './simply-translate.module'; export { TranslateChildConfig } from './translate/translate.service'; export { diff --git a/projects/translate/src/simply-translate.module.ts b/projects/translate/src/simply-translate.module.ts index 5564176..623d5b2 100644 --- a/projects/translate/src/simply-translate.module.ts +++ b/projects/translate/src/simply-translate.module.ts @@ -14,7 +14,6 @@ import { import { TranslatePipe, TranslateToPipe, TranslatePipeDetect } from './translate/translate.pipe'; import { TranslateDirective } from './translate/translate.directive'; import { TranslateResolve } from './translate/translate.resolver'; -import { TranslateLoaderCache } from './translate/proxy/loader/translate.loader-cache'; export type AddMiddlewareFunc = (...any: any[]) => Array; export type LoadDictionariesFunc = ( @@ -147,7 +146,6 @@ export class TranslateModule { TranslateRootService, TranslateService, TranslateResolve, - TranslateLoaderCache, { provide: TRANSLATE_CHILD, useValue: {}, diff --git a/projects/translate/src/translate/translate.service.ts b/projects/translate/src/translate/translate.service.ts index 62d8b00..05b3f8e 100644 --- a/projects/translate/src/translate/translate.service.ts +++ b/projects/translate/src/translate/translate.service.ts @@ -9,8 +9,8 @@ import { TranslateKey, Dictionaries, DictionaryEntry, + FallbackWithDifferentLanguageMiddleware, } from 'simply-translate'; -import { FallbackWithDifferentLanguageMiddleware } from 'simply-translate/es/core/middleware/fallback-with-different-language-middleware'; export interface DefaultTranslateConfig { lang?: string; diff --git a/src/app/app.module.ts b/src/app/app.module.ts index a2f45e6..1770df7 100644 --- a/src/app/app.module.ts +++ b/src/app/app.module.ts @@ -13,6 +13,7 @@ import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { forkJoin } from 'rxjs'; import { ComponentsModule } from './components/components.module'; import { TryProxyComponent } from './try-proxy/try-proxy.component'; +import { TranslateProxyMore, TranslateProxyOneMore } from './try-proxy/translate.proxy'; function getDictionary(lang: string, client: HttpClient) { return client.get(`/assets/translations/${lang}.json`); @@ -53,7 +54,7 @@ function getDictionary(lang: string, client: HttpClient) { AppRoutingModule, MoreModule, ], - providers: [], + providers: [TranslateProxyMore, TranslateProxyOneMore], exports: [], bootstrap: [AppComponent], }) diff --git a/src/app/try-proxy/schema.ts b/src/app/try-proxy/schema.ts index 1461194..ef2c7f8 100644 --- a/src/app/try-proxy/schema.ts +++ b/src/app/try-proxy/schema.ts @@ -1,4 +1,4 @@ -import { Namespace, NumberParam, NumberNullableParam, StringProp, StringParam, TranslateSchema, ValueProp } from 'projects/translate/src/public_api'; +import { Namespace, NumberParam, NumberNullableParam, StringProp, StringParam, TranslateSchema, ValueProp } from 'simply-translate-angular-proxy'; export const commonDictionary = TranslateSchema({ proxy: Namespace({ @@ -35,3 +35,13 @@ export const moreDictionary = TranslateSchema({ }); export type MoreDictionary = typeof moreDictionary; + +export const oneMoreDictionary = TranslateSchema({ + proxy: Namespace({ + one_more: Namespace({ + one_more_translate: StringProp(), + }), + }), +}); + +export type OneMoreDictionary = typeof oneMoreDictionary; diff --git a/src/app/try-proxy/translate.proxy.ts b/src/app/try-proxy/translate.proxy.ts index cf400c0..47802c6 100644 --- a/src/app/try-proxy/translate.proxy.ts +++ b/src/app/try-proxy/translate.proxy.ts @@ -1,7 +1,7 @@ import { Injectable } from '@angular/core'; -import type { CommonDictionary, MoreDictionary } from 'src/app/try-proxy/schema'; import { Dictionary } from 'simply-translate'; -import { TranslateProxy, TranslateProxyLoader } from 'projects/translate/src/public_api'; +import { TranslateProxy, TranslateProxyLoader } from 'simply-translate-angular-proxy'; +import type { CommonDictionary, MoreDictionary, OneMoreDictionary } from 'src/app/try-proxy/schema'; @Injectable({ providedIn: 'root' }) @TranslateProxyLoader({ @@ -19,7 +19,7 @@ export class TranslateProxyCommon extends TranslateProxy { } } -@Injectable({ providedIn: 'root' }) +@Injectable() @TranslateProxyLoader({ id: 'more', extends: [TranslateProxyCommon], @@ -34,3 +34,19 @@ export class TranslateProxyMore extends TranslateProxy { + onLoaderError(args: { lang: string; id: string; error: any }): void { + console.error(`Error loading one more translations for lang=${args.lang}, id=${args.id}`, args.error); + } +} diff --git a/src/app/try-proxy/try-proxy.component.ts b/src/app/try-proxy/try-proxy.component.ts index f99d4bf..945d4a1 100644 --- a/src/app/try-proxy/try-proxy.component.ts +++ b/src/app/try-proxy/try-proxy.component.ts @@ -1,6 +1,6 @@ import { Component, computed, signal } from '@angular/core'; import { TranslateRootService } from 'src/_translate.imports'; -import { TranslateProxyCommon, TranslateProxyMore } from './translate.proxy'; +import { TranslateProxyCommon, TranslateProxyMore, TranslateProxyOneMore } from './translate.proxy'; @Component({ selector: 'app-try-proxy', @@ -31,6 +31,7 @@ import { TranslateProxyCommon, TranslateProxyMore } from './translate.proxy';
More Proxy
{{ t9nProxy.more.more_translate.Signal()() }}
+
{{ t9nOneMoreProxy.one_more.one_more_translate.Signal()() }}
`, }) export class TryProxyComponent { @@ -38,12 +39,14 @@ export class TryProxyComponent { selectedLang = this.root.lang; dynamicKey = 'hello_world'; protected t9nProxy = this.translateMore.object.proxy; + protected t9nOneMoreProxy = this.translateOneMore.object.proxy; countDaysValue = signal(undefined as unknown as number); countDays = this.t9nProxy.day_since_new_year.Signal(computed(() => ({ days: this.countDaysValue() }))); constructor( private root: TranslateRootService, private translateMore: TranslateProxyMore, + private translateOneMore: TranslateProxyOneMore, ) { setInterval(() => { this.countDaysValue.set(this.countDaysValue() + 1); diff --git a/src/assets/translations/proxy/one-more/en-US.json b/src/assets/translations/proxy/one-more/en-US.json new file mode 100644 index 0000000..e2570e0 --- /dev/null +++ b/src/assets/translations/proxy/one-more/en-US.json @@ -0,0 +1,5 @@ +{ + "proxy": { + "one_more": { "one_more_translate": "One More Translate" } + } +} diff --git a/src/assets/translations/proxy/one-more/ru-RU.json b/src/assets/translations/proxy/one-more/ru-RU.json new file mode 100644 index 0000000..ff6c9ad --- /dev/null +++ b/src/assets/translations/proxy/one-more/ru-RU.json @@ -0,0 +1,3 @@ +{ + "more": { "more_translate": "Больше перевести" } +} diff --git a/tsconfig.json b/tsconfig.json index da5111c..89038ea 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -14,17 +14,18 @@ "types": ["node", "jasmine"], "lib": ["es2022", "dom"], // Upgraded to match target ES2022 "paths": { + "simply-translate-angular-proxy": [ + "./dist/proxy" + ], "simply-translate-angular": ["dist/translate"] }, "useDefineForClassFields": false, "resolveJsonModule": true, "esModuleInterop": true }, - // 2. MANDATORY ADDITION: Tell TypeScript which files must consume these types "include": [ "src/**/*.ts", - "src/**/*.spec.ts", - "projects/translate/src/translate/proxy/translate.proxy.ts" + "src/**/*.spec.ts" ], "angularCompilerOptions": { "enableI18nLegacyMessageIdFormat": false, From ead3d701319c7816abd2b69b7145faac8f3e2aa4 Mon Sep 17 00:00:00 2001 From: Oleg Date: Mon, 19 Oct 2026 16:08:18 +0300 Subject: [PATCH 16/18] Add standalone provideTranslate() API and migrate demo to standalone - Add provideTranslate() with withConfig/withDictionaries/withLoader/ withMiddleware/withOnReady features, provideTranslateChild(), withTranslateChild() and translateChildResolver; pipes and directive are standalone and exported as TRANSLATE_IMPORTS - Deprecate TranslateModule.forRoot()/forChild(); both now delegate to the new providers - Loaders may return an Observable, Promise or plain object; only the first result is used and an empty loader contributes {} instead of failing startup or navigation - Child scopes load dictionaries per language, reload when the language changes and retry a failed load on the next navigation - Root guard is dev-only and not applied to forRoot(), so importing forRoot() in a lazy module keeps working - Fix forChild({ extend }) receiving { lang, fallbackLang } instead of the TranslateService - Fix scoped TranslateService throwing when no dictionary exists for the current language - Keep TranslateChildConfig.loadDictionaries' 0.21 public signature --- README.md | 6 +- package.json | 3 +- projects/translate/CHANGELOG.md | 19 ++ projects/translate/README.md | 289 +++++++++--------- .../__test__/provide-translate-child.spec.ts | 175 +++++++++++ .../src/__test__/provide-translate.spec.ts | 190 ++++++++++++ .../src/providers/translate.features.ts | 73 +++++ .../src/providers/translate.initializer.ts | 44 +++ .../src/providers/translate.providers.ts | 163 ++++++++++ projects/translate/src/public_api.ts | 4 + .../translate/src/simply-translate.module.ts | 131 ++++---- .../src/translate/translate.directive.ts | 1 + .../translate/src/translate/translate.pipe.ts | 6 +- .../src/translate/translate.resolver.ts | 85 ++++-- .../src/translate/translate.service.ts | 12 +- .../src/translate/translate.utils.ts | 31 ++ projects/translate/tsconfig.lib.json | 2 +- src/_translate.imports.ts | 9 +- src/app/another-dynamic/dynamic.component.ts | 4 + src/app/another-dynamic/dynamic.module.ts | 34 --- src/app/another-dynamic/dynamic.routes.ts | 30 ++ src/app/another-dynamic/dynamic.routing.ts | 17 -- .../other-dynamic.component.ts | 3 + src/app/app.component.ts | 7 +- src/app/app.config.ts | 44 +++ src/app/app.module.ts | 73 ----- src/app/app.routes.ts | 18 ++ src/app/app.routing.ts | 22 -- src/app/app.spec.ts | 102 +++++++ src/app/components/components.module.ts | 15 - src/app/components/translate-to.component.ts | 6 +- src/app/components/try-date.component.ts | 6 +- src/app/components/visits/visits.component.ts | 4 + src/app/dynamic/dynamic.component.ts | 4 + src/app/dynamic/dynamic.module.ts | 44 --- src/app/dynamic/dynamic.routes.ts | 36 +++ src/app/dynamic/dynamic.routing.ts | 17 -- src/app/dynamic/other-dynamic.component.ts | 3 + src/app/more/more.module.ts | 37 --- src/app/more/more.routing.ts | 15 - src/app/more/title.directive.ts | 1 + src/app/switch-lang/switch-lang.component.ts | 6 +- src/app/translate.component.ts | 11 +- .../try-directive/try-directive.component.ts | 6 +- src/app/try-proxy/try-proxy.component.ts | 8 +- src/main.ts | 8 +- tsconfig.json | 24 +- 47 files changed, 1305 insertions(+), 543 deletions(-) create mode 100644 projects/translate/src/__test__/provide-translate-child.spec.ts create mode 100644 projects/translate/src/__test__/provide-translate.spec.ts create mode 100644 projects/translate/src/providers/translate.features.ts create mode 100644 projects/translate/src/providers/translate.initializer.ts create mode 100644 projects/translate/src/providers/translate.providers.ts create mode 100644 projects/translate/src/translate/translate.utils.ts delete mode 100644 src/app/another-dynamic/dynamic.module.ts create mode 100644 src/app/another-dynamic/dynamic.routes.ts delete mode 100644 src/app/another-dynamic/dynamic.routing.ts create mode 100644 src/app/app.config.ts delete mode 100644 src/app/app.module.ts create mode 100644 src/app/app.routes.ts delete mode 100644 src/app/app.routing.ts create mode 100644 src/app/app.spec.ts delete mode 100644 src/app/components/components.module.ts delete mode 100644 src/app/dynamic/dynamic.module.ts create mode 100644 src/app/dynamic/dynamic.routes.ts delete mode 100644 src/app/dynamic/dynamic.routing.ts delete mode 100644 src/app/more/more.module.ts delete mode 100644 src/app/more/more.routing.ts diff --git a/README.md b/README.md index 36c27b3..7e88d94 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ Monorepo for [simply-translate](https://www.npmjs.com/package/simply-translate) ### [simply-translate-angular](projects/translate/README.md) -The core translation library — `TranslateModule`, directive, pipes, `TranslateService`, and dictionary loading (root/lazy). See [projects/translate/README.md](projects/translate/README.md) for setup and usage, and its [changelog](projects/translate/CHANGELOG.md). +The core translation library — `provideTranslate()`, standalone directive and pipes, `TranslateService`, and dictionary loading (root/lazy). See [projects/translate/README.md](projects/translate/README.md) for setup and usage, and its [changelog](projects/translate/CHANGELOG.md). ### [simply-translate-angular-proxy](projects/proxy/README.md) @@ -16,12 +16,12 @@ Optional add-on built on top of `simply-translate-angular` — `TranslateProxy` ```bash npm ci -npm test # tests both libraries once in headless Chrome +npm test # both libraries and the demo app, once in headless Chrome npm run build:prod # builds dist/translate and dist/proxy npm run start:demo # demo app on http://localhost:4800 (run build:prod first) ``` -The proxy library and the demo app import `simply-translate-angular` from `dist/translate`, so build the translate library before working on them. +The proxy library imports `simply-translate-angular` from `dist/translate`, and the demo app imports `simply-translate-angular-proxy` from `dist/proxy`, so build those before working on them — `npm test` does it in order. ## Releasing diff --git a/package.json b/package.json index 3ca1b42..2b1299b 100644 --- a/package.json +++ b/package.json @@ -14,9 +14,10 @@ "build:demo:prod": "node --max-old-space-size=8192 ./node_modules/@angular/cli/bin/ng build --configuration production --aot", "start:demo": "ng serve --port 4800 --live-reload false", "restart:all": "npm run build:prod && npm run start:demo", - "test": "npm run test:translate && npm run build:translate && npm run test:proxy", + "test": "npm run test:translate && npm run build:translate && npm run test:proxy && npm run build:proxy && npm run test:demo", "test:translate": "ng test translate --watch=false --browsers=ChromeHeadless", "test:proxy": "ng test proxy --watch=false --browsers=ChromeHeadless", + "test:demo": "ng test simply-translate --watch=false --browsers=ChromeHeadless", "test:watch": "ng test translate", "e2e": "ng e2e" }, diff --git a/projects/translate/CHANGELOG.md b/projects/translate/CHANGELOG.md index 3d51c41..61aa166 100644 --- a/projects/translate/CHANGELOG.md +++ b/projects/translate/CHANGELOG.md @@ -9,6 +9,23 @@ All notable changes to `simply-translate-angular` are listed here. 1. If you use `TranslateProxy`, `TranslateSchema`, the schema builders, `validateDictionary`/`assertValidDictionary` or `@TranslateProxyLoader`, install [`simply-translate-angular-proxy`](https://www.npmjs.com/package/simply-translate-angular-proxy) and import them from there instead of `simply-translate-angular`. 2. Apply the [simply-translate 1.0.0 upgrade steps](https://github.com/oleg-wx/translate/blob/master/CHANGELOG.md): `defaultLang` → `lang`, `$less: true` → `placeholder: 'single'`, and no deep imports such as `simply-translate/es/...`. +### Added + +- Standalone, functional setup. `provideTranslate(config?, ...features)` replaces `TranslateModule.forRoot()`, and `provideTranslateChild()` in `Route.providers` replaces `TranslateModule.forChild()`. +- Features: `withConfig()`, `withDictionaries()`, `withLoader()`, `withMiddleware()` and `withOnReady()`. `withLoader()` may be used more than once; the loaders run in parallel and their dictionaries are merged. +- `translateChildResolver`, a functional route resolver replacing the `TranslateResolve` class, and `withTranslateChild()` which returns the scope providers and that resolver together, ready to spread into a route. +- `TRANSLATE_IMPORTS` for standalone components. The pipes and the `translate` directive are now standalone and can also be imported individually. +- Loaders may return a `Promise` or a plain `Dictionaries` object, not only an `Observable`. +- `provideTranslate()` throws when used twice, and `provideTranslateChild()` throws when there is no root. Both checks are dev-mode only, and `TranslateModule.forRoot()` is not checked, so importing it in a lazily loaded module still works. + +### Changed + +- Every configuration callback runs inside an injection context, so dependencies are taken with `inject()`. The `deps: [...]` array is deprecated. +- `TranslateModule.forRoot()` / `.forChild()` are deprecated and now delegate to the new providers. Existing NgModule applications keep working unchanged. +- Only a loader's first result is used, and a loader that completes without emitting contributes no dictionaries instead of failing startup or navigation. +- A child scope loads its dictionaries again for each newly selected language, and retries a load that failed on the next navigation. +- `TranslateChildConfig.deps` is no longer read; `TranslateModule.forChild({ deps })` still resolves them. + ### Breaking - `TranslateProxy`, the schema API (`TranslateSchema`, `StringProp`, `ValueProp`, `Namespace`, param markers, `InferTranslateSchemaType`), dictionary validation, the per-proxy loader and `translateLoaderResolver` moved to the separate [`simply-translate-angular-proxy`](https://www.npmjs.com/package/simply-translate-angular-proxy) package. @@ -17,6 +34,8 @@ All notable changes to `simply-translate-angular` are listed here. ### Fixed - The library no longer deep-imports `simply-translate` internals, which the `exports` map of `simply-translate` 1.0.0 blocks. +- `TranslateModule.forChild({ extend })` passed `{ lang, fallbackLang }` to `extend` instead of the `TranslateService`. +- A scoped `TranslateService` threw when translating with no language set or with a language that has no dictionary. ## 0.21.20 diff --git a/projects/translate/README.md b/projects/translate/README.md index 9a9d39d..610e7b8 100644 --- a/projects/translate/README.md +++ b/projects/translate/README.md @@ -17,34 +17,48 @@ npm i simply-translate-angular ### Import ```javascript -import { TranslateModule, TranslateService } from 'simply-translate-angular'; +import { provideTranslate, TranslateService, TRANSLATE_IMPORTS } from 'simply-translate-angular'; ``` ### Initialize +`provideTranslate()` goes into the application providers. Everything optional is passed as a *feature* (`withLoader`, `withMiddleware`, …), and every feature callback runs inside an injection context, so dependencies are taken with `inject()`. + ```javascript -@NgModule({ - declarations: [AppComponent, AppViewComponent], - imports: [ - TranslateModule.forRoot({ - // dependencies - deps: [ HttpClient ], - // language - lang: window.navigator.language, - fallbackLang: 'ru-RU', - // static dictionaries - dictionaries:{'ru-RU':{...}}, - // load dictionaries - loadDictionaries:({lang, fallbackLang}, client /* params are injected dependencies received in the same order as they are in deps */) =>{ - return of({ - [lang]: {...} - }); - } - }) - ] +bootstrapApplication(AppComponent, { + providers: [ + provideHttpClient(), + provideTranslate( + { + lang: window.navigator.language, + fallbackLang: 'ru-RU', + }, + // static dictionaries, available before anything loads + withDictionaries({ 'ru-RU': { ... } }), + // dictionaries fetched while the application initializes + withLoader(({ lang, fallbackLang }) => inject(HttpClient).get(`/assets/translations/${lang}.json`).pipe( + map((dictionary) => ({ [lang]: dictionary })), + )), + ), + ], }); ``` +Declarables are standalone. Add `TRANSLATE_IMPORTS` (the three pipes and the directive) to any component that translates: + +```javascript +@Component({ + standalone: true, + imports: [TRANSLATE_IMPORTS], + template: `

`, +}) +export class HelloComponent {} +``` + +Import them individually (`TranslatePipe`, `TranslateToPipe`, `TranslatePipeDetect`, `TranslateDirective`) when a component needs only some. + +Using NgModules? `TranslateModule.forRoot()` / `.forChild()` still work — see [Legacy NgModule API](#legacy-ngmodule-api). + See [Load dictionaries](#load-dictionaries) ### Use Directive @@ -111,7 +125,7 @@ hello$ = translate.translateObservable('hello_user', { user: 'Oleg' }); // Obser ``` To change language, use `TranslateRootService` `lang` property. -To detect changes, subscribe to `languageChange$` and `dictionaryChange$`. **Note** that `loadDictionaries` method in root settings will not execute when language changes. +To detect changes, subscribe to `languageChange$` and `dictionaryChange$`. **Note** that root loaders (`withLoader()`) run once during initialization and will not execute again when the language changes. ```javascript export class Component { @@ -125,163 +139,162 @@ export class Component { #### Root -Default `forRoot` initialization can use injected dependencies (e.g. `HttpClient`) to fetch dictionaries. `loadDictionaries` returns an `Observable` of a set of dictionaries +`withLoader()` fetches dictionaries during application initialization; the application does not start until they settle. It may return an `Observable`, a `Promise` or a plain `Dictionaries` object, and it runs inside an injection context. ```javascript -export function getDictionary(lang: string, client: HttpClient) { - return client.get(`/assets/translations/${lang}.json`); +function getDictionary(lang: string) { + return inject(HttpClient).get(`/assets/translations/${lang}.json`); } -@NgModule({ - declarations: [...], - imports: [ - ... - TranslateModule.forRoot({ - // dependencies - deps: [ HttpClient ], - - lang: window.navigator.language, - fallbackLang: 'ru-RU', - - loadDictionaries: ({lang, fallbackLang}, client /* params are injected dependencies received in the same order as they are in deps */) => { - - const res$ = forkJoin([getDictionary(lang, client), getDictionary(fallbackLang, client)]).pipe( - map((res) => { - return { [lang]: res[0], [fallbackLang]: res[1] }; - }) - ); - - return res$; - }, - }), - ... - ], - ... -}) +provideTranslate( + { + lang: window.navigator.language, + fallbackLang: 'ru-RU', + }, + withLoader(({ lang, fallbackLang }) => + forkJoin([getDictionary(lang), getDictionary(fallbackLang)]).pipe( + map(([dictionary, fallback]) => ({ [lang]: dictionary, [fallbackLang]: fallback })), + ), + ), +); ``` -**Note**: it might be useful to **hardcode** _fallback dictionary_ in .ts or .json file then import it rather than use http client to download. +`withLoader()` may be used several times — the loaders run in parallel and their dictionaries are merged, which lets a feature contribute its own without touching the bootstrap config. + +**Note**: it might be useful to **hardcode** the _fallback dictionary_ in a .ts or .json file and import it rather than use the http client to download it. ```javascript import fallback from './translations/fallback'; -TranslateModule.forRoot({ - lang: window.navigator.language, - fallbackLang: env.fallbackLanguage, - dictionaries: { - [env.fallbackLanguage]: fallback, - }, - - deps: [ HttpClient ], - loadDictionaries: ({lang, fallbackLang}, client /* params are injected dependencies received in the same order as they are in deps */) => { - return getDictionary(lang, client).pipe( - map((res) => { - return { [lang]: res }; - }) - ); +provideTranslate( + { + lang: window.navigator.language, + fallbackLang: env.fallbackLanguage, }, -}), + withDictionaries({ [env.fallbackLanguage]: fallback }), + withLoader(({ lang }) => getDictionary(lang).pipe(map((res) => ({ [lang]: res })))), +); ``` -**Note**: For more complex scenarios you may use initialization functions with `APP_INITIALIZER` token. +`withOnReady()` runs once every loader has settled, before the application starts: -#### Lazy +```javascript +provideTranslate( + { lang: window.navigator.language }, + withLoader(...), + withOnReady(() => inject(SplashScreen).hide()), +); +``` -Loading dictionaries for **Lazy** modules is a bit trickier. +#### Lazy routes -```javascript -export function getDictionary(lang: string, client: HttpClient) { - return client.get(`/assets/translations/${lang}.dynamic.json`); -} +A route scopes translation with `provideTranslateChild()` in its `providers`, plus `translateChildResolver` in its `resolve` so navigation waits for the dictionaries. `withTranslateChild()` is the two of them in one object, ready to spread into the route: -@NgModule({ - declarations: [...], - imports: [ - TranslateModule.forChild({ - deps: [ HttpClient ], - loadDictionaries: ({ lang, fallbackLang }, client: HttpClient) => { - return forkJoin([getDictionary(lang, client), getDictionary(fallbackLang, client)]).pipe( - map((res) => { - return { [lang]: res[0], [fallbackLang]: res[1] }; - }) - ); - }, +```javascript +const routes: Routes = [ + { + path: 'dynamic', + ...withTranslateChild({ + loadDictionaries: ({ lang, fallbackLang }) => + forkJoin([getDictionary(lang), getDictionary(fallbackLang)]).pipe( + map(([dictionary, fallback]) => ({ [lang]: dictionary, [fallbackLang]: fallback })), + ), }), - ... - ] -}) -export class DynamicModule {} + loadComponent: () => import('./dynamic.component').then((m) => m.DynamicComponent), + }, +]; ``` -Then you **must** add the `TranslateResolve` resolver to every lazy route to wait for child `loadDictionaries`. +Spelled out, that is: ```javascript -const routes: Routes = [{ path: '', component: DynamicComponent, resolve: { translate: TranslateResolve } }]; - -@NgModule({ - imports: [RouterModule.forChild(routes)], - exports: [RouterModule], -}) -export class DynamicRoutingModule {} +{ + path: 'dynamic', + providers: [provideTranslateChild({ loadDictionaries })], + resolve: { translate: translateChildResolver }, + loadComponent: ..., +} ``` -**Deprecated: Under consideration of removing**: For rare cases you may use `id` parameter for Lazy loaded module, that allows having different values with same key. -"Lazy" values will be available only for lazy modules with that special `id`. +Components under that route get their own `TranslateService` instance; everywhere else keeps the root one. + +**Deprecated: under consideration for removal**: the `id` parameter gives a scope its own values for keys that already exist at the root. Those values are visible only inside that scope, and keys the scope does not define fall back to the root dictionary. ```javascript -@NgModule({ - declarations: [...], - imports: [ - TranslateModule.forRoot({ - dictionaries: {'en-US':{ - 'key':'Value' - }} - }) - ] -}) +provideTranslate({ lang: 'en-US' }, withDictionaries({ 'en-US': { key: 'Value' } })); ``` ```javascript -@NgModule({ - declarations: [...], - imports: [ - TranslateModule.forChild({ - id: 'lazy', - dictionaries: {'en-US':{ - 'key':'Value for Lazy' - }} - }) - ] -}) +{ + path: 'lazy', + ...withTranslateChild({ id: 'lazy', dictionaries: { 'en-US': { key: 'Value for Lazy' } } }), + loadComponent: ..., +} ``` ### Pipeline **(experimental)** -Currently it is possible to **append** middleware to the end of translation pipeline. -It might be specially useful to add **logger** or rarely fine-tune translation result. +Currently it is possible to **append** middleware to the end of the translation pipeline. +It might be especially useful to add a **logger** or to rarely fine-tune the translation result. + +```javascript +provideTranslate( + { lang: window.navigator.language }, + withMiddleware(() => { + const logger = inject(Logger); + return [ + ({ params, result }, next) => { + if (result.fallingBack) { + logger.log(`Translation absent [${params.lang}:${params.key}]`); + } + next(); + }, + ]; + }), +); +``` + +Middleware is appended before any loader runs, so it sees every dictionary as it arrives. + +### Legacy NgModule API + +`TranslateModule.forRoot()` and `TranslateModule.forChild()` are deprecated but still supported — they build the same providers as `provideTranslate()` and `provideTranslateChild()`. Importing `TranslateModule` into an NgModule still exports the pipes and the directive to its declarations. ```javascript @NgModule({ - declarations: [...], + declarations: [AppComponent], imports: [ - ... TranslateModule.forRoot({ - // dependencies - deps: [ Logger ], - addMiddleware: (logger /* injected dependencies */) => { - return [ - ({params, result}, next) => { - if (result.fallingBack) { - logger.log(`Translation absent [${params.lang}:${params.key}]`); - } - next(); - }, - ]; - }, + // dependencies, resolved and passed to every callback below + deps: [HttpClient], + lang: window.navigator.language, + fallbackLang: 'ru-RU', + dictionaries: { 'ru-RU': { ... } }, + loadDictionaries: ({ lang, fallbackLang }, client) => of({ [lang]: { ... } }), }), - ... ], - ... }) +export class AppModule {} ``` + +Lazy NgModules use `TranslateModule.forChild()` and need `TranslateResolve` on every route that waits for its dictionaries: + +```javascript +const routes: Routes = [{ path: '', component: DynamicComponent, resolve: { translate: TranslateResolve } }]; +``` + +To migrate: + +| Legacy | Functional | +| --- | --- | +| `TranslateModule.forRoot(config)` | `provideTranslate(config, ...features)` | +| `TranslateModule.forChild(config)` | `provideTranslateChild(config)` in `Route.providers` | +| `TranslateResolve` | `translateChildResolver` | +| `deps: [Dep]` + callback parameters | `inject(Dep)` inside the callback | +| `dictionaries` | `withDictionaries()` | +| `loadDictionaries` | `withLoader()` | +| `addMiddleware` | `withMiddleware()` | +| `final` | `withOnReady()` | +| `init` | `withLoader()` | +| `imports: [TranslateModule]` | `imports: [TRANSLATE_IMPORTS]` | diff --git a/projects/translate/src/__test__/provide-translate-child.spec.ts b/projects/translate/src/__test__/provide-translate-child.spec.ts new file mode 100644 index 0000000..3fcdb07 --- /dev/null +++ b/projects/translate/src/__test__/provide-translate-child.spec.ts @@ -0,0 +1,175 @@ +import { Component, createEnvironmentInjector, EnvironmentInjector, NgModule } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { provideRouter, RouterModule, Routes } from '@angular/router'; +import { RouterTestingHarness } from '@angular/router/testing'; +import { of, throwError } from 'rxjs'; +import { + provideTranslate, + provideTranslateChild, + TranslateModule, + TranslateResolve, + TranslateRootService, + TranslateService, + TRANSLATE_IMPORTS, + withDictionaries, + withTranslateChild, +} from '../public_api'; + +@Component({ + standalone: true, + imports: [...TRANSLATE_IMPORTS], + template: `{{ 'hello_user' | translate }}`, +}) +class ScopedComponent { + constructor(public service: TranslateService) {} +} + +const routes: Routes = [ + { + path: 'scoped', + ...withTranslateChild({ + id: 'child', + loadDictionaries: ({ lang }) => of({ [lang!]: { hello_user: 'Hello USER Child' } }), + }), + component: ScopedComponent, + }, + { + path: 'plain', + component: ScopedComponent, + }, +]; + +describe('provideTranslateChild', () => { + let harness: RouterTestingHarness; + + beforeEach(async () => { + TestBed.configureTestingModule({ + providers: [ + provideRouter(routes), + provideTranslate({ lang: 'test', fallbackLang: 'fallback' }, withDictionaries({ test: { hello_user: 'Hello User' } })), + ], + }); + harness = await RouterTestingHarness.create(); + }); + + it('prefers the scoped dictionary once the resolver has run', async () => { + await harness.navigateByUrl('/scoped', ScopedComponent); + harness.detectChanges(); + + expect(harness.routeNativeElement!.querySelector('#text')!.textContent).toBe('Hello USER Child'); + }); + + it('leaves routes without a scope on the root dictionary', async () => { + await harness.navigateByUrl('/plain', ScopedComponent); + harness.detectChanges(); + + expect(harness.routeNativeElement!.querySelector('#text')!.textContent).toBe('Hello User'); + }); + + it('gives the scoped route its own TranslateService instance', async () => { + const scoped = await harness.navigateByUrl('/scoped', ScopedComponent); + const scopedService = scoped.service; + + const plain = await harness.navigateByUrl('/plain', ScopedComponent); + expect(plain.service).not.toBe(scopedService); + expect(plain.service).toBe(TestBed.inject(TranslateService)); + }); + + it('falls back to the root key when the scope has no entry for it', async () => { + const component = await harness.navigateByUrl('/scoped', ScopedComponent); + + expect(component.service.translate('not_in_child')).toBe('not_in_child'); + }); +}); + +describe('provideTranslateChild loading', () => { + let harness: RouterTestingHarness; + let calls: string[]; + let failNext: boolean; + + beforeEach(async () => { + calls = []; + failNext = false; + + TestBed.configureTestingModule({ + providers: [ + provideRouter([ + { + path: 'scoped', + ...withTranslateChild({ + id: 'child', + loadDictionaries: ({ lang }) => { + calls.push(lang!); + if (failNext) { + failNext = false; + return throwError(() => new Error('offline')); + } + return of({ [lang!]: { hello_user: `Hello ${lang} Child` } }); + }, + }), + component: ScopedComponent, + }, + { path: 'legacy', loadChildren: () => LegacyChildModule }, + { path: 'plain', component: ScopedComponent }, + ]), + provideTranslate({ lang: 'test' }, withDictionaries({ test: { hello_user: 'Hello User' } })), + ], + }); + harness = await RouterTestingHarness.create(); + }); + + it('loads the scope again for a language selected later', async () => { + const component = await harness.navigateByUrl('/scoped', ScopedComponent); + + TestBed.inject(TranslateRootService).lang = 'de'; + + expect(calls).toEqual(['test', 'de']); + expect(component.service.translate('hello_user')).toBe('Hello de Child'); + }); + + it('retries a failed load on the next navigation', async () => { + failNext = true; + await harness.navigateByUrl('/scoped').catch(() => null); + await harness.navigateByUrl('/plain', ScopedComponent); + + const component = await harness.navigateByUrl('/scoped', ScopedComponent); + + expect(calls).toEqual(['test', 'test']); + expect(component.service.translate('hello_user')).toBe('Hello test Child'); + }); + + it('translates without a dictionary for the current language', () => { + const root = TestBed.inject(TranslateRootService); + const scoped = createEnvironmentInjector([provideTranslateChild({ id: 'child' })], TestBed.inject(EnvironmentInjector)).get(TranslateService); + + root.lang = 'unknown'; + expect(scoped.translate('hello_user')).toBe('hello_user'); + + root.lang = undefined; + expect(() => scoped.translate('hello_user')).not.toThrow(); + }); + + it('passes the scoped TranslateService to the legacy forChild({ extend })', async () => { + await harness.navigateByUrl('/legacy'); + + expect(legacyExtendedWith).toEqual(jasmine.any(TranslateService)); + expect(legacyExtendedWith).not.toBe(TestBed.inject(TranslateService)); + }); +}); + +let legacyExtendedWith: unknown; + +@NgModule({ + imports: [ + TranslateModule.forChild({ + id: 'legacy', + extend: (service: TranslateService) => { + legacyExtendedWith = service; + return of({}); + }, + }), + // the resolver must sit inside the lazy module to see its scope + RouterModule.forChild([{ path: '', component: ScopedComponent, resolve: { translate: TranslateResolve } }]), + ], +}) +class LegacyChildModule {} diff --git a/projects/translate/src/__test__/provide-translate.spec.ts b/projects/translate/src/__test__/provide-translate.spec.ts new file mode 100644 index 0000000..cb24dce --- /dev/null +++ b/projects/translate/src/__test__/provide-translate.spec.ts @@ -0,0 +1,190 @@ +import { ApplicationInitStatus, Component, createEnvironmentInjector, EnvironmentInjector, inject } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { BehaviorSubject, concat, debounceTime, EMPTY, NEVER, of } from 'rxjs'; +import { + DEFAULT_CONFIG, + Dictionaries, + TranslateModule, + provideTranslate, + provideTranslateChild, + ROOT_DICTIONARIES, + TranslateRootService, + TranslateService, + TRANSLATE_IMPORTS, + withConfig, + withDictionaries, + withLoader, + withMiddleware, + withOnReady, +} from '../public_api'; +import { InjectedTestClass, InjectedValue, INJECTED_TOKEN } from './core/test.component'; + +@Component({ + standalone: true, + // nested, the form the README documents + imports: [TRANSLATE_IMPORTS], + template: `{{ 'hello_user' | translate }}`, +}) +class StandaloneTestComponent {} + +/** `TestBed.inject()` creates the test module, which runs the `APP_INITIALIZER`s. */ +function whenInitialized(): Promise { + return TestBed.inject(ApplicationInitStatus).donePromise; +} + +describe('provideTranslate', () => { + it('applies the config passed as the first argument', () => { + TestBed.configureTestingModule({ providers: [provideTranslate({ lang: 'test', fallbackLang: 'fallback' })] }); + + const service = TestBed.inject(TranslateRootService); + expect(service.lang).toBe('test'); + expect(service.fallbackLang).toBe('fallback'); + }); + + it('defaults the placeholder to "default"', () => { + TestBed.configureTestingModule({ providers: [provideTranslate()] }); + + expect(TestBed.inject(DEFAULT_CONFIG).placeholder).toBe('default'); + expect(TestBed.inject(ROOT_DICTIONARIES)).toEqual({}); + }); + + it('accepts features instead of a config object', () => { + TestBed.configureTestingModule({ + providers: [provideTranslate(withConfig({ lang: 'test' }), withDictionaries({ test: { hello_user: 'Hello User' } }))], + }); + + expect(TestBed.inject(TranslateRootService).translate('hello_user')).toBe('Hello User'); + }); + + it('rejects a feature that may only be used once', () => { + expect(() => provideTranslate(withConfig({ lang: 'a' }), withConfig({ lang: 'b' }))).toThrowError(/withConfig\(\) can only be used once/); + }); + + it('rejects a child scope without a root', () => { + TestBed.configureTestingModule({ providers: [provideTranslateChild({ id: 'child' })] }); + + expect(() => TestBed.inject(TranslateService)).toThrowError(/requires provideTranslate\(\)/); + }); + + describe('initialization', () => { + let order: string[]; + + beforeEach(async () => { + order = []; + + TestBed.configureTestingModule({ + providers: [ + { provide: INJECTED_TOKEN, useValue: { value: 0 } }, + provideTranslate( + { lang: 'test', fallbackLang: 'fallback' }, + withDictionaries({ test: { from_dictionaries: 'root' } }), + withMiddleware(() => { + order.push('middleware'); + inject(InjectedTestClass).value++; + inject(INJECTED_TOKEN).value++; + return []; + }), + withLoader(({ lang, fallbackLang }) => { + order.push(`loader-a:${lang}:${fallbackLang}`); + inject(InjectedTestClass).value++; + return of({ test: { from_loader_a: 'a' } }).pipe(debounceTime(10)); + }), + // a plain object is as good as an observable + withLoader(() => { + order.push('loader-b'); + return { test: { from_loader_b: 'b' } }; + }), + withOnReady(() => { + order.push('onReady'); + inject(InjectedTestClass).value++; + }), + ), + ], + }); + + await whenInitialized(); + }); + + it('runs middleware first, then the loaders, then onReady', () => { + expect(order[0]).toBe('middleware'); + expect(order[order.length - 1]).toBe('onReady'); + expect(order).toContain('loader-a:test:fallback'); + expect(order).toContain('loader-b'); + }); + + it('merges dictionaries from every source', () => { + const service = TestBed.inject(TranslateRootService); + expect(service.translate('from_dictionaries')).toBe('root'); + expect(service.translate('from_loader_a')).toBe('a'); + expect(service.translate('from_loader_b')).toBe('b'); + }); + + it('injects dependencies inside the feature callbacks', () => { + expect(TestBed.inject(InjectedTestClass).value).toBe(3); + expect(TestBed.inject(INJECTED_TOKEN).value).toBe(1); + }); + }); + + describe('root guard', () => { + it('rejects provideTranslate() in a child injector', () => { + TestBed.configureTestingModule({ providers: [provideTranslate()] }); + const parent = TestBed.inject(EnvironmentInjector); + + expect(() => createEnvironmentInjector([provideTranslate()], parent)).toThrowError(/called more than once/); + }); + + it('lets TranslateModule.forRoot() be imported again in a lazily loaded module', () => { + TestBed.configureTestingModule({ imports: [TranslateModule.forRoot()] }); + const parent = TestBed.inject(EnvironmentInjector); + + expect(() => createEnvironmentInjector(TranslateModule.forRoot().providers!, parent)).not.toThrow(); + }); + }); + + describe('misbehaving loaders', () => { + it('start the application with the first result of each loader', async () => { + const repeating = new BehaviorSubject({ test: { from_repeating: 'first' } }); + let extended = 0; + + TestBed.configureTestingModule({ + providers: [ + provideTranslate( + { lang: 'test' }, + withLoader(() => EMPTY), + withLoader(() => concat(of({ test: { from_never_completing: 'yes' } }), NEVER)), + withLoader(() => repeating), + withOnReady(() => { + const service = inject(TranslateRootService); + service.dictionaryChange$.subscribe(() => extended++); + }), + ), + ], + }); + + await whenInitialized(); + repeating.next({ test: { from_repeating: 'second' } }); + + const service = TestBed.inject(TranslateRootService); + expect(service.translate('from_never_completing')).toBe('yes'); + expect(service.translate('from_repeating')).toBe('first'); + expect(extended).toBe(0); + }); + }); + + describe('declarables', () => { + it('work in a standalone component through TRANSLATE_IMPORTS', async () => { + TestBed.configureTestingModule({ + providers: [provideTranslate({ lang: 'test' }, withDictionaries({ test: { hello_user: 'Hello User' } }))], + imports: [StandaloneTestComponent], + }); + + const fixture = TestBed.createComponent(StandaloneTestComponent); + fixture.detectChanges(); + await fixture.whenStable(); + + const element: HTMLElement = fixture.elementRef.nativeElement; + expect(element.querySelector('#pipe')!.textContent).toBe('Hello User'); + expect(element.querySelector('#directive')!.textContent!.trim()).toBe('Hello User'); + }); + }); +}); diff --git a/projects/translate/src/providers/translate.features.ts b/projects/translate/src/providers/translate.features.ts new file mode 100644 index 0000000..cbed0fc --- /dev/null +++ b/projects/translate/src/providers/translate.features.ts @@ -0,0 +1,73 @@ +import { InjectionToken, Provider } from '@angular/core'; +import { Dictionaries, MiddlewareFunc, MiddlewareStatic } from 'simply-translate'; +import { DefaultTranslateConfig, DEFAULT_CONFIG, LoadedDictionaries, ROOT_DICTIONARIES } from '../translate/translate.service'; + +/** + * Loads dictionaries while the application initializes. Called inside an injection + * context, so dependencies are taken with `inject()` instead of a `deps` array. + */ +export type TranslateLoaderFn = (opts: { lang: string | undefined; fallbackLang: string | undefined }) => LoadedDictionaries; + +/** Returns middleware to append to the pipeline. Called inside an injection context. */ +export type TranslateMiddlewareFn = () => Array | void; + +/** Runs once every loader has settled. Called inside an injection context. */ +export type TranslateOnReadyFn = () => void; + +export const TRANSLATE_LOADER_FNS = new InjectionToken('TRANSLATE_LOADER_FNS'); +export const TRANSLATE_MIDDLEWARE_FNS = new InjectionToken('TRANSLATE_MIDDLEWARE_FNS'); +export const TRANSLATE_ON_READY_FNS = new InjectionToken('TRANSLATE_ON_READY_FNS'); + +export enum TranslateFeatureKind { + Config, + Dictionaries, + Loader, + Middleware, + OnReady, +} + +export interface TranslateFeature { + ɵkind: K; + ɵproviders: Provider[]; +} + +function feature(ɵkind: K, ɵproviders: Provider[]): TranslateFeature { + return { ɵkind, ɵproviders }; +} + +export function isTranslateFeature(value: unknown): value is TranslateFeature { + return !!value && typeof value === 'object' && 'ɵkind' in (value as object) && 'ɵproviders' in (value as object); +} + +/** Language, fallback language and placeholder behaviour. */ +export function withConfig(config: DefaultTranslateConfig): TranslateFeature { + const value: DefaultTranslateConfig = { + lang: config.lang, + fallbackLang: config.fallbackLang, + placeholder: config.placeholder !== undefined ? config.placeholder : 'default', + }; + return feature(TranslateFeatureKind.Config, [{ provide: DEFAULT_CONFIG, useValue: value }]); +} + +/** Dictionaries known up front, available before any loader runs. */ +export function withDictionaries(dictionaries: Dictionaries): TranslateFeature { + return feature(TranslateFeatureKind.Dictionaries, [{ provide: ROOT_DICTIONARIES, useValue: dictionaries }]); +} + +/** + * Loads dictionaries during `APP_INITIALIZER`. Several loaders may be registered; + * they run in parallel and the application waits for all of them. + */ +export function withLoader(load: TranslateLoaderFn): TranslateFeature { + return feature(TranslateFeatureKind.Loader, [{ provide: TRANSLATE_LOADER_FNS, useValue: load, multi: true }]); +} + +/** Appends middleware to the root pipeline before any loader runs. */ +export function withMiddleware(addMiddleware: TranslateMiddlewareFn): TranslateFeature { + return feature(TranslateFeatureKind.Middleware, [{ provide: TRANSLATE_MIDDLEWARE_FNS, useValue: addMiddleware, multi: true }]); +} + +/** Runs after every loader has settled, before the application starts. */ +export function withOnReady(onReady: TranslateOnReadyFn): TranslateFeature { + return feature(TranslateFeatureKind.OnReady, [{ provide: TRANSLATE_ON_READY_FNS, useValue: onReady, multi: true }]); +} diff --git a/projects/translate/src/providers/translate.initializer.ts b/projects/translate/src/providers/translate.initializer.ts new file mode 100644 index 0000000..270be24 --- /dev/null +++ b/projects/translate/src/providers/translate.initializer.ts @@ -0,0 +1,44 @@ +import { EnvironmentInjector, inject, runInInjectionContext } from '@angular/core'; +import { forkJoin, lastValueFrom, tap } from 'rxjs'; +import { DEFAULT_CONFIG, TranslateRootService } from '../translate/translate.service'; +import { extendAll, firstDictionaries$ } from '../translate/translate.utils'; +import { TranslateMiddlewareFn, TRANSLATE_LOADER_FNS, TRANSLATE_MIDDLEWARE_FNS, TRANSLATE_ON_READY_FNS } from './translate.features'; + +/** + * Factory for the `APP_INITIALIZER` installed by `provideTranslate()`. Middleware is + * appended first, then every loader runs in parallel, then the `onReady` hooks fire. + * Only a loader's first result is used; one that completes empty contributes `{}`. + */ +export function translateInitializerFactory(): () => Promise { + const injector = inject(EnvironmentInjector); + const service = inject(TranslateRootService); + const config = inject(DEFAULT_CONFIG, { optional: true }); + const middlewareFns = inject(TRANSLATE_MIDDLEWARE_FNS, { optional: true }) ?? []; + const loaderFns = inject(TRANSLATE_LOADER_FNS, { optional: true }) ?? []; + const onReadyFns = inject(TRANSLATE_ON_READY_FNS, { optional: true }) ?? []; + + return () => { + middlewareFns.forEach((fn) => { + const middleware = runInInjectionContext(injector, fn) as Exclude, void> | undefined; + middleware?.forEach((mw) => service.pipeline.addMiddleware(mw)); + }); + + const opts = { lang: config?.lang, fallbackLang: config?.fallbackLang }; + const runOnReady = () => onReadyFns.forEach((fn) => runInInjectionContext(injector, fn)); + + if (!loaderFns.length) { + runOnReady(); + return Promise.resolve(); + } + + // each loader contributes its first result exactly once, so forkJoin always emits once + const loaded$ = loaderFns.map((fn) => firstDictionaries$(runInInjectionContext(injector, () => fn(opts)))); + + return lastValueFrom( + forkJoin(loaded$).pipe( + tap((results) => results.forEach((dictionaries) => extendAll(service, dictionaries))), + tap(() => runOnReady()), + ), + ); + }; +} diff --git a/projects/translate/src/providers/translate.providers.ts b/projects/translate/src/providers/translate.providers.ts new file mode 100644 index 0000000..6909e79 --- /dev/null +++ b/projects/translate/src/providers/translate.providers.ts @@ -0,0 +1,163 @@ +import { + APP_INITIALIZER, + EnvironmentProviders, + ENVIRONMENT_INITIALIZER, + inject, + InjectionToken, + isDevMode, + makeEnvironmentProviders, + Provider, +} from '@angular/core'; +import { Dictionaries } from 'simply-translate'; +import { TranslateDirective } from '../translate/translate.directive'; +import { TranslatePipe, TranslatePipeDetect, TranslateToPipe } from '../translate/translate.pipe'; +import { translateChildResolver, TranslateResolve } from '../translate/translate.resolver'; +import { + DefaultTranslateConfig, + DEFAULT_CONFIG, + ROOT_DICTIONARIES, + TranslateChildConfig, + TranslateRootService, + TranslateService, + TRANSLATE_CHILD, +} from '../translate/translate.service'; +import { asDictionaries$ } from '../translate/translate.utils'; +import { isTranslateFeature, TranslateFeature, TranslateFeatureKind, TranslateLoaderFn, withConfig } from './translate.features'; +import { translateInitializerFactory } from './translate.initializer'; + +/** Everything a template needs: the three pipes and the `translate` directive. */ +export const TRANSLATE_IMPORTS = [TranslatePipe, TranslateToPipe, TranslatePipeDetect, TranslateDirective] as const; + +const TRANSLATE_ROOT_GUARD = new InjectionToken('TRANSLATE_ROOT_GUARD'); + +/** Features that may only be used once, mapped to the name to report when they are not. */ +const SINGLE_USE_FEATURES: Partial> = { + [TranslateFeatureKind.Config]: 'withConfig', + [TranslateFeatureKind.Dictionaries]: 'withDictionaries', +}; + +function assertFeaturesUsedOnce(features: readonly TranslateFeature[]) { + const seen = new Set(); + features.forEach(({ ɵkind }) => { + const name = SINGLE_USE_FEATURES[ɵkind]; + if (name && seen.has(ɵkind)) { + throw new Error(`provideTranslate(): ${name}() can only be used once.`); + } + seen.add(ɵkind); + }); +} + +function rootGuard() { + if (inject(TRANSLATE_ROOT_GUARD, { optional: true, skipSelf: true })) { + throw new Error('provideTranslate() was called more than once. Lazily loaded routes should use provideTranslateChild() instead.'); + } +} + +function childGuard() { + if (!inject(TRANSLATE_ROOT_GUARD, { optional: true })) { + throw new Error('provideTranslateChild() requires provideTranslate() in the application providers.'); + } +} + +/** + * Sets up translation for the whole application. + * + * ```ts + * bootstrapApplication(AppComponent, { + * providers: [ + * provideTranslate( + * { lang: 'en', fallbackLang: 'en' }, + * withLoader(({ lang }) => inject(HttpClient).get(`/i18n/${lang}.json`)), + * ), + * ], + * }); + * ``` + */ +export function provideTranslate(config?: DefaultTranslateConfig, ...features: TranslateFeature[]): EnvironmentProviders; +export function provideTranslate(...features: TranslateFeature[]): EnvironmentProviders; +export function provideTranslate( + configOrFeature?: DefaultTranslateConfig | TranslateFeature, + ...rest: TranslateFeature[] +): EnvironmentProviders { + const features = isTranslateFeature(configOrFeature) + ? [configOrFeature, ...rest] + : [withConfig((configOrFeature as DefaultTranslateConfig) ?? {}), ...rest]; + + if (isDevMode()) { + assertFeaturesUsedOnce(features); + } + + return ɵtranslateRootProviders(features, { guard: isDevMode() }); +} + +/** + * The root providers behind `provideTranslate()` and `TranslateModule.forRoot()`. + * `forRoot()` passes `guard: false` because NgModule apps may legitimately import + * it in a lazily loaded module as well. + */ +export function ɵtranslateRootProviders(features: TranslateFeature[], { guard }: { guard: boolean }): EnvironmentProviders { + return makeEnvironmentProviders([ + TranslateRootService, + TranslateService, + TranslateResolve, + { provide: TRANSLATE_CHILD, useValue: {} }, + { provide: DEFAULT_CONFIG, useValue: { placeholder: 'default' } as DefaultTranslateConfig }, + { provide: ROOT_DICTIONARIES, useValue: {} as Dictionaries }, + { provide: TRANSLATE_ROOT_GUARD, useValue: true }, + ...(guard ? [{ provide: ENVIRONMENT_INITIALIZER, multi: true, useValue: rootGuard }] : []), + { provide: APP_INITIALIZER, multi: true, useFactory: translateInitializerFactory }, + // features last, so that withConfig()/withDictionaries() override the defaults above + features.map((feature) => feature.ɵproviders), + ]); +} + +export interface TranslateChildOptions { + /** Key prefix for this scope. Keys fall back to the root dictionary when it has no entry under the prefix. */ + id?: string; + /** Dictionaries merged into the root service as soon as the scope is created. */ + dictionaries?: Dictionaries; + /** + * Loads dictionaries for this scope. Runs inside an injection context, so dependencies + * are taken with `inject()`. Needs `translateChildResolver` on the route to be awaited. + */ + loadDictionaries?: TranslateLoaderFn; +} + +/** + * Scopes translation to a route and the components below it. Goes in `Route.providers`; + * pair it with `translateChildResolver` (or use `withTranslateChild()`) when it loads + * dictionaries asynchronously. + */ +export function provideTranslateChild(options: TranslateChildOptions = {}): EnvironmentProviders { + const load = options.loadDictionaries; + const value: TranslateChildConfig = { + id: options.id, + dictionaries: options.dictionaries, + loadDictionaries: load && ((opts) => asDictionaries$(load(opts))), + }; + + return makeEnvironmentProviders([ + TranslateService, + TranslateResolve, + { provide: TRANSLATE_CHILD, useValue: value }, + ...(isDevMode() ? [{ provide: ENVIRONMENT_INITIALIZER, multi: true, useValue: childGuard }] : []), + ]); +} + +/** + * `provideTranslateChild()` plus the resolver that awaits its dictionaries, ready to + * spread into a route: + * + * ```ts + * { path: 'orders', ...withTranslateChild({ id: 'orders', loadDictionaries: () => ... }), loadComponent: ... } + * ``` + */ +export function withTranslateChild(options: TranslateChildOptions = {}): { + providers: Array; + resolve: { translate: typeof translateChildResolver }; +} { + return { + providers: [provideTranslateChild(options)], + resolve: { translate: translateChildResolver }, + }; +} diff --git a/projects/translate/src/public_api.ts b/projects/translate/src/public_api.ts index f457bd2..a752f1c 100644 --- a/projects/translate/src/public_api.ts +++ b/projects/translate/src/public_api.ts @@ -2,6 +2,10 @@ export * from './translate/translate.directive'; export * from './translate/translate.pipe'; export * from './translate/translate.resolver'; export * from './translate/translate.service'; +export * from './providers/translate.features'; +export * from './providers/translate.providers'; +export { translateInitializerFactory } from './providers/translate.initializer'; +export { asDictionaries$, extendAll } from './translate/translate.utils'; export * from './simply-translate.module'; export { TranslateChildConfig } from './translate/translate.service'; export { diff --git a/projects/translate/src/simply-translate.module.ts b/projects/translate/src/simply-translate.module.ts index 623d5b2..abc3d53 100644 --- a/projects/translate/src/simply-translate.module.ts +++ b/projects/translate/src/simply-translate.module.ts @@ -1,19 +1,17 @@ -import { APP_INITIALIZER, ModuleWithProviders, NgModule } from '@angular/core'; +import { inject, ModuleWithProviders, NgModule, ProviderToken } from '@angular/core'; import { combineLatest, lastValueFrom, Observable, of, tap } from 'rxjs'; import { Dictionaries, Dictionary, MiddlewareFunc, MiddlewareStatic } from 'simply-translate'; +import { DefaultTranslateConfig, TranslateRootService, TranslateService, TranslateServiceBase } from './translate/translate.service'; import { - DefaultTranslateConfig, - DEFAULT_CONFIG, - ROOT_DICTIONARIES, - TranslateChildConfig, - TranslateRootService, - TranslateService, - TranslateServiceBase, - TRANSLATE_CHILD, -} from './translate/translate.service'; -import { TranslatePipe, TranslateToPipe, TranslatePipeDetect } from './translate/translate.pipe'; -import { TranslateDirective } from './translate/translate.directive'; -import { TranslateResolve } from './translate/translate.resolver'; + TranslateFeature, + TranslateLoaderFn, + withConfig, + withDictionaries, + withLoader, + withMiddleware, + withOnReady, +} from './providers/translate.features'; +import { provideTranslateChild, TRANSLATE_IMPORTS, ɵtranslateRootProviders } from './providers/translate.providers'; export type AddMiddlewareFunc = (...any: any[]) => Array; export type LoadDictionariesFunc = ( @@ -23,6 +21,10 @@ export type LoadDictionariesFunc = ( export type InitFunc = (service: TranslateRootService, ...any: any[]) => Observable>; export type FinalFunc = (service: TService, ...any: any[]) => void; +/** + * @deprecated Kept for `TranslateModule.forRoot()`. `provideTranslate()` installs its own + * `APP_INITIALIZER`; see `translateInitializerFactory`. + */ export function factory( config: DefaultTranslateConfig, init?: InitFunc, @@ -32,7 +34,7 @@ export function factory( ) { const ret = (service: TranslateRootService, ...deps: any[]) => { return function () { - let customMiddleware: ReturnType|undefined = undefined; + let customMiddleware: ReturnType | undefined = undefined; if (addMiddlewareFn) { customMiddleware = addMiddlewareFn(...deps); // add some middlewares @@ -94,6 +96,7 @@ export function factory( return ret; } +/** @deprecated `provideTranslate()` guards itself; see the error it throws when used twice. */ export function forRootGuard(service: TranslateService): any { if (service) { throw new Error(`TranslateModule.forRoot() called twice. Lazy loaded modules should use TranslateModule.forChild() instead.`); @@ -108,6 +111,7 @@ export interface Config extends DefaultTranslateConfig { final?: FinalFunc; addMiddleware?: AddMiddlewareFunc; dictionaries?: Dictionaries; + /** @deprecated Take dependencies with `inject()` inside the callbacks instead. */ deps?: any[]; } @@ -116,72 +120,69 @@ export interface ChildConfig { extend?: (service: TranslateService, ...any) => Observable>; loadDictionaries?: ({ lang, fallbackLang }, ...any) => Observable>; dictionaries?: Dictionaries; + /** @deprecated Take dependencies with `inject()` inside `loadDictionaries` instead. */ deps?: any[]; id?: string; } +/** Resolves a legacy `deps: [...]` array from the current injection context. */ +function resolveDeps(deps: any[] | undefined): any[] { + return (deps ?? []).map((token: ProviderToken) => inject(token)); +} + +/** Translates a legacy `forRoot()` config into the feature set `provideTranslate()` understands. */ +export function configToFeatures(config: Config = {}): TranslateFeature[] { + const features: TranslateFeature[] = [ + withConfig({ lang: config.lang, fallbackLang: config.fallbackLang, placeholder: config.placeholder }), + withDictionaries(config.dictionaries ?? {}), + ]; + + const { addMiddleware, loadDictionaries, init, final, deps } = config; + + if (addMiddleware) { + features.push(withMiddleware(() => addMiddleware(...resolveDeps(deps)))); + } + if (loadDictionaries) { + features.push(withLoader((opts) => loadDictionaries(opts, ...resolveDeps(deps)))); + } + if (init) { + features.push(withLoader(() => init(inject(TranslateRootService), ...resolveDeps(deps)))); + } + if (final) { + features.push(withOnReady(() => final(inject(TranslateRootService), ...resolveDeps(deps)))); + } + + return features; +} + @NgModule({ - declarations: [TranslatePipe, TranslateToPipe, TranslatePipeDetect, TranslateDirective], - exports: [TranslatePipe, TranslateToPipe, TranslatePipeDetect, TranslateDirective], + imports: [...TRANSLATE_IMPORTS], + exports: [...TRANSLATE_IMPORTS], }) export class TranslateModule { + /** @deprecated Use `provideTranslate()` in the application providers instead. */ static forRoot(config?: Config): ModuleWithProviders { - config = config ?? { - placeholder: 'default', - deps: [], - }; - - config.placeholder = config.placeholder !== undefined ? config.placeholder : 'default'; - config.deps = config.deps !== undefined ? [TranslateRootService, ...config?.deps] : [TranslateRootService]; - - const value: DefaultTranslateConfig = { - lang: config.lang, - placeholder: config.placeholder, - fallbackLang: config.fallbackLang, - }; - return { ngModule: TranslateModule, - providers: [ - TranslateRootService, - TranslateService, - TranslateResolve, - { - provide: TRANSLATE_CHILD, - useValue: {}, - }, - { - provide: DEFAULT_CONFIG, - useValue: value, - }, - { provide: ROOT_DICTIONARIES, useValue: config.dictionaries ?? {} }, - { - provide: APP_INITIALIZER, - useFactory: factory(config, config.init, config.addMiddleware, config.loadDictionaries, config.final), - deps: config.deps, - multi: true, - }, - ], + // unguarded: NgModule apps may also import forRoot() in a lazily loaded module + providers: [ɵtranslateRootProviders(configToFeatures(config), { guard: false })], }; } - static forChild(config?: ChildConfig): ModuleWithProviders { - const value: TranslateChildConfig = { - loadDictionaries: config?.loadDictionaries ?? config?.extend, - dictionaries: config?.dictionaries, - deps: config?.deps ?? [], - id: config?.id, - }; + /** @deprecated Use `provideTranslateChild()` in `Route.providers` instead. */ + static forChild(config: ChildConfig = {}): ModuleWithProviders { + const { loadDictionaries, extend, deps } = config; + + let load: TranslateLoaderFn | undefined; + if (loadDictionaries) { + load = (opts) => loadDictionaries(opts, ...resolveDeps(deps)); + } else if (extend) { + load = () => extend(inject(TranslateService), ...resolveDeps(deps)); + } + return { ngModule: TranslateModule, - providers: [ - TranslateService, - TranslateResolve, - { - provide: TRANSLATE_CHILD, - useValue: value, - }, - ], + providers: [provideTranslateChild({ id: config.id, dictionaries: config.dictionaries, loadDictionaries: load })], }; } } diff --git a/projects/translate/src/translate/translate.directive.ts b/projects/translate/src/translate/translate.directive.ts index 3f95578..08b8f12 100644 --- a/projects/translate/src/translate/translate.directive.ts +++ b/projects/translate/src/translate/translate.directive.ts @@ -4,6 +4,7 @@ import { TranslateService } from './translate.service'; @Directive({ selector: '[translate]', + standalone: true, }) export class TranslateDirective implements OnInit { private _element: ElementRef = inject(ElementRef); diff --git a/projects/translate/src/translate/translate.pipe.ts b/projects/translate/src/translate/translate.pipe.ts index 752b6a2..13f1c95 100644 --- a/projects/translate/src/translate/translate.pipe.ts +++ b/projects/translate/src/translate/translate.pipe.ts @@ -2,7 +2,7 @@ import { inject, Pipe, PipeTransform } from '@angular/core'; import { DictionaryEntry, TranslateDynamicProps, TranslateKey } from 'simply-translate'; import { TranslateService } from './translate.service'; -@Pipe({ name: 'translate' }) +@Pipe({ name: 'translate', standalone: true }) export class TranslatePipe implements PipeTransform { constructor(protected service: TranslateService) {} @@ -15,7 +15,7 @@ export class TranslatePipe implements PipeTransform { } } -@Pipe({ name: 'translateTo' }) +@Pipe({ name: 'translateTo', standalone: true }) export class TranslateToPipe implements PipeTransform { constructor(protected service: TranslateService) {} @@ -28,7 +28,7 @@ export class TranslateToPipe implements PipeTransform { } } -@Pipe({ name: 'translate$', pure: false }) +@Pipe({ name: 'translate$', pure: false, standalone: true }) export class TranslatePipeDetect extends TranslatePipe { private _latestValue: string = ''; private _key!: TranslateKey; diff --git a/projects/translate/src/translate/translate.resolver.ts b/projects/translate/src/translate/translate.resolver.ts index a3d405c..d6b5012 100644 --- a/projects/translate/src/translate/translate.resolver.ts +++ b/projects/translate/src/translate/translate.resolver.ts @@ -1,9 +1,11 @@ -import { Inject, Injectable, Injector, Optional, ProviderToken } from '@angular/core'; +import { DestroyRef, ErrorHandler, Inject, inject, Injectable, Injector, Optional, runInInjectionContext } from '@angular/core'; -import { isObservable, Observable, of, tap, finalize } from 'rxjs'; -import { Dictionary } from 'simply-translate'; +import { Observable, of, tap, shareReplay, skip } from 'rxjs'; +import { Dictionaries } from 'simply-translate'; import { TranslateChildConfig, TranslateService, TRANSLATE_CHILD } from './translate.service'; +import { extendAll, firstDictionaries$ } from './translate.utils'; +/** @deprecated Use `translateChildResolver` (or `withTranslateChild()`) on the route instead. */ export function translateResolve() { return { translate: TranslateResolve, @@ -11,39 +13,68 @@ export function translateResolve() { } @Injectable() -export class TranslateResolve { - private _extended?: true | Observable; - protected readonly extend: () => Observable; +export class TranslateResolve { + /** Per language: the load in flight, or `true` once its dictionaries are merged. */ + private readonly _extended = new Map>(); + protected readonly extend: () => Observable; - constructor(protected service: TranslateService, injector: Injector, @Optional() @Inject(TRANSLATE_CHILD) settings?: TranslateChildConfig) { + constructor( + protected service: TranslateService, + injector: Injector, + @Optional() @Inject(TRANSLATE_CHILD) settings?: TranslateChildConfig, + ) { if (settings?.loadDictionaries) { - const deps_ = settings.deps ?? []; const loadDictionaries = settings.loadDictionaries; this.extend = () => { - const deps = deps_.map((d: ProviderToken) => injector.get(d)); - return loadDictionaries({ lang: service.lang, fallbackLang: service.fallbackLang }, ...deps); + const opts = { lang: service.lang, fallbackLang: service.fallbackLang }; + return runInInjectionContext(injector, () => firstDictionaries$(loadDictionaries(opts))); }; + + // a language selected after the scope was first resolved needs its dictionaries too + const errorHandler = inject(ErrorHandler); + const sub = service.languageChange$.pipe(skip(1)).subscribe(() => { + if (this._extended.size) { + this.resolve()?.subscribe({ error: (error) => errorHandler.handleError(error) }); + } + }); + inject(DestroyRef).onDestroy(() => sub.unsubscribe()); } } public resolve(): Observable | null { - if (typeof this.extend === 'function') { - if (this._extended !== true) { - if (isObservable(this._extended)) { - return this._extended; - } - return (this._extended = this.extend().pipe( - tap((res: { [lang: string]: Dictionary }) => { - for (let lang in res) { - this.service.extendDictionary(lang, res[lang]); - } - }), - finalize(() => { - this._extended = true; - }) - )); - } + if (typeof this.extend !== 'function') { + return null; + } + + const lang = this.service.lang ?? ''; + const extended = this._extended.get(lang); + if (extended === true) { + return null; + } + if (extended) { + return extended; } - return null; + + const load$ = this.extend().pipe( + tap({ + next: (res) => extendAll(this.service, res), + complete: () => this._extended.set(lang, true), + // forget the failed attempt so the next navigation retries it + error: () => this._extended.delete(lang), + }), + shareReplay({ bufferSize: 1, refCount: false }), + ); + this._extended.set(lang, load$); + return load$; } } + +/** + * Route resolver that awaits the dictionaries declared by `provideTranslateChild()`. + * Resolves immediately when the scope has no loader. + * + * ```ts + * { path: 'orders', providers: [provideTranslateChild({ id: 'orders', loadDictionaries })], resolve: { translate: translateChildResolver } } + * ``` + */ +export const translateChildResolver = (): Observable => inject(TranslateResolve).resolve() ?? of(null); diff --git a/projects/translate/src/translate/translate.service.ts b/projects/translate/src/translate/translate.service.ts index 05b3f8e..874a692 100644 --- a/projects/translate/src/translate/translate.service.ts +++ b/projects/translate/src/translate/translate.service.ts @@ -208,10 +208,18 @@ export class TranslateRootService implements TranslateServiceBase { } } +/** Dictionaries returned by a loader, in any shape the initializer or resolver can unwrap. */ +export type LoadedDictionaries = Dictionaries | Promise | Observable; + export interface TranslateChildConfig { id?: string; dictionaries?: Dictionaries; + /** Called inside an injection context, so dependencies are taken with `inject()`. */ loadDictionaries?: (opts: { lang: string; fallbackLang: string }, ...deps: any[]) => Observable; + /** + * @deprecated No longer read. Take dependencies with `inject()` inside `loadDictionaries`, + * or pass `deps` to `TranslateModule.forChild()`. + */ deps?: any[]; } @@ -303,7 +311,9 @@ export class TranslateService implements TranslateServiceBase { _key = [this._id, ...key]; } - if (this._root['_service'].dictionaries[this.lang][this._id] !== undefined) { + // no dictionary for the current language (not set, or not loaded yet) means no scope entries either + const dictionary = this.lang ? this._root['_service'].dictionaries[this.lang] : undefined; + if (dictionary?.[this._id] !== undefined) { if (this._root.hasTranslation(_key)) { return _key; } else { diff --git a/projects/translate/src/translate/translate.utils.ts b/projects/translate/src/translate/translate.utils.ts new file mode 100644 index 0000000..d828ea1 --- /dev/null +++ b/projects/translate/src/translate/translate.utils.ts @@ -0,0 +1,31 @@ +import { defaultIfEmpty, from, isObservable, Observable, of, take } from 'rxjs'; +import { Dictionaries } from 'simply-translate'; +import { LoadedDictionaries, TranslateServiceBase } from './translate.service'; + +/** Normalizes whatever a loader returned into an observable of dictionaries. */ +export function asDictionaries$(loaded: LoadedDictionaries): Observable { + if (isObservable(loaded)) { + return loaded; + } + if (loaded instanceof Promise) { + return from(loaded); + } + return of(loaded ?? {}); +} + +/** + * The first dictionaries a loader produces, or `{}` when it completes without any. + * Keeps one misbehaving loader from blocking or repeating its caller: a loader that + * never completes after emitting, emits twice, or emits nothing (`catchError(() => EMPTY)`). + */ +export function firstDictionaries$(loaded: LoadedDictionaries): Observable { + return asDictionaries$(loaded).pipe(take(1), defaultIfEmpty({} as Dictionaries)); +} + +/** Merges every language of `dictionaries` into the service. */ +export function extendAll(service: TranslateServiceBase, dictionaries: Dictionaries | undefined) { + if (!dictionaries) { + return; + } + Object.keys(dictionaries).forEach((lang) => service.extendDictionary(lang, dictionaries[lang])); +} diff --git a/projects/translate/tsconfig.lib.json b/projects/translate/tsconfig.lib.json index 099261b..b65aa8e 100644 --- a/projects/translate/tsconfig.lib.json +++ b/projects/translate/tsconfig.lib.json @@ -3,7 +3,7 @@ "compilerOptions": { "outDir": "../../out-tsc/lib", "module": "es2015", - "moduleResolution": "node", + "moduleResolution": "bundler", "declaration": true, "sourceMap": true, "inlineSources": true, diff --git a/src/_translate.imports.ts b/src/_translate.imports.ts index 263e13a..9852e12 100644 --- a/src/_translate.imports.ts +++ b/src/_translate.imports.ts @@ -1,3 +1,6 @@ -//export { TranslateModule,TranslateResolve } from 'simply-translate-angular'; -export { TranslateModule, TranslateResolve, TranslateService, TranslateRootService } from 'projects/translate/src/public_api'; -export { Dictionary, Dictionaries } from 'simply-translate'; +// In a real application this is simply: +// export * from 'simply-translate-angular'; +// It must resolve to the same copy simply-translate-angular-proxy imports (dist/translate, see tsconfig paths): +// pointing at projects/translate/src instead creates a second TranslateService class, and the proxies +// fail with "No provider for TranslateService". Run `npm run build:translate` after changing the library. +export * from 'simply-translate-angular'; diff --git a/src/app/another-dynamic/dynamic.component.ts b/src/app/another-dynamic/dynamic.component.ts index 9757c6f..ae5e436 100644 --- a/src/app/another-dynamic/dynamic.component.ts +++ b/src/app/another-dynamic/dynamic.component.ts @@ -1,5 +1,9 @@ import { Component } from '@angular/core'; +import { RouterLink } from '@angular/router'; +import { TRANSLATE_IMPORTS } from 'src/_translate.imports'; @Component({ + standalone: true, + imports: [TRANSLATE_IMPORTS, RouterLink], styles: [ ` :host { diff --git a/src/app/another-dynamic/dynamic.module.ts b/src/app/another-dynamic/dynamic.module.ts deleted file mode 100644 index a86299e..0000000 --- a/src/app/another-dynamic/dynamic.module.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { NgModule } from '@angular/core'; -import { CommonModule } from '@angular/common'; -import { DynamicComponent } from './dynamic.component'; -import { AnotherDynamicRoutingModule } from './dynamic.routing'; -import { Dictionary } from 'simply-translate'; -import { HttpClient } from '@angular/common/http'; -import { forkJoin, map } from 'rxjs'; -import { OtherDynamicComponent } from './other-dynamic.component'; -import { TranslateModule } from 'src/_translate.imports'; - -function getDictionary(lang: string, client: HttpClient) { - return client.get(`/assets/translations/${lang}.other-dynamic.json`); -} - -@NgModule({ - declarations: [DynamicComponent, OtherDynamicComponent], - imports: [ - TranslateModule.forChild({ - id: 'another_dynamic', - deps: [HttpClient], - loadDictionaries: ({ lang }, client: HttpClient) => { - return forkJoin([getDictionary(lang, client), getDictionary('ru-RU', client)]).pipe( - map((res) => { - return { [lang]: { ...res[0], same_key: 'Same in another Dynamic' }, ['ru-RU']: res[1] }; - }) - ); - }, - }), - CommonModule, - AnotherDynamicRoutingModule, - ], - exports: [DynamicComponent], -}) -export class AnotherDynamicModule {} diff --git a/src/app/another-dynamic/dynamic.routes.ts b/src/app/another-dynamic/dynamic.routes.ts new file mode 100644 index 0000000..ead925c --- /dev/null +++ b/src/app/another-dynamic/dynamic.routes.ts @@ -0,0 +1,30 @@ +import { HttpClient } from '@angular/common/http'; +import { inject } from '@angular/core'; +import { Routes } from '@angular/router'; +import { forkJoin, map } from 'rxjs'; +import { Dictionary, withTranslateChild } from 'src/_translate.imports'; +import { DynamicComponent } from './dynamic.component'; +import { OtherDynamicComponent } from './other-dynamic.component'; + +function getDictionary(lang: string, client: HttpClient) { + return client.get(`/assets/translations/${lang}.other-dynamic.json`); +} + +export const routes: Routes = [ + { + path: '', + ...withTranslateChild({ + id: 'another_dynamic', + loadDictionaries: ({ lang }) => { + const client = inject(HttpClient); + return forkJoin([getDictionary(lang!, client), getDictionary('ru-RU', client)]).pipe( + map(([current, fallback]) => ({ [lang!]: { ...current, same_key: 'Same in another Dynamic' }, 'ru-RU': fallback })), + ); + }, + }), + children: [ + { path: '', component: DynamicComponent }, + { path: 'other', component: OtherDynamicComponent }, + ], + }, +]; diff --git a/src/app/another-dynamic/dynamic.routing.ts b/src/app/another-dynamic/dynamic.routing.ts deleted file mode 100644 index b89abf6..0000000 --- a/src/app/another-dynamic/dynamic.routing.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { NgModule } from '@angular/core'; -import { RouterModule, Routes } from '@angular/router'; -import { TranslateResolve } from 'src/_translate.imports'; -import { DynamicComponent } from './dynamic.component'; -import { OtherDynamicComponent } from './other-dynamic.component'; - -const routes: Routes = [ - { path: '', component: DynamicComponent, resolve: { resolve: TranslateResolve } }, - { path: 'other', component: OtherDynamicComponent, resolve: { resolve: TranslateResolve } }, - // {path:'dynamic', loadChildren:'app/dynamic/dynamic.module#DynamicModule'} -]; - -@NgModule({ - imports: [RouterModule.forChild(routes)], - exports: [RouterModule], -}) -export class AnotherDynamicRoutingModule {} diff --git a/src/app/another-dynamic/other-dynamic.component.ts b/src/app/another-dynamic/other-dynamic.component.ts index 7be1288..7acf0d0 100644 --- a/src/app/another-dynamic/other-dynamic.component.ts +++ b/src/app/another-dynamic/other-dynamic.component.ts @@ -1,5 +1,8 @@ import { Component } from '@angular/core'; +import { TRANSLATE_IMPORTS } from 'src/_translate.imports'; @Component({ + standalone: true, + imports: [TRANSLATE_IMPORTS], selector: 'app-dynamic', template: `

{{ 'hello_user_dynamic' | translateTo: 'ru-RU': { user: 'Basil' } }}

diff --git a/src/app/app.component.ts b/src/app/app.component.ts index 6cb60c0..d81c349 100644 --- a/src/app/app.component.ts +++ b/src/app/app.component.ts @@ -1,7 +1,10 @@ import { Component, ViewEncapsulation } from '@angular/core'; -import { FormControl } from '@angular/forms'; -import { Router } from '@angular/router'; +import { FormControl, ReactiveFormsModule } from '@angular/forms'; +import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router'; +import { TRANSLATE_IMPORTS } from 'src/_translate.imports'; @Component({ + standalone: true, + imports: [TRANSLATE_IMPORTS, ReactiveFormsModule, RouterOutlet, RouterLink, RouterLinkActive], selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'], diff --git a/src/app/app.config.ts b/src/app/app.config.ts new file mode 100644 index 0000000..777426b --- /dev/null +++ b/src/app/app.config.ts @@ -0,0 +1,44 @@ +import { HttpClient, provideHttpClient } from '@angular/common/http'; +import { ApplicationConfig, inject } from '@angular/core'; +import { provideRouter } from '@angular/router'; +import { forkJoin, map } from 'rxjs'; +import { Dictionary, provideTranslate, withLoader, withMiddleware } from 'src/_translate.imports'; +import { routes } from './app.routes'; +import { TranslateProxyMore, TranslateProxyOneMore } from './try-proxy/translate.proxy'; + +function getDictionary(lang: string, client: HttpClient) { + return client.get(`/assets/translations/${lang}.json`); +} + +export const appConfig: ApplicationConfig = { + providers: [ + provideHttpClient(), + provideRouter(routes), + + provideTranslate( + { + lang: 'en-US', + fallbackLang: 'en-US', + }, + + withMiddleware(() => [ + ({ params, result }) => { + if (result.fallingBack) { + console.warn('falling back:', `${params.key.toString()}, [${params.lang}]`); + } + }, + ]), + + // dependencies come from inject(), there is no deps array any more + withLoader(({ lang }) => { + const client = inject(HttpClient); + return forkJoin([getDictionary(lang!, client), getDictionary('ru-RU', client)]).pipe( + map(([current, fallback]) => ({ [lang!]: current, 'ru-RU': fallback })), + ); + }), + ), + + TranslateProxyMore, + TranslateProxyOneMore, + ], +}; diff --git a/src/app/app.module.ts b/src/app/app.module.ts deleted file mode 100644 index 1770df7..0000000 --- a/src/app/app.module.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { BrowserModule } from '@angular/platform-browser'; -import { effect, NgModule } from '@angular/core'; -import { AppComponent } from './app.component'; -import { MoreModule } from './more/more.module'; -import { AppRoutingModule } from './app.routing'; -import { AppTranslateComponent } from './translate.component'; -import { SwitchLangComponent } from './switch-lang/switch-lang.component'; -import { TryDirectiveComponent } from './try-directive/try-directive.component'; -import { map } from 'rxjs/operators'; -import { HttpClient, HttpClientModule } from '@angular/common/http'; -import { Dictionary, TranslateModule } from 'src/_translate.imports'; -import { FormsModule, ReactiveFormsModule } from '@angular/forms'; -import { forkJoin } from 'rxjs'; -import { ComponentsModule } from './components/components.module'; -import { TryProxyComponent } from './try-proxy/try-proxy.component'; -import { TranslateProxyMore, TranslateProxyOneMore } from './try-proxy/translate.proxy'; - -function getDictionary(lang: string, client: HttpClient) { - return client.get(`/assets/translations/${lang}.json`); -} - -@NgModule({ - declarations: [AppComponent, AppTranslateComponent, SwitchLangComponent, TryDirectiveComponent, TryProxyComponent], - imports: [ - HttpClientModule, - BrowserModule, - FormsModule, - ReactiveFormsModule, - ComponentsModule, - TranslateModule.forRoot({ - deps: [HttpClient], - - lang: 'en-US', - fallbackLang: 'en-US', - - addMiddleware: (client: HttpClient) => { - return [ - ({ params, result }) => { - if (result.fallingBack) { - console.warn('falling back:', `${params.key.toString()}, [${params.lang}]`); - } - }, - ]; - }, - - loadDictionaries: ({ lang, fallbackLang }, client: HttpClient) => { - return forkJoin([getDictionary(lang, client), getDictionary('ru-RU', client)]).pipe( - map(([current, fallback]) => { - return { [lang]: current, 'ru-RU': fallback }; - }), - ); - }, - }), - AppRoutingModule, - MoreModule, - ], - providers: [TranslateProxyMore, TranslateProxyOneMore], - exports: [], - bootstrap: [AppComponent], -}) -export class AppModule { - constructor() { - // this.translate.object.namespace.hello_user.$().subscribe(); - - // this.translate.object.i_have_been_here_count.$({ count: 10 }).subscribe((res) => { - // console.log('Translate', res); - // }); - - // effect(() => { - // console.log('Signal', this.a()); - // }); - } -} diff --git a/src/app/app.routes.ts b/src/app/app.routes.ts new file mode 100644 index 0000000..68eb394 --- /dev/null +++ b/src/app/app.routes.ts @@ -0,0 +1,18 @@ +import { Routes } from '@angular/router'; +import { TranslateToComponent } from './components/translate-to.component'; +import { TryDateComponent } from './components/try-date.component'; +import { SwitchLangComponent } from './switch-lang/switch-lang.component'; +import { AppTranslateComponent } from './translate.component'; +import { TryDirectiveComponent } from './try-directive/try-directive.component'; +import { TryProxyComponent } from './try-proxy/try-proxy.component'; + +export const routes: Routes = [ + { path: 'translate', component: AppTranslateComponent }, + { path: 'translate-to', component: TranslateToComponent }, + { path: 'try-date', component: TryDateComponent }, + { path: 'switch-lang', component: SwitchLangComponent }, + { path: 'try-directive', component: TryDirectiveComponent }, + { path: 'try-proxy', component: TryProxyComponent }, + { path: 'dynamic', loadChildren: () => import('./dynamic/dynamic.routes').then((m) => m.routes) }, + { path: 'another-dynamic', loadChildren: () => import('./another-dynamic/dynamic.routes').then((m) => m.routes) }, +]; diff --git a/src/app/app.routing.ts b/src/app/app.routing.ts deleted file mode 100644 index 2a30e1d..0000000 --- a/src/app/app.routing.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { NgModule } from '@angular/core'; -import { RouterModule, Routes } from '@angular/router'; -import { AppTranslateComponent } from './translate.component'; -import { SwitchLangComponent } from './switch-lang/switch-lang.component'; -import { TryDirectiveComponent } from './try-directive/try-directive.component'; -import { TryProxyComponent } from './try-proxy/try-proxy.component'; - -const routes: Routes = [ - { path: 'translate', component: AppTranslateComponent }, - { path: 'switch-lang', component: SwitchLangComponent }, - { path: 'try-directive', component: TryDirectiveComponent }, - { path: 'try-proxy', component: TryProxyComponent }, - { path: 'dynamic', loadChildren: ()=>import('./dynamic/dynamic.module').then((m) => m.DynamicModule) }, - { path: 'another-dynamic', loadChildren: ()=>import('./another-dynamic/dynamic.module').then((m) => m.AnotherDynamicModule) }, - // {path:'dynamic', loadChildren:'app/dynamic/dynamic.module#DynamicModule'} -]; - -@NgModule({ - imports: [RouterModule.forRoot(routes)], - exports: [RouterModule], -}) -export class AppRoutingModule {} diff --git a/src/app/app.spec.ts b/src/app/app.spec.ts new file mode 100644 index 0000000..f7a884b --- /dev/null +++ b/src/app/app.spec.ts @@ -0,0 +1,102 @@ +import { provideHttpClientTesting, HttpTestingController } from '@angular/common/http/testing'; +import { ApplicationInitStatus } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { RouterTestingHarness } from '@angular/router/testing'; +import { TranslateRootService } from 'src/_translate.imports'; +import { appConfig } from './app.config'; +import { DynamicComponent } from './dynamic/dynamic.component'; +import { DynamicComponent as AnotherDynamicComponent } from './another-dynamic/dynamic.component'; +import { TranslateProxyMore } from './try-proxy/translate.proxy'; + +import enUS from '../assets/translations/en-US.json'; +import ruRU from '../assets/translations/ru-RU.json'; +import enUSDynamic from '../assets/translations/en-US.dynamic.json'; +import ruRUDynamic from '../assets/translations/ru-RU.dynamic.json'; +import enUSOther from '../assets/translations/en-US.other-dynamic.json'; +import ruRUOther from '../assets/translations/ru-RU.other-dynamic.json'; + +const ROOT_DICTIONARIES: Record = { + '/assets/translations/en-US.json': enUS, + '/assets/translations/ru-RU.json': ruRU, + '/assets/translations/en-US.dynamic.json': enUSDynamic, + '/assets/translations/ru-RU.dynamic.json': ruRUDynamic, + '/assets/translations/en-US.other-dynamic.json': enUSOther, + '/assets/translations/ru-RU.other-dynamic.json': ruRUOther, +}; + +describe('demo application wiring', () => { + let http: HttpTestingController; + let harness: RouterTestingHarness; + + /** Answers every dictionary request the application has made so far. */ + function flushDictionaries() { + http.match(() => true).forEach((request) => { + const body = ROOT_DICTIONARIES[request.request.url]; + expect(body).withContext(`unexpected request ${request.request.url}`).toBeDefined(); + request.flush(body); + }); + } + + /** + * Navigates and keeps answering dictionary requests until the navigation settles — + * the lazy chunk, the child providers and the resolver each take a turn of their own. + */ + async function navigate(url: string, component: new (...args: any[]) => T): Promise { + let settled = false; + const navigation = harness.navigateByUrl(url, component).then((instance) => ((settled = true), instance)); + + for (let i = 0; i < 50 && !settled; i++) { + await new Promise((resolve) => setTimeout(resolve, 0)); + flushDictionaries(); + } + + return navigation; + } + + beforeEach(async () => { + TestBed.configureTestingModule({ + providers: [...appConfig.providers, provideHttpClientTesting()], + }); + + // injecting creates the test module, which runs the APP_INITIALIZER + http = TestBed.inject(HttpTestingController); + flushDictionaries(); + await TestBed.inject(ApplicationInitStatus).donePromise; + + harness = await RouterTestingHarness.create(); + }); + + afterEach(() => http.verify()); + + it('loads the root dictionaries during initialization', () => { + expect(TestBed.inject(TranslateRootService).translate('welcome_to_app')).toBe('Welcome to Translation Testing Application'); + expect(TestBed.inject(TranslateRootService).translate('same_key')).toBe('Same in the Root'); + }); + + it('gives the proxies the TranslateService that provideTranslate() registered', () => { + // fails with NullInjectorError when the demo and the proxy package load different copies of the library + expect(() => TestBed.inject(TranslateProxyMore)).not.toThrow(); + http.match((request) => request.url.startsWith('/assets/translations/proxy/')).forEach((request) => request.flush({})); + }); + + it('scopes the lazy "dynamic" route to its own dictionary', async () => { + await navigate('/dynamic', DynamicComponent); + harness.detectChanges(); + + const text = harness.routeNativeElement!.textContent!; + expect(text).toContain('Same in the Dynamic'); + expect(text).toContain('Same Dic'); + // keys the scope does not define still come from the root + expect(text).toContain('Only in the Root'); + }); + + it('scopes the lazy "another-dynamic" route to its own dictionary', async () => { + await navigate('/another-dynamic', AnotherDynamicComponent); + harness.detectChanges(); + + const text = harness.routeNativeElement!.textContent!; + expect(text).toContain('Same in another Dynamic'); + expect(text).toContain('Same other Dic'); + expect(text).toContain('Only in the Root'); + }); +}); diff --git a/src/app/components/components.module.ts b/src/app/components/components.module.ts deleted file mode 100644 index 58af77c..0000000 --- a/src/app/components/components.module.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { NgModule } from '@angular/core'; -import { CommonModule } from '@angular/common'; -import { VisitsComponent } from './visits/visits.component'; -import { TranslateModule } from 'src/_translate.imports'; -import { TranslateToComponent } from './translate-to.component'; -import { TryDateComponent } from './try-date.component'; -import { RouterModule } from '@angular/router'; -import { FormsModule, ReactiveFormsModule } from '@angular/forms'; - -@NgModule({ - declarations: [VisitsComponent, TranslateToComponent, TryDateComponent], - imports: [CommonModule, TranslateModule, RouterModule, FormsModule,ReactiveFormsModule], - exports: [VisitsComponent, TranslateToComponent, TryDateComponent], -}) -export class ComponentsModule {} diff --git a/src/app/components/translate-to.component.ts b/src/app/components/translate-to.component.ts index 991c6f4..edf1645 100644 --- a/src/app/components/translate-to.component.ts +++ b/src/app/components/translate-to.component.ts @@ -1,8 +1,12 @@ import { ChangeDetectorRef, Component } from '@angular/core'; -import { ActivatedRoute, Router } from '@angular/router'; +import { ActivatedRoute } from '@angular/router'; import { Subscription } from 'rxjs'; +import { TRANSLATE_IMPORTS } from 'src/_translate.imports'; +import { VisitsComponent } from './visits/visits.component'; @Component({ + standalone: true, + imports: [TRANSLATE_IMPORTS, VisitsComponent], selector: 'translate-to', templateUrl: './translate-to.component.html', }) diff --git a/src/app/components/try-date.component.ts b/src/app/components/try-date.component.ts index 6578fe6..263f917 100644 --- a/src/app/components/try-date.component.ts +++ b/src/app/components/try-date.component.ts @@ -1,8 +1,10 @@ import { Component, OnInit } from '@angular/core'; -import { ActivatedRoute, Router } from '@angular/router'; -import { Subscription } from 'rxjs'; +import { FormsModule } from '@angular/forms'; +import { TRANSLATE_IMPORTS } from 'src/_translate.imports'; @Component({ + standalone: true, + imports: [TRANSLATE_IMPORTS, FormsModule], selector: 'app-more', template: `
diff --git a/src/app/components/visits/visits.component.ts b/src/app/components/visits/visits.component.ts index 1bd2e6d..f72a0d6 100644 --- a/src/app/components/visits/visits.component.ts +++ b/src/app/components/visits/visits.component.ts @@ -1,9 +1,13 @@ +import { NgIf } from '@angular/common'; import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Input, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { Subscription } from 'rxjs'; +import { TRANSLATE_IMPORTS } from 'src/_translate.imports'; import { StorageService } from '../../storage.service'; @Component({ + standalone: true, + imports: [TRANSLATE_IMPORTS, NgIf], selector: 'app-visits', template: `
diff --git a/src/app/dynamic/dynamic.component.ts b/src/app/dynamic/dynamic.component.ts index fdd0020..6724e80 100644 --- a/src/app/dynamic/dynamic.component.ts +++ b/src/app/dynamic/dynamic.component.ts @@ -1,5 +1,9 @@ import { Component } from '@angular/core'; +import { RouterLink } from '@angular/router'; +import { TRANSLATE_IMPORTS } from 'src/_translate.imports'; @Component({ + standalone: true, + imports: [TRANSLATE_IMPORTS, RouterLink], styles: [ ` :host { diff --git a/src/app/dynamic/dynamic.module.ts b/src/app/dynamic/dynamic.module.ts deleted file mode 100644 index 6a8eda7..0000000 --- a/src/app/dynamic/dynamic.module.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { NgModule } from '@angular/core'; -import { CommonModule } from '@angular/common'; -import { DynamicComponent } from './dynamic.component'; -import { DynamicRoutingModule } from './dynamic.routing'; -import { Dictionary } from 'simply-translate'; -import { HttpClient } from '@angular/common/http'; -import { forkJoin, map } from 'rxjs'; -import { OtherDynamicComponent } from './other-dynamic.component'; -import { TranslateModule } from 'src/_translate.imports'; - -export function getDictionary(lang: string, client: HttpClient) { - return client.get(`/assets/translations/${lang}.dynamic.json`); -} - -@NgModule({ - declarations: [DynamicComponent, OtherDynamicComponent], - imports: [ - TranslateModule.forChild({ - id: 'dynamic', - deps: [HttpClient], - dictionaries: { - 'en-US': { - same_key: 'Same in the Dynamic', - }, - }, - loadDictionaries: ({ lang, fallbackLang }, client: HttpClient) => { - return forkJoin([getDictionary(lang, client), getDictionary('ru-RU', client)]).pipe( - map((res) => { - return { [lang]: res[0], 'ru-RU': res[1] }; - }) - ); - }, - // final: (service, client: HttpClient) => { - // service.lang.subscribe((lang) => { - // debugger; - // }); - // }, - }), - CommonModule, - DynamicRoutingModule, - ], - exports: [DynamicComponent], -}) -export class DynamicModule {} diff --git a/src/app/dynamic/dynamic.routes.ts b/src/app/dynamic/dynamic.routes.ts new file mode 100644 index 0000000..ceed6dc --- /dev/null +++ b/src/app/dynamic/dynamic.routes.ts @@ -0,0 +1,36 @@ +import { HttpClient } from '@angular/common/http'; +import { inject } from '@angular/core'; +import { Routes } from '@angular/router'; +import { forkJoin, map } from 'rxjs'; +import { Dictionary, withTranslateChild } from 'src/_translate.imports'; +import { DynamicComponent } from './dynamic.component'; +import { OtherDynamicComponent } from './other-dynamic.component'; + +export function getDictionary(lang: string, client: HttpClient) { + return client.get(`/assets/translations/${lang}.dynamic.json`); +} + +export const routes: Routes = [ + { + path: '', + // scope providers + the resolver that waits for them, for this route and its children + ...withTranslateChild({ + id: 'dynamic', + dictionaries: { + 'en-US': { + same_key: 'Same in the Dynamic', + }, + }, + loadDictionaries: ({ lang }) => { + const client = inject(HttpClient); + return forkJoin([getDictionary(lang!, client), getDictionary('ru-RU', client)]).pipe( + map(([current, fallback]) => ({ [lang!]: current, 'ru-RU': fallback })), + ); + }, + }), + children: [ + { path: '', component: DynamicComponent }, + { path: 'other', component: OtherDynamicComponent }, + ], + }, +]; diff --git a/src/app/dynamic/dynamic.routing.ts b/src/app/dynamic/dynamic.routing.ts deleted file mode 100644 index d882727..0000000 --- a/src/app/dynamic/dynamic.routing.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { NgModule } from '@angular/core'; -import { RouterModule, Routes } from '@angular/router'; -import { TranslateResolve } from 'src/_translate.imports'; -import { DynamicComponent } from './dynamic.component'; -import { OtherDynamicComponent } from './other-dynamic.component'; - -const routes: Routes = [ - { path: '', component: DynamicComponent, resolve: { resolve: TranslateResolve } }, - { path: 'other', component: OtherDynamicComponent, resolve: { resolve: TranslateResolve } }, - // {path:'dynamic', loadChildren:'app/dynamic/dynamic.module#DynamicModule'} -]; - -@NgModule({ - imports: [RouterModule.forChild(routes)], - exports: [RouterModule], -}) -export class DynamicRoutingModule {} diff --git a/src/app/dynamic/other-dynamic.component.ts b/src/app/dynamic/other-dynamic.component.ts index 7be1288..7acf0d0 100644 --- a/src/app/dynamic/other-dynamic.component.ts +++ b/src/app/dynamic/other-dynamic.component.ts @@ -1,5 +1,8 @@ import { Component } from '@angular/core'; +import { TRANSLATE_IMPORTS } from 'src/_translate.imports'; @Component({ + standalone: true, + imports: [TRANSLATE_IMPORTS], selector: 'app-dynamic', template: `

{{ 'hello_user_dynamic' | translateTo: 'ru-RU': { user: 'Basil' } }}

diff --git a/src/app/more/more.module.ts b/src/app/more/more.module.ts deleted file mode 100644 index 12f977b..0000000 --- a/src/app/more/more.module.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { BrowserModule } from '@angular/platform-browser'; -import { NgModule } from '@angular/core'; -import { FormsModule } from '@angular/forms'; -import { TitleDirective } from './title.directive'; -import { RouterModule } from '@angular/router'; -import { TranslateModule } from 'src/_translate.imports'; -import { ComponentsModule } from '../components/components.module'; -import { MoreRoutingModule } from './more.routing'; - -@NgModule({ - declarations: [TitleDirective], - imports: [ - MoreRoutingModule, - BrowserModule, - FormsModule, - ComponentsModule, - TranslateModule, - ], - exports: [], - providers: [ - // { - // provide: APP_INITIALIZER, - // useFactory: (service: TranslationService) => { - // service.defaultLang = 'en-US'; - // service.appendDictionary('en-US', { - // hello_user2: 'Hello to you {user}', - // }); - // return () => Promise.resolve(); - // }, - // deps: [TranslationService], - // multi: true, - // }, - // { provide: TranslationService, useFactory: () => new TranslationService({}), multi:false }, - // TranslationService - ], -}) -export class MoreModule {} diff --git a/src/app/more/more.routing.ts b/src/app/more/more.routing.ts deleted file mode 100644 index b32d318..0000000 --- a/src/app/more/more.routing.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { NgModule } from '@angular/core'; -import { RouterModule, Routes } from '@angular/router'; -import { TranslateToComponent } from '../components/translate-to.component'; -import { TryDateComponent } from '../components/try-date.component'; - -const routes: Routes = [ - { path: 'translate-to', component: TranslateToComponent }, - { path: 'try-date', component: TryDateComponent }, -]; - -@NgModule({ - imports: [RouterModule.forChild(routes)], - exports: [RouterModule], -}) -export class MoreRoutingModule {} diff --git a/src/app/more/title.directive.ts b/src/app/more/title.directive.ts index a9e9df4..b2db622 100644 --- a/src/app/more/title.directive.ts +++ b/src/app/more/title.directive.ts @@ -1,6 +1,7 @@ import { Directive, ElementRef, Input, OnChanges, SimpleChanges } from '@angular/core'; @Directive({ + standalone: true, selector: '[appTitle]', }) export class TitleDirective implements OnChanges { diff --git a/src/app/switch-lang/switch-lang.component.ts b/src/app/switch-lang/switch-lang.component.ts index ed82f8a..e3f8f9c 100644 --- a/src/app/switch-lang/switch-lang.component.ts +++ b/src/app/switch-lang/switch-lang.component.ts @@ -1,8 +1,12 @@ +import { AsyncPipe, NgFor } from '@angular/common'; import { Component } from '@angular/core'; +import { FormsModule } from '@angular/forms'; import { Observable } from 'rxjs'; -import { TranslateRootService, TranslateService } from 'src/_translate.imports'; +import { TRANSLATE_IMPORTS, TranslateRootService, TranslateService } from 'src/_translate.imports'; @Component({ + standalone: true, + imports: [TRANSLATE_IMPORTS, FormsModule, NgFor, AsyncPipe], selector: 'app-switch-lang', template: ` diff --git a/src/app/try-proxy/try-proxy.component.ts b/src/app/try-proxy/try-proxy.component.ts index 945d4a1..21c1857 100644 --- a/src/app/try-proxy/try-proxy.component.ts +++ b/src/app/try-proxy/try-proxy.component.ts @@ -1,8 +1,12 @@ +import { AsyncPipe, NgFor } from '@angular/common'; import { Component, computed, signal } from '@angular/core'; -import { TranslateRootService } from 'src/_translate.imports'; -import { TranslateProxyCommon, TranslateProxyMore, TranslateProxyOneMore } from './translate.proxy'; +import { FormsModule } from '@angular/forms'; +import { TRANSLATE_IMPORTS, TranslateRootService } from 'src/_translate.imports'; +import { TranslateProxyMore, TranslateProxyOneMore } from './translate.proxy'; @Component({ + standalone: true, + imports: [TRANSLATE_IMPORTS, FormsModule, NgFor, AsyncPipe], selector: 'app-try-proxy', template: `