langsys-js-typescript 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,10 +1,40 @@
1
- ## 0.5.0 - 2026-08-10
1
+ ## 0.6.1 - 2026-08-15
2
+
3
+ ### Fixed
4
+
5
+ - **`data-langsys-phrase="false"` / `="0"` are now honored as opt-outs.** 0.6.0 taught the tokenizer to skip subtrees carrying `langsys-php`'s keep-together marker, but matched on attribute presence alone. PHP's `hasPhraseAttribute()` treats presence as intent *while letting an explicit off value opt out* — so we skipped subtrees the author had deliberately un-marked, leaving that content translated by neither SDK. Matching is now value-aware and case-insensitive, mirroring PHP exactly.
6
+
7
+ Found by reading `HtmlParser.php` rather than trusting a summary of it — the same second-hand-documentation error this class of bug keeps producing.
8
+
9
+ ## 0.6.0 - 2026-08-15
10
+
11
+ ### Fixed
12
+
13
+ - **`md5` now agrees with a standard UTF-8 MD5 for all input.** It packed UTF-16 code units straight into byte lanes, so it matched a real MD5 only for ASCII. Two consequences, both confirmed against the published 0.5.0 build:
14
+ - *Cross-SDK divergence (certain, universal).* Every non-ASCII content block received a different `custom_id` in the JS SDK than in `langsys-php`, which hashes UTF-8 bytes. Any project rendering the same block through both SDKs got two catalog entries for one block.
15
+ - *Self-collision (real, rare).* A character's high byte was OR-ed into the neighbouring byte lane, vanishing whenever that lane already carried those bits — so `"éa"` and `"ǩa"` hashed identically, as did `"Café"`/`"Cafǩ"` and `"Don’t"`/`"Don<0x19>t"`. Distinct content blocks could share one `custom_id`, letting one block's translations serve another's content. A 20,000-phrase scan of realistic copy found no collisions, so reaching one needs a specific pairing — but the failure mode is silent and wrong when it happens.
16
+
17
+ The message bit-length was also a code-unit count rather than a byte count, so astral characters (`😀`) mis-lengthed the message independently of the packing bug.
18
+
19
+ **Migration is automatic and lossless.** `Translate` now resolves a content block against the corrected id first and falls back to the legacy id when that misses, so blocks registered by an older SDK keep serving their existing translations instead of orphaning. The fallback is **lookup-only** — registration always uses the corrected id, so the legacy-keyed population can only shrink. **Pure-ASCII ids are byte-identical to before**, so only non-ASCII blocks are affected at all.
20
+
21
+ Found by the `langsys-skill` and `langsys-php` agents; the collision mechanism and the JSON-offset dependency below were established jointly with them.
22
+
23
+ ### Added
24
+
25
+ - **`md5Legacy(input)`** and **`generateLegacyCustomId(category, tokens)`** — the pre-0.6.0 hash, exported for migration tooling and cross-SDK reconciliation. Lookup-only; never register new content under these. Deprecated on arrival, to be removed once catalogs have been rebased.
26
+
27
+ ### Notes
28
+
29
+ - Collisions are a property of the **final hashed string**, not the phrase: `JSON.stringify` shifts every character's offset, so a pair that collides standalone may not collide once wrapped, and changing `category` moves every character into different lanes. Reason at the `generateCustomId` level, never at bare `md5()`.
30
+
31
+ ## 0.5.0 - 2026-08-14
2
32
 
3
33
  ### Changed (breaking, types only)
4
34
 
5
35
  - **`PhraseOptions.params` is now `Record<string, ParamPrimitive>`**, matching `TranslateOptions.params` and `t()`. It was `Record<string, unknown>`, which allowed values — objects, arrays, functions — that interpolation can only render as `[object Object]`. No runtime behavior changes; this is a compile-time narrowing that surfaces those calls as errors instead of silently rendering garbage. `Phrase.setParams()` now also accepts `undefined`, matching `Translate.setParams()`.
6
36
 
