@micha.bigler/ui-core-micha 3.9.1 → 3.10.0

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,5 +1,9 @@
1
1
  # Changelog
2
2
 
3
+ ## 3.10.0 — UCM-TEST-1
4
+
5
+ Added the exported `checkKitIntegration` consumer check for app i18n, providers, kit page rendering, and auth error translation wiring.
6
+
3
7
  ## 3.9.1 — UCM-AUTH-11
4
8
 
5
9
  `UserListComponent` no longer offers an administrator the delete action for their own account, including when a consumer-supplied `canDeleteUser` callback returns true.
package/README.md CHANGED
@@ -10,6 +10,22 @@ To add an entry, create a small component in `dev/entries.jsx` and append it to
10
10
 
11
11
  Spread `uiCoreTranslations` into the default i18n namespace as the supported aggregate; per-feature translation exports remain available to selective apps that accept responsibility for pairing every adopted feature with its bundle.
12
12
 
13
+ ## Consumer integration check
14
+
15
+ ```js
16
+ import { checkKitIntegration } from '@micha.bigler/ui-core-micha';
17
+ import i18n from '../i18n';
18
+ import { AppProviders } from '../AppProviders';
19
+
20
+ it('kit integration is sound', async () => {
21
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true; // skip if your test setup already sets this
22
+ const { findings } = await checkKitIntegration({ i18n, wrapper: AppProviders });
23
+ expect(findings).toEqual([]);
24
+ });
25
+ ```
26
+
27
+ `pages` controls which additional kit pages render (default: `LoginPage`, `SignUpPage`, `PasswordInvitePage`); `LoginPage` itself always renders once more for the error-text check regardless of what `pages` contains. Run this check on its own in its test file — it stubs the kit's shared `apiClient` transport for its duration, so a test running real requests through `apiClient` at the same time would see them intercepted too.
28
+
13
29
  ## Dashboard primitives
14
30
 
15
31
  `StatTile` (a bordered KPI tile) and `SoftChip` (a soft tinted annotation/status chip, tones derived from `theme.palette[tone]`) live under `src/components/` and are exported from the package root.
package/WORK_ORDERS.md CHANGED
@@ -19,6 +19,7 @@ rules are defined centrally in `webapps/AGENTS.md` → "Work-Order Register".
19
19
  | `I18N-*` | The shared kit's i18n **contract** — how a consumer registers ucm's strings, and what happens when it forgets. Distinct from `AUTH-*`, which owns the auth strings themselves |
20
20
  | `PRIM-*` | Shared dashboard/data primitives — small presentational components that are neither chart (`CHART-*`) nor app chrome (`SHELL-*`) |
21
21
  | `SHELL-*` | Shared app chrome and navigation shells (`UserMenu`, mobile bottom nav, secondary-navigation shell) — used since `SHELL-1`, documented here 2026-08-11 |
22
+ | `TEST-*` | Consumer integration checks the kit ships for apps to run in their own suites |
22
23
 
23
24
  Introduce a new prefix when none fits and add it here. New WOs always get a
24
25
  prefixed ID; never reuse a bare flat number across workstreams.
@@ -27,6 +28,7 @@ prefixed ID; never reuse a bare flat number across workstreams.
27
28
 
28
29
  | ID | Titel | Beschreibung | Datum | Status | Commit(s) | Notiz |
29
30
  |---|---|---|---|---|---|---|
31
+ | UCM-TEST-1 | A kit integration check every app runs in its own suite | Exported `checkKitIntegration({ i18n, wrapper, pages })` -> `{ findings }` (shape of `assertThemeComplete`): kit keys present in the app's i18n, one `i18next` instance, kit pages render in the app's providers without raw keys, the `invalid`-email case shows the field text. Replaces per-app hand-written wiring tests and manual auth walks. Full order [`work-orders/UCM-TEST-1.md`](work-orders/UCM-TEST-1.md) | 2026-10-01 | done | 2cde120 | Tier 3 (shared-core, auth surface) · operator decision 2026-10-01: central check, apps adopt with their next bump · companion: `workflow-templates` WFT-CI-31. Codex implemented (available today, no fallback). Orchestrator independently found + fixed before review: a false-positive in the raw-code render heuristic (a legitimate short lowercase kit-shipped value, e.g. German `"oder"` for `Auth.LOGIN_OR`, would otherwise be flagged as a leaked backend code — added a `KIT_VALUES` exemption + a pinning test), and independently proved Required Test 5 (resolver-bypassed -> error-text finding) via a transient mutation of `resolveErrorText.js`, restored clean. Independent `reviewer` (all 4 lenses) + `ui_reviewer` (Codex gpt-5.6-luna, concurrent background batch, full diff): **review: codex/gpt-5.6-luna · lenses: envelope,regression,duplication,tests,ui · 9 raised · 6 accepted · worst accepted: blocker**. Accepted and fixed: catalogue check didn't force `fallbackLng: false` per lookup, so a consumer's own `fallbackLng` config (survey_app's is `"de"`, not `"false"`) could silently resolve a missing-language key through the fallback and mask it (tests lens) — fixed, plus a dedicated test using a real fallback-configured instance; Required Test 6 only checked adapter reference-identity, not that a real post-check request actually reaches the real adapter (envelope lens) — strengthened with a sentinel-adapter test; React 19's `act()` needs `IS_REACT_ACT_ENVIRONMENT`, undocumented for consumers (ui lens) — added to the README example; README's `pages` description implied it fully replaces the default set, when `LoginPage` always additionally renders for the error-text check regardless (ui lens, nit) — clarified. Accepted, documented rather than redesigned: mutating the shared `apiClient.defaults.adapter` for the check's duration is process-wide and could intercept a concurrent real request from other code in the same test file (regression lens, blocker) — this is the Envelope's own decided stub design (`src/utils/auth-errors.js`-style module-singleton stubbing, same pattern already used throughout this suite), not fixable without abandoning that decision; added a README caveat instead of restructuring. Rejected: `RAW_CODE` only matches lowercase-snake-case, missing uppercase/hyphenated shapes (envelope + tests lenses, same point from both) — every real backend error code in this codebase (`src/utils/auth-errors.js`, allauth headless responses) is lowercase snake_case; widening the regex matches no real shape here and raises false-positive risk for marginal benefit. `KIT_VALUES` could let a leaked code evade detection if it coincidentally equals a real kit translation value (tests lens) — true but reintroducing the "oder" false positive to close it is a worse trade; no real backend code collides with the kit's UI copy in practice. The correctly-wired/legitimate-word/resolver/adapter-restore tests would all pass against a hardcoded `{findings:[]}` stub in isolation (tests lens, nit) — true of any happy-path assertion; each is paired with a failure-case test proving the same code path actually detects the defect (Required Tests 2-5), which is where the real proof lives. `duplication`: no capability-level overlap with `assertThemeComplete` or any shared-core/app module. **Verification** (WO's own instruction): ran `checkKitIntegration` once against survey_app's real wiring — not by touching that repo, but from inside this repo's own resolved environment, replicating `survey_app/frontend/i18n/index.js`'s real merge + config exactly (`fallbackLng: "de"`, survey_app's actual `translations.json`) plus this repo's real `AuthProvider` — **result: `findings: []`**, including against the real fallback-configured instance the tests-lens finding above was about. Orchestrator's own scoped run: `tests/checkKitIntegration.test.jsx` + `tests/resolveErrorText.test.js` (12 tests) + 7 directly-dependent files (33 tests) = 45/45 green via `npx vitest run <files> --pool=threads --maxWorkers=1`. No rendered gate — library-only change, no running app to preview. **Released as `3.10.0`** (minor — new exported capability, per the WO's own instruction). Per-app adoption rows are added by the Expertenchat when each app's next bump is scoped — not part of this WO. |
30
32
  | UCM-AUTH-11 | [`UserListComponent` offers an admin the delete action on their own row](work-orders/UCM-AUTH-11.md) | Without a `canDeleteUser` prop, `canDelete` falls back to `canEdit`, which is true for a superuser or role `admin` on EVERY row, their own included (`src/components/UserListComponent.jsx` `defaultCanEdit`/`canDelete`, ~l.128-156); the backend (dcm) still allows an admin's generic self-delete. Default should never offer deleting one's own row. | 2026-09-30 | released | 83bac37 | From django-core-micha `DCM-AUTH-4` (dropped there): operator decision 2026-09-30, UI-only, backend unchanged. Affected consumers measured: kerzenziehen and reimbursements render ucm's `AccountPage` without props (jg-ferien passes its own `userListCanDeleteUser` and already excludes itself). Both apps pin ucm **2.41.3**, so reaching them needs a major bump (3.0.0 removed chart layout props) — tracked as its own follow-up, not this WO. Gate #1 approved 2026-09-30 (operator handover). Codex implemented (available today, no fallback): new `isOwnRow(targetUser)` helper (`String(id) === String(id)`, `false` whenever either id is unresolved — covers the loading-state risk) gates the delete button's RENDER — `{showDeleteAction && !isOwnRow(row) && (...)}` — not its `disabled` state, so a consumer's `canDeleteUser` returning `true` for the own row cannot bring the button back; `canDelete`/`canEdit`/`defaultCanEdit` untouched. Independent `reviewer` (all 4 lenses) + `ui_reviewer` + `sec_reviewer` (Codex gpt-5.6-luna, concurrent background batch, full diff): **review: codex/gpt-5.6-luna · lenses: envelope,regression,duplication,tests,ui,sec · 3 raised · 1 accepted · worst accepted: nit**. Accepted (nit, tests lens): the committed fixtures only ever used numeric ids for both `currentUser` and the own row, so a strict-equality implementation would have passed every committed test despite violating the Envelope's own `3`/`"3"` identity requirement — added a fifth case with a string-vs-number id mismatch. Rejected: envelope lens's claim that "Required Test 5 (mutation proof) is missing" — the WO's own Part B (mirroring `UCM-THEME-15`/`UCM-PRIM-2`'s established pattern in this repo) asks for a TRANSIENT demonstration during implementation, not a permanent fifth test case; the implementer's own `PROGRESS` narration confirms it removed the gate, watched tests 1 and 3 fail (2 delete buttons found instead of 1), then restored — exactly as asked. Envelope lens's claim that "package.json remains 3.9.0 so the release is incomplete" — true at the moment the reviewer read the diff (version bump + register are the Orchestrator's own finalize step, explicitly forbidden to the implementer), not a defect in the change itself; done now. `regression`/`duplication`/`ui`/`sec` lenses: no findings — `sec_reviewer` specifically confirmed the render-gate cannot be reopened via `canDeleteUser`/`canEditUser`/`extraRowActions`, and that the backend's own continued refusal of an admin's self-delete (`DCM-AUTH-4`) means this UI-only fix is not masking a still-open server-side gap. Orchestrator's own scoped run: `tests/UserListComponent.test.jsx` 7/7 green + `tests/userScreenTranslations.test.jsx` (directly-dependent, also renders this component) 4/4 green, via `npx vitest run <files> --pool=threads --maxWorkers=1` (default fork pool repeatedly failed to start workers in this sandbox — an environment flake, not a code issue). No rendered gate — library component, no running app to preview; unit-tested only. **Released as `3.9.1`** (patch — behaviour fix of an existing component, no API change, per the WO's own instruction). `npm view @micha.bigler/ui-core-micha version` will read `3.9.1` once the registry's version-list index catches up to the just-completed publish (provenance-signed publishes report success immediately but can take a few minutes to appear in `npm view`/the registry API — confirmed via the GitHub Actions job log on the prior `UCM-AUTH-10` release, not re-verified here to avoid the same registry-lag false alarm). **Not done in this session** (per the WO's own Part C): registering the kerzenziehen/reimbursements major-bump follow-up rows in their own `WORK_ORDERS.md` registers — flagged for whoever next works in those repos. |
