Skip to content

Bug sweep: list arrays, loader state in configure(), locale detection and file parser edge cases #4

Closed

Description

@n4ff4h

A read-through of src/ turned up the bugs below. Each one was reproduced against the current build (dist/index.js at 7673021) unless marked otherwise. They are independent, so they can be fixed in separate commits; they are ordered by how likely a real app is to hit them.

Per AGENTS.md: every fix needs a test next to the code (Thaana in user-facing cases), a changeset, and docs where behaviour changes. Fixes that change translation output (1, 2, 11) need cases in test/parity/cases.json followed by pnpm parity:generate — never edit golden.json by hand.

Parity with Laravel

1. List arrays in language files are unreachable

isGroup() (src/translator.ts:22) rejects arrays, so a PHP list such as 'days' => ['އާދީއްތަ', 'ހޯމަ'] (which lang:js exports as a JSON array) can't be returned, indexed, or have replacements made in it.

const t = createTranslator({ locale: "dv" })
t.load({ messages: { days: ["އާދީއްތަ", "ހޯމަ"], nested: { list: [":name a"] } } }, { locale: "dv" })

t.get("messages.days")                  // "messages.days"       Laravel: ["އާދީއްތަ", "ހޯމަ"]
t.get("messages.days.0")                // "messages.days.0"     Laravel: "އާދީއްތަ"
t.get("messages.nested", { name: "X" }) // { list: [":name a"] } Laravel: { list: ["X a"] }

Laravel's getLine() returns any non-empty array and runs array_walk_recursive over it; Arr::get() walks numeric indexes. Affected: dataGet() (:48), replaceDeep() (:122), the group check in get() (:354), and the Translation type in src/types.ts, which has to admit arrays. mergeInto() also stores arrays by reference, so the caller's input object and the tree share them; clone while fixing. An empty array must still fall through to the next locale, as count($line) > 0 does.

2. A JSON line of "0" is returned instead of the key

src/translator.ts:360 uses line || missingKey. Laravel uses $line ?: $key, and "0" is falsy in PHP, so Laravel returns the key.

t.load({ zero: "0" }, { locale: "dv" })
t.get("zero") // "0"   Laravel: "zero"

Only JSON lines are affected; a "0" inside a group is returned as is by both.

Loader and configure()

3. configure({ locale }) and configure({ fallback }) don't notify or fetch

configure() (src/translator.ts:179) assigns the locale and fallback directly. Unlike setLocale() / setFallback(), subscribers aren't told and an already configured loader isn't asked for the new locale. The Vue plugin goes through this path (app.use(i18n, { locale })).

const calls = []
const t = createTranslator({ locale: "en", fallback: null, loader: (l) => (calls.push(l), { hi: l }) })
await t.ready()
let notified = 0
t.subscribe(() => notified++)
t.configure({ locale: "dv" })
await t.ready()
// calls: ["en"]   notified: 0   t.get("hi"): "hi"
// expected: calls ["en", "dv"], notified >= 1, t.get("hi") === "dv"

4. Replacing the loader while a fetch is in flight skips the new loader

configure({ loader }) clears loaded but not pending (:190-198). fetchLocale() then sees the old request in pending and returns, so the new loader is never called for that locale, and when the old request lands it marks the locale as loaded.

let resolveOld
const t = createTranslator({ locale: "dv", fallback: null, loader: () => new Promise((r) => (resolveOld = r)) })
const calls = []
t.configure({ loader: (l) => (calls.push(l), { hi: "new" }) })
resolveOld({ hi: "old" })
await t.ready()
// calls: []   t.get("hi"): "old"      expected: calls ["dv"], "new"

A result from a superseded loader should also not be merged or mark the locale loaded.

5. Only the first {locale} in a loader URL is filled in

src/translator.ts:519 uses String.prototype.replace with a string pattern.

createTranslator({ locale: "dv", loader: "/lang/{locale}/{locale}.json" })
// fetches "/lang/dv/{locale}.json"

Locale detection

6. A content-language list isn't a locale