7
- **Impact:** code typing its params as `Record<string, unknown>` and passing it straight through no longer compiles — including all three framework bindings as of this release. The fix is one line at each call site: declare the params as `Record<string, ParamPrimitive>` (exported from the package root). Runtime is unaffected, so a wrapper that skips the type change still *works*; it just fails `tsc`.
37
+ **Impact — two distinct cases.** First, and most visible to application code: **passing an object or array as a param value no longer compiles** (`params={{ user: someObject }}`). That code was already broken at runtime — interpolation could only render it as `[object Object]` — so this converts a silent bug into a build error, but it does bite at build time. Second: code typing its params as `Record<string, unknown>` and forwarding it no longer compiles, which covered all three framework bindings; the fix there is one line per call site, declaring `Record<string, ParamPrimitive>` (exported from the package root). Usefully, that narrowed declaration compiles against 0.4.x *and* 0.5.0, so wrappers can land it independently of the version bump. Runtime is unaffected throughout — code that skips the type change still *works*, it just fails `tsc`.
8
38
 
9
39
  ### Added
10
40
 
@@ -12,13 +42,13 @@
12
42
  - Warning against building phrases with template literals (`` t(`Hello, ${name}!`) ``), which registers every runtime value as its own catalog phrase and pollutes the catalog shared across every Langsys SDK.
13
43
  - Params doc comments now name the `%name%` markup spelling alongside the canonical `{name}`, including Vue's `{{ name }}` case.
14
44
 
15
- ## 0.4.3 - 2026-07-08
45
+ ## 0.4.3 - 2026-08-08
16
46
 
17
47
  ### Fixed
18
48
 
19
49
  - **The params diagnostic no longer names the wrong framework.** 0.4.2's warning hardcoded "the framework compiler (Svelte/JSX)" and the `{key}` spelling, which misdiagnoses Vue users — Vue consumes `{{ key }}`, not single braces, so a Vue developer hitting the warning was pointed at a syntax their framework never touches. The message is now framework-neutral and names both brace spellings.
20
50
 
21
- ## 0.4.2 - 2026-07-08
51
+ ## 0.4.2 - 2026-08-08
22
52
 
23
53
  ### Added
24
54
 
@@ -64,7 +94,23 @@ Full CLDR compliance, matching the backend's CLDR migration. Everything rides on
64
94
 
65
95
  - `canonicalizeLocale(locale)` — exported BCP 47 canonicalizer, useful when seeding your own `UserLocaleStore`.
66
96
 
67
- ## 0.2.1 - 2026-06-11
97
+ ## 0.2.3 - 2026-07-01
98
+
99
+ > Reconstructed retroactively (2026-08-15) from git history — this release shipped without a changelog entry.
100
+
101
+ ### Fixed
102
+
103
+ - **`ready()` never settled on an SSR-seeded locale, hanging every content-block consumer.** The SSR handoff calls `markLoaded()` to prime the fetch cache so `change()` short-circuits, but `readyResolve()` lived only in `getTranslations()`. With no fetch ever firing, `Translate` and `Phrase` awaited `ready()` forever on the seeded locale and never rendered. Now resolved in `markLoaded()` — a seeded catalog counts as ready — and in the legacy `skipFetch` branch of `change()`, which had the same hole.
104
+
105
+ ## 0.2.2 - 2026-06-24
106
+
107
+ > Reconstructed retroactively (2026-08-15) from git history — this release shipped without a changelog entry.
108
+
109
+ ### Fixed
110
+
111
+ - **Switching back to the initial/SSR locale left the previous language on screen.** The init-time locale subscription recomputed `skipFetch` on every settle as `initialTranslationsLocale === locale && !!initialTranslations`. Since `initialTranslations` stays truthy for the whole session, every *return* to the initial locale skipped `change()`'s store updates, so the previous locale's catalog stayed active and the `t` signal never rebuilt. Replaced the persistent skip flag with `Translations.markLoaded()`, which primes the same `lastLoaded` cache `change()` consults: the first settle after the SSR handoff is still a cache hit with no redundant fetch, but switching back later flows through `change()` normally.
112
+
113
+ ## 0.2.1 - 2026-06-12
68
114
 
69
115
  ### Changed
70
116
 
@@ -74,6 +120,25 @@ Full CLDR compliance, matching the backend's CLDR migration. Everything rides on
74
120
  - Missing-phrase registration now chunks into batches of 200 to respect the `/translatable-items` per-request cap.
75
121
  - Added `LangsysAppAPI.createTranslatableItems()` as the single write entry point for both phrases and content blocks.
76
122
 
