An open source design system that's fully customizable and agent ready
TypeScript
feat(lint): require provider-backed locale APIs (#5171)
nynexman4464383e17645638
diff --git a/eslint.config.js b/eslint.config.jsindex da8cf19af0..f03871f5e9 100644--- a/eslint.config.js+++ b/eslint.config.js@@ -202,6 +202,24 @@ export default defineConfig('@astryx/copyright-header': 'error',},},+ // Locale-sensitive formatting in shipped packages must go through the+ // provider-aware locale utilities, never raw Intl — see the rule's own doc+ // comment and internal/eslint-plugin-astryx/README.md for the approved+ // infrastructure boundary. Lab adopts this gate when a component graduates.+ {+ files: [+ "packages/core/src/**/*.{ts,tsx}",+ "packages/charts/src/**/*.{ts,tsx}",+ "packages/richtext/src/**/*.{ts,tsx}",+ "packages/vega/src/**/*.{ts,tsx}",+ ],+ plugins: {+ '@astryx': astryxEslintPlugin,+ },+ rules: {+ '@astryx/no-raw-intl-locale': 'error',+ },+ },// Astryx design token enforcement - applies to core package (excluding theme files){files: ["packages/core/src/**/*.{ts,tsx}"],diff --git a/internal/eslint-plugin-astryx/README.md b/internal/eslint-plugin-astryx/README.mdindex a635b17187..38148d4799 100644--- a/internal/eslint-plugin-astryx/README.md+++ b/internal/eslint-plugin-astryx/README.md@@ -18,6 +18,157 @@ This plugin implements a two-tier linting strategy:## Rules+### `@astryx/no-raw-intl-locale`++`InternationalizationProvider` is the sole user-facing locale source. This+rule forbids two independent things, anywhere in the lint scope:++1. **Raw `Intl` access** — constructing a locale-sensitive `Intl` formatter,+ calling `toLocaleString`/`toLocaleDateString`/`toLocaleTimeString`/+ `toLocaleUpperCase`/`toLocaleLowerCase`/`localeCompare` **directly**, or+ referencing the global `Intl` object at all outside an approved file —+ regardless of whether a call has a locale argument, and regardless of+ whether that argument is a literal, a variable, or `navigator.language`.+ An explicit locale expression does **not** satisfy this rule by itself;+ only going through the approved locale-aware boundary does. Beyond the+ direct-call shape, the rule also flags aliasing (`const DTF =+Intl.DateTimeFormat`), destructuring (`const {DateTimeFormat} = Intl`),+ and indexing with a computed key (`Intl[key]`) — each of these constructs+ a formatter without ever appearing as the call the direct-call check+ watches for, so the reference itself is what gets reported.+2. **`navigator.language`/`navigator.languages` as a locale source** — in+ _any_ position, not only as an argument to an `Intl`/locale-method call.+ `recognition.lang = lang ?? navigator.language` is flagged even though no+ `Intl` API is involved.++Shipped component code should read the locale through the public+provider-aware utilities instead — `useLocale()`/`useCollator()` (exported+from `@astryxdesign/core/i18n`) — or an existing formatting helper such as+`plainDateFormat`/`formatInstant`/`formatFilterValue`, so the value always+traces back to the provider.++**Raw `Intl` is controlled by two closed file lists in the rule source:**++- `APPROVED_IMPLEMENTATION_FILES` contains the pure formatter/parser+ implementations. Direct Intl calls there still require a syntactically+ explicit locale; `Intl.NumberFormat(undefined)`, an omitted locale, and+ locale methods without their locale argument are errors. Aliasing or+ destructuring Intl is also rejected. The only temporary ambient exceptions+ are the existing calls inside the named `plainDateFormat` and+ `isLocaleDayFirst` functions, pending #5120.+- `APPROVED_TEST_ORACLE_FILES` contains named tests that deliberately construct+ independent Intl expectations so assertions are not circular.++Approved implementations:++- `packages/core/src/utils/plainDate.ts`, `.../utils/dateParser.ts` — date+ formatting/parsing core+- `packages/core/src/Timestamp/formatInstant.ts`,+ `.../Timestamp/tooltipEntries.ts` — Timestamp formatting and its+ non-display time-zone validity probe+- `packages/core/src/PowerSearch/formatFilterValue.ts`+- `packages/core/src/i18n/useCollator.ts`+- `packages/charts/src/formatters.ts`++Named test oracles:++- `packages/charts/src/formatters.test.ts`+- `packages/core/src/Calendar/Calendar.test.tsx`+- `packages/core/src/NumberInput/NumberInput.test.tsx`+- `packages/core/src/Table/plugins/tree/useTableTreeState.test.tsx`+- `packages/core/src/Timestamp/tooltipEntries.test.ts`+- `packages/core/src/PowerSearch/formatFilterValue.test.ts`+- `packages/core/src/Timestamp/Timestamp.test.tsx`++These lists are the **only** exception mechanism. There is no rule option or+`eslint.config.js` override that widens them. A new entry requires a rule-source+change and a focused rule test. `navigator.language`/`navigator.languages`+remains rejected unconditionally, implementation or test oracle.++`Intl.Locale` is never flagged, in any form — a bare reference, an alias, a+call — it inspects a tag rather than formatting display output. `Intl.Segmenter`+is exempt everywhere (infra or not) for exactly two shapes: a direct call+with grapheme segmentation (including its standards-defined default+granularity — grapheme boundaries do not vary meaningfully by locale, which+is also why `packages/core/src/utils/characters.ts` and+`packages/core/src/hooks/useStreamingText.ts` call it with none), and the+`typeof Intl.Segmenter === 'function'` feature-detection idiom those same two+files pair it with (which constructs nothing). Word, sentence, and otherwise+unknown segmentation options are genuinely locale-sensitive and follow the+same policy as every other formatter — and, like every other formatter,+_aliasing_ `Intl.Segmenter` instead of calling it directly is **not** exempt+outside an approved file: the exemption is a call shape, not a reference, so+`const Seg = Intl.Segmenter; new Seg(undefined, {granularity: 'grapheme'})`+is still flagged even though the eventual call is grapheme-only.++**Known limitations (syntax-only, by design):**++- The rule does not trace an alias back to its origin: `const lang =+navigator.language; new Intl.DateTimeFormat(lang)` flags the+ `navigator.language` read but not the later `Intl` call as+ navigator-sourced (it still gets the generic raw-Intl message, since it's+ outside an approved file).+- The locale-sensitive prototype methods are matched on **method name+ alone**, with no knowledge of the receiver's type. A custom class that+ happens to define its own same-named method for unrelated,+ non-locale-sensitive behavior would still be flagged — a false positive+ a syntax-only rule cannot rule out. This has not surfaced in the current+ codebase.+- A **computed method name held in a variable** — `date[computedMethodName]()`+ — cannot be resolved to `'toLocaleString'` (or any other name) without+ value-flow analysis, so it is **not** caught. `Intl[key]` closes the+ equivalent gap only for the `Intl` object itself (a single, nameable+ global reference); it cannot generalize to an arbitrary method name on an+ arbitrary receiver.++A locally shadowed `Intl` or `navigator` (a parameter, an import, a local+factory) is not the platform global and is not flagged as one — a shadowed+`Intl` skips every Intl-specific check entirely (including its own aliasing),+and a shadowed `navigator` is not treated as the browser global (so+`navigator.language` through it is not flagged as `navigatorLocale` — a call+built on a shadowed-Intl-but-real-navigator combination still gets+`navigatorLocale` for the real navigator read, independent of the Intl+shadow). There is no autofix: choosing the right locale source is an API+decision.++The repository enables the rule as an error for shipped source and tests in+`core`, `charts`, `richtext`, and `vega`. It intentionally does not cover+`lab`, applications, scripts, or stories. Lab must meet this requirement when+a component graduates to a shipped package.++**Bad:**++```ts+new Intl.DateTimeFormat().format(date);+new Intl.DateTimeFormat(locale).format(date); // an explicit locale alone isn't enough+new Intl.DateTimeFormat(navigator.language).format(date);+value.toLocaleString(locale);+left.localeCompare(right, locale);+const DTF = Intl.DateTimeFormat; // aliasing bypasses the direct-call check too+const {DateTimeFormat} = Intl; // ...and so does destructuring+```++**Good:**++```tsx+// Component code: read the provider locale through the public hook.+import {useLocale, useCollator} from '@astryxdesign/core/i18n';++function Example() {+ const locale = useLocale();+ return <span>{plainDateFormat(date, DATE_FORMAT_LONG, locale)}</span>;+}++// String comparison: useCollator(), not a raw Intl.Collator/localeCompare.+function useSortedNames(names: string[]) {+ const collator = useCollator({numeric: true});+ return useMemo(+ () => [...names].sort((a, b) => collator.compare(a, b)),+ [names, collator],+ );+}+```+### `@astryx/no-hardcoded-styles`Detects hardcoded CSS values in `stylex.create()` that should use Astryx tokens:diff --git a/internal/eslint-plugin-astryx/index.js b/internal/eslint-plugin-astryx/index.jsindex 6fdb6c3cef..865cef6a6f 100644--- a/internal/eslint-plugin-astryx/index.js+++ b/internal/eslint-plugin-astryx/index.js@@ -11,6 +11,7 @@* - no-raw-paragraph: Disallows components from rendering a <p> by default (render <div> so any content composes)* - no-style-only-wrapper: Disallows div/span wrappers that only style a single Astryx component (use xstyle)* - no-nullish-jsx-guard: Flags `!= null` JSX render guards for rendered values (use isRenderable so false/''/true slots don't leak an empty element)+ * - no-raw-intl-locale: Forbids raw Intl formatting/comparison outside the approved i18n infrastructure boundary, and navigator.language(s) as a locale source* - no-unguarded-ime-keydown: Flags an onKeyDown on an editable surface that branches on command keys without an IME composition guard (isImeKeyEvent/isComposing)* - no-hover-on-disabled: Flags a :hover condition that can still match a disabled element (browsers suppress a disabled control's events, not its hover styling)*@@ -30,6 +31,7 @@ import noClassnameClobberRule from './no-classname-clobber.js';import noHardcodedAnchorRule from './no-hardcoded-anchor.js';import noRawParagraphRule from './no-raw-paragraph.js';import noNullishJsxGuardRule from './no-nullish-jsx-guard.js';+import noRawIntlLocaleRule from './no-raw-intl-locale.js';import noUnguardedImeKeydownRule from './no-unguarded-ime-keydown.js';import noBorderShorthandRule from './no-border-shorthand.js';import noPhysicalPropertiesRule from './no-physical-properties.js';@@ -254,6 +256,7 @@ const plugin = {'no-hardcoded-anchor': noHardcodedAnchorRule,'no-raw-paragraph': noRawParagraphRule,'no-nullish-jsx-guard': noNullishJsxGuardRule,+ 'no-raw-intl-locale': noRawIntlLocaleRule,'no-unguarded-ime-keydown': noUnguardedImeKeydownRule,'no-border-shorthand': noBorderShorthandRule,'no-physical-properties': noPhysicalPropertiesRule,@@ -298,6 +301,7 @@ plugin.configs.strict = {// Kept as 'warn' so it surfaces everywhere (including CI) without failing// the build; promote to 'error' once core is migrated (see issue #2538).'@astryx/no-nullish-jsx-guard': 'warn',+ '@astryx/no-raw-intl-locale': 'error',// All editable command-key handlers in core now guard IME composition// (Selector, MultiSelector, DateInput, DateTimeInput, TimeInput, and// Typeahead's edit-mode Escape were fixed alongside this rule); error to@@ -344,6 +348,7 @@ plugin.configs.recommended = {'@astryx/no-hardcoded-anchor': 'warn','@astryx/no-raw-paragraph': 'warn','@astryx/no-nullish-jsx-guard': 'warn',+ '@astryx/no-raw-intl-locale': 'error',// IME composition migration complete; error to prevent regressions// (see strict config above and issue #4892).'@astryx/no-unguarded-ime-keydown': 'error',diff --git a/internal/eslint-plugin-astryx/no-raw-intl-locale.js b/internal/eslint-plugin-astryx/no-raw-intl-locale.jsnew file mode 100644index 0000000000..31e73e80bd--- /dev/null+++ b/internal/eslint-plugin-astryx/no-raw-intl-locale.js@@ -0,0 +1,566 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file no-raw-intl-locale.js+ * @description Forbid raw `Intl` access — direct formatter/method calls AND+ * any other reference to the global `Intl` object (aliasing, destructuring,+ * computed indexing) — outside the approved i18n infrastructure boundary.+ * Separately, forbid `navigator.language`/`navigator.languages` as a locale+ * source anywhere in the lint scope, in any position, not only as an+ * argument to an `Intl`/locale-method call.+ *+ * `InternationalizationProvider` is the sole user-facing locale source.+ * Shipped component code must read it through the public provider-aware+ * locale utilities (`useLocale()`, `useCollator()` from+ * `@astryxdesign/core/i18n`, or an existing formatting helper such as+ * `plainDateFormat`/`formatInstant`/`formatFilterValue`) — never construct an+ * `Intl` formatter or call a locale-sensitive prototype method directly.+ * Passing an explicit locale expression does not satisfy this rule: a+ * hardcoded literal, `navigator.language`, or an arbitrary variable are all+ * still raw Intl access from the policy's point of view.+ *+ * Raw `Intl` is confined to two short, explicit lists below. Approved+ * implementations may call Intl directly but still require an explicit locale;+ * named test-oracle files may construct independent expected values. The only+ * ambient implementation exceptions are the two named legacy helper bodies+ * pending #5120. No ESLint option can widen these boundaries.+ *+ * `navigator.language`/`navigator.languages` are rejected everywhere,+ * including inside an approved infrastructure file — the provider is the+ * only sanctioned entry point for a real locale, so infrastructure code must+ * still receive one from a caller rather than reading the host default+ * itself. This is a standalone check, not limited to Intl call arguments:+ * `recognition.lang = lang ?? navigator.language` is flagged even though no+ * `Intl` API is involved.+ *+ * `Intl.Locale` is not policed — any reference to it, however used, is out+ * of scope: it inspects a tag rather than formatting display output.+ * `Intl.Segmenter` called directly with grapheme segmentation (the+ * standards-defined default granularity) is exempt everywhere, infra or not+ * — grapheme boundaries do not vary meaningfully by locale, which is also why+ * `packages/core/src/utils/characters.ts` and+ * `packages/core/src/hooks/useStreamingText.ts` call it with no locale (their+ * `typeof Intl.Segmenter === 'function'` feature-detection read is also+ * exempt, since it constructs nothing). Any other `Intl.Segmenter`+ * granularity (word, sentence, …) is genuinely locale-sensitive and follows+ * the same rule as every other formatter — and, like every other formatter,+ * aliasing it defeats the exemption: only the direct+ * `new Intl.Segmenter(undefined, {granularity: 'grapheme'})` call shape (or+ * the `typeof` check) is recognized, not a variable that might hold it.+ *+ * Beyond the direct-call shape (`new Intl.X(...)`/`Intl.X(...)`), this rule+ * also flags any OTHER reference to the global `Intl` identifier outside an+ * approved file: `const DTF = Intl.DateTimeFormat`, `const {DateTimeFormat} =+ * Intl`, and `Intl[key]` all construct a formatter without ever appearing as+ * a call this rule's other checks can see, so the reference itself — not a+ * later call through the alias — is what gets reported.+ *+ * KNOWN LIMITATIONS (syntax-only, by design — see the repository's+ * `no-raw-intl-locale` README section for the full discussion):+ * - This does not trace an alias back to its origin: `const lang =+ * navigator.language; new Intl.DateTimeFormat(lang)` reports the+ * `navigator.language` read but not the later `Intl` call as+ * navigator-sourced (it still gets `rawIntlLocale`).+ * - The locale-sensitive PROTOTYPE methods+ * (toLocaleString/toLocaleDateString/toLocaleTimeString/+ * toLocaleUpperCase/toLocaleLowerCase/localeCompare) are matched on+ * METHOD NAME alone, with no knowledge of the receiver's type. A custom+ * class that happens to define its own same-named method for unrelated,+ * non-locale-sensitive behavior will still be flagged (a false+ * positive); there is no receiver-type analysis available to a+ * syntax-only rule. This has not surfaced in the current codebase.+ * - A COMPUTED method name that isn't a literal or a no-substitution+ * template — `date[computedMethodName]()` where `computedMethodName` is+ * a variable — cannot be resolved to `'toLocaleString'` (or any other+ * name) without value-flow analysis, so it is NOT caught. This mirrors+ * the same limitation `Intl[key]` closes only for the `Intl` object+ * itself (a static, nameable global), not for its methods on arbitrary+ * receivers.+ */++// String/Date prototype methods that take a locale (or locales list) as+// their first argument. `localeCompare` is handled separately — its locale+// argument is second.+const LOCALE_FIRST_METHODS = new Set([+ 'toLocaleString',+ 'toLocaleDateString',+ 'toLocaleTimeString',+ 'toLocaleUpperCase',+ 'toLocaleLowerCase',+]);++/**+ * Approved implementation files may construct direct Intl formatters and call+ * locale-sensitive methods only with a syntactically explicit locale. Named+ * test-oracle files may construct independent expected values so tests do not+ * reuse the production helper under test. Aliasing/destructuring Intl remains+ * forbidden in implementations; only test-oracle files trust arbitrary raw+ * Intl references.+ *+ * `navigator.language`/`navigator.languages` are never covered by either list.+ * Paths match against the end of the filename for absolute/relative parity;+ * every added file requires a rule-source change and focused rule test.+ */+const APPROVED_IMPLEMENTATION_FILES = [+ // Date formatting/parsing core. The two pre-existing ambient call sites are+ // separately constrained by LEGACY_AMBIENT_CALLS below until #5120 lands.+ 'packages/core/src/utils/plainDate.ts',+ 'packages/core/src/utils/dateParser.ts',+ // Timestamp's shared instant formatter and its tooltip zone resolution+ // (the latter's fixed en-US locale only probes identifier validity).+ 'packages/core/src/Timestamp/formatInstant.ts',+ 'packages/core/src/Timestamp/tooltipEntries.ts',+ 'packages/core/src/PowerSearch/formatFilterValue.ts',+ 'packages/core/src/i18n/useCollator.ts',+ 'packages/charts/src/formatters.ts',+];++const APPROVED_TEST_ORACLE_FILES = [+ 'packages/charts/src/formatters.test.ts',+ 'packages/core/src/Calendar/Calendar.test.tsx',+ 'packages/core/src/NumberInput/NumberInput.test.tsx',+ 'packages/core/src/Table/plugins/tree/useTableTreeState.test.tsx',+ 'packages/core/src/Timestamp/tooltipEntries.test.ts',+ 'packages/core/src/PowerSearch/formatFilterValue.test.ts',+ 'packages/core/src/Timestamp/Timestamp.test.tsx',+];++// Temporary compatibility exceptions for the two public helpers whose locale+// parameters are still pending in #5120. Scope by file + enclosing function,+// not by file, so a second ambient formatter in either module is rejected.+const LEGACY_AMBIENT_CALLS = new Map([+ ['packages/core/src/utils/plainDate.ts', new Set(['plainDateFormat'])],+ ['packages/core/src/utils/dateParser.ts', new Set(['isLocaleDayFirst'])],+]);++function unwrap(node) {+ let current = node;+ while (+ current?.type === 'ChainExpression' ||+ current?.type === 'TSAsExpression' ||+ current?.type === 'TSNonNullExpression' ||+ current?.type === 'TSTypeAssertion'+ ) {+ current = current.expression;+ }+ return current;+}++function staticPropertyName(member) {+ if (member?.type !== 'MemberExpression') {+ return null;+ }+ const property = unwrap(member.property);+ if (!member.computed && property?.type === 'Identifier') {+ return property.name;+ }+ if (+ member.computed &&+ property?.type === 'Literal' &&+ typeof property.value === 'string'+ ) {+ return property.value;+ }+ if (+ member.computed &&+ property?.type === 'TemplateLiteral' &&+ property.expressions.length === 0+ ) {+ return property.quasis[0].value.cooked;+ }+ return null;+}++function isUndefinedExpression(node) {+ const value = unwrap(node);+ return (+ value == null ||+ (value.type === 'Identifier' && value.name === 'undefined') ||+ (value.type === 'UnaryExpression' && value.operator === 'void')+ );+}++function segmenterUsesOnlyGraphemes(optionsNode) {+ const options = unwrap(optionsNode);+ if (options == null || isUndefinedExpression(options)) {+ return true;+ }+ if (options.type !== 'ObjectExpression') {+ return false;+ }++ let granularity = null;+ for (const property of options.properties) {+ if (property.type === 'SpreadElement') {+ return false;+ }+ if (property.type !== 'Property' || property.kind !== 'init') {+ continue;+ }+ const name = property.computed+ ? property.key.type === 'Literal' &&+ typeof property.key.value === 'string'+ ? property.key.value+ : null+ : property.key.type === 'Identifier'+ ? property.key.name+ : property.key.type === 'Literal'+ ? property.key.value+ : null;+ if (name === 'granularity') {+ granularity = unwrap(property.value);+ }+ }++ // ECMA-402 defaults Segmenter granularity to grapheme. A literal object with+ // no spread and no granularity therefore has the same intentionally+ // grapheme-only use as an explicit {granularity: 'grapheme'} here.+ if (granularity == null) {+ return true;+ }+ return granularity.type === 'Literal' && granularity.value === 'grapheme';+}++/**+ * Whether `identifier` resolves to the platform global of that name — i.e.+ * has no local declaration/parameter/import shadowing it in any enclosing+ * scope. Shared by the `Intl` and `navigator` checks below.+ */+function isGlobalBinding(sourceCode, identifier) {+ let scope = sourceCode.getScope(identifier);+ while (scope) {+ const variable = scope.set?.get(identifier.name);+ if (variable) {+ return variable.defs.length === 0;+ }+ scope = scope.upper;+ }+ return true;+}++/**+ * Whether `node` is (possibly wrapped) `navigator.language` or+ * `navigator.languages`, with `navigator` resolving to the platform global —+ * a locally shadowed `navigator` (a parameter, an import, a local factory)+ * is not the browser global and must not be flagged.+ */+function isNavigatorLocale(sourceCode, node) {+ const value = unwrap(node);+ if (value?.type !== 'MemberExpression') {+ return false;+ }+ const object = unwrap(value.object);+ if (+ object?.type !== 'Identifier' ||+ object.name !== 'navigator' ||+ !isGlobalBinding(sourceCode, object)+ ) {+ return false;+ }+ const property = staticPropertyName(value);+ return property === 'language' || property === 'languages';+}++function normalizeFilename(filename) {+ return filename.replace(/\\/g, '/');+}++function isListedFile(filename, approvedFiles) {+ const normalized = normalizeFilename(filename);+ return approvedFiles.some(approved => normalized.endsWith(approved));+}++function enclosingFunctionName(node) {+ let current = node.parent;+ while (current != null) {+ if (current.type === 'FunctionDeclaration') {+ return current.id?.name ?? null;+ }+ current = current.parent;+ }+ return null;+}++function isLegacyAmbientCall(filename, node) {+ const normalized = normalizeFilename(filename);+ for (const [approved, functionNames] of LEGACY_AMBIENT_CALLS) {+ if (normalized.endsWith(approved)) {+ return functionNames.has(enclosingFunctionName(node));+ }+ }+ return false;+}++/**+ * Whether `identifier` (an `Intl` reference) sits in a position that does+ * not read its VALUE at all — a non-computed property name (`x.Intl`) or an+ * object-literal key (`{Intl: 1}`) — and so must not be scope-resolved as a+ * reference to the global. `isGlobalBinding`'s scope walk would otherwise+ * match the global `Intl` for these positions too, since it only checks+ * "is a variable named Intl visible here", not "is this identifier used as+ * a value".+ */+function isNonReferencePosition(identifier) {+ const parent = identifier.parent;+ if (!parent) {+ return false;+ }+ if (+ parent.type === 'TSQualifiedName' &&+ parent.left === identifier+ ) {+ // Type-only reference such as `collator: Intl.Collator`; it emits no+ // runtime Intl access and is part of the public TypeScript contract.+ return true;+ }+ if (+ parent.type === 'MemberExpression' &&+ parent.property === identifier &&+ !parent.computed+ ) {+ return true;+ }+ if (+ (parent.type === 'Property' || parent.type === 'TSPropertySignature') &&+ parent.key === identifier &&+ !parent.computed &&+ parent.value !== identifier+ ) {+ return true;+ }+ return false;+}++/**+ * Whether `memberExpr` (an `Intl.<prop>` or `Intl[<prop>]` access) is used+ * as the callee of the New/Call expression it is immediately part of — the+ * shape `checkIntlFormatter` already owns end-to-end (including reporting).+ * The generic Intl-reference check defers to it here so the same occurrence+ * is never reported twice.+ */+function isDirectInvocationCallee(memberExpr) {+ const parent = memberExpr.parent;+ return (+ (parent?.type === 'CallExpression' || parent?.type === 'NewExpression') &&+ parent.callee === memberExpr+ );+}++const rule = {+ meta: {+ type: 'problem',+ docs: {+ description:+ 'Forbid raw Intl access (calls, aliasing, destructuring, computed indexing) outside the approved i18n infrastructure boundary; forbid navigator.language(s) as a locale source anywhere',+ category: 'Best Practices',+ recommended: true,+ },+ messages: {+ rawIntlLocale:+ 'Do not call Intl directly. Use a public provider-aware locale ' ++ 'utility instead (useLocale()/useCollator() from ' ++ '@astryxdesign/core/i18n, or an existing formatting helper such as ' ++ 'plainDateFormat/formatInstant/formatFilterValue) so the locale ' ++ 'always traces back to InternationalizationProvider. An explicit ' ++ 'locale argument does not satisfy this rule — literals, variables, ' ++ 'and navigator.language are all still raw Intl access here. Raw ' ++ 'Intl is reserved for the approved infrastructure files listed in ' ++ 'internal/eslint-plugin-astryx/README.md.',+ rawIntlReference:+ 'Do not reference the global Intl object outside the approved i18n ' ++ 'infrastructure files. Aliasing (const DTF = Intl.DateTimeFormat), ' ++ 'destructuring (const {DateTimeFormat} = Intl), or indexing with a ' ++ 'computed key (Intl[key]) can construct a locale-sensitive ' ++ 'formatter without ever appearing as the direct call this rule ' ++ 'otherwise checks. Call the formatter directly inside an approved ' ++ 'file, or use a public provider-aware locale utility ' ++ '(useLocale()/useCollator() from @astryxdesign/core/i18n) instead.',+ ambientIntlInImplementation:+ 'Approved Intl implementation files must still pass an explicit locale. ' ++ 'A missing, undefined, or void locale would reintroduce host-dependent ' ++ 'behavior; only the two named legacy helper call sites are temporarily ' ++ 'exempt until #5120 lands.',+ navigatorLocale:+ 'Do not source a locale from navigator.language/navigator.languages, ' ++ 'in any position — not only as an argument to Intl or a locale ' ++ 'method. InternationalizationProvider is the sole locale source for ' ++ 'Astryx — read it through the provider-aware locale utilities ' ++ 'instead, even inside an approved i18n infrastructure file.',+ },+ schema: [],+ },++ create(context) {+ const sourceCode = context.sourceCode ?? context.getSourceCode();+ const filename = context.filename ?? context.getFilename();+ const implementationFile = isListedFile(+ filename,+ APPROVED_IMPLEMENTATION_FILES,+ );+ const testOracleFile = isListedFile(filename, APPROVED_TEST_ORACLE_FILES);++ function report(node, messageId) {+ context.report({node, messageId});+ }++ /** @returns whether the call/new-expression was an Intl formatter (handled either way) */+ function checkIntlFormatter(node) {+ const callee = unwrap(node.callee);+ if (callee?.type !== 'MemberExpression') {+ return false;+ }+ const object = unwrap(callee.object);+ if (+ object?.type !== 'Identifier' ||+ object.name !== 'Intl' ||+ !isGlobalBinding(sourceCode, object)+ ) {+ return false;+ }++ const formatter = staticPropertyName(callee);+ if (formatter === 'Locale') {+ // Intl.Locale inspects a tag; it never formats display output, so it+ // is out of scope regardless of how it's called.+ return true;+ }+ if (+ formatter === 'Segmenter' &&+ segmenterUsesOnlyGraphemes(node.arguments[1])+ ) {+ return true;+ }++ // Every other static member — a named formatter, an unrecognized+ // static API, or an unresolvable computed key (`Intl[key](...)`) —+ // funnels through the same navigator/infra check. A computed key that+ // can't be proven to be 'Locale' or a grapheme-only 'Segmenter' call+ // must not be silently allowed just because its name is unknown.+ const localeArg = node.arguments[0];+ if (isNavigatorLocale(sourceCode, localeArg)) {+ // Reported once by the standalone navigator visitor below.+ } else if (testOracleFile) {+ // Named tests may build independent Intl oracles, including the host+ // default where that is the behavior under test.+ } else if (implementationFile) {+ if (+ isUndefinedExpression(localeArg) &&+ !isLegacyAmbientCall(filename, node)+ ) {+ report(node, 'ambientIntlInImplementation');+ }+ } else {+ report(node, 'rawIntlLocale');+ }+ return true;+ }++ function checkLocaleMethod(node) {+ const callee = unwrap(node.callee);+ if (callee?.type !== 'MemberExpression') {+ return;+ }+ const method = staticPropertyName(callee);++ let localeArg;+ if (LOCALE_FIRST_METHODS.has(method)) {+ localeArg = node.arguments[0];+ } else if (method === 'localeCompare') {+ localeArg = node.arguments[1];+ } else {+ return;+ }++ if (isNavigatorLocale(sourceCode, localeArg)) {+ // Reported once by the standalone navigator visitor below.+ } else if (testOracleFile) {+ // Named tests may use locale methods as independent oracles.+ } else if (implementationFile) {+ if (isUndefinedExpression(localeArg)) {+ report(node, 'ambientIntlInImplementation');+ }+ } else {+ report(node, 'rawIntlLocale');+ }+ }++ return {+ NewExpression(node) {+ checkIntlFormatter(node);+ },+ CallExpression(node) {+ if (!checkIntlFormatter(node)) {+ checkLocaleMethod(node);+ }+ },++ // Unconditional: navigator.language/languages is never an acceptable+ // locale source, in ANY position — an Intl argument, an assignment+ // target's value, a default parameter, anywhere. This is the single+ // place that reports `navigatorLocale`; the call-shape checks above+ // recognize the same expression and defer to this visitor instead of+ // reporting it a second time.+ MemberExpression(node) {+ if (isNavigatorLocale(sourceCode, node)) {+ report(node, 'navigatorLocale');+ }+ },++ // Any OTHER reference to the global `Intl` identifier — one not+ // already owned by checkIntlFormatter's direct-call handling above —+ // is raw Intl access outside an approved file: aliasing, destructuring,+ // or a bare computed-index read all construct a formatter without ever+ // being the direct call this rule's other checks can see.+ Identifier(node) {+ if (node.name !== 'Intl') {+ return;+ }+ if (isNonReferencePosition(node)) {+ return;+ }+ if (!isGlobalBinding(sourceCode, node)) {+ return;+ }++ const parent = node.parent;+ const isObjectOfMember =+ parent?.type === 'MemberExpression' && parent.object === node;++ if (isObjectOfMember && isDirectInvocationCallee(parent)) {+ // Owned by checkIntlFormatter (NewExpression/CallExpression+ // handlers above) — including its Locale/grapheme-Segmenter+ // exemptions and its own report-or-not decision. Reporting here+ // too would duplicate that diagnostic.+ return;+ }++ if (isObjectOfMember) {+ const property = staticPropertyName(parent);+ if (property === 'Locale') {+ // Bare `Intl.Locale` access (not a call) — e.g. `x instanceof+ // Intl.Locale` — is out of scope, same as the call form.+ return;+ }+ if (+ property === 'Segmenter' &&+ parent.parent?.type === 'UnaryExpression' &&+ parent.parent.operator === 'typeof'+ ) {+ // `typeof Intl.Segmenter === 'function'` feature-detection reads+ // the binding but constructs nothing; the two grapheme-only call+ // sites in this repo pair every such check with the direct call+ // form above, which is separately exempted.+ return;+ }+ }++ if (testOracleFile) {+ return;+ }+ report(node, 'rawIntlReference');+ },+ };+ },+};++export default rule;diff --git a/internal/eslint-plugin-astryx/no-raw-intl-locale.test.mjs b/internal/eslint-plugin-astryx/no-raw-intl-locale.test.mjsnew file mode 100644index 0000000000..6df6c339ea--- /dev/null+++ b/internal/eslint-plugin-astryx/no-raw-intl-locale.test.mjs@@ -0,0 +1,443 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file no-raw-intl-locale.test.mjs+ * @description Tests for the Astryx no-raw-intl-locale ESLint rule.+ */++import {RuleTester} from 'eslint';+import tseslint from 'typescript-eslint';+import rule from './no-raw-intl-locale.js';++const tester = new RuleTester({+ languageOptions: {+ parser: tseslint.parser,+ parserOptions: {+ ecmaVersion: 2024,+ sourceType: 'module',+ },+ },+});++const rawIntlLocale = {messageId: 'rawIntlLocale'};+const rawIntlReference = {messageId: 'rawIntlReference'};+const ambientIntlInImplementation = {+ messageId: 'ambientIntlInImplementation',+};+const navigatorLocale = {messageId: 'navigatorLocale'};++// A file outside the approved infrastructure allowlist — the common case for+// shipped component code. Used as the default `filename` for every case that+// doesn't specifically test the infra boundary.+const COMPONENT_FILE = 'packages/core/src/Calendar/Calendar.tsx';+const INFRA_FILE = 'packages/core/src/utils/plainDate.ts';+const DATE_PARSER_INFRA_FILE = 'packages/core/src/utils/dateParser.ts';+const COLLATOR_INFRA_FILE = 'packages/core/src/i18n/useCollator.ts';+const CHARTS_INFRA_FILE = 'packages/charts/src/formatters.ts';+const TIMESTAMP_TEST_ORACLE_FILE = 'packages/core/src/Timestamp/Timestamp.test.tsx';+const CALENDAR_TEST_ORACLE_FILE = 'packages/core/src/Calendar/Calendar.test.tsx';+// A test file that is NOT one of the named oracle exceptions — proves the+// allowlist is exact-file, not "any *.test.tsx".+const OTHER_TEST_FILE = 'packages/core/src/DateInput/DateInput.test.tsx';+// The two feature-detection call sites the `typeof Intl.Segmenter` exemption+// exists for — neither is on the infra allowlist, since the exemption is+// meant to hold everywhere.+const CHARACTERS_FILE = 'packages/core/src/utils/characters.ts';++tester.run('no-raw-intl-locale', rule, {+ valid: [+ // -- Intl.Locale is never a formatter, anywhere, in any form --+ {code: `new Intl.Locale();`, filename: COMPONENT_FILE},+ {code: `new Intl.Locale(locale).baseName;`, filename: COMPONENT_FILE},+ {code: `x instanceof Intl.Locale;`, filename: COMPONENT_FILE},+ {code: `const Loc = Intl.Locale;`, filename: COMPONENT_FILE},++ // -- Grapheme-only Intl.Segmenter is exempt everywhere, infra or not --+ {code: `new Intl.Segmenter();`, filename: COMPONENT_FILE},+ {code: `Intl.Segmenter(undefined);`, filename: COMPONENT_FILE},+ {+ code: `new Intl.Segmenter(void 0, {granularity: 'grapheme'});`,+ filename: COMPONENT_FILE,+ },+ {code: `new Intl.Segmenter(undefined, {});`, filename: COMPONENT_FILE},+ {+ code: `new Intl.Segmenter('fr', {granularity: 'grapheme'});`,+ filename: COMPONENT_FILE,+ },+ // The exact feature-detection idiom characters.ts/useStreamingText.ts+ // use, paired with the grapheme-only call — neither file is on the infra+ // allowlist, since this exemption holds everywhere.+ {+ code: `typeof Intl.Segmenter === 'function' ? new Intl.Segmenter(undefined, {granularity: 'grapheme'}) : null;`,+ filename: CHARACTERS_FILE,+ },++ // -- Type-only references emit no runtime Intl access. --+ {+ code: `let collator: Intl.Collator; type Options = Intl.CollatorOptions;`,+ filename: COMPONENT_FILE,+ },++ // -- A locally shadowed Intl is not the platform global --+ {+ code: `function format(Intl) { return new Intl.DateTimeFormat(); }`,+ filename: COMPONENT_FILE,+ },+ {+ code: `const Intl = factory(); Intl.NumberFormat();`,+ filename: COMPONENT_FILE,+ },+ // A shadowed Intl used to alias one of its members is still not a+ // reference to the platform global.+ {+ code: `function f(Intl) { const DTF = Intl.DateTimeFormat; return DTF; }`,+ filename: COMPONENT_FILE,+ },+ // `Intl` as a non-computed property name, or an object-literal key, is+ // not a value reference to the global at all.+ {code: `x.Intl.DateTimeFormat();`, filename: COMPONENT_FILE},+ {code: `const obj = {Intl: 5};`, filename: COMPONENT_FILE},++ // -- Approved implementation files may call Intl directly, but still+ // require a syntactically explicit non-navigator locale. --+ {+ code: `new Intl.DateTimeFormat(locale, {dateStyle: 'long'});`,+ filename: INFRA_FILE,+ },+ {code: `new Intl.NumberFormat(locale).format(123);`, filename: INFRA_FILE},+ {code: `new Intl.DateTimeFormat('en-US', {timeZone});`, filename: INFRA_FILE},+ // -- The only ambient implementation calls are the two named legacy+ // helpers pending #5120. A second call in either file is invalid. --+ {+ code: `function plainDateFormat() { return new Intl.DateTimeFormat(undefined, options); }`,+ filename: INFRA_FILE,+ },+ {+ code: `function isLocaleDayFirst() { return new Intl.DateTimeFormat(); }`,+ filename: DATE_PARSER_INFRA_FILE,+ },+ {code: `value.toLocaleString(locale);`, filename: INFRA_FILE},+ {code: `left.localeCompare(right, locale);`, filename: INFRA_FILE},+ {+ code: `abs.toLocaleString(locale);`,+ filename: CHARTS_INFRA_FILE,+ },+ {+ code: `new Intl.Collator(locale, options);`,+ filename: COLLATOR_INFRA_FILE,+ },+ // -- Named test-oracle files retain meaningful explicit-locale fixtures. --+ {+ code: `number.toLocaleString('en-US');`,+ filename: 'packages/core/src/NumberInput/NumberInput.test.tsx',+ },+ {+ code: `left.localeCompare(right, 'en-US');`,+ filename: 'packages/core/src/Table/plugins/tree/useTableTreeState.test.tsx',+ },++ // -- A named test-oracle file may also construct raw Intl with a+ // non-navigator locale argument, exactly like an infra implementation+ // file — it is the same allowlist, not a separate mechanism. --+ {+ code: `new Intl.DateTimeFormat('en', {timeZoneName: 'long'}).formatToParts(date);`,+ filename: TIMESTAMP_TEST_ORACLE_FILE,+ },+ {+ code: `new Intl.DateTimeFormat('en', {year: 'numeric', month: 'long'}).format(date);`,+ filename: CALENDAR_TEST_ORACLE_FILE,+ },++ // -- KNOWN GAP (syntax-only limitation, documented in the rule's file+ // doc and README): a computed method name held in a variable cannot+ // be resolved to 'toLocaleString' (or any other name) without+ // value-flow analysis, so this locale-sensitive call is NOT caught.+ // This is intentionally left unclosed — see LOCALE_FIRST_METHODS'+ // static-name matching, which no syntax-only rule can generalize past+ // a literal or no-substitution template. --+ {+ code: `const method = 'toLocaleString'; value[method]();`,+ filename: COMPONENT_FILE,+ },+ ],++ invalid: [+ // -- Approved implementation files still reject ambient locale calls and+ // indirect Intl references. --+ {+ code: `new Intl.NumberFormat(undefined).format(value);`,+ filename: CHARTS_INFRA_FILE,+ errors: [ambientIntlInImplementation],+ },+ {+ code: `value.toLocaleString();`,+ filename: CHARTS_INFRA_FILE,+ errors: [ambientIntlInImplementation],+ },+ {+ code: `function anotherFormatter() { return new Intl.DateTimeFormat(undefined, options); }`,+ filename: INFRA_FILE,+ errors: [ambientIntlInImplementation],+ },+ {+ code: `const DTF = Intl.DateTimeFormat; new DTF(locale);`,+ filename: INFRA_FILE,+ errors: [rawIntlReference],+ },+ {+ code: `const {DateTimeFormat} = Intl; new DateTimeFormat(locale);`,+ filename: INFRA_FILE,+ errors: [rawIntlReference],+ },++ // -- The core policy change: an explicit locale no longer satisfies the+ // rule outside the approved infrastructure files. --+ {+ code: `new Intl.DateTimeFormat(locale, {dateStyle: 'long'});`,+ filename: COMPONENT_FILE,+ errors: [rawIntlLocale],+ },+ {+ code: `new Intl.NumberFormat(locale).format(value);`,+ filename: COMPONENT_FILE,+ errors: [rawIntlLocale],+ },+ // -- Hard-coded display locales don't satisfy it either --+ {+ code: `new Intl.DateTimeFormat('en-US').format(date);`,+ filename: COMPONENT_FILE,+ errors: [rawIntlLocale],+ },+ // -- Nor does a missing/ambient locale, as before --+ {code: `new Intl.DateTimeFormat();`, filename: COMPONENT_FILE, errors: [rawIntlLocale]},+ {+ code: `Intl.NumberFormat(undefined);`,+ filename: COMPONENT_FILE,+ errors: [rawIntlLocale],+ },+ {+ code: `new Intl.RelativeTimeFormat(void 0);`,+ filename: COMPONENT_FILE,+ errors: [rawIntlLocale],+ },+ {+ code: `new Intl['ListFormat'](locale);`,+ filename: COMPONENT_FILE,+ errors: [rawIntlLocale],+ },+ {+ code: `Intl?.DisplayNames?.(locale, {type: 'language'});`,+ filename: COMPONENT_FILE,+ errors: [rawIntlLocale],+ },+ // -- A dynamic computed key on Intl itself, used directly as a call,+ // can't be proven to be Locale or a grapheme Segmenter, so it must+ // not be silently allowed the way a truly unrecognized static name+ // used to be. --+ {+ code: `new Intl[key](locale);`,+ filename: COMPONENT_FILE,+ errors: [rawIntlLocale],+ },+ // -- Non-grapheme Segmenter granularities are locale-sensitive and follow+ // the same policy as every other formatter. --+ {+ code: `new Intl.Segmenter('th', {granularity: 'word'});`,+ filename: COMPONENT_FILE,+ errors: [rawIntlLocale],+ },+ {+ code: `Intl.Segmenter(locale, {granularity: 'sentence'});`,+ filename: COMPONENT_FILE,+ errors: [rawIntlLocale],+ },+ {+ code: `new Intl.Segmenter(undefined, options);`,+ filename: COMPONENT_FILE,+ errors: [rawIntlLocale],+ },+ {+ code: `new Intl.Segmenter(undefined, {...options});`,+ filename: COMPONENT_FILE,+ errors: [rawIntlLocale],+ },+ // -- Locale-sensitive prototype methods, with or without a locale arg --+ {code: `value.toLocaleString();`, filename: COMPONENT_FILE, errors: [rawIntlLocale]},+ {+ code: `value.toLocaleString(locale);`,+ filename: COMPONENT_FILE,+ errors: [rawIntlLocale],+ },+ {+ code: `date['toLocaleDateString'](locale);`,+ filename: COMPONENT_FILE,+ errors: [rawIntlLocale],+ },+ {+ code: `time?.toLocaleTimeString?.(locale);`,+ filename: COMPONENT_FILE,+ errors: [rawIntlLocale],+ },+ // -- New in this policy: the case-conversion locale methods --+ {+ code: `value.toLocaleUpperCase();`,+ filename: COMPONENT_FILE,+ errors: [rawIntlLocale],+ },+ {+ code: `value.toLocaleUpperCase(locale);`,+ filename: COMPONENT_FILE,+ errors: [rawIntlLocale],+ },+ {+ code: `value.toLocaleLowerCase(locale);`,+ filename: COMPONENT_FILE,+ errors: [rawIntlLocale],+ },+ {+ code: `left.localeCompare(right);`,+ filename: COMPONENT_FILE,+ errors: [rawIntlLocale],+ },+ {+ code: `left.localeCompare(right, locale);`,+ filename: COMPONENT_FILE,+ errors: [rawIntlLocale],+ },+ {+ code: `left['localeCompare'](right, locale, {numeric: true});`,+ filename: COMPONENT_FILE,+ errors: [rawIntlLocale],+ },++ // -- navigator.language / navigator.languages are rejected as a locale+ // source, with a dedicated message, everywhere including infra --+ {+ code: `new Intl.DateTimeFormat(navigator.language);`,+ filename: COMPONENT_FILE,+ errors: [navigatorLocale],+ },+ {+ code: `new Intl.NumberFormat(navigator.languages);`,+ filename: COMPONENT_FILE,+ errors: [navigatorLocale],+ },+ {+ code: `new Intl.DateTimeFormat(navigator['language']);`,+ filename: COMPONENT_FILE,+ errors: [navigatorLocale],+ },+ {+ code: `value.toLocaleString(navigator.language);`,+ filename: COMPONENT_FILE,+ errors: [navigatorLocale],+ },+ {+ code: `left.localeCompare(right, navigator.language);`,+ filename: COMPONENT_FILE,+ errors: [navigatorLocale],+ },+ {+ code: `new Intl.DateTimeFormat(navigator.language);`,+ filename: INFRA_FILE,+ errors: [navigatorLocale],+ },+ {+ code: `new Intl.Collator(navigator.language, options);`,+ filename: COLLATOR_INFRA_FILE,+ errors: [navigatorLocale],+ },++ // -- New in this policy: navigator.language/languages is banned in ANY+ // position, not only as an Intl/locale-method argument. --+ {+ code: `recognition.lang = lang ?? navigator.language;`,+ filename: COMPONENT_FILE,+ errors: [navigatorLocale],+ },+ {+ code: `const preferred = navigator.languages[0];`,+ filename: COMPONENT_FILE,+ errors: [navigatorLocale],+ },+ {+ code: `someFn(navigator.language);`,+ filename: COMPONENT_FILE,+ errors: [navigatorLocale],+ },+ {+ // Even inside an approved infra file, and even with no Intl call in+ // sight.+ code: `const fallback = navigator.language;`,+ filename: INFRA_FILE,+ errors: [navigatorLocale],+ },++ // -- A locally shadowed `navigator` outside infra still fails, just for+ // the general reason rather than as a navigator-sourced locale. --+ {+ code: `function f(navigator) { return new Intl.DateTimeFormat(navigator.language); }`,+ filename: COMPONENT_FILE,+ errors: [rawIntlLocale],+ },++ // -- Shadowing Intl does not also shadow navigator: the Intl call is+ // exempted from Intl-specific reporting (Intl here is a parameter,+ // not the global), but navigator.language is still the real global+ // and is independently flagged. --+ {+ code: `function f(Intl) { return Intl.DateTimeFormat(navigator.language); }`,+ filename: COMPONENT_FILE,+ errors: [navigatorLocale],+ },++ // -- The allowlist is exact-file: an ordinary component test not on the+ // list still fails, proving this isn't a general "*.test.tsx" carve-out. --+ {+ code: `new Intl.DateTimeFormat('en', {year: 'numeric', month: 'long'});`,+ filename: OTHER_TEST_FILE,+ errors: [rawIntlLocale],+ },++ // -- New in this policy: referencing the global Intl object OUTSIDE the+ // direct-call shape — aliasing, destructuring, or a bare computed+ // index — is flagged even with no locale argument in sight, because+ // the eventual call this alias enables is invisible to every other+ // check in this rule. Exactly one diagnostic each: the reference+ // itself, not any later call through the alias. --+ {+ code: `const DTF = Intl.DateTimeFormat; new DTF(locale);`,+ filename: COMPONENT_FILE,+ errors: [rawIntlReference],+ },+ {+ code: `const {DateTimeFormat} = Intl; new DateTimeFormat(locale);`,+ filename: COMPONENT_FILE,+ errors: [rawIntlReference],+ },+ {+ code: `const {DateTimeFormat, NumberFormat} = Intl;`,+ filename: COMPONENT_FILE,+ errors: [rawIntlReference],+ },+ {+ code: `const ctor = Intl[key];`,+ filename: COMPONENT_FILE,+ errors: [rawIntlReference],+ },+ {+ code: `const formatters = Intl;`,+ filename: COMPONENT_FILE,+ errors: [rawIntlReference],+ },+ // A shadowed Intl inside the SAME infra file is fine to alias — the file+ // trust boundary covers it — but outside infra, aliasing Intl.Segmenter+ // (rather than calling it directly with grapheme options) still isn't+ // exempt: the exemption is a call shape, not a bare reference.+ {+ code: `const Seg = Intl.Segmenter; new Seg(undefined, {granularity: 'grapheme'});`,+ filename: COMPONENT_FILE,+ errors: [rawIntlReference],+ },+ ],+});