31
33
  | UCM-AUTH-10 | Error texts never show a raw backend code | One resolver for every kit error display: backend `i18nKey` > field key `Auth.field.<field>.<code>` > code key (AUTH-2) > backend message > caller default; `apiClient` sends the UI language as `Accept-Language`; `invalid`/`required` field keys for every submitted field; ~40 call sites migrated; reconstructs the missing 3.7.0 changelog entry. Full order [`work-orders/UCM-AUTH-10.md`](work-orders/UCM-AUTH-10.md) | 2026-09-30 | done | 9019d3d | Tier 3 (shared-core, auth screens, header on every request) · operator decision 2026-09-30: code-based UI, backend message as last specific fallback, UI language sent to the backend · found in `survey_app` SVA-DEP-1 acceptance (pre-existing, not a bump regression). Codex implemented (available today, no fallback): new `src/utils/resolveErrorText.js` (plain function, not a hook — called inside `catch` blocks) implementing steps 0-4 via `i18n.exists`/`i18n.t`; `extractErrorInfo`/`normaliseApiError` now carry `field` (`param` allauth / `field` dcm, normalised to one name), `i18nKey`, and `backendMessage` (never falls back to the code — the literal bug) as separate fields; `apiClient` gained a request interceptor sending `Accept-Language: i18next.language` only when `i18next.isInitialized` (never guesses); ~40 call sites across 22 files migrated to the uniform pattern (state now always holds resolved display text, never a bare key; render sites dropped their `t()` wrapper); 48 new `Auth.field.<field>.{invalid,required}` keys (24 fields, enumerated from `authApi.jsx`, all 4 locales + `de_informal` where wording differs); `CHANGELOG.md`'s missing `3.7.0` entry reconstructed. Independent `reviewer` (all 4 lenses) + `ui_reviewer` + `sec_reviewer` (Codex gpt-5.6-luna, concurrent background batch, full diff): **review: codex/gpt-5.6-luna · lenses: envelope,regression,duplication,tests,ui,sec · 12 raised · 4 accepted · worst accepted: defect**. Accepted: (defect, envelope lens — a real guard blind spot) `MFAComponent.jsx`'s `setErrorKey('Auth.MFA_TOTP_ALREADY_ACTIVE')` was a plain literal-key setter the mechanical sweep missed — the call-site-guard test only matches the `.code` pattern, not "any literal setter needs `t()` now that render dropped its wrapper"; would have displayed the raw key on screen, exactly the bug this WO exists to fix. Fixed (wrapped in `t()`); no dedicated test exists for this component, fix verified by direct code inspection only. (nit, ui_reviewer) the new field-key catalogue omitted `RegistrationMethodsManager.jsx`'s 5 boolean policy-toggle fields (`allow_admin_invite`, `allow_self_signup_{access_code,open,email_domain,qr}`); added, all 4 locales. (nit, tests lens) `resolveErrorText.test.js`'s "dcm field shape" case was byte-identical to the allauth-shape case, testing nothing new (the param/field normalisation it claimed to cover already happens one layer down, in `extractErrorInfo`, and is genuinely tested there); removed the redundant duplicate. Rejected: 2 lenses (envelope, ui_reviewer) claimed `SupportRecoveryRequestsTab.jsx` calls `resolveErrorText(i18n, …)` without destructuring `i18n` — verified directly against the file twice, `const { t, i18n } = useTranslation()` is present at line 42 and every call site is a closure over it; a stale/misread finding from both lenses, not a real defect. 3 lenses (envelope, regression, tests) flagged step 3 (`backendMessage` rendered verbatim) as an exposure risk — this is the Envelope's own **decided** design (`Operator decision: … the backend message as the last specific fallback`), not an implementation defect; `sec_reviewer` — the lens specifically briefed with dcm's S4 audit-log rationale and tasked with exactly this question — found no HTML-injection path and confirmed React's text-node escaping covers every render site, which is what the Envelope's own risk-review request was actually asking. `sec_reviewer` additionally flagged `BulkInviteCsvTab.jsx:88`'s `err.message` and `PasswordInvitePage.jsx:117`'s `err.raw.messages` as chain bypasses — the former is a purely local CSV-file-read error with no backend response involved at all (confirmed no `apiClient` call in that `try` block), the latter is `UCM-AUTH-9`'s already-shipped, already-reviewed password-rejection-reason display, unchanged by this WO and out of scope per its own non-goal ("no change to which errors are shown, where, or what triggers one"). `envelope`+`tests` lenses' claim that `auth-errors.js`'s native `.message` still falls back to the code — deliberate, per this WO's own Part B ("you may leave `err.message` with its existing fallback-to-code behaviour untouched") and covered by the implementer's own test; the field the resolver actually reads (`backendMessage`) correctly never falls back, which is what the Envelope's separation requirement is about. Orchestrator's own scoped run: 14 files, 102 tests green (`resolveErrorText`/`loginPageErrorResolution`/`errorCallSiteGuard`/`apiClientLanguage`/`authErrors`/`AccountPage`/`PasswordInvitePage`/`SignUpPage`/`UserListComponent`/`QrSignupManager.registrationContext`/`i18nAggregate`/`authTranslations`/`themeCompleteness`/`i18nGermanVariant`), via `npx vitest run <files> --pool=threads --maxWorkers=1` (the default fork pool repeatedly failed to start workers in this sandbox — an environment flake, not a code issue; the threads pool is stable). **Verification (the operator's exact screenshot case, rendered end to end):** `en` → "Enter a valid email address."; `de` → "Bitte geben Sie eine gültige E-Mail-Adresse ein." — both resolve via step 1 (`Auth.field.email.invalid`), never the raw `invalid` code, confirmed by `tests/loginPageErrorResolution.test.jsx` (`en`) and by the locale-agnostic resolver design (same key, `de` value) for `de`. No rendered browser gate — verified via the real `LoginPage` component rendered against a real i18next instance in the test harness. **Released as `3.9.0`** (minor, per the Envelope's own instruction — `resolveErrorText` is internal-only, not part of the public `src/index.js` surface). `npm view @micha.bigler/ui-core-micha version` should read `3.9.0` once `publish.yml` runs on this push. No consumer bump in this session (non-goal). |
32
34
  | UCM-THEME-15 | Derive status and control-border colours against the theme's own page | Baseline-supplied status `main` and `controlBorder` colours are derived against `#FFFFFF` + `background.default` (like `controlBorder.focus`), only when they would fail; a passing theme resolves byte-identically, app-set values are never touched. Full order [`work-orders/UCM-THEME-15.md`](work-orders/UCM-THEME-15.md) | 2026-09-29 | done | 4515e73 | Tier 3 (inside shared-core) · operator decision 2026-09-29: option (a), no exemptible contrast findings · unblocks `survey_app` SVA-THEME-1 and `survey_contact_app` SCA-THEME-1 (site half) after their pin bumps · lands before UCM-THEME-14. Gate #1 carried by the committed Envelope + mini-handover. Codex implemented (available today, no fallback): new `deriveDarkenedPageColour`/`deriveAlphaPageColour` helpers alongside (not replacing) the untouched `deriveFocusColour`/`clearsContrast`, using the kit's own alpha-aware `calculateContrastRatio` (not MUI's `getContrastRatio`, which is not documented to alpha-composite — matters for the translucent `controlBorder.main`/`.hover`); rule 3 (baseline vs app-supplied) checked per-key straight off `appConfig.palette`, never the resolved theme; `withMainShades` exported from `tokens.js` (internal-only, not part of the public package surface) so re-derivation reuses the real shade formula instead of duplicating it. Independent `reviewer` (all 4 lenses) + `ui_reviewer` (Codex gpt-5.6-luna, concurrent background batch, full diff), `ui_reviewer` specifically traced rule 3 through every merge path (the three-arg `paletteTheme` build and the final layered `createTheme` call) including a partial `controlBorder` override (app sets `.hover` only) — confirmed no defect, per-key checks hold: **review: codex/gpt-5.6-luna · lenses: envelope,regression,duplication,tests,ui · 6 raised · 3 accepted · worst accepted: defect**. Accepted (defect, tests+envelope lenses, same finding): the app-override test only covered `success.main`/`controlBorder.main`, leaving `warning`/`error`/`info` and `controlBorder.hover`/`.error` unpinned — extended to cover a second overridden status + all three `controlBorder` states, plus asserted the two NOT-overridden status keys (`error`/`info`) still derive normally on the same tinted page (proves rule 3 is per-key, not per-object). (defect, tests lens) the termination test asserted only the status-derivation path terminates — added assertions that `controlBorder.main/hover/error` are also defined (not thrown) on the unreachable page. (nit, ui_reviewer) `DESIGN.md` said the baseline "promises a passing colour" — overstated, since capped derivation can still leave an unreachable page failing; softened to name the cap explicitly. Rejected: nit that exporting `withMainShades` violates "no API change" (it is an internal `tokens.js`↔`createAppTheme.js` module export, never re-exported from the public `src/index.js` surface — verified directly, zero consumer-visible surface change); nit that the byte-identity test "isn't evidence of the new derivation" (it is a different, explicitly required test — Required Test #2 — a regression/parity guard, not required to also prove the derivation path, which tests #1/#3/#4 already do). Orchestrator's own scoped run: `tests/createAppThemePageContrast.test.js` 9/9 green + 45/45 directly-dependent (`createAppTheme`/`themeCompleteness`), all via `npx vitest run <files> --maxWorkers=1`. No rendered gate — library component, no running app to preview; unit-tested only. **Verification data (re-derived from the built themes, per the Envelope's own acceptance criterion):** baseline `#FAFAFA` — unchanged (`success #1B8038`/`warning #976100`/`error #BF3227`/`info #01579B`/`border.main rgba(33,37,41,.50)`/`border.hover rgba(33,37,41,.65)`/`border.error #BF3227`). `hafen #D8E4E1`, `jg-fegbern #eceae2`, `routing #E8EAF6`, `uph #E6EAF0` (all four move the same two channels): `success rgb(24-25,115-121,50-53)`, `warning rgb(135-143,87-92,0)`, `border.main rgba(33,37,41,0.55)`; `error`/`info`/`border.hover`/`border.error` unchanged (matches the Envelope's table — only success/warning/border.main failed on these). `ygbs #E398C7` (all measured channels failed, all move): `success rgb(16,76,33)`, `warning rgb(90,58,0)`, `error rgb(124,32,25)`, `info rgb(0,65,116)`, `border.main rgba(33,37,41,0.6)`, `border.error rgb(171,45,35)`; `border.hover` unchanged (`.65` alpha already clears 3:1 even on this page). **Released as `3.8.0`** (minor: changed default for currently-failing themes only, no API change, no adopted app moves — per the Envelope's own framing). `npm view @micha.bigler/ui-core-micha version` should read `3.8.0` once `publish.yml` runs on this push. Next: add `planned` pin-bump rows in `survey_app/WORK_ORDERS.md` and `survey_contact_app/WORK_ORDERS.md` (from `2.41.3`, classify via the dependency-bump test in `AGENTS.md` → Tiering) and unblock `SVA-THEME-1`/`SCA-THEME-1` — not done in this session, flagged for the next one touching those repos. |
package/dist/index.js CHANGED
@@ -6,6 +6,8 @@
6
6
  import './theme/fonts';
7
7
  // --- 0. Theme ---
8
8
  export { createAppTheme, assertThemeComplete, assertKitSxDisjoint, calculateContrastRatio, KIT_COMPONENT_SX_REGISTRY, reportOffPaletteColours, reportKitSxBypasses, reportRedundantThemeValues, reportThemeAdoption, THEME_COMPLETENESS_SURFACES, } from './theme';
9
+ // --- 0.1 Consumer integration ---
10
+ export { checkKitIntegration } from './testing/checkKitIntegration';
9
11
  // --- 1. Auth Context (Essentiell für den Wrapper) ---
10
12
  export { AuthContext, AuthProvider } from './auth/AuthContext';
11
13
  export { UserMenu } from './auth/UserMenu';
@@ -0,0 +1,201 @@
1
+ import React, { act } from 'react';
2
+ import { createRoot } from 'react-dom/client';
3
+ import { MemoryRouter } from 'react-router-dom';
4
+ import i18next from 'i18next';
5
+ import apiClient from '../auth/apiClient';
6
+ import { LoginPage } from '../pages/LoginPage';
7
+ import { SignUpPage } from '../pages/SignUpPage';
8
+ import { PasswordInvitePage } from '../pages/PasswordInvitePage';
9
+ import { uiCoreTranslations } from '../i18n/uiCoreTranslations';
10
+ const KIT_LANGUAGES = ['de', 'en', 'fr', 'sw'];
11
+ const LOGIN_PATH = '/api/auth/browser/v1/auth/login';
12
+ const RAW_CODE = /^[a-z][a-z0-9_]*$/;
13
+ function pageName(Page) {
14
+ return (Page === null || Page === void 0 ? void 0 : Page.displayName) || (Page === null || Page === void 0 ? void 0 : Page.name) || 'page';
15
+ }
16
+ function appLanguages(i18n) {
17
+ var _a, _b;
18
+ const candidates = [
19
+ (_a = i18n === null || i18n === void 0 ? void 0 : i18n.options) === null || _a === void 0 ? void 0 : _a.supportedLngs,
20
+ Object.keys(((_b = i18n === null || i18n === void 0 ? void 0 : i18n.options) === null || _b === void 0 ? void 0 : _b.resources) || {}),
21
+ i18n === null || i18n === void 0 ? void 0 : i18n.languages,
22
+ ];
23
+ for (const candidate of candidates) {
24
+ const languages = Array.isArray(candidate)
25
+ ? candidate.filter((language) => language && language !== 'cimode')
26
+ : [];
27
+ if (languages.length > 0)
28
+ return languages;
29
+ }
30
+ return [];
31
+ }
32
+ function textNodes(container) {
33
+ var _a;
34
+ const result = [];
35
+ const document = container.ownerDocument;
36
+ const filter = ((_a = document.defaultView) === null || _a === void 0 ? void 0 : _a.NodeFilter) || NodeFilter;
37
+ const walker = document.createTreeWalker(container, filter.SHOW_TEXT);
38
+ let node;
39
+ while ((node = walker.nextNode())) {
40
+ const text = node.textContent.trim();
41
+ if (text)
42
+ result.push(text);
43
+ }
44
+ return result;
45
+ }
46
+ const KIT_KEYS = new Set(Object.keys(uiCoreTranslations));
47
+ // Every legitimate string the kit itself ships, across all locales -- a short,
48
+ // all-lowercase, no-space word can still be entirely legitimate rendered prose
49
+ // (e.g. `Auth.LOGIN_OR`'s German value is literally "oder", which the bare
50
+ // RAW_CODE shape below would otherwise flag as a raw backend code). Exempting
51
+ // anything that IS one of the kit's own translated values keeps the check
52
+ // looking for text that is NEITHER a key NOR a real translation -- which is
53
+ // exactly what a leaked backend code is, and a legitimate short word never is.
54
+ const KIT_VALUES = new Set(Object.values(uiCoreTranslations).flatMap((entry) => Object.values(entry)));
55
+ function scanPage(container, name) {
56
+ return textNodes(container)
57
+ .filter((text) => (KIT_KEYS.has(text)
58
+ || (!KIT_VALUES.has(text) && text.length > 2 && RAW_CODE.test(text))))
59
+ .map((text) => ({
60
+ check: 'render',
61
+ reason: `${name} rendered raw kit key or backend code: ${text}`,
62
+ }));
63
+ }
64
+ async function renderPage(Page, wrapper, initialEntries = ['/']) {
65
+ const container = document.createElement('div');
66
+ const root = createRoot(container);
67
+ try {
68
+ await act(async () => {
69
+ root.render(React.createElement(MemoryRouter, { initialEntries }, React.createElement(wrapper, null, React.createElement(Page))));
70
+ await Promise.resolve();
71
+ });
72
+ return { container, findings: scanPage(container, pageName(Page)) };
73
+ }
74
+ finally {
75
+ await act(async () => {
76
+ root.unmount();
77
+ });
78
+ }
79
+ }
80
+ function transportFailure(config) {
81
+ return Promise.reject(new Error(`checkKitIntegration blocked request: ${(config === null || config === void 0 ? void 0 : config.url) || 'unknown'}`));
82
+ }
83
+ function loginFailure() {
84
+ return Promise.reject({
85
+ response: {
86
+ status: 400,
87
+ data: {
88
+ errors: [{
89
+ code: 'invalid',
90
+ param: 'email',
91
+ message: 'The email address is invalid.',
92
+ }],
93
+ },
94
+ },
95
+ });
96
+ }
97
+ async function renderFindings(Page, wrapper, initialEntries) {
98
+ try {
99
+ const rendered = await renderPage(Page, wrapper, initialEntries);
100
+ return rendered.findings;
101
+ }
102
+ catch (error) {
103
+ return [{
104
+ check: 'render',
105
+ reason: `${pageName(Page)} threw while rendering: ${(error === null || error === void 0 ? void 0 : error.message) || String(error)}`,
106
+ }];
107
+ }
108
+ }
109
+ async function errorTextFindings(i18n, wrapper) {
110
+ const Page = LoginPage;
111
+ const name = pageName(Page);
112
+ const container = document.createElement('div');
113
+ const root = createRoot(container);
114
+ try {
115
+ await act(async () => {
116
+ root.render(React.createElement(MemoryRouter, { initialEntries: ['/login'] }, React.createElement(wrapper, null, React.createElement(Page))));
117
+ await Promise.resolve();
118
+ });
119
+ const inputs = Array.from(container.querySelectorAll('input'));
120
+ const email = inputs.find((input) => input.type === 'email');
121
+ const password = inputs.find((input) => input.type === 'password');
122
+ const form = container.querySelector('form');
123
+ if (!email || !password || !form) {
124
+ return [{ check: 'error-text', reason: `${name} did not render its login form.` }];
125
+ }
126
+ const setValue = (input, value) => {
127
+ const setter = Object.getOwnPropertyDescriptor(input.ownerDocument.defaultView.HTMLInputElement.prototype, 'value').set;
128
+ setter.call(input, value);
129
+ input.dispatchEvent(new Event('input', { bubbles: true }));
130
+ input.dispatchEvent(new Event('change', { bubbles: true }));
131
+ };
132
+ await act(async () => {
133
+ setValue(email, 'not-an-email@example.com');
134
+ setValue(password, 'password');
135
+ form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
136
+ await Promise.resolve();
137
+ await Promise.resolve();
138
+ });
139
+ const expected = i18n.t('Auth.field.email.invalid');
140
+ const renderedTexts = textNodes(container);
141
+ if (renderedTexts.includes(expected))
142
+ return [];
143
+ return [{
144
+ check: 'error-text',
145
+ reason: `${name} did not show ${expected} for the allauth invalid-email response.`,
146
+ }];
147
+ }
148
+ catch (error) {
149
+ return [{
150
+ check: 'error-text',
151
+ reason: `${name} error flow failed: ${(error === null || error === void 0 ? void 0 : error.message) || String(error)}`,
152
+ }];
153
+ }
154
+ finally {
155
+ await act(async () => {
156
+ root.unmount();
157
+ });
158
+ }
159
+ }
160
+ /** Check that an app's i18n instance and providers wire the kit pages correctly. */
161
+ export async function checkKitIntegration({ i18n, wrapper, pages = [LoginPage, SignUpPage, PasswordInvitePage], }) {
162
+ const findings = [];
163
+ const languages = appLanguages(i18n);
164
+ const sharedLanguages = KIT_LANGUAGES.filter((language) => languages.includes(language));
165
+ for (const [key] of Object.entries(uiCoreTranslations)) {
166
+ for (const language of sharedLanguages) {
167
+ // fallbackLng: false forces a true per-language check -- without it, a
168
+ // consumer's own fallbackLng config (e.g. "en") would let a key missing
169
+ // in "fr" silently resolve through the fallback and read as present.
170
+ if (!(i18n === null || i18n === void 0 ? void 0 : i18n.exists(key, { lng: language, fallbackLng: false }))) {
171
+ findings.push({
172
+ check: 'catalogue',
173
+ reason: `Missing kit translation key ${key} for language ${language}.`,
174
+ });
175
+ }
176
+ }
177
+ }
178
+ if (!i18next.isInitialized || i18n !== i18next) {
179
+ findings.push({
180
+ check: 'instance',
181
+ reason: 'The app i18n is not the initialized kit default instance; Accept-Language will be missing or wrong.',
182
+ });
183
+ }
184
+ const originalAdapter = apiClient.defaults.adapter;
185
+ apiClient.defaults.adapter = async (config) => {
186
+ if ((config === null || config === void 0 ? void 0 : config.url) === LOGIN_PATH || String((config === null || config === void 0 ? void 0 : config.url) || '').endsWith(LOGIN_PATH)) {
187
+ return loginFailure();
188
+ }
189
+ return transportFailure(config);
190
+ };
191
+ try {
192
+ for (const Page of pages) {
193
+ findings.push(...await renderFindings(Page, wrapper));
194
+ }
195
+ findings.push(...await errorTextFindings(i18n, wrapper));
196
+ }
197
+ finally {
198
+ apiClient.defaults.adapter = originalAdapter;
199
+ }
200
+ return { findings };
201
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@micha.bigler/ui-core-micha",
3
- "version": "3.9.1",
3
+ "version": "3.10.0",
4
4
  "main": "dist/index.js",
5
5
  "module": "dist/index.js",
6
6
  "sideEffects": [
package/src/index.js CHANGED
@@ -20,6 +20,9 @@ export {
20
20
  THEME_COMPLETENESS_SURFACES,
21
21
  } from './theme';
22
22
 
23
+ // --- 0.1 Consumer integration ---
24
+ export { checkKitIntegration } from './testing/checkKitIntegration';
25
+
23
26
  // --- 1. Auth Context (Essentiell für den Wrapper) ---
24
27
  export { AuthContext, AuthProvider } from './auth/AuthContext';
25
28
  export { UserMenu } from './auth/UserMenu';
@@ -0,0 +1,233 @@
1
+ import React, { act } from 'react';
2
+ import { createRoot } from 'react-dom/client';
3
+ import { MemoryRouter } from 'react-router-dom';
4
+ import i18next from 'i18next';
5
+
6
+ import apiClient from '../auth/apiClient';
7
+ import { LoginPage } from '../pages/LoginPage';
8
+ import { SignUpPage } from '../pages/SignUpPage';
9
+ import { PasswordInvitePage } from '../pages/PasswordInvitePage';
10
+ import { uiCoreTranslations } from '../i18n/uiCoreTranslations';
11
+
12
+ const KIT_LANGUAGES = ['de', 'en', 'fr', 'sw'];
13
+ const LOGIN_PATH = '/api/auth/browser/v1/auth/login';
14
+ const RAW_CODE = /^[a-z][a-z0-9_]*$/;
15
+
16
+ function pageName(Page) {
17
+ return Page?.displayName || Page?.name || 'page';
18
+ }
19
+
20
+ function appLanguages(i18n) {
21
+ const candidates = [
22
+ i18n?.options?.supportedLngs,
23
+ Object.keys(i18n?.options?.resources || {}),
24
+ i18n?.languages,
25
+ ];
26
+
27
+ for (const candidate of candidates) {
28
+ const languages = Array.isArray(candidate)
29
+ ? candidate.filter((language) => language && language !== 'cimode')
30
+ : [];
31
+ if (languages.length > 0) return languages;
32
+ }
33
+ return [];
34
+ }
35
+
36
+ function textNodes(container) {
37
+ const result = [];
38
+ const document = container.ownerDocument;
39
+ const filter = document.defaultView?.NodeFilter || NodeFilter;
40
+ const walker = document.createTreeWalker(container, filter.SHOW_TEXT);
41
+ let node;
42
+ while ((node = walker.nextNode())) {
43
+ const text = node.textContent.trim();
44
+ if (text) result.push(text);
45
+ }
46
+ return result;
47
+ }
48
+
49
+ const KIT_KEYS = new Set(Object.keys(uiCoreTranslations));
50
+ // Every legitimate string the kit itself ships, across all locales -- a short,
51
+ // all-lowercase, no-space word can still be entirely legitimate rendered prose
52
+ // (e.g. `Auth.LOGIN_OR`'s German value is literally "oder", which the bare
53
+ // RAW_CODE shape below would otherwise flag as a raw backend code). Exempting
54
+ // anything that IS one of the kit's own translated values keeps the check
55
+ // looking for text that is NEITHER a key NOR a real translation -- which is
56
+ // exactly what a leaked backend code is, and a legitimate short word never is.
57
+ const KIT_VALUES = new Set(
58
+ Object.values(uiCoreTranslations).flatMap((entry) => Object.values(entry)),
59
+ );
60
+
61
+ function scanPage(container, name) {
62
+ return textNodes(container)
63
+ .filter((text) => (
64
+ KIT_KEYS.has(text)
65
+ || (!KIT_VALUES.has(text) && text.length > 2 && RAW_CODE.test(text))
66
+ ))
67
+ .map((text) => ({
68
+ check: 'render',
69
+ reason: `${name} rendered raw kit key or backend code: ${text}`,
70
+ }));
71
+ }
72
+
73
+ async function renderPage(Page, wrapper, initialEntries = ['/']) {
74
+ const container = document.createElement('div');
75
+ const root = createRoot(container);
76
+ try {
77
+ await act(async () => {
78
+ root.render(React.createElement(
79
+ MemoryRouter,
80
+ { initialEntries },
81
+ React.createElement(wrapper, null, React.createElement(Page)),
82
+ ));
83
+ await Promise.resolve();
84
+ });
85
+ return { container, findings: scanPage(container, pageName(Page)) };
86
+ } finally {
87
+ await act(async () => {
88
+ root.unmount();
89
+ });
90
+ }
91
+ }
92
+
93
+ function transportFailure(config) {
94
+ return Promise.reject(new Error(`checkKitIntegration blocked request: ${config?.url || 'unknown'}`));
95
+ }
96
+
97
+ function loginFailure() {
98
+ return Promise.reject({
99
+ response: {
100
+ status: 400,
101
+ data: {
102
+ errors: [{
103
+ code: 'invalid',
104
+ param: 'email',
105
+ message: 'The email address is invalid.',
106
+ }],
107
+ },
108
+ },
109
+ });
110
+ }
111
+
112
+ async function renderFindings(Page, wrapper, initialEntries) {
113
+ try {
114
+ const rendered = await renderPage(Page, wrapper, initialEntries);
115
+ return rendered.findings;
116
+ } catch (error) {
117
+ return [{
118
+ check: 'render',
119
+ reason: `${pageName(Page)} threw while rendering: ${error?.message || String(error)}`,
120
+ }];
121
+ }
122
+ }
123
+
124
+ async function errorTextFindings(i18n, wrapper) {
125
+ const Page = LoginPage;
126
+ const name = pageName(Page);
127
+ const container = document.createElement('div');
128
+ const root = createRoot(container);
129
+ try {
130
+ await act(async () => {
131
+ root.render(React.createElement(
132
+ MemoryRouter,
133
+ { initialEntries: ['/login'] },
134
+ React.createElement(wrapper, null, React.createElement(Page)),
135
+ ));
136
+ await Promise.resolve();
137
+ });
138
+
139
+ const inputs = Array.from(container.querySelectorAll('input'));
140
+ const email = inputs.find((input) => input.type === 'email');
141
+ const password = inputs.find((input) => input.type === 'password');
142
+ const form = container.querySelector('form');
143
+ if (!email || !password || !form) {
144
+ return [{ check: 'error-text', reason: `${name} did not render its login form.` }];
145
+ }
146
+
147
+ const setValue = (input, value) => {
148
+ const setter = Object.getOwnPropertyDescriptor(
149
+ input.ownerDocument.defaultView.HTMLInputElement.prototype,
150
+ 'value',
151
+ ).set;
152
+ setter.call(input, value);
153
+ input.dispatchEvent(new Event('input', { bubbles: true }));
154
+ input.dispatchEvent(new Event('change', { bubbles: true }));
155
+ };
156
+
157
+ await act(async () => {
158
+ setValue(email, 'not-an-email@example.com');
159
+ setValue(password, 'password');
160
+ form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
161
+ await Promise.resolve();
162
+ await Promise.resolve();
163
+ });
164
+
165
+ const expected = i18n.t('Auth.field.email.invalid');
166
+ const renderedTexts = textNodes(container);
167
+ if (renderedTexts.includes(expected)) return [];
168
+ return [{
169
+ check: 'error-text',
170
+ reason: `${name} did not show ${expected} for the allauth invalid-email response.`,
171
+ }];
172
+ } catch (error) {
173
+ return [{
174
+ check: 'error-text',
175
+ reason: `${name} error flow failed: ${error?.message || String(error)}`,
176
+ }];
177
+ } finally {
178
+ await act(async () => {
179
+ root.unmount();
180
+ });
181
+ }
182
+ }
183
+
184
+ /** Check that an app's i18n instance and providers wire the kit pages correctly. */
185
+ export async function checkKitIntegration({
186
+ i18n,
187
+ wrapper,
188
+ pages = [LoginPage, SignUpPage, PasswordInvitePage],
189
+ }) {
190
+ const findings = [];
191
+ const languages = appLanguages(i18n);
192
+ const sharedLanguages = KIT_LANGUAGES.filter((language) => languages.includes(language));
193
+
194
+ for (const [key] of Object.entries(uiCoreTranslations)) {
195
+ for (const language of sharedLanguages) {
196
+ // fallbackLng: false forces a true per-language check -- without it, a
197
+ // consumer's own fallbackLng config (e.g. "en") would let a key missing
198
+ // in "fr" silently resolve through the fallback and read as present.
199
+ if (!i18n?.exists(key, { lng: language, fallbackLng: false })) {
200
+ findings.push({
201
+ check: 'catalogue',
202
+ reason: `Missing kit translation key ${key} for language ${language}.`,
203
+ });
204
+ }
205
+ }
206
+ }
207
+
208
+ if (!i18next.isInitialized || i18n !== i18next) {
209
+ findings.push({
210
+ check: 'instance',
211
+ reason: 'The app i18n is not the initialized kit default instance; Accept-Language will be missing or wrong.',
212
+ });
213
+ }
214
+
215
+ const originalAdapter = apiClient.defaults.adapter;
216
+ apiClient.defaults.adapter = async (config) => {
217
+ if (config?.url === LOGIN_PATH || String(config?.url || '').endsWith(LOGIN_PATH)) {
218
+ return loginFailure();
219
+ }
220
+ return transportFailure(config);
221
+ };
222
+
223
+ try {
224
+ for (const Page of pages) {
225
+ findings.push(...await renderFindings(Page, wrapper));
226
+ }
227
+ findings.push(...await errorTextFindings(i18n, wrapper));
228
+ } finally {
229
+ apiClient.defaults.adapter = originalAdapter;
230
+ }
231
+
232
+ return { findings };
233
+ }
@@ -0,0 +1,219 @@
1
+ // @vitest-environment jsdom
2
+ import React from 'react';
3
+ import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
4
+ import i18next from 'i18next';
5
+ import { I18nextProvider } from 'react-i18next';
6
+
7
+ import apiClient from '../src/auth/apiClient';
8
+ import { AuthContext } from '../src/auth/AuthContext';
9
+ import { checkKitIntegration } from '../src/testing/checkKitIntegration';
10
+ import { uiCoreTranslations } from '../src/i18n/uiCoreTranslations';
11
+ import { LoginPage } from '../src/pages/LoginPage';
12
+
13
+ const languages = ['de', 'en', 'fr', 'sw'];
14
+ const authMethods = {
15
+ password_login: true,
16
+ password_reset: false,
17
+ signup: false,
18
+ signup_modes: [],
19
+ social_login: false,
20
+ passkey_login: false,
21
+ };
22
+
23
+ function resources() {
24
+ return Object.fromEntries(languages.map((language) => [language, {
25
+ translation: Object.fromEntries(
26
+ Object.entries(uiCoreTranslations).map(([key, values]) => [key, values[language]]),
27
+ ),
28
+ }]));
29
+ }
30
+
31
+ function makeWrapper(instance, authMethodsOverride = authMethods) {
32
+ return function FixtureWrapper({ children }) {
33
+ return (
34
+ <I18nextProvider i18n={instance}>
35
+ <AuthContext.Provider value={{
36
+ user: null,
37
+ loading: false,
38
+ login: vi.fn(),
39
+ authMethods: authMethodsOverride,
40
+ }}>
41
+ {children}
42
+ </AuthContext.Provider>
43
+ </I18nextProvider>
44
+ );
45
+ };
46
+ }
47
+
48
+ beforeAll(async () => {
49
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true;
50
+ await i18next.init({
51
+ lng: 'en',
52
+ fallbackLng: false,
53
+ supportedLngs: languages,
54
+ resources: resources(),
55
+ keySeparator: false,
56
+ nsSeparator: false,
57
+ interpolation: { escapeValue: false },
58
+ });
59
+ });
60
+
61
+ afterEach(async () => {
62
+ await i18next.changeLanguage('en');
63
+ for (const language of languages) {
64
+ i18next.removeResourceBundle(language, 'translation');
65
+ i18next.addResourceBundle(language, 'translation', resources()[language].translation, true, true);
66
+ }
67
+ });
68
+
69
+ describe('checkKitIntegration', () => {
70
+ it('passes for a correctly wired app fixture', async () => {
71
+ const { findings } = await checkKitIntegration({
72
+ i18n: i18next,
73
+ wrapper: makeWrapper(i18next),
74
+ pages: [LoginPage],
75
+ });
76
+
77
+ expect(findings).toEqual([]);
78
+ });
79
+
80
+ it('does not flag a legitimate short lowercase translated word as a raw backend code', async () => {
81
+ // Auth.LOGIN_OR's German value is literally "oder" -- all-lowercase, no
82
+ // spaces, length 4 -- the exact shape a naive raw-code heuristic would
83
+ // false-positive on. Render LoginForm's sign-up/forgot-password divider
84
+ // (onSignUp truthy) in German to actually exercise that rendered text.
85
+ await i18next.changeLanguage('de');
86
+ const { findings } = await checkKitIntegration({
87
+ i18n: i18next,
88
+ wrapper: makeWrapper(i18next, { ...authMethods, signup: true, signup_modes: ['self_signup_open'] }),
89
+ pages: [LoginPage],
90
+ });
91
+
92
+ expect(findings).toEqual([]);
93
+ });
94
+
95
+ it('reports one catalogue finding for one missing language key', async () => {
96
+ const key = 'Auth.field.email.invalid';
97
+ const french = { ...resources().fr.translation };
98
+ delete french[key];
99
+ i18next.removeResourceBundle('fr', 'translation');
100
+ i18next.addResourceBundle('fr', 'translation', french, true, true);
101
+
102
+ const { findings } = await checkKitIntegration({
103
+ i18n: i18next,
104
+ wrapper: makeWrapper(i18next),
105
+ pages: [],
106
+ });
107
+
108
+ expect(findings).toHaveLength(1);
109
+ expect(findings[0]).toMatchObject({ check: 'catalogue' });
110
+ expect(findings[0].reason).toContain(`${key} for language fr`);
111
+ });
112
+
113
+ it('still reports a missing key when the consumer app configures a fallback language', async () => {
114
+ // A consumer typically sets fallbackLng (e.g. "en"), not "false" like the
115
+ // fixture above. Without forcing fallbackLng: false per-call, i18next's
116
+ // exists() would resolve the missing "fr" key through the fallback and
117
+ // read as present, masking the real gap this check exists to catch.
118
+ const key = 'Auth.field.email.invalid';
119
+ const french = { ...resources().fr.translation };
120
+ delete french[key];
121
+ i18next.removeResourceBundle('fr', 'translation');
122
+ i18next.addResourceBundle('fr', 'translation', french, true, true);
123
+ i18next.options.fallbackLng = 'en';
124
+
125
+ try {
126
+ const { findings } = await checkKitIntegration({
127
+ i18n: i18next,
128
+ wrapper: makeWrapper(i18next),
129
+ pages: [],
130
+ });
131
+
132
+ expect(findings).toHaveLength(1);
133
+ expect(findings[0]).toMatchObject({ check: 'catalogue' });
134
+ expect(findings[0].reason).toContain(`${key} for language fr`);
135
+ } finally {
136
+ i18next.options.fallbackLng = false;
137
+ }
138
+ });
139
+
140
+ it('reports when the app passes a separate i18next instance', async () => {
141
+ const separate = i18next.createInstance();
142
+ await separate.init({
143
+ lng: 'en',
144
+ fallbackLng: false,
145
+ supportedLngs: languages,
146
+ resources: resources(),
147
+ keySeparator: false,
148
+ nsSeparator: false,
149
+ });
150
+
151
+ const { findings } = await checkKitIntegration({
152
+ i18n: separate,
153
+ wrapper: makeWrapper(separate),
154
+ pages: [],
155
+ });
156
+
157
+ expect(findings.some(({ check }) => check === 'instance')).toBe(true);
158
+ });
159
+
160
+ it('reports a page when the consumer wrapper throws', async () => {
161
+ function ThrowingWrapper() {
162
+ throw new Error('provider exploded');
163
+ }
164
+
165
+ const before = apiClient.defaults.adapter;
166
+ const { findings } = await checkKitIntegration({
167
+ i18n: i18next,
168
+ wrapper: ThrowingWrapper,
169
+ pages: [LoginPage],
170
+ });
171
+
172
+ expect(findings.some(({ check, reason }) => check === 'render' && reason.includes('LoginPage'))).toBe(true);
173
+ expect(apiClient.defaults.adapter).toBe(before);
174
+ });
175
+
176
+ it('passes the exact invalid-email resolver regression through the real login page', async () => {
177
+ const { findings } = await checkKitIntegration({
178
+ i18n: i18next,
179
+ wrapper: makeWrapper(i18next),
180
+ pages: [],
181
+ });
182
+
183
+ expect(findings).toEqual([]);
184
+ });
185
+
186
+ it('restores the transport adapter after a successful check', async () => {
187
+ const before = apiClient.defaults.adapter;
188
+ await checkKitIntegration({
189
+ i18n: i18next,
190
+ wrapper: makeWrapper(i18next),
191
+ pages: [],
192
+ });
193
+ expect(apiClient.defaults.adapter).toBe(before);
194
+ });
195
+
196
+ it('no longer intercepts a real request once the check has finished', async () => {
197
+ // Proves the restore is functional, not just reference-equal: a request
198
+ // made AFTER the check completes must reach the app's own adapter, not
199
+ // the check's stub (which would reject it as "blocked" or fake a login
200
+ // failure for the allauth login path).
201
+ const sentinel = vi.fn().mockResolvedValue({ data: 'real-response', status: 200, headers: {}, config: {} });
202
+ const before = apiClient.defaults.adapter;
203
+ apiClient.defaults.adapter = sentinel;
204
+
205
+ try {
206
+ await checkKitIntegration({
207
+ i18n: i18next,
208
+ wrapper: makeWrapper(i18next),
209
+ pages: [],
210
+ });
211
+
212
+ const response = await apiClient.get('/api/some/path');
213
+ expect(sentinel).toHaveBeenCalled();
214
+ expect(response.data).toBe('real-response');
215
+ } finally {
216
+ apiClient.defaults.adapter = before;
217
+ }
218
+ });
219
+ });
@@ -0,0 +1,304 @@
1
+ # UCM-TEST-1: A kit integration check every app runs in its own suite
2
+
3
+ # A. Envelope, authored by the Expertenchat
4
+
5
+ ## Goal & expected outcome
6
+
7
+ The kit's auth screens are the same code in every app, so their behaviour is accepted once, in the kit.
8
+ What differs per app is **how the app wires the kit in**: its i18n setup, its providers around the kit's
9
+ pages, the `i18next` instance the kit reads. Today each bump order writes its own tests for that, app by
10
+ app, and the operator walked the same auth flows by hand in every app.
11
+
12
+ After this order the kit ships **one exported check**, `checkKitIntegration`, that an app calls from a
13
+ single test in its own suite. It returns findings in the style of `assertThemeComplete`: an empty list
14
+ means the app's wiring is sound. Every later bump in every app then re-checks the wiring automatically.
15
+
16
+ **Operator decisions (2026-10-01):** the check lives centrally in the kit, not as copies per app; a
17
+ separate, automated staging smoke covers the runtime (`workflow-templates` `WFT-CI-31`); bumps already
18
+ in flight are not held up, and apps adopt the check with their next bump.
19
+
20
+ ## Context the operator established
21
+
22
+ - **Precedent for the shape:** `assertThemeComplete(theme)` returns `{ findings }`, is exported from the
23
+ package root (`src/index.js:12`), and apps assert `findings` equals `[]`.
24
+ - **What apps load from the kit for i18n:** `uiCoreTranslations` (`src/i18n/uiCoreTranslations.js`),
25
+ which spreads the auth, charts, messaging, notifications, onboarding, section-nav and user-menu
26
+ catalogues. Apps spread it into their own i18next resources at start-up, **kit keys last** (e.g.
27
+ `survey_app/frontend/i18n/index.js`).
28
+ - **Which `i18next` the kit reads:** `apiClient` imports the **default** `i18next` instance
29
+ (`src/auth/apiClient.jsx:2,13`) to send `Accept-Language`. Kit components read `t` and `i18n` from
30
+ `useTranslation()` (e.g. `src/pages/LoginPage.jsx:30`). `i18next`/`react-i18next` are peer
31
+ dependencies.
32
+ - **What the per-app bump orders tested by hand** (`survey_app` `SVA-DEP-1`/`SVA-DEP-2`): the kit's
33
+ `SignUpPage` and `PasswordInvitePage` render inside the app's providers
34
+ (`survey_app/frontend/src/AuthRoutesIntegration.test.jsx`), and `i18n.exists('Auth.field.email.invalid')`
35
+ holds in the app's own i18n.
36
+ - **The defect this guards against end to end:** a login with a malformed e-mail showed the raw code
37
+ `invalid` (`UCM-AUTH-10`). The kit's resolver fixes it, but only if the app's i18n carries the kit's
38
+ keys and the kit's pages run on the app's instance.
39
+ - **Consumers measured 2026-09-30:** every consumer runs `vitest` with jsdom. Some mount `LoginPage`
40
+ twice (`webshop-guenter` also in `src/pages/pwa/StaffLoginPage.jsx`). Several mock `react-i18next`
41
+ globally in some test files.
42
+
43
+ ## The check (decided)
44
+
45
+ `checkKitIntegration({ i18n, wrapper, pages })` -> `Promise<{ findings }>`, exported from the package
46
+ root. `i18n` is the app's own instance, `wrapper` the app's own provider component (whatever the app
47
+ puts around its routes), `pages` the kit pages the app mounts (default: the kit's auth pages that the
48
+ app imports). Each finding names its check and a reason. Four checks:
49
+
50
+ 1. **Catalogue.** Every key in `uiCoreTranslations` resolves through the app's `i18n` in every language
51
+ that both the kit ships (`de`/`en`/`fr`/`sw`) and the app supports. A missing key is one finding,
52
+ with key and language.
53
+ 2. **Instance.** The default `i18next` instance is initialised and is the instance the app passed in.
54
+ Otherwise the finding says what will break: `Accept-Language` is missing or wrong.
55
+ 3. **Render.** Each page in `pages` renders inside `wrapper` without throwing, and no rendered text
56
+ node is a raw kit key (`Auth.*` or another key of the kit's catalogues) or a bare backend code. The
57
+ check stubs the kit's `apiClient` transport for its own duration, so no request leaves the test, and
58
+ restores it afterwards.
59
+ 4. **Error text.** `LoginPage` inside `wrapper` receives, through that stub, exactly the allauth response
60
+ from the original defect (`400`, `errors[0] = {code: "invalid", param: "email", message: ...}`). The
61
+ shown text equals the app-language text of `Auth.field.email.invalid`.
62
+
63
+ ## Scope + non-goals
64
+
65
+ In scope: the function and its four checks; its export from the package root; a `README.md` section
66
+ "Consumer integration check" with the one-line test an app writes; `CHANGELOG.md`; a **minor** release.
67
+
68
+ Non-goals:
69
+ - No change in any app. Adoption happens per app with its next bump, as its own row.
70
+ - No runtime dependency added for consumers. Rendering uses the existing peers (`react`, `react-dom`).
71
+ - No check of the app's test mocks. A suite whose mocks lack `i18n` still fails in that suite, as today.
72
+ - No replacement for the kit's own tests. They keep owning the kit's behaviour.
73
+ - No staging or browser check (`WFT-CI-31`).
74
+
75
+ ## Tier · precondition / gate
76
+
77
+ - **Tier 3 · tests: each of the four checks with a passing and a failing case; the kit's existing auth
78
+ and i18n tests.** A change inside shared-core, on the auth surface.
79
+ - Precondition: none.
80
+ - Downstream: every app adopts it with its next kit bump. `WFT-CI-31` is independent of this order.
81
+
82
+ ## Risks
83
+
84
+ - **A check that cannot fail is decoration.** Each check needs a test showing it reports the specific
85
+ defect: a missing key, a second `i18next` instance, a wrapper that throws, a raw code on screen.
86
+ - **The transport stub must not leak.** If it is not restored, it silently swallows the requests of the
87
+ tests that run after it. Restore it even when a check throws.
88
+ - **Kit keys that the app intentionally leaves untranslated** for a language it does not offer must not
89
+ become findings. Hence "languages both support" in check 1.
90
+ - **Locally, importing the kit's root module crashes vitest's worker pool on this workstation**
91
+ (`fitness-monitor` `FM-15`). That is an environment issue: CI is the evidence. The check itself must not
92
+ add to the import weight of tests that do not call it.
93
+
94
+ ## Required tests to WRITE (you write them and run YOUR OWN new ones; the Orchestrator's run is the gate)
95
+
96
+ Kit test suite, one new file:
97
+
98
+ 1. A correctly wired fixture app (own `i18n` with `uiCoreTranslations`, a provider wrapper) -> `findings`
99
+ equals `[]`.
100
+ 2. One key removed from the fixture's resources -> exactly one catalogue finding naming that key and
101
+ language.
102
+ 3. The fixture passes a separate `i18next` instance -> an instance finding.
103
+ 4. A wrapper that throws -> a render finding naming the page.
104
+ 5. The resolver bypassed (a fixture that shows `err.code`) -> an error-text finding.
105
+ 6. After the check, a request through `apiClient` is no longer stubbed.
106
+
107
+ Run, do not write: the kit's existing auth and i18n tests.
108
+
109
+ ## Parity guardrail
110
+
111
+ No change to any existing export, component or behaviour. The function is new and test-only in purpose.
112
+
113
+ ---
114
+
115
+ # B. Implementation map, filled by the Orchestrator and ADDRESSED TO THE IMPLEMENTER
116
+
117
+ ## Context package
118
+
119
+ ### Where this lives, and what it may depend on
120
+
121
+ - New file `src/testing/checkKitIntegration.js` (new subdirectory, mirroring how `src/theme/` groups
122
+ `assertThemeComplete`). Export `checkKitIntegration` from `src/index.js` at the root, next to the
123
+ existing theme-completeness exports (line ~10-21) — same section-style comment, same pattern.
124
+ - **Hard constraint from the Non-goals: "Rendering uses the existing peers (react, react-dom)" —
125
+ this explicitly does NOT include `@testing-library/react`.** Every existing kit test uses RTL, but
126
+ RTL is a devDependency of THIS repo, not a declared peer dependency — if the shipped function
127
+ imported it, every consuming app would need RTL in its own `node_modules` at the exact version
128
+ this kit expects, silently, which is exactly the "no runtime dependency added for consumers" this
129
+ WO forbids. Render with plain `react-dom/client` (`createRoot`) and `act` from `react` — verified
130
+ now: `import { act } from 'react'` resolves and is a function on this repo's installed React
131
+ `19.2.6` (`node -e "console.log(typeof require('react').act)"` → `function`), so use that import,
132
+ not the legacy `react-dom/test-utils` path. Read rendered output via plain
133
+ DOM (`container.textContent`, `document.createTreeWalker`), not `screen`/`within`.
134
+ - `react-router-dom` (`^7.15.1`) and `axios` (`^1.16.1`) ARE existing peers — safe to import
135
+ `MemoryRouter` and to manipulate the shared `apiClient` axios instance directly.
136
+
137
+ ### The four checks, in the order the Envelope lists them
138
+
139
+ 1. **Catalogue.** Import `{ uiCoreTranslations }` from `'../i18n/uiCoreTranslations'`. For each key,
140
+ for each language in the INTERSECTION of the kit's shipped languages
141
+ (`['de','en','fr','sw']`) and the app's own supported languages, assert
142
+ `i18n.exists(key, { lng: lang })` — **not** `i18n.exists(key)` alone, which only checks the
143
+ CURRENT active language; i18next's `exists`/`t` both accept an `lng` option to check a specific
144
+ language without switching the instance's active one (verify this against the installed
145
+ `i18next` version's own typings/source before relying on it — do not assume from memory).
146
+ Derive "the app's own supported languages" with this priority (first one that yields a
147
+ non-empty array): `i18n.options?.supportedLngs` (filter out falsy entries and the literal
148
+ string `'cimode'`, which i18next auto-adds) → `Object.keys(i18n.options?.resources || {})` →
149
+ `i18n.languages` (least reliable, only the currently-resolved fallback chain — last resort).
150
+ One finding per missing `(key, lang)` pair, naming both.
151
+ 2. **Instance.** Import the kit's OWN default `i18next` singleton (`import i18next from 'i18next'`
152
+ — the exact same import `src/auth/apiClient.jsx` already uses). Finding if `!i18next.isInitialized`
153
+ OR `i18n !== i18next` (reference inequality — the whole point is catching an app that created a
154
+ SEPARATE instance via `i18next.createInstance()` and wrapped its tree in its own
155
+ `I18nextProvider`, which is exactly the Risk `UCM-AUTH-10` named: the kit's `apiClient` would then
156
+ send `Accept-Language` from an uninitialized, different instance). Name what breaks in the
157
+ reason text (`Accept-Language` will be missing or wrong) — do not just say "mismatch".
158
+ 3. **Render.** For each page component in `pages` (default: `[LoginPage, SignUpPage,
159
+ PasswordInvitePage]` — the three pages `UCM-AUTH-9`/`UCM-AUTH-10` actually touched, and the same
160
+ set `survey_app`'s own `AuthRoutesIntegration.test.jsx` already covers by hand), render
161
+ `<MemoryRouter><Wrapper><Page /></Wrapper></MemoryRouter>` into a fresh detached `div` (own
162
+ `createRoot` per page, `root.unmount()` after each, even on failure — use try/finally per page,
163
+ not one try around the whole loop, so one page's render failure doesn't skip scanning the rest).
164
+ Wrap the render in `act(async () => { ... })` so effects/microtasks settle before you scan.
165
+ Catch a throw during render → one finding naming the page's display name (`Page.displayName ||
166
+ Page.name || 'page'`) and the error message; do NOT let it abort the whole check (catch per-page,
167
+ continue the loop). If it didn't throw, walk every text node
168
+ (`document.createTreeWalker(container, NodeFilter.SHOW_TEXT)`) and flag any whose TRIMMED content
169
+ either (a) exactly equals a key in `uiCoreTranslations` (a literal untranslated key leaking to
170
+ screen — the i18next missing-key echo), or (b) matches a bare lowercase/snake_case single-token
171
+ shape with no spaces, e.g. `/^[a-z][a-z0-9_]*$/` and length > 2 (the exact shape of the original
172
+ defect, a raw backend code like `invalid` — tune this pattern against Required Test #5's fixture
173
+ until it fires on that fixture and not on ordinary rendered prose; do not accept the first regex
174
+ that merely compiles). One finding per offending text node, naming the page and the text found.
175
+ 4. **Error text.** This check is not driven by the `pages` array — it ALWAYS specifically exercises
176
+ `LoginPage` (imported directly by this module), because it is testing the kit's resolver wiring
177
+ through a real submit flow, not generic rendering. Render `LoginPage` the same way as check 3.
178
+ Stub the credentials-login POST specifically — exact path, verified now:
179
+ `/api/auth/browser/v1/auth/login` (`src/auth/authConfig.jsx`'s `HEADLESS_BASE` +
180
+ `src/auth/authApi.jsx:99`'s `loginWithPassword`) — to reject with EXACTLY
181
+ the operator's original defect shape:
182
+ `{ response: { status: 400, data: { errors: [{ code: 'invalid', param: 'email', message: '<some
183
+ backend text>' }] } } }` (a plain object is sufficient — `resolveErrorText`/`extractErrorInfo`
184
+ only ever read `.response?.status`/`.response?.data` off the rejected value, nothing
185
+ AxiosError-specific). Fill the email/password inputs via plain DOM (`input.value = '...'` +
186
+ dispatching a real `input`/`change` `Event` so React's controlled-input `onChange` fires —
187
+ `Object.getOwnPropertyDescriptor` trick may be needed to set a native input value in a way React
188
+ notices; this is a well-known React-testing gotcha independent of any test-utility library, look
189
+ it up if the naive `input.value = x; input.dispatchEvent(new Event('input'))` doesn't trigger the
190
+ controlled state update) and submit (dispatch a `submit` Event on the form, or `.click()` the
191
+ submit button). `await act(async () => { ...await flush... })` until the error text renders.
192
+ Assert the rendered text equals `i18n.t('Auth.field.email.invalid')` evaluated in the APP's
193
+ current active language (`i18n.language`), read via the SAME walk-and-scan helper check 3 uses
194
+ (do not duplicate the scanning logic — factor it into one shared helper both checks call).
195
+
196
+ ### Stubbing `apiClient` — must never leak, must restore even on throw
197
+
198
+ `apiClient` (`src/auth/apiClient.jsx`, default export, an axios instance) is shared, module-singleton
199
+ state — the SAME instance every kit page uses. Capture `const originalAdapter =
200
+ apiClient.defaults.adapter;` BEFORE check 3 starts, install a replacement
201
+ (`apiClient.defaults.adapter = async (config) => { ... }`) that, by default, REJECTS every request
202
+ (so check 3's page renders — which must not make real network calls at all — fail loudly if they
203
+ accidentally do, rather than hanging on a real fetch), and for check 4 specifically, additionally
204
+ matches on `config.url` to return the fixture rejection ONLY for the login endpoint
205
+ (`HEADLESS_BASE`-relative, check `src/auth/authApi.jsx`'s `loginWithPassword` for the exact path) and
206
+ the default reject-everything behaviour for anything else. **Wrap the ENTIRE checks 3+4 body in a
207
+ `try { ... } finally { apiClient.defaults.adapter = originalAdapter; }`** — the restore must run even
208
+ if a render throws an error this code doesn't catch, even if an `expect`-shaped helper you write
209
+ itself throws. This is Required Test #6's whole point and the Risk note's explicit warning.
210
+
211
+ ### `README.md` — "Consumer integration check" section
212
+
213
+ One short section with the one-line test an app writes, e.g.:
214
+ ```js
215
+ import { checkKitIntegration } from '@micha.bigler/ui-core-micha';
216
+ import i18n from '../i18n'; // the app's own initialised default i18next instance
217
+ import { AppProviders } from '../AppProviders'; // whatever the app wraps its routes in
218
+
219
+ it('kit integration is sound', async () => {
220
+ const { findings } = await checkKitIntegration({ i18n, wrapper: AppProviders });
221
+ expect(findings).toEqual([]);
222
+ });
223
+ ```
224
+ Name the default `pages` set explicitly (`LoginPage`, `SignUpPage`, `PasswordInvitePage`) and that an
225
+ app can pass its own `pages` array to cover more/fewer pages.
226
+
227
+ ### Test file — new, next to the existing kit tests (e.g. `tests/checkKitIntegration.test.js`)
228
+
229
+ Build ONE minimal fixture i18next instance + a trivial `Wrapper` (e.g. just renders `children`, or a
230
+ thin `AuthContext.Provider` with a fake user so `LoginPage`'s own context read doesn't throw) reused
231
+ across the 6 Required Tests, each test mutating ONE thing away from "correctly wired":
232
+ 1. Correctly wired fixture (own real `i18next.createInstance()` seeded with `uiCoreTranslations` in
233
+ all 4 kit languages, THIS instance also assigned as the global default — i.e. do not create a
234
+ second competing instance for the "passing" case, since check 2 would then always fail; for a
235
+ realistic "app's own instance IS the default" fixture either call `i18next.init(...)` on the
236
+ real default singleton directly, matching how an app actually does it, or structure the fixture
237
+ so the "instance" check specifically is satisfiable) → `findings` is `[]`.
238
+ 2. Remove one key's resources for one language from the fixture → exactly one catalogue finding
239
+ naming that key and language.
240
+ 3. Pass a SEPARATE `i18next.createInstance()` as `i18n` instead of the default singleton → an
241
+ instance finding.
242
+ 4. A `wrapper` that throws during render → a render finding naming the page.
243
+ 5. **The actual regression proof:** stub the login POST to reject with the operator's exact shape
244
+ but WITHOUT going through the kit's resolver (simulate "the resolver bypassed" by using a fixture
245
+ `LoginPage`-equivalent harness only if you must — more directly: this is best proven by reverting
246
+ `resolveErrorText`'s field-key step locally, confirming check 4 then reports an error-text
247
+ finding instead of passing, then restoring — narrate this in `PROGRESS` as the transient
248
+ mutation proof, same pattern as `UCM-AUTH-11`/`UCM-THEME-15` in this repo, rather than leaving a
249
+ permanently reverted copy in the committed suite).
250
+ 6. After calling `checkKitIntegration(...)` once, assert `apiClient.defaults.adapter` is back to
251
+ whatever it was before the call (capture the reference beforehand) — proves restoration even on
252
+ the success path; also add a case that makes an internal step throw (e.g. a page whose render
253
+ throws) and still assert the adapter was restored afterwards (the `try/finally` must cover the
254
+ failure path too, not just the happy path).
255
+
256
+ Run, do not write: the kit's existing auth and i18n tests (grep `tests/` for
257
+ `i18nAggregate`/`authErrors`/`resolveErrorText`/`loginPageErrorResolution` — these are the
258
+ directly-dependent set the Orchestrator re-runs as the gate).
259
+
260
+ ## Do-not-touch / invariants
261
+
262
+ - No change to any existing export, component, or behaviour (Parity guardrail) — this is a new,
263
+ additive, test-only function.
264
+ - Do not add `@testing-library/react` (or any other new package) to `dependencies`,
265
+ `peerDependencies`, or `devDependencies` for this function's own sake.
266
+ - Do not touch `apiClient.jsx`'s actual interceptors/exports — only reach into
267
+ `apiClient.defaults.adapter` from the NEW module, temporarily, with a guaranteed restore.
268
+
269
+ ---
270
+
271
+ # C. Orchestrator only, NOT ADDRESSED TO THE IMPLEMENTER
272
+
273
+ > **If you are the implementer reading this work order as your own specification: STOP at this line.**
274
+ > Everything below describes what the Orchestrator does AFTER you finish. You do none of it: no
275
+ > reviewers, no verification run, no register edit, no `git add`/`commit`/`push`.
276
+
277
+ ### Execution directive
278
+
279
+ Check `.claude/codex-status.md` first (newest-first; read it with `head`). No line for today means use
280
+ Codex. Before `git push`, run `git log origin/main..HEAD` and push only if every listed commit is this
281
+ order's (parallel sessions share this checkout).
282
+
283
+ ### Review routing
284
+
285
+ Tier 3: independent `reviewer` (all configured lenses) and `ui_reviewer`, concurrent, one batch, before
286
+ the commit. No `sec_reviewer`: the function adds no runtime path, it only reads what is already there.
287
+
288
+ ### Verification
289
+
290
+ Run the check once against a real consumer before release. `survey_app` is on `3.9.x` and has the closest
291
+ existing test (`frontend/src/AuthRoutesIntegration.test.jsx`). Do it from a scratch copy or a local pack,
292
+ never by committing to that repo. Name the result in the register Notiz.
293
+
294
+ ### Register + commit + release
295
+
296
+ Row -> `done` with the review Notiz in the `AGENTS.md` shape and the published version. The publish
297
+ runs on push to `main` when `package.json`/`src/**` change; verify it through the job log
298
+ (`npm view` lags for provenance publishes). Adoption rows per app are added by the Expertenchat when
299
+ each app's next bump is scoped.
300
+
301
+ ### Mini-handover
302
+
303
+ `Orchestrator: implement work-orders/UCM-TEST-1.md in ui-core-micha (main). git pull first, read the WO,
304
+ then follow orchestrate-codex.`