123
+ ## 0.2.0 - 2026-06-10
124
+
125
+ > Reconstructed retroactively (2026-08-15). This release shipped without a changelog entry, which is how the reversed `t()` signature survived in `CLAUDE.md` for four months — there was no release note to prompt the update. Details recovered from git history (`v0.1.0..v0.2.0`).
126
+
127
+ ### Changed (breaking)
128
+
129
+ - **`t()` argument order flipped to `t(phrase, category?, params?)`.** 0.1.0 shipped `t(category, phrase, params?)`; the phrase now comes first and the category is optional. Implemented via overloads that discriminate on the type at position 2 (string ⇒ category, object ⇒ params). This is the single most consequential API change in the package's history and the one most likely to be miswritten from memory: with a placeholder-free phrase, the old order still type-checks, silently registering the category as the phrase. Nothing catches it until someone reads the catalog.
130
+ - Narrowed `LocaleSource`; extracted the framework-agnostic content-block helpers (`generateCustomId`, `isContentBlockKnown`, `registerContentBlock`, `tokenizeElement`) so non-DOM wrappers can reuse registration without the DOM mutator.
131
+ - Missing phrases are sent with a null category on the wire rather than the `__uncategorized__` sentinel, which is server-internal and must not be sent by clients.
132
+
133
+ ### Added
134
+
135
+ - **`<Phrase>` and `<DontTranslate>`** — markup-sentinel rich-text handling, so a markup-bearing sentence stays one translatable phrase.
136
+ - **ICU MessageFormat** wired through `interpolate()`, with the SDK declaring ICU capability so the server sends raw ICU rather than pre-rendered text.
137
+
138
+ ### Fixed
139
+
140
+ - Content-block dedup unified, and a `custom_id` hash collision fixed. (Note: the deeper `md5` encoding defect behind that class of collision was not found until 0.6.0.)
141
+
77
142
  ## 0.1.0 - 2026-05-19
78
143
 
79
144
  Initial public release. Framework-agnostic TypeScript SDK for the Langsys Translation Manager — the foundation that `langsys-js-svelte` (and future framework-specific bindings) build on.
package/README.md CHANGED
@@ -241,11 +241,13 @@ new Phrase(el, { category: 'ProductCard', params: { n: reviewCount } });
241
241
  That registers as a single phrase — `Based on {n} {m0o}reviews{m0c}` — rather than `"Based on {n}"` and `"reviews"`. Three things depend on it:
242
242
 
243
243
  1. **Grammatical agreement.** The count and the noun it inflects must live in one phrase, or no ICU plural rule can select the right noun form. Russian has four plural categories, Arabic six, Polish four — split them apart and the output is confidently wrong, not merely awkward.
244
- 2. **Reordering.** The markup tokens are ordinary ICU placeholders, so a translator or model *places* them around the translated word: `{m0o}White{m0c} House` → `Casa {m0o}Blanca{m0c}`. Impossible once split at the tag boundary.
244
+ 2. **Reordering.** What you write as `<span>White</span> House` renders in Spanish as `Casa <span>Blanca</span>` — the emphasis follows the word it belongs to, across a word-order change. That works because the markup becomes ordinary ICU placeholders (`{m0o}White{m0c} House` → `Casa {m0o}Blanca{m0c}`), so a translator or model *places* them around the translated word rather than being stuck with the original order. Impossible once the sentence is split at the tag boundary.
245
245
  3. **Phrase-key stability.** Your real elements never reach the translator — they're replaced by neutral tokens and reconstituted at render. Framework scoped-CSS classes (`svelte-a1b2c3`) change every build; if they rode along in the phrase, the key would drift and silently re-translate everything.
246
246
 
247
247
  Use it standalone, or nested inside a `Translate` block to protect specific runs — the block tokenizer skips any subtree carrying `data-ls-phrase` (exported as `PHRASE_MARKER_ATTR`), letting the `Phrase` own it. `setParams()` re-renders on a changed count, same as `Translate`.
248
248
 