<meta http-equiv="content-language" content="dv, en"> is a valid comma-separated list, but detectLocale() (src/locale.ts:28) hands the whole string to normalizeLocale(), giving the locale "dv, en", which matches nothing. Take the first entry. (normalizeLocale("en-US,en;q=0.9") likewise returns "en_US,en;q=0.9".)

7. localeChain() skips the script level

localeChain("zh_Hant_TW") (src/locale.ts:14) is ["zh_Hant_TW", "zh"], so lines loaded for zh_Hant are never found from <html lang="zh-Hant-TW">. Expected ["zh_Hant_TW", "zh_Hant", "zh"]. This extends the "regional locales find their language" entry in docs/differences-from-laravel.md; update it.

File formats (src/formats.ts)

8. PO: an empty Language: header captures the next header

:93 is /^Language:\s*(\S+)/m; \s* runs across the newline. Files with an unset language (.pot templates, fresh Poedit files) load every line into a locale named after the next header.

const t = createTranslator({ locale: "dv" })
t.load('msgid ""\nmsgstr ""\n"Language: \\n"\n"MIME-Version: 1.0\\n"\n\nmsgid "Hello"\nmsgstr "ހެލޯ"\n')
t.get("Hello")                      // "Hello"   expected "ހެލޯ"
t.get("Hello", {}, "MIME-Version:") // "ހެލޯ"

Use [ \t]* and leave the locale undefined when the value is empty.

9. PO: entries not separated by blank lines are lost

:66 splits entries on blank lines, which gettext doesn't require. Within one block later fields overwrite earlier ones, so only the last entry in a block survives:

t.load('msgid "A"\nmsgstr "އ"\nmsgid "B"\nmsgstr "ބ"\n', { format: "po" })
t.get("A") // "A"    expected "އ"
t.get("B") // "ބ"

Start a new entry whenever msgid (or msgctxt, or a comment after a msgstr) follows a msgstr, instead of relying on blank lines.

10. Properties: an escaped backslash at the end of a line is taken as a continuation

:160 joins lines on any backslash before a newline. An even number of trailing backslashes is a literal backslash, not a continuation, and comment lines never continue.

t.load("path=C:\\\\dir\\\\\nnext=x\n", { format: "properties" }) // file text: path=C:\\dir\\  ⏎  next=x
t.get("path") // "C:\\dir\next=x" (with a newline for \n)   expected "C:\\dir\\" i.e. C:\dir\
t.get("next") // "next"                                      expected "x"

t.load("# note \\\nkey=val\n", { format: "properties" })
t.get("key")  // "key"   expected "val"

11. trans_choice() trims more than PHP's trim()

src/message-selector.ts:134 uses String.prototype.trim(), which also strips NBSP, U+2028 and other Unicode whitespace. PHP's trim() strips only space, \t, \n, \r, \0 and \x0B.

t.load({ m: { c: "{0} \u00a0none\u00a0|[1,*] some" } }, { locale: "dv" })
t.choice("m.c", 0) // "none"   Laravel: "\u00a0none\u00a0"

12. Smaller robustness problems with untrusted files

  • XLIFF: a numeric character reference outside the Unicode range (&#99999999;) makes String.fromCodePoint() throw a RangeError at :119, failing the whole file. Leave such a reference as it is.
  • Format sniffing: sniffFormat() (:208) calls any JSON containing a key that starts with @ ARB. A Laravel JSON file with a key like "@handle" then loses that key, every nested group, and has {x} rewritten to :x in all lines. Require @@locale or an @key whose value is an object and whose key is also present, before choosing ARB.
  • translateDom(): JSON.parse of a malformed data-trans-replace (src/dom.ts:9) throws out of the loop, leaving the rest of the page untranslated. Skip that element's replacements (and console.error) instead.

Not included

Activity

  1. added
    bug
    on Nov 22, 2026
  2. n4ff4h commented on Nov 22, 2026

    @n4ff4h
    CollaboratorAuthor

    Fixed on main in c9593c8..a009483, one commit per bug (3 and 4, 6 and 7, 8 and 9, and the three parts of 12 are combined), each with tests and a changeset. Parity cases for 1, 2 and 11 were added to test/parity/cases.json and golden.json regenerated from Laravel. Ships in the next release (#5).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions