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,