249
+ > **Who sets `data-ls-phrase`.** In the framework bindings it's internal — `<Phrase>` puts it on its own host element and you never write it yourself. In **vanilla usage it is yours to set**: the `Phrase` class does not add it, so a `Phrase` nested inside a `Translate` block needs the attribute present in your HTML *before* the wrapping `Translate` tokenizes, or the block will tokenize straight through the phrase and both will fight over the same nodes. Standalone `Phrase` doesn't need it at all. (Not to be confused with `langsys-php`'s `data-langsys-*` attributes, which are author-facing by design.)
250
+
249
251
  If a translation drops or unbalances a markup token, rendering degrades to plain text with the markers stripped — the meaning survives even when the markup doesn't.
250
252
 
251
253
  ## Server-Side Rendering
package/dist/index.d.mts CHANGED
@@ -612,6 +612,32 @@ interface iContentBlock {
612
612
  * and render via your framework's templating.
613
613
  */
614
614
 
615
+ /**
616
+ * Attributes that mark a subtree as a self-managed "keep-together" phrase,
617
+ * which the block tokenizer must skip rather than split at tag boundaries.
618
+ *
619
+ * Two spellings, because two SDKs mark the same thing:
620
+ * - `data-ls-phrase` — set by this SDK's framework `<Phrase>` components.
621
+ * - `data-langsys-phrase` — `langsys-php`'s author-facing marker, which
622
+ * survives into `translatePage()` output.
623
+ *
624
+ * The distinction is invisible in normal use, but on SSR handoff there is only
625
+ * ONE DOM: a page rendered by PHP and then hydrated by a JS SDK is walked by
626
+ * both implementations, so this tokenizer has to recognise PHP's marker or it
627
+ * re-tokenizes a subtree PHP deliberately kept whole. Recognising both is
628
+ * additive — `data-langsys-phrase` never appears in DOM our components emit.
629
+ */
630
+ declare const PHRASE_MARKER_ATTRS: readonly ["data-ls-phrase", "data-langsys-phrase"];
631
+ /**
632
+ * True when an element is marked as a self-managed phrase by either SDK.
633
+ *
634
+ * Presence alone means intent, like any boolean HTML attribute — but an
635
+ * explicit `="false"` or `="0"` opts OUT, matching `langsys-php`'s
636
+ * `hasPhraseAttribute()` exactly. Without the opt-out we would skip a subtree
637
+ * the author had deliberately un-marked, and it would then be translated by
638
+ * neither SDK.
639
+ */
640
+ declare function isPhraseMarked(element: Element): boolean;
615
641
  /**
616
642
  * Compute the deterministic content-block id from a `(category, tokens)` pair.
617
643
  *
@@ -624,6 +650,23 @@ interface iContentBlock {
624
650
  * whether to call `registerContentBlock`.
625
651
  */
626
652
  declare function generateCustomId(category: string, tokens: string[]): string;
653
+ /**
654
+ * The id this block would have had before the 0.6.0 MD5 fix.
655
+ *
656
+ * **Lookup only — never register under this.** Blocks registered by an older
657
+ * SDK are keyed by it, so `Translate` falls back to it when the corrected id
658
+ * misses, which keeps existing translations resolving instead of orphaning
659
+ * them. Registering under it would keep minting ids from a hash that both
660
+ * diverges across SDKs and can collide.
661
+ *
662
+ * Note the collision is a property of the FINAL hashed string, not the phrase:
663
+ * `JSON.stringify` shifts every character's offset, so the same phrase pair can
664
+ * collide standalone and not collide here — and changing `category` moves every
665
+ * character into different lanes. Always reason at this level, not at `md5()`.
666
+ *
667
+ * @deprecated Migration aid; will be removed once catalogs have been rebased.
668
+ */
669
+ declare function generateLegacyCustomId(category: string, tokens: string[]): string;
627
670
  /**
628
671
  * True iff the local translations cache already has the content block
629
672
  * for the given `(category, customId)` — meaning the backend knows about
@@ -684,7 +727,26 @@ declare const sTranslations: Signal<iCategories>;
684
727
  declare const currentlyLoadedLocale: Signal<string>;
685
728
 
686
729
  declare const isEmpty: (data: unknown) => boolean;
730
+ /**
731
+ * MD5 of a string, matching a standard UTF-8 MD5 for all input.
732
+ *
733
+ * Content-block `custom_id`s are derived from this, so it's a wire identity —
734
+ * see `generateCustomId`. Before 0.6.0 this packed UTF-16 code units directly
735
+ * into byte lanes, which agreed with a real MD5 only for ASCII: non-ASCII
736
+ * input both diverged from every other Langsys SDK and could collide (a
737
+ * character's high byte was OR-ed into the neighbouring lane, vanishing
738
+ * whenever that lane already carried those bits — so `éa` and `ǩa` hashed
739
+ * alike). `md5Legacy` preserves the old behavior for migration lookups only.
740
+ */
687
741
  declare function md5(inputString: string): string;
742
+ /**
743
+ * The pre-0.6.0 MD5, retained ONLY so existing content blocks stay resolvable:
744
+ * ids minted by an older SDK are keyed by this. Lookup-only — never register
745
+ * new content under it, or the colliding-id population keeps growing.
746
+ *
747
+ * @deprecated Migration aid; will be removed once catalogs have been rebased.
748
+ */
749
+ declare function md5Legacy(inputString: string): string;
688
750
 
689
751
  /**
690
752
  * Detects ICU MessageFormat syntax in a translation string.
@@ -791,4 +853,4 @@ interface iProject {
791
853
  declare const t: TFunction;
792
854
  declare const tSignal: Signal<TFunction>;
793
855
 
794
- export { type EncodedRichText, type ExtractParamKeys, LangsysApp, LangsysAppAPI, type LocaleSource, Logger, PHRASE_MARKER_ATTR, type ParamPrimitive, type ParamsFor, Phrase, type PhraseOptions, type RichSlot, type Signal, type Subscriber, type TArgs, type TFunction, Translate, type TranslateOptions, type TranslationParams, Translations, type Unsubscriber, type Updater, canonicalizeLocale, createSignal, currentlyLoadedLocale, encodeRichText, findUnusedParamKeys, generateCustomId, getValue, type iCategories, type iContentBlock, type iCountry, type iCountryDialCode, type iCountryList, type iCurrency, type iCurrencyList, type iLangsysConfig, type iLangsysInitConfig, type ResponseObject as iLangsysResponse, type iLanguageName, type iLocaleData, type iLocaleDefault, type iLocaleFlat, type iProject, type iTranslations, interpolate, isContentBlockKnown, isEmpty, isICU, logger, markupTokenValues, md5, normalizeMarkupPlaceholders, persist, reconstitute, registerContentBlock, sTranslations, stripSentinels, t, tSignal, tokenizeElement };
856
+ export { type EncodedRichText, type ExtractParamKeys, LangsysApp, LangsysAppAPI, type LocaleSource, Logger, PHRASE_MARKER_ATTR, PHRASE_MARKER_ATTRS, type ParamPrimitive, type ParamsFor, Phrase, type PhraseOptions, type RichSlot, type Signal, type Subscriber, type TArgs, type TFunction, Translate, type TranslateOptions, type TranslationParams, Translations, type Unsubscriber, type Updater, canonicalizeLocale, createSignal, currentlyLoadedLocale, encodeRichText, findUnusedParamKeys, generateCustomId, generateLegacyCustomId, getValue, type iCategories, type iContentBlock, type iCountry, type iCountryDialCode, type iCountryList, type iCurrency, type iCurrencyList, type iLangsysConfig, type iLangsysInitConfig, type ResponseObject as iLangsysResponse, type iLanguageName, type iLocaleData, type iLocaleDefault, type iLocaleFlat, type iProject, type iTranslations, interpolate, isContentBlockKnown, isEmpty, isICU, isPhraseMarked, logger, markupTokenValues, md5, md5Legacy, normalizeMarkupPlaceholders, persist, reconstitute, registerContentBlock, sTranslations, stripSentinels, t, tSignal, tokenizeElement };
package/dist/index.d.ts CHANGED
@@ -612,6 +612,32 @@ interface iContentBlock {
612
612
  * and render via your framework's templating.
613
613
  */
614
614
 
615
+ /**
616
+ * Attributes that mark a subtree as a self-managed "keep-together" phrase,
617
+ * which the block tokenizer must skip rather than split at tag boundaries.
618
+ *
619
+ * Two spellings, because two SDKs mark the same thing:
620
+ * - `data-ls-phrase` — set by this SDK's framework `<Phrase>` components.
621
+ * - `data-langsys-phrase` — `langsys-php`'s author-facing marker, which
622
+ * survives into `translatePage()` output.
623
+ *
624
+ * The distinction is invisible in normal use, but on SSR handoff there is only
625
+ * ONE DOM: a page rendered by PHP and then hydrated by a JS SDK is walked by
626
+ * both implementations, so this tokenizer has to recognise PHP's marker or it
627
+ * re-tokenizes a subtree PHP deliberately kept whole. Recognising both is
628
+ * additive — `data-langsys-phrase` never appears in DOM our components emit.
629
+ */
630
+ declare const PHRASE_MARKER_ATTRS: readonly ["data-ls-phrase", "data-langsys-phrase"];
631
+ /**
632
+ * True when an element is marked as a self-managed phrase by either SDK.
633
+ *
634
+ * Presence alone means intent, like any boolean HTML attribute — but an
635
+ * explicit `="false"` or `="0"` opts OUT, matching `langsys-php`'s
636
+ * `hasPhraseAttribute()` exactly. Without the opt-out we would skip a subtree
637
+ * the author had deliberately un-marked, and it would then be translated by
638
+ * neither SDK.
639
+ */
640
+ declare function isPhraseMarked(element: Element): boolean;
615
641
  /**
616
642
  * Compute the deterministic content-block id from a `(category, tokens)` pair.
617
643
  *
@@ -624,6 +650,23 @@ interface iContentBlock {
624
650
  * whether to call `registerContentBlock`.
625
651
  */
626
652
  declare function generateCustomId(category: string, tokens: string[]): string;
653
+ /**
654
+ * The id this block would have had before the 0.6.0 MD5 fix.
655
+ *
656
+ * **Lookup only — never register under this.** Blocks registered by an older
657
+ * SDK are keyed by it, so `Translate` falls back to it when the corrected id
658
+ * misses, which keeps existing translations resolving instead of orphaning
659
+ * them. Registering under it would keep minting ids from a hash that both
660
+ * diverges across SDKs and can collide.
661
+ *
662
+ * Note the collision is a property of the FINAL hashed string, not the phrase:
663
+ * `JSON.stringify` shifts every character's offset, so the same phrase pair can
664
+ * collide standalone and not collide here — and changing `category` moves every
665
+ * character into different lanes. Always reason at this level, not at `md5()`.
666
+ *
667
+ * @deprecated Migration aid; will be removed once catalogs have been rebased.
668
+ */
669
+ declare function generateLegacyCustomId(category: string, tokens: string[]): string;
627
670
  /**
628
671
  * True iff the local translations cache already has the content block
629
672
  * for the given `(category, customId)` — meaning the backend knows about
@@ -684,7 +727,26 @@ declare const sTranslations: Signal<iCategories>;
684
727
  declare const currentlyLoadedLocale: Signal<string>;
685
728
 
686
729
  declare const isEmpty: (data: unknown) => boolean;
730
+ /**
731
+ * MD5 of a string, matching a standard UTF-8 MD5 for all input.
732
+ *
733
+ * Content-block `custom_id`s are derived from this, so it's a wire identity —
734
+ * see `generateCustomId`. Before 0.6.0 this packed UTF-16 code units directly
735
+ * into byte lanes, which agreed with a real MD5 only for ASCII: non-ASCII
736
+ * input both diverged from every other Langsys SDK and could collide (a
737
+ * character's high byte was OR-ed into the neighbouring lane, vanishing
738
+ * whenever that lane already carried those bits — so `éa` and `ǩa` hashed
739
+ * alike). `md5Legacy` preserves the old behavior for migration lookups only.
740
+ */
687
741
  declare function md5(inputString: string): string;
742
+ /**
743
+ * The pre-0.6.0 MD5, retained ONLY so existing content blocks stay resolvable:
744
+ * ids minted by an older SDK are keyed by this. Lookup-only — never register
745
+ * new content under it, or the colliding-id population keeps growing.
746
+ *
747
+ * @deprecated Migration aid; will be removed once catalogs have been rebased.
748
+ */
749
+ declare function md5Legacy(inputString: string): string;
688
750
 
689
751
  /**
690
752
  * Detects ICU MessageFormat syntax in a translation string.
@@ -791,4 +853,4 @@ interface iProject {
791
853
  declare const t: TFunction;
792
854
  declare const tSignal: Signal<TFunction>;
793
855
 
794
- export { type EncodedRichText, type ExtractParamKeys, LangsysApp, LangsysAppAPI, type LocaleSource, Logger, PHRASE_MARKER_ATTR, type ParamPrimitive, type ParamsFor, Phrase, type PhraseOptions, type RichSlot, type Signal, type Subscriber, type TArgs, type TFunction, Translate, type TranslateOptions, type TranslationParams, Translations, type Unsubscriber, type Updater, canonicalizeLocale, createSignal, currentlyLoadedLocale, encodeRichText, findUnusedParamKeys, generateCustomId, getValue, type iCategories, type iContentBlock, type iCountry, type iCountryDialCode, type iCountryList, type iCurrency, type iCurrencyList, type iLangsysConfig, type iLangsysInitConfig, type ResponseObject as iLangsysResponse, type iLanguageName, type iLocaleData, type iLocaleDefault, type iLocaleFlat, type iProject, type iTranslations, interpolate, isContentBlockKnown, isEmpty, isICU, logger, markupTokenValues, md5, normalizeMarkupPlaceholders, persist, reconstitute, registerContentBlock, sTranslations, stripSentinels, t, tSignal, tokenizeElement };
856
+ export { type EncodedRichText, type ExtractParamKeys, LangsysApp, LangsysAppAPI, type LocaleSource, Logger, PHRASE_MARKER_ATTR, PHRASE_MARKER_ATTRS, type ParamPrimitive, type ParamsFor, Phrase, type PhraseOptions, type RichSlot, type Signal, type Subscriber, type TArgs, type TFunction, Translate, type TranslateOptions, type TranslationParams, Translations, type Unsubscriber, type Updater, canonicalizeLocale, createSignal, currentlyLoadedLocale, encodeRichText, findUnusedParamKeys, generateCustomId, generateLegacyCustomId, getValue, type iCategories, type iContentBlock, type iCountry, type iCountryDialCode, type iCountryList, type iCurrency, type iCurrencyList, type iLangsysConfig, type iLangsysInitConfig, type ResponseObject as iLangsysResponse, type iLanguageName, type iLocaleData, type iLocaleDefault, type iLocaleFlat, type iProject, type iTranslations, interpolate, isContentBlockKnown, isEmpty, isICU, isPhraseMarked, logger, markupTokenValues, md5, md5Legacy, normalizeMarkupPlaceholders, persist, reconstitute, registerContentBlock, sTranslations, stripSentinels, t, tSignal, tokenizeElement };
package/dist/index.js CHANGED
@@ -937,8 +937,23 @@ var isEmpty = (data) => {
937
937
  if (typeof data === "object") return Object.keys(data).length === 0;
938
938
  return false;
939
939
  };
940
+ function toUtf8ByteString(input) {
941
+ const bytes = new TextEncoder().encode(input);
942
+ let out = "";
943
+ for (let i = 0; i < bytes.length; i += 8192) {
944
+ out += String.fromCharCode(...bytes.subarray(i, i + 8192));
945
+ }
946
+ return out;
947
+ }
940
948
  function md5(inputString) {
941
949
  if (typeof inputString !== "string") inputString = JSON.stringify(inputString);
950
+ return md5Core(toUtf8ByteString(inputString));
951
+ }
952
+ function md5Legacy(inputString) {
953
+ if (typeof inputString !== "string") inputString = JSON.stringify(inputString);
954
+ return md5Core(inputString);
955
+ }
956
+ function md5Core(inputString) {
942
957
  const hc = "0123456789abcdef";
943
958
  function rh(n) {
944
959
  let j, s = "";
@@ -1070,6 +1085,14 @@ var TRANSLATABLE_ATTRIBUTES = [
1070
1085
  "data-required-message",
1071
1086
  "data-pattern-message"
1072
1087
  ];
1088
+ var PHRASE_MARKER_ATTRS = ["data-ls-phrase", "data-langsys-phrase"];
1089
+ function isPhraseMarked(element) {
1090
+ return PHRASE_MARKER_ATTRS.some((attr) => {
1091
+ if (!element.hasAttribute(attr)) return false;
1092
+ const value = (element.getAttribute(attr) ?? "").toLowerCase();
1093
+ return value !== "false" && value !== "0";
1094
+ });
1095
+ }
1073
1096
  var VALUE_TRANSLATABLE_ELEMENTS = ["button"];
1074
1097
  var VALUE_TRANSLATABLE_INPUT_TYPES = ["submit", "button"];
1075
1098
  var SEMANTIC_STYLE_PROPERTIES = [
@@ -1124,6 +1147,9 @@ var SEMANTIC_STYLE_PROPERTIES = [
1124
1147
  function generateCustomId(category, tokens) {
1125
1148
  return md5(JSON.stringify([category, tokens]));
1126
1149
  }
1150
+ function generateLegacyCustomId(category, tokens) {
1151
+ return md5Legacy(JSON.stringify([category, tokens]));
1152
+ }
1127
1153
  function isContentBlockKnown(category, customId) {
1128
1154
  const cats = sTranslations.get();
1129
1155
  const lookupCat = category || "__uncategorized__";
@@ -1183,7 +1209,7 @@ function _walkForTokens(liveRoot, cloneNodes, tokens, indices) {
1183
1209
  if (node.nodeType === Node.ELEMENT_NODE) {
1184
1210
  const el = node;
1185
1211
  if (el.getAttribute("translate") === "no") return;
1186
- if (el.hasAttribute("data-ls-phrase")) return;
1212
+ if (isPhraseMarked(el)) return;
1187
1213
  }
1188
1214
  if (node.hasChildNodes()) {
1189
1215
  _applyStylesToClone(liveRoot, node, [...indices, index]);
@@ -1333,7 +1359,8 @@ var Translate = class {
1333
1359
  return true;
1334
1360
  }
1335
1361
  async handleContentBlock(contentBlock) {
1336
- if (isEmpty(this.custom_id)) {
1362
+ const derivedId = isEmpty(this.custom_id);
1363
+ if (derivedId) {
1337
1364
  this.custom_id = generateCustomId(contentBlock.category, contentBlock.tokens);
1338
1365
  }
1339
1366
  contentBlock.custom_id = this.custom_id;
@@ -1345,6 +1372,17 @@ var Translate = class {
1345
1372
  }
1346
1373
  return;
1347
1374
  }
1375
+ if (derivedId) {
1376
+ const legacyId = generateLegacyCustomId(contentBlock.category, contentBlock.tokens);
1377
+ if (legacyId !== this.custom_id && isContentBlockKnown(contentBlock.category, legacyId)) {
1378
+ this.custom_id = legacyId;
1379
+ if (this.tokens.length > 1 && this.element) {
1380
+ this.translate(Array.from(this.element.childNodes));
1381
+ this.lastTranslatedLocale = currentlyLoadedLocale.get();
1382
+ }
1383
+ return;
1384
+ }
1385
+ }
1348
1386
  void registerContentBlock(contentBlock);
1349
1387
  if (this.tokens.length > 1 && this.element) {
1350
1388
  this.translate(Array.from(this.element.childNodes));
@@ -1360,7 +1398,7 @@ var Translate = class {
1360
1398
  if (node?.nodeType === Node.ELEMENT_NODE) {
1361
1399
  const element = node;
1362
1400
  if (element.getAttribute("translate") === "no") return;
1363
- if (element.hasAttribute("data-ls-phrase")) return;
1401
+ if (isPhraseMarked(element)) return;
1364
1402
  this.translateAttributes(node);
1365
1403
  }
1366
1404
  if (node?.nodeType !== Node.TEXT_NODE) {
@@ -1605,6 +1643,7 @@ exports.LangsysApp = LangsysApp;
1605
1643
  exports.LangsysAppAPI = LangsysAppAPI;
1606
1644
  exports.Logger = Logger;
1607
1645
  exports.PHRASE_MARKER_ATTR = PHRASE_MARKER_ATTR;
1646
+ exports.PHRASE_MARKER_ATTRS = PHRASE_MARKER_ATTRS;
1608
1647
  exports.Phrase = Phrase;
1609
1648
  exports.Translate = Translate;
1610
1649
  exports.Translations = Translations;
@@ -1614,14 +1653,17 @@ exports.currentlyLoadedLocale = currentlyLoadedLocale;
1614
1653
  exports.encodeRichText = encodeRichText;
1615
1654
  exports.findUnusedParamKeys = findUnusedParamKeys;
1616
1655
  exports.generateCustomId = generateCustomId;
1656
+ exports.generateLegacyCustomId = generateLegacyCustomId;
1617
1657
  exports.getValue = getValue;
1618
1658
  exports.interpolate = interpolate;
1619
1659
  exports.isContentBlockKnown = isContentBlockKnown;
1620
1660
  exports.isEmpty = isEmpty;
1621
1661
  exports.isICU = isICU;
1662
+ exports.isPhraseMarked = isPhraseMarked;
1622
1663
  exports.logger = logger;
1623
1664
  exports.markupTokenValues = markupTokenValues;
1624
1665
  exports.md5 = md5;
1666
+ exports.md5Legacy = md5Legacy;
1625
1667
  exports.normalizeMarkupPlaceholders = normalizeMarkupPlaceholders;
1626
1668
  exports.persist = persist;
1627
1669
  exports.reconstitute = reconstitute;