@lenne.tech/nuxt-extensions 1.26.0 → 1.28.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/CLAUDE.md CHANGED
@@ -43,7 +43,7 @@ src/
43
43
  | `useLtAiSettings()` | The user's own AI settings: MCP confirmation switch (`GET/PUT /ai/settings`, `enforced` → show disabled) |
44
44
  | `useLtAiStatus()` | Whether the API's AI module is on (`GET /ai/status`, public; 404 = off): `enabled`, `mcp`, shared `useState`, one request per app start, fails closed |
45
45
  | `useLtAiUsage()` | Full token/prompt usage breakdown (`GET /ai/usage`) |
46
- | `useLtAiPrompts()` | User-facing CRUD for re-usable prompt snippets ("Vorlagen", `scope: 'user'` / `'tenant'`) |
46
+ | `useLtAiPrompts()` | User-facing CRUD for re-usable prompt snippets ("Vorlagen", `scope: 'user'` / `'tenant'`). `load()` = active only (chat picker); `load({ includeDisabled: true })` = management list (nest-server >= 12.7.0), kept for the reload after create/update/remove |
47
47
  | `useLtAiPlaceholders()` | Loads the backend's `{{placeholder}}` registry for editor sidebars |
48
48
  | `useLtAiAdmin()` | Admin CRUD: connections, preferences, budget limits, slots, prompt hints, interactions — server-gated |
49
49
 
@@ -62,7 +62,7 @@ export default defineNuxtConfig({
62
62
  modules: ['@lenne.tech/nuxt-extensions'],
63
63
  ltExtensions: {
64
64
  auth: {
65
- enabled: true,
65
+ enabled: true, // only gates the 401 interceptor (= interceptor.enabled); the auth composables stay
66
66
  basePath: '/iam', // Better-Auth endpoint prefix
67
67
  loginPath: '/auth/login',
68
68
  enableAdmin: true,
@@ -121,6 +121,27 @@ The API base URL is resolved at runtime from `NUXT_PUBLIC_API_URL` (client + SSR
121
121
  3. The backend sets the session as an `httpOnly` cookie (`iam.session_token`); `lt-auth-state` is the non-httpOnly client-side cache used by middleware
122
122
  4. Subsequent authenticated requests use `ltAuthFetch` (Cookie mode by default, JWT fallback)
123
123
 
124
+ ### One authenticated fetch (DEV-4074)
125
+
126
+ `useLtAuth().fetchWithAuth` and `ltAuthFetch` / `createLtAuthFetch` are ONE implementation:
127
+ `createLtAuthFetchFor` in `lib/auth-state.ts`. They used to be two copies, and only one of them
128
+ renewed an expired JWT. Do not write a third one; a caller with its own state passes it in.
129
+
130
+ - **A 401 while signed in fetches a JWT once and retries once.** Cookie mode: the switch to JWT.
131
+ JWT mode: the bearer had expired (15 minutes against a 7-day session). One `GET <basePath>/token`
132
+ per burst, shared by every caller (`requestLtJwtAfter401`); each caller stores the token where it
133
+ keeps its own (`adoptJwt`: the cookies, or the composable's `useCookie` refs).
134
+ - **A 401 the bearer did not cause is never retried in JWT mode.** `ltAuthFetch`: Better-Auth's own
135
+ routes (under the auth base), where a 401 is the verdict of sign-in, 2FA or passkey; sending a wrong
136
+ password or code again counts twice against the rate limit. `fetchWithAuth`: the cookie-bound paths.
137
+ - **Cookies in JWT mode differ on purpose.** `ltAuthFetch` always sends them: nest-server
138
+ (>= 11.13.1) falls back to the session cookie when the bearer fails, and Better-Auth's own routes
139
+ read the session from it. `fetchWithAuth` sends them only to passkey, 2FA and `/get-session`
140
+ (`cookiesInJwtMode: 'auth-paths'`, as ng-base does). Changing either is a behaviour change.
141
+ - **The JWT comes from `auth.basePath`.** Without an argument, `ltAuthFetch`, `createLtAuthFetch()`
142
+ and `attemptLtJwtSwitch()` read it from the runtime config. `requestLtJwt()` is the only place a
143
+ JWT is fetched, `useLtAuth().switchToJwtMode()` included.
144
+
124
145
  ## AI Assistant Flow
125
146
 
126
147
  - All AI composables route through `ltAuthFetch` (Cookie/JWT dual mode) and `buildLtAiUrl` (SSR/public URL resolution), so they inherit the same auth + URL behaviour as the rest of the library.
@@ -184,12 +205,29 @@ A service worker must never cache `/sync` or `/iam` responses (nest-server
184
205
 
185
206
  ## Testing Helpers
186
207
 
187
- Import from `@lenne.tech/nuxt-extensions/testing`:
208
+ Playwright helpers, imported from `@lenne.tech/nuxt-extensions/testing` (the starter's E2E tests use
209
+ them this way):
188
210
 
189
211
  ```typescript
190
- import { createTestUser, loginTestUser } from '@lenne.tech/nuxt-extensions/testing';
212
+ import { fillInput, generateTestUser, gotoAndWaitForHydration, waitForURLAndHydration } from '@lenne.tech/nuxt-extensions/testing';
213
+
214
+ const user = generateTestUser('e2e');
215
+ await gotoAndWaitForHydration(page, '/auth/register');
216
+ await fillInput(page, 'input[name="email"]', user.email);
191
217
  ```
192
218
 
219
+ | Group | Exports |
220
+ |-------|---------|
221
+ | Hydration | `waitForHydration`, `gotoAndWaitForHydration`, `waitForURLAndHydration`, `DEFAULT_HYDRATION_TIMEOUT` |
222
+ | Input | `fillInput`, `fillInputs` |
223
+ | Test data | `generateTestUser` (type `TestUser`), `generateRandomString` |
224
+ | TOTP / 2FA | `generateTOTP`, `extractTOTPSecret`, `parseTOTPUrl` |
225
+ | Waiting, reading | `waitForElement`, `waitForNetworkIdle`, `hasText`, `getAllText` |
226
+
227
+ There is no `createTestUser` or `loginTestUser`. A test registers and signs in through the pages, as
228
+ the starter's specs do. `test/doc-imports.test.ts` fails when this file or the README imports a
229
+ name that `/testing` or `/lib` does not export.
230
+
193
231
  ## Authentication Cookie Rules
194
232
 
195
233
  The `useLtAuth()` composable manages the `lt-auth-state` cookie for authentication state. Projects that implement custom auth middleware MUST follow these rules:
@@ -381,6 +419,41 @@ optionally behind a setup token (`LTNS_0054` when wrong). `GET /system-setup/sta
381
419
  configuration. Pass the error itself to `translateError(error)`: the `#LTNS_` code is in the
382
420
  body, `error.message` holds only the transport line.
383
421
 
422
+ ## Package Entry Points (DEV-4079)
423
+
424
+ - **npm `.`** is `dist/module.mjs`, built from `src/module.ts`: the module and every type
425
+ (`export type * from './runtime/types'`). Runtime values come from auto-imports or `./lib`;
426
+ `./testing` holds the Playwright helpers.
427
+ - **`src/index.ts` is the entry of the VENDORED core, not dead code.** npm mode never builds it,
428
+ but the lt CLI copies it to `app/core/index.ts` and rewrites `from '@lenne.tech/nuxt-extensions'`
429
+ to `app/core`. Deleting it breaks every type import of a vendored project. It re-exports whole
430
+ barrels (`export *`); never turn it back into a hand-written list, which lost three composables.
431
+ - **Every package `src/` imports is declared**, as a dependency or a peer. A package that is only
432
+ there when the project installs it is an optional peer, with a stub alias in `module.ts` if it is
433
+ imported statically (`test/optional-peers.test.ts`).
434
+ - **One declaration per type** under `src/runtime/types`. `test/package-exports.test.ts` holds
435
+ the last three rules.
436
+
437
+ ## Error Translation: loaded after mount (DEV-4078)
438
+
439
+ `plugins/error-translation.client.ts` starts `loadTranslations()` in `app:mounted` and does not
440
+ await it. `test/error-translation-loading.test.ts` holds both halves.
441
+
442
+ - **Never make the plugin async again, and never start the load before the mount.** Awaited, it
443
+ held back every client start for one API request. Started early but not awaited, it races
444
+ hydration: the server renders the developer message (it loads no translations), and
445
+ translations arriving before hydration render another text on the client.
446
+ - **Loads are shared per Nuxt app and locale** (`inFlightLoads`), and `isLoading` is shared
447
+ state. A second caller waits for the request in flight instead of returning before the
448
+ translations are there. A load for another locale is never swallowed by one in flight.
449
+ - **Until the load is done, `translateError` returns the developer message.** That is the
450
+ documented fallback, not a bug. `loadTranslations()` never rejects; a failure is logged, and
451
+ the next call tries again.
452
+ - **SSR translates nothing by default** (one request and the whole table in every payload). The
453
+ README shows the opt-in: a project's own `.server` plugin awaits `loadTranslations()`, and the
454
+ payload carries the state to the client. It needs `@nuxtjs/i18n`, so both sides pick the same
455
+ locale.
456
+
384
457
  ## Form Label Repair
385
458
 
386
459
  **The defect:** Nuxt UI's `FormField` derives the label's `for` and the control's `id` from one
@@ -506,6 +579,19 @@ fields at `app:beforeMount` and restores them at `app:mounted`, dispatching a sy
506
579
  else.** Vendoring turns them into project source, where they cause TS2310, and the cli removes a
507
580
  block only while it holds that one interface. Type server-only config where it is read.
508
581
 
582
+ ## Transition Components and Tailwind 4
583
+
584
+ The `LtTransition*` components are the only place this module uses Tailwind classes.
585
+
586
+ - **Tailwind 4 syntax: `duration-(--start-duration)`, never `duration-[--start-duration]`.**
587
+ Tailwind 4 compiles the v3 shorthand to `transition-duration: --start-duration`, which the browser
588
+ drops: the fade ran in 0 s and the duration props did nothing (DEV-4071).
589
+ `test/transition-classes.test.ts` compiles every class with the stack's Tailwind version.
590
+ - **npm mode needs a `@source` line** for `node_modules/@lenne.tech/nuxt-extensions/dist/runtime` in
591
+ the stylesheet that imports Tailwind (README, "Transition Components"). Nuxt UI only adds the
592
+ layers' `app` directories, without a hook a module could use. A missing `@source` path is
593
+ ignored, so the line is harmless in vendor mode.
594
+
509
595
  ## Development Rules
510
596
 
511
597
  1. **ALWAYS read source code** in `dist/runtime/` to understand available composables and components
package/README.md CHANGED
@@ -32,6 +32,8 @@ Reusable Nuxt 4 composables, components, and Better-Auth integration for lenne.t
32
32
  | `better-auth` | `>=1.7.16 <1.8.0` | **required peer** — pin it, see below |
33
33
  | `@better-auth/passkey` | `>=1.7.16 <1.8.0` | optional peer, passkey/WebAuthn only |
34
34
  | `tus-js-client` | `>=4.0.0` | optional peer, resumable uploads only |
35
+ | `@nuxt/ui` | `>=3.0.0` | optional peer: toasts of `showErrorToast` and the auth flows; without it they go to the console |
36
+ | `tailwindcss` | `>=4.0.0` | optional peer, `LtTransition*` components only (Tailwind 4 class syntax, see "Transition Components") |
35
37
  | `@lenne.tech/nest-server` | `>= 11.37.0` | **only if you use the backend** — see the lock-step rule |
36
38
 
37
39
  **Why `better-auth` is pinned to one minor line, and why you must not widen it:**
@@ -166,7 +168,7 @@ export default defineNuxtConfig({
166
168
  ltExtensions: {
167
169
  // Auth configuration
168
170
  auth: {
169
- enabled: true, // Enable auth features
171
+ enabled: true, // Only gates the 401 interceptor below; useLtAuth() etc. stay available
170
172
  baseURL: '', // API base URL (empty = use env vars)
171
173
  basePath: '/iam', // Better-Auth endpoint prefix
172
174
  loginPath: '/auth/login', // Login redirect path
@@ -522,6 +524,54 @@ JWT from `/iam/token`.
522
524
  session token.**
523
525
  - **`authenticateWithPasskey()` returns no `session`.**
524
526
 
527
+ #### Authenticated requests: `fetchWithAuth` and `ltAuthFetch`
528
+
529
+ `useLtAuth().fetchWithAuth` and `ltAuthFetch` (from `/lib`, also used by the Better-Auth client,
530
+ the AI composables and offline sync) run through one implementation.
531
+
532
+ - **JWT mode sends `Authorization: Bearer <jwt>`.** `ltAuthFetch` always sends the cookies as well,
533
+ so nest-server (>= 11.13.1) falls back to the session cookie when the bearer fails.
534
+ `fetchWithAuth` sends them in JWT mode only to passkey, 2FA and `/get-session`.
535
+ - **A 401 while signed in fetches a JWT once and retries the request once.** In cookie mode that
536
+ is the switch to JWT; in JWT mode it renews an expired JWT, which lives 15 minutes while the
537
+ session lasts 7 days. Requests that fail in the same burst share one `GET <basePath>/token`. A
538
+ 401 that survives the fresh token reaches the caller unchanged, and so does a 401 in JWT mode from
539
+ Better-Auth's own routes (sign-in, 2FA, passkey): there it is the flow's verdict, and a wrong
540
+ password or code must not be sent twice.
541
+ - **The JWT comes from `auth.basePath`.** Without an argument, `ltAuthFetch`, `createLtAuthFetch()`
542
+ and `attemptLtJwtSwitch()` read it from the module config; they used to fetch it from `/iam`
543
+ whatever was configured. A path passed explicitly still wins.
544
+
545
+ #### Server-side rendering: backend calls are anonymous
546
+
547
+ During SSR, `ltAuthFetch`, the AI composables and offline sync call the API **without** a session:
548
+ on the server `getLtAuthMode()` is `'cookie'`, `getLtJwtToken()` is `null` and `isLtAuthenticated()`
549
+ is `false`. The one exception is `useLtAuth().fetchWithAuth` (see the last point below). That is deliberate. The auth helpers are module singletons shared by every request a
550
+ Nitro process renders, so they may not carry one request's cookies. And the session cookie
551
+ (`iam.session_token`) belongs to the API host: nest-server sets it host-only unless
552
+ `crossSubDomainCookies` is configured, so the app server never receives it. `validateSession()` on
553
+ the server therefore relies on the `lt-auth-state` cookie only, which is a display cache, not proof
554
+ of a session.
555
+
556
+ For pages that show user data:
557
+
558
+ - **Load it in the browser.** `useAsyncData(key, fetcher, { server: false })` or `onMounted`, with a
559
+ skeleton or loading state for the first paint. This is what nuxt-base-starter does.
560
+ `useLazyAsyncData` alone is not enough: `lazy` only stops it from blocking navigation, the
561
+ fetcher still runs during SSR, and its anonymous answer (a 401 or the public subset) goes into
562
+ the payload, which the browser does not fetch again. Add `server: false` there too.
563
+ - **Render only public data on the server**, and never decide access there: an SSR guard that reads
564
+ `lt-auth-state` decides what to render, the API decides what the user may see.
565
+ - If a page truly needs user data in the SSR HTML, that needs a server route of the app that
566
+ forwards the request's own session to the API, set up per project together with a shared cookie
567
+ domain. `ltAuthFetch` does not do it.
568
+ - **`useLtAuth().fetchWithAuth` during SSR is not anonymous.** It reads the request's cookies through
569
+ `useCookie`, and in JWT mode (the normal state after sign-in) it sends the request's `lt-jwt-token`
570
+ as the bearer. It cannot renew that token on the server, so the call works until the JWT expires
571
+ (15 minutes) and then answers 401. Do not use it for SSR-rendered user data, and never cache
572
+ (`swr`, `isr`, a CDN) a route whose SSR output went through it: one user's data would be served to
573
+ the next.
574
+
525
575
  #### Admin detection (`role` vs `roles`)
526
576
 
527
577
  `isAdmin` accepts **both** user shapes, so the same frontend works against either backend:
@@ -802,6 +852,22 @@ override that never calls `super.onUploadComplete(upload)`).
802
852
  </template>
803
853
  ```
804
854
 
855
+ The components style themselves with Tailwind 4 utilities. Tailwind only generates the classes it
856
+ finds in your sources, and a package in `node_modules` is not among them, so in npm mode add the
857
+ package's runtime to the stylesheet that imports Tailwind:
858
+
859
+ ```css
860
+ /* app/assets/css/tailwind.css */
861
+ @import 'tailwindcss';
862
+ @import '@nuxt/ui';
863
+ @source '../../../node_modules/@lenne.tech/nuxt-extensions/dist/runtime';
864
+ ```
865
+
866
+ The path is relative to that stylesheet. A vendored core (`app/core`) is scanned with the app
867
+ anyway, and Tailwind ignores a `@source` path that does not exist, so the line can stay after a
868
+ switch to vendor mode. Without it, a transition whose classes the app does not use elsewhere runs
869
+ without its duration or easing.
870
+
805
871
  ### Web Share API
806
872
 
807
873
  ```vue
@@ -827,6 +893,48 @@ const base64 = ltArrayBufferToBase64Url(buffer);
827
893
  const uint8 = ltBase64UrlToUint8Array(base64String);
828
894
  ```
829
895
 
896
+ ### Error Translation
897
+
898
+ `useLtErrorTranslation()` turns a backend error such as `#LTNS_0100: Unauthorized - User is
899
+ not logged in` into the text for the user's locale, loaded from the API's
900
+ `GET /i18n/errors/<locale>`.
901
+
902
+ ```typescript
903
+ const { translateError, showErrorToast } = useLtErrorTranslation();
904
+
905
+ const message = translateError(error); // "Sie sind nicht angemeldet."
906
+ showErrorToast(error, 'Anmeldung fehlgeschlagen');
907
+ ```
908
+
909
+ **The translations load after the app is mounted, and the start does not wait for them.**
910
+ Until they are there, `translateError` returns the developer message (`Unauthorized - User is
911
+ not logged in`), never an empty string. A template that renders `translateError(...)` switches
912
+ to the translation as soon as it arrives. A toast takes the text it had when it was shown. Code
913
+ that has to have the translations first awaits them; a load already in flight is shared, not
914
+ repeated:
915
+
916
+ ```typescript
917
+ const { loadTranslations, translateError } = useLtErrorTranslation();
918
+ await loadTranslations(); // resolves once loaded, or once the load failed (logged, never thrown)
919
+ ```
920
+
921
+ **Messages rendered during SSR carry the developer message.** The server loads no translations
922
+ by default: that would cost one API request and the whole table in the payload of every page,
923
+ for messages that almost always appear after an action in the browser. The client translates
924
+ them after the mount. A project that renders errors on the server, such as an `error.vue` for a
925
+ failed `useAsyncData`, loads the table there itself, in a plugin of its own:
926
+
927
+ ```typescript
928
+ // plugins/error-translations-ssr.server.ts
929
+ export default defineNuxtPlugin(async () => {
930
+ await useLtErrorTranslation().loadTranslations();
931
+ });
932
+ ```
933
+
934
+ The state reaches the client in the payload, so the browser fetches nothing again and hydration
935
+ sees the same text as the server. This needs `@nuxtjs/i18n`: without it, the server takes
936
+ `errorTranslation.defaultLocale` and the browser its own language, and the two can differ.
937
+
830
938
  ## AI Assistant
831
939
 
832
940
  Headless, provider-agnostic composables for the `@lenne.tech/nest-server` **AI module**
@@ -866,6 +974,21 @@ await load();
866
974
  is private to the owner; `scope: 'tenant'` is shared across the owner's tenant. The list
867
975
  returned by `load()` is already server-filtered to what the user is allowed to see.
868
976
 
977
+ `load()` lists active prompts only, which is what a chat picker offers. A management screen
978
+ calls `load({ includeDisabled: true })` (nest-server >= 12.7.0), so a prompt saved with
979
+ `enabled: false` stays in the list and can be switched on again:
980
+
981
+ ```typescript
982
+ // Settings page: every prompt, disabled ones included
983
+ const { load, prompts, update } = useLtAiPrompts();
984
+ onMounted(() => load({ includeDisabled: true }));
985
+ // The reload after create / update / remove asks for the same list
986
+ await update(prompt.id, { enabled: false });
987
+ ```
988
+
989
+ Each `useLtAiPrompts()` call has its own list, so the chat picker on the same page stays on
990
+ active prompts. An API before 12.7.0 ignores the parameter and lists active prompts only.
991
+
869
992
  ### AI status
870
993
 
871
994
  `useLtAiStatus()` says whether the API's AI module is on, so AI pages and navigation entries can
@@ -1116,20 +1239,23 @@ The package works **with or without** `@nuxtjs/i18n`:
1116
1239
  ## Development
1117
1240
 
1118
1241
  ```bash
1119
- # Install dependencies
1120
- npm install
1242
+ # Install dependencies (the repository pins pnpm in `packageManager`)
1243
+ pnpm install
1121
1244
 
1122
1245
  # Generate type stubs
1123
- npm run dev:prepare
1246
+ pnpm run dev:prepare
1124
1247
 
1125
1248
  # Develop with playground
1126
- npm run dev
1249
+ pnpm run dev
1127
1250
 
1128
1251
  # Build the module
1129
- npm run build
1252
+ pnpm run build
1130
1253
 
1131
1254
  # Run tests
1132
- npm run test
1255
+ pnpm test
1256
+
1257
+ # Everything a merge needs: audit, lint, types, tests, build, package manifest
1258
+ pnpm run check
1133
1259
  ```
1134
1260
 
1135
1261
  ## License
package/dist/module.d.mts CHANGED
@@ -3,7 +3,7 @@ import { LtExtensionsModuleOptions } from '../dist/runtime/types/index.js';
3
3
  export * from '../dist/runtime/types/index.js';
4
4
 
5
5
  declare const name = "@lenne.tech/nuxt-extensions";
6
- declare const version = "1.26.0";
6
+ declare const version = "1.28.0";
7
7
  declare const configKey = "ltExtensions";
8
8
  declare const DEFAULT_LT_AUTH_STATE_COOKIE = "lt-auth-state";
9
9
  declare const DEFAULT_LT_JWT_TOKEN_COOKIE = "lt-jwt-token";
package/dist/module.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "configKey": "ltExtensions",
3
3
  "name": "@lenne.tech/nuxt-extensions",
4
- "version": "1.26.0",
4
+ "version": "1.28.0",
5
5
  "builder": {
6
6
  "@nuxt/module-builder": "1.0.3",
7
7
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -3,7 +3,7 @@ import { pathToFileURL } from 'node:url';
3
3
  import { SECURITY_TXT_DEFAULT_VALID_DAYS, SECURITY_TXT_DEFAULT_LANGUAGES, SECURITY_TXT_DEFAULT_CONTACT, SECURITY_TXT_PATH } from '../dist/runtime/server/lib/security-txt.js';
4
4
 
5
5
  const name = "@lenne.tech/nuxt-extensions";
6
- const version = "1.26.0";
6
+ const version = "1.28.0";
7
7
  const configKey = "ltExtensions";
8
8
  const DEFAULT_LT_AUTH_STATE_COOKIE = "lt-auth-state";
9
9
  const DEFAULT_LT_JWT_TOKEN_COOKIE = "lt-jwt-token";
@@ -301,7 +301,7 @@ const module$1 = defineNuxtModule({
301
301
  console.log(`[${name}] v${version}`);
302
302
  if (nuxt.options.dev) {
303
303
  console.log(`[${name}] Module loaded with config:`, {
304
- auth: resolvedOptions.auth?.enabled ? "enabled" : "disabled",
304
+ authInterceptor: resolvedOptions.auth?.enabled && resolvedOptions.auth?.interceptor?.enabled ? "on" : "off",
305
305
  i18nAutoMerge: resolvedOptions.i18n?.autoMerge,
306
306
  tusEndpoint: resolvedOptions.tus?.defaultEndpoint
307
307
  });
@@ -8,10 +8,10 @@ const props = defineProps({
8
8
  <template>
9
9
  <div :style="`--start-duration: ${props.startDuration}ms; --leave-duration: ${props.leaveDuration}ms;`">
10
10
  <Transition
11
- enter-active-class="transition ease-out duration-[--start-duration]"
11
+ enter-active-class="transition ease-out duration-(--start-duration)"
12
12
  enter-from-class="transform opacity-0"
13
13
  enter-to-class="transform opacity-100"
14
- leave-active-class="transition ease-in duration-[--leave-duration]"
14
+ leave-active-class="transition ease-in duration-(--leave-duration)"
15
15
  leave-from-class="transform opacity-100"
16
16
  leave-to-class="transform opacity-0"
17
17
  >
@@ -8,10 +8,10 @@ const props = defineProps({
8
8
  <template>
9
9
  <div :style="`--start-duration: ${props.startDuration}ms; --leave-duration: ${props.leaveDuration}ms;`">
10
10
  <Transition
11
- enter-active-class="transition ease-out duration-[--start-duration]"
11
+ enter-active-class="transition ease-out duration-(--start-duration)"
12
12
  enter-from-class="transform opacity-0 scale-95"
13
13
  enter-to-class="transform opacity-100 scale-100"
14
- leave-active-class="transition ease-in duration-[--leave-duration]"
14
+ leave-active-class="transition ease-in duration-(--leave-duration)"
15
15
  leave-from-class="transform opacity-100 scale-100"
16
16
  leave-to-class="transform opacity-0 scale-95"
17
17
  >
@@ -1,6 +1,6 @@
1
1
  import { useNuxtApp, useCookie, useState, useRequestHeaders, useRuntimeConfig, ref, computed, watch } from "#imports";
2
2
  import { ltArrayBufferToBase64Url, ltBase64UrlToUint8Array } from "../../utils/crypto.js";
3
- import { clearLtAuthCookies, getLtApiBase, getLtAuthCookieNames, getLtJwtToken, isLtJwtShaped, resolveLtAuthState } from "../../lib/auth-state.js";
3
+ import { clearLtAuthCookies, createLtAuthFetchFor, getLtApiBase, getLtAuthCookieNames, getLtJwtToken, isLtJwtShaped, requestLtJwt, resolveLtAuthState } from "../../lib/auth-state.js";
4
4
  import { useLtAuthClient } from "../use-lt-auth-client.js";
5
5
  const VALIDATE_SESSION_TIMEOUT_MS = 1e4;
6
6
  const LT_SYNC_SIGN_OUT_FLUSH_MS = 5e3;
@@ -12,7 +12,6 @@ function isLtSyncEnabled() {
12
12
  return false;
13
13
  }
14
14
  }
15
- let staleJwtRefresh = null;
16
15
  function useTranslation() {
17
16
  const nuxtApp = useNuxtApp();
18
17
  const i18n = nuxtApp.$i18n;
@@ -114,88 +113,35 @@ export function useLtAuth() {
114
113
  clearLtAuthCookies();
115
114
  }
116
115
  }
116
+ function adoptJwt(token) {
117
+ if (jwtToken.value !== token) {
118
+ jwtToken.value = token;
119
+ }
120
+ if (authState.value && authState.value.authMode !== "jwt") {
121
+ authState.value = { ...authState.value, authMode: "jwt" };
122
+ }
123
+ }
117
124
  async function switchToJwtMode() {
118
- try {
119
- const apiBase = getLtApiBase();
120
- const response = await fetch(`${apiBase}/token`, {
121
- method: "GET",
122
- credentials: "include"
123
- });
124
- if (response.ok) {
125
- const data = await response.json();
126
- if (isLtJwtShaped(data.token)) {
127
- jwtToken.value = data.token;
128
- if (authState.value) {
129
- authState.value = { ...authState.value, authMode: "jwt" };
130
- }
131
- return true;
132
- }
133
- }
134
- return false;
135
- } catch {
125
+ const token = await requestLtJwt();
126
+ if (!token) {
136
127
  return false;
137
128
  }
129
+ adoptJwt(token);
130
+ return true;
138
131
  }
139
132
  async function refreshJwtToken() {
140
133
  if (!isJwtMode.value || !jwtToken.value) return false;
141
134
  return switchToJwtMode();
142
135
  }
143
- const PATHS_REQUIRING_COOKIES = ["/passkey/", "/two-factor/", "/2fa/", "/get-session"];
144
- function urlRequiresCookies(url) {
145
- return PATHS_REQUIRING_COOKIES.some((path) => url.includes(path));
146
- }
147
- async function fetchWithAuth(url, options = {}) {
148
- const headers = new Headers(options.headers);
149
- if (isJwtMode.value && jwtToken.value) {
150
- headers.set("Authorization", `Bearer ${jwtToken.value}`);
136
+ const fetchWithAuth = createLtAuthFetchFor({
137
+ cookiesInJwtMode: "auth-paths",
138
+ state: {
139
+ adoptJwt,
140
+ isAuthenticated: () => isAuthenticated.value,
141
+ jwtToken: () => jwtToken.value,
142
+ mode: () => isJwtMode.value ? "jwt" : "cookie"
151
143
  }
152
- const needsCookies = !isJwtMode.value || urlRequiresCookies(url);
153
- const response = await fetch(url, {
154
- ...options,
155
- headers,
156
- credentials: needsCookies ? "include" : "omit"
157
- });
158
- if (response.status === 401 && !isJwtMode.value && isAuthenticated.value) {
159
- const switched = await switchToJwtMode();
160
- if (switched) {
161
- headers.set("Authorization", `Bearer ${jwtToken.value}`);
162
- const retryNeedsCookies = urlRequiresCookies(url);
163
- return fetch(url, {
164
- ...options,
165
- headers,
166
- credentials: retryNeedsCookies ? "include" : "omit"
167
- });
168
- }
169
- }
170
- if (response.status === 401 && isJwtMode.value && isAuthenticated.value && !needsCookies) {
171
- const freshToken = await refreshStaleJwt();
172
- if (freshToken) {
173
- headers.set("Authorization", `Bearer ${freshToken}`);
174
- return fetch(url, {
175
- ...options,
176
- headers,
177
- credentials: "omit"
178
- });
179
- }
180
- }
181
- return response;
182
- }
183
- async function refreshStaleJwt() {
184
- const mint = async () => await switchToJwtMode() ? jwtToken.value : null;
185
- if (!import.meta.client) {
186
- return mint();
187
- }
188
- if (!staleJwtRefresh) {
189
- staleJwtRefresh = mint().finally(() => {
190
- staleJwtRefresh = null;
191
- });
192
- }
193
- const token = await staleJwtRefresh;
194
- if (token && jwtToken.value !== token) {
195
- jwtToken.value = token;
196
- }
197
- return token;
198
- }
144
+ });
199
145
  const AUTHZ_KEYS = ["banExpires", "banReason", "banned", "emailVerified", "role", "roles", "twoFactorEnabled"];
200
146
  function mergeSessionUser(sessionUser) {
201
147
  const cached = resolvedAuthState.value?.user;
@@ -455,7 +401,7 @@ export function useLtAuth() {
455
401
  if (!credential) {
456
402
  return {
457
403
  success: false,
458
- error: t("lt.auth.passkeyCreationAborted", "Passkey-Erstellung abgebrochen")
404
+ error: t("lt.auth.passkeyCreationAborted", "Passkey-Erstellung wurde abgebrochen")
459
405
  };
460
406
  }
461
407
  const attestationResponse = credential.response;
@@ -3,8 +3,10 @@
3
3
  *
4
4
  * Any signed-in user can author re-usable prompts ("Vorlagen") for themselves
5
5
  * (`scope: 'user'` = private) or for their tenant (`scope: 'tenant'` = public).
6
- * `load()` returns every prompt the current user is allowed to see (own +
7
- * tenant), already filtered by the server.
6
+ * `load()` returns every active prompt the current user is allowed to see (own +
7
+ * tenant), already filtered by the server. That is what a chat picker offers.
8
+ * A management screen calls `load({ includeDisabled: true })` (nest-server >= 12.7.0),
9
+ * so a prompt switched off stays in the list and can be switched on again.
8
10
  *
9
11
  * Pair this with your own prompt picker / settings UI. The nuxt-base-starter
10
12
  * ships a reference picker inside the AI chat and a settings page.
@@ -4,11 +4,17 @@ export function useLtAiPrompts() {
4
4
  const prompts = ref([]);
5
5
  const loading = ref(false);
6
6
  const error = ref(null);
7
- async function load() {
7
+ let includeDisabled = false;
8
+ async function load(options) {
9
+ includeDisabled = options?.includeDisabled === true;
10
+ await fetchPrompts();
11
+ }
12
+ async function fetchPrompts() {
8
13
  loading.value = true;
9
14
  error.value = null;
10
15
  try {
11
- prompts.value = await ltAiRequest("GET", "/prompts") || [];
16
+ const path = includeDisabled ? "/prompts?includeDisabled=true" : "/prompts";
17
+ prompts.value = await ltAiRequest("GET", path) || [];
12
18
  } catch (err) {
13
19
  error.value = err.message;
14
20
  prompts.value = [];
@@ -21,7 +27,7 @@ export function useLtAiPrompts() {
21
27
  error.value = null;
22
28
  try {
23
29
  const created = await ltAiRequest("POST", "/prompts", input);
24
- await load();
30
+ await fetchPrompts();
25
31
  return created;
26
32
  } catch (err) {
27
33
  error.value = err.message;
@@ -35,7 +41,7 @@ export function useLtAiPrompts() {
35
41
  error.value = null;
36
42
  try {
37
43
  const updated = await ltAiRequest("PUT", `/prompts/${encodeURIComponent(id)}`, input);
38
- await load();
44
+ await fetchPrompts();
39
45
  return updated;
40
46
  } catch (err) {
41
47
  error.value = err.message;
@@ -49,7 +55,7 @@ export function useLtAiPrompts() {
49
55
  error.value = null;
50
56
  try {
51
57
  const removed = await ltAiRequest("DELETE", `/prompts/${encodeURIComponent(id)}`);
52
- await load();
58
+ await fetchPrompts();
53
59
  return removed;
54
60
  } catch (err) {
55
61
  error.value = err.message;
@@ -17,10 +17,6 @@
17
17
  * ```
18
18
  */
19
19
  import { type LtAuthClient } from '../lib/auth-client.js';
20
- /**
21
- * Reset the auth client singleton (useful for testing or config changes)
22
- */
23
- export declare function resetLtAuthClient(): void;
24
20
  /**
25
21
  * Returns the Better-Auth client singleton
26
22
  *
@@ -1,9 +1,6 @@
1
1
  import { useRuntimeConfig } from "#imports";
2
- import { getOrCreateLtAuthClient, resetLtAuthClientSingleton } from "../lib/auth-client.js";
2
+ import { getOrCreateLtAuthClient } from "../lib/auth-client.js";
3
3
  import { isLocalDevApiProxy } from "../lib/auth-state.js";
4
- export function resetLtAuthClient() {
5
- resetLtAuthClientSingleton();
6
- }
7
4
  export function useLtAuthClient() {
8
5
  try {
9
6
  const runtimeConfig = useRuntimeConfig();
@@ -8,6 +8,10 @@
8
8
  * Translations loaded from: GET /i18n/errors/:locale
9
9
  *
10
10
  * URL handling is delegated to {@link buildLtApiUrl} (SSR / proxy / direct).
11
+ *
12
+ * Until the translations for the current locale are loaded, `translateError` returns the
13
+ * developer message. The plugin starts the load after the app is mounted and does not wait
14
+ * for it (DEV-4078); every instance shares that request, see {@link inFlightLoads}.
11
15
  */
12
16
  import type { UseLtErrorTranslationReturn } from '../types/error.js';
13
17
  /**
@@ -1,12 +1,21 @@
1
- import { computed, ref, useState, useNuxtApp, useRuntimeConfig } from "#imports";
1
+ import { computed, useState, useNuxtApp, useRuntimeConfig } from "#imports";
2
2
  import { buildLtApiUrl } from "../lib/auth-state.js";
3
3
  import { ltAddToast } from "../lib/toast.js";
4
4
  const ERROR_CODE_REGEX = /^#([A-Z_]+_\d+):\s*(.+)$/;
5
+ const inFlightLoads = /* @__PURE__ */ new WeakMap();
6
+ function inFlightLoadsOf(app) {
7
+ let loads = inFlightLoads.get(app);
8
+ if (!loads) {
9
+ loads = /* @__PURE__ */ new Map();
10
+ inFlightLoads.set(app, loads);
11
+ }
12
+ return loads;
13
+ }
5
14
  export function useLtErrorTranslation() {
6
15
  const nuxtApp = useNuxtApp();
7
16
  const runtimeConfig = useRuntimeConfig();
8
17
  const translations = useState("lt-error-translations", () => ({}));
9
- const isLoading = ref(false);
18
+ const isLoading = useState("lt-error-translations-loading", () => false);
10
19
  const config = runtimeConfig.public?.ltExtensions?.errorTranslation;
11
20
  function t(key, germanFallback) {
12
21
  const i18n = nuxtApp.$i18n;
@@ -31,17 +40,33 @@ export function useLtErrorTranslation() {
31
40
  function buildErrorUrl(locale) {
32
41
  return buildLtApiUrl(`/i18n/errors/${locale}`);
33
42
  }
34
- async function loadTranslations(locale) {
43
+ function loadTranslations(locale) {
35
44
  const targetLocale = locale || detectLocale();
36
45
  if (translations.value[targetLocale]) {
37
- return;
46
+ return Promise.resolve();
38
47
  }
39
- if (isLoading.value) {
40
- return;
48
+ const loads = inFlightLoadsOf(nuxtApp);
49
+ const pending = loads.get(targetLocale);
50
+ if (pending) {
51
+ return pending;
52
+ }
53
+ let url;
54
+ try {
55
+ url = buildErrorUrl(targetLocale);
56
+ } catch (error) {
57
+ console.warn(`[LtErrorTranslation] Failed to load translations for ${targetLocale}:`, error);
58
+ return Promise.resolve();
41
59
  }
42
60
  isLoading.value = true;
61
+ const load = fetchTranslations(url, targetLocale).finally(() => {
62
+ loads.delete(targetLocale);
63
+ isLoading.value = loads.size > 0;
64
+ });
65
+ loads.set(targetLocale, load);
66
+ return load;
67
+ }
68
+ async function fetchTranslations(url, targetLocale) {
43
69
  try {
44
- const url = buildErrorUrl(targetLocale);
45
70
  const response = await $fetch(url);
46
71
  if (response?.errors) {
47
72
  translations.value = {
@@ -51,8 +76,6 @@ export function useLtErrorTranslation() {
51
76
  }
52
77
  } catch (error) {
53
78
  console.warn(`[LtErrorTranslation] Failed to load translations for ${targetLocale}:`, error);
54
- } finally {
55
- isLoading.value = false;
56
79
  }
57
80
  }
58
81
  function extractMessage(errorOrMessage) {
@@ -274,25 +274,82 @@ export declare function setLtAuthMode(mode: LtAuthMode): void;
274
274
  * @param basePath - The auth API base path. If not provided, reads from runtime config (default: '/iam')
275
275
  */
276
276
  export declare function getLtApiBase(basePath?: string): string;
277
+ /**
278
+ * `GET <auth>/token` with the session cookie: a fresh JWT, or `null` (refused, not JWT-shaped, offline).
279
+ *
280
+ * INTERNAL — the one place a JWT is fetched: {@link attemptLtJwtSwitch}, the 401 recovery of
281
+ * {@link createLtAuthFetch} and `useLtAuth().switchToJwtMode()` all go through it. Not part of the
282
+ * public API (absent from the barrels and auto-imports).
283
+ *
284
+ * @param basePath - The auth API base path; `auth.basePath` from the runtime config when omitted
285
+ */
286
+ export declare function requestLtJwt(basePath?: string): Promise<null | string>;
277
287
  /**
278
288
  * Attempt to switch to JWT mode by fetching a token
279
289
  *
280
- * @param basePath - The auth API base path (default: '/iam')
290
+ * @param basePath - The auth API base path; `auth.basePath` from the runtime config when omitted
281
291
  */
282
292
  export declare function attemptLtJwtSwitch(basePath?: string): Promise<boolean>;
283
293
  /**
284
294
  * Check if user is authenticated (has auth-state with user)
285
295
  */
286
296
  export declare function isLtAuthenticated(): boolean;
297
+ /**
298
+ * Where a caller of the authenticated fetch keeps its auth mode and its JWT.
299
+ *
300
+ * INTERNAL — `useLtAuth()` hands in its own `useCookie` refs, so its `fetchWithAuth` reads and
301
+ * writes what the composable shows; every other caller uses the browser cookies. Not part of the
302
+ * public API.
303
+ */
304
+ export interface LtAuthFetchState {
305
+ /** Store a freshly fetched JWT and switch to JWT mode. */
306
+ adoptJwt: (token: string) => void;
307
+ isAuthenticated: () => boolean;
308
+ jwtToken: () => null | string;
309
+ mode: () => LtAuthMode;
310
+ }
311
+ /** INTERNAL — options of {@link createLtAuthFetchFor}. */
312
+ export interface LtAuthFetchOptions {
313
+ /** The auth API base path for the JWT; `auth.basePath` from the runtime config when omitted. */
314
+ basePath?: string;
315
+ /**
316
+ * Cookies in JWT mode. `'always'` (default): the session cookie rides along, and nest-server
317
+ * (>= 11.13.1) falls back to it when the bearer fails; Better-Auth's own routes read the session
318
+ * from it. `'auth-paths'`: only {@link LT_PATHS_REQUIRING_COOKIES} get it, as in
319
+ * `useLtAuth().fetchWithAuth` (and ng-base's auth fetch).
320
+ */
321
+ cookiesInJwtMode?: 'always' | 'auth-paths';
322
+ state: LtAuthFetchState;
323
+ }
324
+ /**
325
+ * The authenticated fetch, one implementation for every caller.
326
+ *
327
+ * INTERNAL — `useLtAuth().fetchWithAuth` builds itself from it with its own state; everyone else
328
+ * uses {@link createLtAuthFetch} / {@link ltAuthFetch}. Not part of the public API.
329
+ *
330
+ * 1. JWT mode adds `Authorization: Bearer <jwt>`; cookies follow `cookiesInJwtMode`.
331
+ * 2. A 401 while signed in fetches a JWT once (shared by the burst, see {@link requestLtJwtAfter401})
332
+ * and retries the request once with it. In cookie mode that is the switch to JWT; in JWT mode the
333
+ * bearer was most likely expired: the JWT lives 15 minutes, the session behind it 7 days, and
334
+ * nothing renews it while the user works.
335
+ * 3. A 401 that survives the fresh token, or one no token can be fetched for, reaches the caller
336
+ * unchanged. So does a 401 in JWT mode that the bearer did not cause: with `'auth-paths'` on a
337
+ * cookie-bound path (the cookie failed there), with `'always'` on Better-Auth's own routes, where
338
+ * the cookie rides along anyway and a 401 is the flow's verdict. A wrong password or 2FA code
339
+ * sent a second time would count twice against the rate limit.
340
+ */
341
+ export declare function createLtAuthFetchFor(options: LtAuthFetchOptions): (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
287
342
  /**
288
343
  * Custom fetch function that handles Cookie/JWT dual-mode authentication
289
344
  *
290
345
  * This function:
291
- * 1. In cookie mode: Uses credentials: 'include'
292
- * 2. In JWT mode: Adds Authorization header
293
- * 3. On 401 in cookie mode: Attempts to switch to JWT and retries
346
+ * 1. Always sends the cookies (`credentials: 'include'`)
347
+ * 2. In JWT mode: Adds the Authorization header
348
+ * 3. On 401 while signed in: fetches a JWT once (cookie mode: switch to JWT; JWT mode: renew the
349
+ * expired one) and retries the request once
294
350
  *
295
- * @param basePath - The auth API base path for JWT switch (default: '/iam')
351
+ * @param basePath - The auth API base path for the JWT; `auth.basePath` from the runtime config when omitted
296
352
  */
297
353
  export declare function createLtAuthFetch(basePath?: string): (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
354
+ /** Default auth fetch; fetches its JWT from `auth.basePath` (default `/iam`). */
298
355
  export declare const ltAuthFetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
@@ -204,60 +204,105 @@ export function getLtApiBase(basePath) {
204
204
  }
205
205
  return buildLtApiUrl(basePath || "/iam");
206
206
  }
207
- export async function attemptLtJwtSwitch(basePath = "/iam") {
207
+ export async function requestLtJwt(basePath) {
208
208
  try {
209
- const apiBase = getLtApiBase(basePath);
210
- const response = await fetch(`${apiBase}/token`, {
211
- method: "GET",
212
- credentials: "include"
209
+ const response = await fetch(`${getLtApiBase(basePath)}/token`, {
210
+ credentials: "include",
211
+ method: "GET"
213
212
  });
214
- if (response.ok) {
215
- const data = await response.json();
216
- if (isLtJwtShaped(data.token)) {
217
- setLtJwtToken(data.token);
218
- setLtAuthMode("jwt");
219
- console.debug("[LtAuth] Switched to JWT mode");
220
- return true;
221
- }
213
+ if (!response.ok) {
214
+ return null;
222
215
  }
223
- return false;
216
+ const data = await response.json();
217
+ const token = data?.token;
218
+ return isLtJwtShaped(token) ? token : null;
224
219
  } catch {
220
+ return null;
221
+ }
222
+ }
223
+ export async function attemptLtJwtSwitch(basePath) {
224
+ const token = await requestLtJwt(basePath);
225
+ if (!token) {
225
226
  return false;
226
227
  }
228
+ ltCookieAuthFetchState.adoptJwt(token);
229
+ console.debug("[LtAuth] Switched to JWT mode");
230
+ return true;
227
231
  }
228
232
  export function isLtAuthenticated() {
229
233
  if (import.meta.server) return false;
230
234
  return !!resolveLtAuthState(document.cookie)?.user;
231
235
  }
232
- export function createLtAuthFetch(basePath = "/iam") {
236
+ const LT_PATHS_REQUIRING_COOKIES = ["/passkey/", "/two-factor/", "/2fa/", "/get-session"];
237
+ function ltUrlRequiresCookies(url) {
238
+ return LT_PATHS_REQUIRING_COOKIES.some((path) => url.includes(path));
239
+ }
240
+ function ltUrlPath(url) {
241
+ try {
242
+ return new URL(url, "http://lt.invalid").pathname;
243
+ } catch {
244
+ return url;
245
+ }
246
+ }
247
+ function isLtAuthRoute(url, basePath) {
248
+ const base = ltUrlPath(getLtApiBase(basePath)).replace(/\/+$/, "");
249
+ const path = ltUrlPath(url);
250
+ return path === base || path.startsWith(`${base}/`);
251
+ }
252
+ const ltCookieAuthFetchState = {
253
+ adoptJwt: (token) => {
254
+ setLtJwtToken(token);
255
+ setLtAuthMode("jwt");
256
+ },
257
+ isAuthenticated: isLtAuthenticated,
258
+ jwtToken: getLtJwtToken,
259
+ mode: getLtAuthMode
260
+ };
261
+ let ltJwtAfter401 = null;
262
+ function requestLtJwtAfter401(basePath) {
263
+ if (!import.meta.client) {
264
+ return requestLtJwt(basePath);
265
+ }
266
+ if (!ltJwtAfter401) {
267
+ ltJwtAfter401 = requestLtJwt(basePath).finally(() => {
268
+ ltJwtAfter401 = null;
269
+ });
270
+ }
271
+ return ltJwtAfter401;
272
+ }
273
+ export function createLtAuthFetchFor(options) {
274
+ const { basePath, cookiesInJwtMode = "always", state } = options;
275
+ const credentialsFor = (url, jwtMode) => jwtMode && cookiesInJwtMode === "auth-paths" && !ltUrlRequiresCookies(url) ? "omit" : "include";
276
+ const bearerMayHaveFailed = (url) => cookiesInJwtMode === "auth-paths" ? !ltUrlRequiresCookies(url) : !isLtAuthRoute(url, basePath);
233
277
  return async function ltAuthFetch2(input, init) {
234
- const authMode = getLtAuthMode();
235
- const jwtToken = getLtJwtToken();
278
+ const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
279
+ const jwtMode = state.mode() === "jwt";
236
280
  const headers = new Headers(init?.headers);
237
- if (authMode === "jwt" && jwtToken) {
238
- headers.set("Authorization", `Bearer ${jwtToken}`);
281
+ const sentToken = jwtMode ? state.jwtToken() : null;
282
+ if (sentToken) {
283
+ headers.set("Authorization", `Bearer ${sentToken}`);
239
284
  }
240
- const response = await fetch(input, {
241
- ...init,
242
- headers,
243
- credentials: "include"
244
- });
245
- if (response.status === 401 && authMode === "cookie" && isLtAuthenticated()) {
285
+ const response = await fetch(input, { ...init, credentials: credentialsFor(url, jwtMode), headers });
286
+ if (response.status !== 401 || !state.isAuthenticated()) {
287
+ return response;
288
+ }
289
+ if (jwtMode && !bearerMayHaveFailed(url)) {
290
+ return response;
291
+ }
292
+ if (!jwtMode) {
246
293
  console.debug("[LtAuth] Cookie auth failed, attempting JWT fallback...");
247
- const switched = await attemptLtJwtSwitch(basePath);
248
- if (switched) {
249
- const newToken = getLtJwtToken();
250
- if (newToken) {
251
- headers.set("Authorization", `Bearer ${newToken}`);
252
- return fetch(input, {
253
- ...init,
254
- headers,
255
- credentials: "include"
256
- });
257
- }
258
- }
259
294
  }
260
- return response;
295
+ const token = await requestLtJwtAfter401(basePath);
296
+ if (!token) {
297
+ return response;
298
+ }
299
+ state.adoptJwt(token);
300
+ const retryHeaders = new Headers(headers);
301
+ retryHeaders.set("Authorization", `Bearer ${token}`);
302
+ return fetch(input, { ...init, credentials: credentialsFor(url, true), headers: retryHeaders });
261
303
  };
262
304
  }
263
- export const ltAuthFetch = createLtAuthFetch("/iam");
305
+ export function createLtAuthFetch(basePath) {
306
+ return createLtAuthFetchFor({ basePath, state: ltCookieAuthFetchState });
307
+ }
308
+ export const ltAuthFetch = createLtAuthFetch();
@@ -1,19 +1,17 @@
1
1
  {
2
2
  "lt": {
3
3
  "auth": {
4
- "loggingOut": "Abmelden...",
5
4
  "noPasskeySelected": "Kein Passkey ausgewählt",
6
5
  "passkeyAborted": "Passkey-Authentifizierung wurde abgebrochen",
6
+ "passkeyAlreadyRegistered": "Du hast bereits einen Passkey für diese Website registriert. Lösche ihn zuerst oder verwende einen anderen Authenticator.",
7
7
  "passkeyCreationAborted": "Passkey-Erstellung wurde abgebrochen",
8
8
  "passkeyError": "Konnte Passkey-Optionen nicht laden",
9
9
  "passkeyFailed": "Passkey-Anmeldung fehlgeschlagen",
10
10
  "passkeyRegisterFailed": "Passkey-Registrierung fehlgeschlagen",
11
- "registerOptionsError": "Konnte Registrierungsoptionen nicht laden",
12
- "sessionExpired": "Sitzung abgelaufen"
11
+ "registerOptionsError": "Konnte Registrierungsoptionen nicht laden"
13
12
  },
14
13
  "error": {
15
- "title": "Fehler",
16
- "loadFailed": "Fehlerübersetzungen konnten nicht geladen werden"
14
+ "title": "Fehler"
17
15
  },
18
16
  "share": {
19
17
  "copied": "Link kopiert",
@@ -1,19 +1,17 @@
1
1
  {
2
2
  "lt": {
3
3
  "auth": {
4
- "loggingOut": "Logging out...",
5
4
  "noPasskeySelected": "No passkey selected",
6
5
  "passkeyAborted": "Passkey authentication was cancelled",
6
+ "passkeyAlreadyRegistered": "You already registered a passkey for this website. Delete it first or use another authenticator.",
7
7
  "passkeyCreationAborted": "Passkey creation was cancelled",
8
8
  "passkeyError": "Could not load passkey options",
9
9
  "passkeyFailed": "Passkey login failed",
10
10
  "passkeyRegisterFailed": "Passkey registration failed",
11
- "registerOptionsError": "Could not load registration options",
12
- "sessionExpired": "Session expired"
11
+ "registerOptionsError": "Could not load registration options"
13
12
  },
14
13
  "error": {
15
- "title": "Error",
16
- "loadFailed": "Failed to load error translations"
14
+ "title": "Error"
17
15
  },
18
16
  "share": {
19
17
  "copied": "Link copied",
@@ -1,8 +1,18 @@
1
1
  /**
2
2
  * Error Translation Plugin
3
3
  *
4
- * Automatically loads error translations on app start.
5
- * Provides global helper methods: $ltTranslateError, $ltShowErrorToast
4
+ * Loads the error translations for the current locale once the app is mounted, and provides
5
+ * the global helpers $ltTranslateError and $ltShowErrorToast.
6
+ *
7
+ * The load does not hold back the start (DEV-4078). Until it is done, `translateError`
8
+ * returns the developer message, and every template that renders it switches to the
9
+ * translation when it arrives, because the translations live in shared state.
10
+ *
11
+ * It starts after the mount on purpose, not merely without `await`: server-rendered HTML
12
+ * carries the developer message, since the server loads no translations. Translations that
13
+ * arrived before hydration would make the client render a different text than the server
14
+ * did (a hydration mismatch). After the mount, hydration has already seen the server's text.
15
+ * How a project translates messages during SSR: README, "Error Translation".
6
16
  */
7
17
  import type { ObjectPlugin, Plugin } from '#app';
8
18
  declare const _default: Plugin & ObjectPlugin;
@@ -1,17 +1,15 @@
1
1
  import { defineNuxtPlugin, useRuntimeConfig } from "#imports";
2
2
  import { useLtErrorTranslation } from "../composables/use-lt-error-translation.js";
3
- export default defineNuxtPlugin(async (nuxtApp) => {
3
+ export default defineNuxtPlugin((nuxtApp) => {
4
4
  const runtimeConfig = useRuntimeConfig();
5
5
  const config = runtimeConfig.public?.ltExtensions?.errorTranslation;
6
6
  if (config?.enabled === false) {
7
7
  return;
8
8
  }
9
9
  const { loadTranslations, translateError, showErrorToast } = useLtErrorTranslation();
10
- try {
11
- await loadTranslations();
12
- } catch (error) {
13
- console.warn("[LtErrorTranslation] Initial load failed:", error);
14
- }
10
+ nuxtApp.hook("app:mounted", () => {
11
+ void nuxtApp.runWithContext(() => loadTranslations());
12
+ });
15
13
  nuxtApp.provide("ltTranslateError", translateError);
16
14
  nuxtApp.provide("ltShowErrorToast", showErrorToast);
17
15
  });
@@ -366,7 +366,10 @@ export interface LtAiPrompt {
366
366
  createdAt?: string;
367
367
  /** Optional description. */
368
368
  description?: string;
369
- /** Whether the prompt is active (disabled prompts are hidden). */
369
+ /**
370
+ * Whether the prompt is active. The server lists disabled prompts only on request
371
+ * (`useLtAiPrompts().load({ includeDisabled: true })`, nest-server >= 12.7.0).
372
+ */
370
373
  enabled?: boolean;
371
374
  /** Optional icon hint (lucide name or single emoji). */
372
375
  icon?: string;
@@ -477,6 +480,18 @@ export interface UseLtAiUsageReturn {
477
480
  load: () => Promise<void>;
478
481
  usage: DeepReadonly<Ref<LtAiUsageInfo | null>>;
479
482
  }
483
+ /**
484
+ * Options of `useLtAiPrompts().load()`.
485
+ */
486
+ export interface LtAiPromptsLoadOptions {
487
+ /**
488
+ * Also list disabled prompts (`GET /ai/prompts?includeDisabled=true`, nest-server >= 12.7.0).
489
+ * For a management screen, where a disabled prompt must stay editable. A chat picker leaves it
490
+ * off, because it must offer active prompts only. A server before 12.7.0 ignores the parameter
491
+ * and lists active prompts only.
492
+ */
493
+ includeDisabled?: boolean;
494
+ }
480
495
  /**
481
496
  * User-facing prompt composable. Lets any signed-in user manage their own
482
497
  * prompts ("Vorlagen") and use the visible ones (own private + tenant public)
@@ -485,7 +500,11 @@ export interface UseLtAiUsageReturn {
485
500
  export interface UseLtAiPromptsReturn {
486
501
  create: (input: LtAiPromptInput) => Promise<LtAiPrompt>;
487
502
  error: DeepReadonly<Ref<null | string>>;
488
- load: () => Promise<void>;
503
+ /**
504
+ * Loads the prompts the user may see. Its options also apply to the reload after `create`,
505
+ * `update` and `remove`, so a prompt saved as disabled stays in a management list.
506
+ */
507
+ load: (options?: LtAiPromptsLoadOptions) => Promise<void>;
489
508
  loading: DeepReadonly<Ref<boolean>>;
490
509
  prompts: DeepReadonly<Ref<LtAiPrompt[]>>;
491
510
  remove: (id: string) => Promise<LtAiPrompt>;
@@ -88,6 +88,11 @@ export interface LtAuthClientConfig {
88
88
  /**
89
89
  * Normalized response type for Better-Auth operations
90
90
  * The Vue client returns complex union types - this provides a consistent interface
91
+ *
92
+ * @deprecated No function of this module returns or accepts it. Its `data.token` invites
93
+ * storing whatever token an answer carries, and Better-Auth's 2FA answer carries the session
94
+ * token there, which application code must never hold. Type the result of the method you
95
+ * call instead. Removed in the next major version.
91
96
  */
92
97
  export interface LtAuthResponse {
93
98
  data?: null | {
@@ -18,15 +18,6 @@ export interface LtParsedError {
18
18
  /** Translated user-friendly message */
19
19
  translatedMessage: string;
20
20
  }
21
- /**
22
- * Error translation module options
23
- */
24
- export interface LtErrorTranslationModuleOptions {
25
- /** Enable error translation feature (default: true) */
26
- enabled?: boolean;
27
- /** Default locale if not detected (default: 'de') */
28
- defaultLocale?: string;
29
- }
30
21
  /**
31
22
  * Return type for useLtErrorTranslation composable
32
23
  */
@@ -62,11 +53,16 @@ export interface UseLtErrorTranslationReturn {
62
53
  parseError: (errorOrMessage: unknown) => LtParsedError;
63
54
  /** Show translated error as toast notification */
64
55
  showErrorToast: (errorOrMessage: unknown, title?: string) => void;
65
- /** Manually load translations for a locale */
56
+ /**
57
+ * Load the translations for a locale (default: the current one). The plugin calls it after
58
+ * the app is mounted and does not wait for it; await it where the translations have to be
59
+ * there first. A load already in flight for that locale is shared, not repeated. Resolves
60
+ * once they are loaded, or once the load failed (logged, never rejected).
61
+ */
66
62
  loadTranslations: (locale?: string) => Promise<void>;
67
63
  /** Check if translations are loaded for current locale */
68
64
  isLoaded: ComputedRef<boolean>;
69
- /** Check if translations are currently loading */
65
+ /** `true` while a load is in flight; shared by every instance of the composable */
70
66
  isLoading: Ref<boolean>;
71
67
  /** Current detected locale */
72
68
  currentLocale: ComputedRef<string>;
@@ -3,4 +3,4 @@ export type { LtFileInfo, LtUploadItem, LtUploadOptions, LtUploadProgress, LtUpl
3
3
  export type { LtAiModuleOptions, LtAuthCookieNamesOptions, LtAuthModuleOptions, LtErrorTranslationModuleOptions, LtExtensionsModuleOptions, LtExtensionsPublicRuntimeConfig, LtFormLabelAssociationOptions, LtI18nModuleOptions, LtPreHydrationInputOptions, LtSecurityTxtOptions, LtSystemSetupModuleOptions, LtTusModuleOptions, } from './module.js';
4
4
  export type { LtErrorTranslationResponse, LtParsedError, UseLtErrorTranslationReturn } from './error.js';
5
5
  export type { LtSyncConflict, LtSyncConflictResolution, LtSyncIdFormat, LtSyncItemStatus, LtSyncModuleOptions, LtSyncPushResult, LtSyncRecord, LtSyncResult, UseLtOfflineSyncOptions, UseLtOfflineSyncReturn, } from './sync.js';
6
- export type { LtAiAction, LtAiAvailableConnection, LtAiBudgetLimit, LtAiBudgetSummary, LtAiConnection, LtAiConnectionInput, LtAiConnectionPreference, LtAiEffectiveSlot, LtAiInteraction, LtAiMessage, LtAiMode, LtAiPlaceholder, LtAiPrompt, LtAiPromptHint, LtAiPromptHintInput, LtAiPromptInput, LtAiPromptRunInput, LtAiResponse, LtAiSettings, LtAiSettingsInput, LtAiSlot, LtAiStatus, LtAiSlotInput, LtAiStreamEvent, LtAiStreamHandlers, LtAiUsage, LtAiUsageInfo, LtAiUsageScope, UseLtAiAdminReturn, UseLtAiChatOptions, UseLtAiChatReturn, UseLtAiConnectionsReturn, UseLtAiPlaceholdersReturn, UseLtAiPromptsReturn, UseLtAiReturn, UseLtAiSettingsReturn, UseLtAiStatusReturn, UseLtAiUsageReturn, } from './ai.js';
6
+ export type { LtAiAction, LtAiAvailableConnection, LtAiBudgetLimit, LtAiBudgetSummary, LtAiConnection, LtAiConnectionInput, LtAiConnectionPreference, LtAiEffectiveSlot, LtAiInteraction, LtAiMessage, LtAiMode, LtAiPlaceholder, LtAiPrompt, LtAiPromptHint, LtAiPromptHintInput, LtAiPromptInput, LtAiPromptRunInput, LtAiPromptsLoadOptions, LtAiResponse, LtAiSettings, LtAiSettingsInput, LtAiSlot, LtAiStatus, LtAiSlotInput, LtAiStreamEvent, LtAiStreamHandlers, LtAiUsage, LtAiUsageInfo, LtAiUsageScope, UseLtAiAdminReturn, UseLtAiChatOptions, UseLtAiChatReturn, UseLtAiConnectionsReturn, UseLtAiPlaceholdersReturn, UseLtAiPromptsReturn, UseLtAiReturn, UseLtAiSettingsReturn, UseLtAiStatusReturn, UseLtAiUsageReturn, } from './ai.js';
@@ -61,7 +61,13 @@ export interface LtAuthModuleOptions {
61
61
  baseURL?: string;
62
62
  /** Override the cookie names used for auth state and JWT storage */
63
63
  cookieNames?: LtAuthCookieNamesOptions;
64
- /** Enable the auth module (default: true) */
64
+ /**
65
+ * Gate of the 401 auth interceptor plugin (default: true). Despite its name it does not switch
66
+ * the auth module off: `useLtAuth()`, `useLtAuthClient()`, the auth helpers and the Better-Auth
67
+ * client stay registered, because the AI composables and offline sync authenticate through
68
+ * `ltAuthFetch` and TUS uploads send the same session. `false` has the same effect as
69
+ * `interceptor.enabled: false`; prefer that.
70
+ */
65
71
  enabled?: boolean;
66
72
  /** Enable admin plugin (default: true) */
67
73
  enableAdmin?: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nuxt-extensions",
3
- "version": "1.26.0",
3
+ "version": "1.28.0",
4
4
  "description": "Reusable Nuxt 4 composables, components, and Better-Auth integration for lenne.tech projects",
5
5
  "repository": {
6
6
  "type": "git",
@@ -82,9 +82,11 @@
82
82
  },
83
83
  "peerDependencies": {
84
84
  "@better-auth/passkey": ">=1.7.16 <1.8.0",
85
+ "@nuxt/ui": ">=3.0.0",
85
86
  "@playwright/test": ">=1.0.0",
86
87
  "better-auth": ">=1.7.16 <1.8.0",
87
88
  "nuxt": "^4.0.0",
89
+ "tailwindcss": ">=4.0.0",
88
90
  "tus-js-client": ">=4.0.0"
89
91
  },
90
92
  "peerDependenciesMeta": {
@@ -94,9 +96,15 @@
94
96
  "@better-auth/passkey": {
95
97
  "optional": true
96
98
  },
99
+ "@nuxt/ui": {
100
+ "optional": true
101
+ },
97
102
  "@playwright/test": {
98
103
  "optional": true
99
104
  },
105
+ "tailwindcss": {
106
+ "optional": true
107
+ },
100
108
  "tus-js-client": {
101
109
  "optional": true
102
110
  }
@@ -120,6 +128,7 @@
120
128
  "oxlint-tsgolint": "7.0.2005",
121
129
  "reka-ui": "2.11.0",
122
130
  "semver": "7.8.6",
131
+ "tailwindcss": "4.3.4",
123
132
  "tus-js-client": "4.3.1",
124
133
  "typescript": "5.9.3",
125
134
  "vitest": "5.1.0",