@choosemycompany/lib 0.6.0 → 0.8.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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @choosemycompany/lib
2
2
 
3
- Composables, stores et types partagés entre les apps front ChooseMyCompany (`commercial`, `workspace`).
3
+ Composables, stores and types shared between the ChooseMyCompany front-end apps (`commercial`, `workspace`).
4
4
 
5
5
  ## Installation
6
6
 
@@ -8,36 +8,43 @@ Composables, stores et types partagés entre les apps front ChooseMyCompany (`co
8
8
  pnpm add @choosemycompany/lib
9
9
  ```
10
10
 
11
- ## Utilisation
11
+ ## Usage
12
12
 
13
13
  ```ts
14
14
  import { useHttp, useStore, type Store, type View } from '@choosemycompany/lib'
15
15
  ```
16
16
 
17
- Un seul entry point, tout est ré-exporté depuis `@choosemycompany/lib`.
17
+ A single entry point: everything is re-exported from `@choosemycompany/lib`.
18
18
 
19
- ## Dépendances
19
+ ## Dependencies
20
20
 
21
- Le package s'attend à être consommé **dans un projet Nuxt 4** avec les peer deps suivantes installées :
21
+ The package expects to be consumed **inside a Nuxt 4 project**, with the following peer deps installed:
22
22
 
23
23
  - `vue`, `vue-i18n`, `vue-router`, `pinia`
24
- - `mande` (client HTTP)
25
- - `h3` (pour `useErrorHandling`)
24
+ - `mande` (HTTP client)
25
+ - `h3` (for `useErrorHandling`)
26
26
  - `@nuxtjs/i18n` (`useLocalePath`)
27
- - `nuxt` (pour `useRuntimeConfig`, `useState`, `showError` importés depuis `nuxt/app`)
27
+ - `nuxt` (for `useRuntimeConfig`, `useState`, `showError`, imported from `nuxt/app`)
28
28
 
29
- Les composables utilisant `useRuntimeConfig()`, `useRoute()`, `useI18n()` doivent être appelés dans un scope Nuxt (setup, plugin, middleware).
29
+ Composables using `useRuntimeConfig()`, `useRoute()` or `useI18n()` must be called inside a Nuxt scope (setup, plugin, middleware).
30
30
 
31
- ## Développement local (HMR via sandbox)
31
+ ## Local development (HMR through the sandbox)
32
32
 
33
33
  ```bash
34
- pnpm install
35
- pnpm --filter sandbox dev # n'existe pas : sandbox est indépendant
36
- # ou
37
34
  cd sandbox && pnpm install && pnpm dev
38
35
  ```
39
36
 
40
- La sandbox utilise un alias Vite `@choosemycompany/lib` → `../src/index.ts`, donc chaque modif des sources de la lib déclenche du HMR immédiat.
37
+ Then <http://localhost:3000>. The sandbox has its own `package.json` and its own lockfile: it is not part of a pnpm workspace, hence the `cd`.
38
+
39
+ The sandbox uses a Vite alias `@choosemycompany/lib` → `../src/index.ts`, so every change to the lib's sources triggers immediate HMR. A mock API is served by Nitro: `/api/philosophers` for `useHttp` + `useStore`, and an authentication backend for the `/auth` page.
40
+
41
+ ### The `/auth` page
42
+
43
+ It exercises `useAuthSession` against a mocked auth backend: `POST /auth/api/v2/login`, `POST /auth/api/v2/login/token/refresh` and `POST /auth/api/v2/logout` served at the **origin** like the real auth-api, a protected resource under `/api/session/protected`, and `POST /api/session/simulate` to age the session without waiting 4 h.
44
+
45
+ The scenario: sign in, call the protected API, expire the token, call again. The app writes a single `http.get` and the trace shows three calls — the `401`, the renewal, the replay.
46
+
47
+ Known limitation: production runs a cross-site guard, `RejectCrossSiteCookieAuthenticatedRequest`, which answers `403` to an unsafe request that is authenticated by cookie, carries no `Authorization` header, and comes from another site. The sandbox has no equivalent, so the lib's `403` path cannot be exercised here.
41
48
 
42
49
  ## Build & publish
43
50
 
@@ -45,10 +52,10 @@ La sandbox utilise un alias Vite `@choosemycompany/lib` → `../src/index.ts`, d
45
52
  pnpm build # vite build → dist/
46
53
  pnpm typecheck
47
54
  pnpm test
48
- pnpm publish # via CI CircleCI sur push main
55
+ pnpm publish # through CircleCI on a push to main
49
56
  ```
50
57
 
51
- ## Changements d'API notables
58
+ ## Notable API changes
52
59
 
53
- - `useStore` : signature unifiée qui absorbe la variante `workspace` (search, filters, 4ᵉ générique `FilterItem`). Méthode publique : `isPending(key)`. `getViewKey` trie les clés pour garantir un cache déterministe.
54
- - `usePrimaryTypeTranslation(primaryTypes)` : reçoit désormais la liste des primaryTypes en argument au lieu de l'importer depuis `@/entities/form` de commercial.
60
+ - `useStore`: unified signature absorbing the `workspace` variant (search, filters, a fourth `FilterItem` generic). Public method: `isPending(key)`. `getViewKey` sorts keys to guarantee a deterministic cache.
61
+ - `usePrimaryTypeTranslation(primaryTypes)`: now receives the list of primary types as an argument instead of importing it from commercial's `@/entities/form`.
@@ -16,7 +16,7 @@ declare global {
16
16
  * The function is a **safe no-op** in three situations:
17
17
  * - running on the server (no `window`)
18
18
  * - the gtag snippet is not loaded (`window.gtag` undefined)
19
- * - `gtagId` is empty in `runtimeConfig` (e.g. preview / staging environments)
19
+ * - `gtagId` is empty in `runtimeConfig` (no tag configured for this deployment)
20
20
  *
21
21
  * That way consumer code can call `reportConversion()` unconditionally without
22
22
  * branching for the environment.
@@ -0,0 +1,14 @@
1
+ /** Why a session ended. Lets the consuming app tailor its exit message. */
2
+ export type SessionExpiryReason =
3
+ /** The refresh endpoint refused the refresh token of an open session. */
4
+ 'refresh-rejected'
5
+ /**
6
+ * The renewal found no session to renew: the visitor is anonymous. Reached
7
+ * only on a session that was never open, so it is the "never signed in" case,
8
+ * not the "signed out" one — an app showing an expiry message must skip it.
9
+ */
10
+ | 'no-session'
11
+ /** The refresh call itself could not complete (network, CORS, 5xx). */
12
+ | 'refresh-unreachable'
13
+ /** The app cleared the session on purpose (logout). */
14
+ | 'logout';
@@ -0,0 +1,74 @@
1
+ import { SessionExpiryReason } from './types';
2
+ /**
3
+ * Refresh endpoint of the CMC API, resolved against the **origin** of the
4
+ * declared base URL, never appended to it: that base URL may carry a path
5
+ * prefix, while the auth API always sits at this path on the origin. Internal.
6
+ */
7
+ export declare const REFRESH_URI = "/auth/api/v2/login/token/refresh";
8
+ /**
9
+ * Path prefix of the auth API. A call to it is never renewed and replayed: it
10
+ * speaks *about* the session rather than relying on it, so a `401` from `login`
11
+ * is a wrong password, one from `refresh` is a dead refresh token, and one from
12
+ * `logout` is nothing worth replaying. Internal.
13
+ */
14
+ export declare const AUTH_API_PREFIX = "/auth/api/v2/";
15
+ /**
16
+ * Name of the Web Locks entry that serialises the refresh across tabs. Namespaced
17
+ * so it cannot collide with a lock the application takes. Internal.
18
+ */
19
+ export declare const REFRESH_LOCK = "cmc-auth-session-refresh";
20
+ /**
21
+ * Shared session store: whether a session is open, and how to renew it when a
22
+ * call comes back `401`.
23
+ *
24
+ * The store holds **no token**. The access token lives in a cookie that the
25
+ * browser attaches to every same-site request on its own, so the store has
26
+ * nothing to read, carry, or put on a header. What it tracks is the one thing
27
+ * the app cannot get from the cookie jar: whether the session is still usable,
28
+ * and why it stopped being so.
29
+ *
30
+ * That the store reads no token is what lets the cookies become `httpOnly`
31
+ * without touching this code. The refresh cookie already is; the access cookie
32
+ * follows when the backend flips it.
33
+ *
34
+ * Paired with {@link useHttp}'s `401` interceptor: a refused call triggers one
35
+ * renewal and one replay. The app watches {@link isExpired} and decides where
36
+ * to send the user.
37
+ *
38
+ * Renewal is **reactive only** — no timer renews ahead of expiry. A timer would
39
+ * buy one faster request every four hours and would not even cover the case it
40
+ * looks like it covers: `setTimeout` does not fire while the laptop sleeps.
41
+ *
42
+ * See `docs/useAuthSession.md` for the wiring and the guarantees.
43
+ */
44
+ export declare const useAuthSession: import('pinia').StoreDefinition<"cmc-auth-session", Pick<{
45
+ isOpen: import('vue').Ref<boolean, boolean>;
46
+ isExpired: import('vue').Ref<boolean, boolean>;
47
+ expiryReason: import('vue').Ref<SessionExpiryReason | undefined, SessionExpiryReason | undefined>;
48
+ isAuthenticated: import('vue').ComputedRef<boolean>;
49
+ open: () => void;
50
+ expire: (reason: SessionExpiryReason) => void;
51
+ clear: () => void;
52
+ logout: () => void;
53
+ refresh: () => Promise<void>;
54
+ }, "isOpen" | "isExpired" | "expiryReason">, Pick<{
55
+ isOpen: import('vue').Ref<boolean, boolean>;
56
+ isExpired: import('vue').Ref<boolean, boolean>;
57
+ expiryReason: import('vue').Ref<SessionExpiryReason | undefined, SessionExpiryReason | undefined>;
58
+ isAuthenticated: import('vue').ComputedRef<boolean>;
59
+ open: () => void;
60
+ expire: (reason: SessionExpiryReason) => void;
61
+ clear: () => void;
62
+ logout: () => void;
63
+ refresh: () => Promise<void>;
64
+ }, "isAuthenticated">, Pick<{
65
+ isOpen: import('vue').Ref<boolean, boolean>;
66
+ isExpired: import('vue').Ref<boolean, boolean>;
67
+ expiryReason: import('vue').Ref<SessionExpiryReason | undefined, SessionExpiryReason | undefined>;
68
+ isAuthenticated: import('vue').ComputedRef<boolean>;
69
+ open: () => void;
70
+ expire: (reason: SessionExpiryReason) => void;
71
+ clear: () => void;
72
+ logout: () => void;
73
+ refresh: () => Promise<void>;
74
+ }, "logout" | "open" | "expire" | "clear" | "refresh">>;
package/dist/env.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Runtime environment flags, shared by the domains that need to behave
3
+ * differently under SSR. Internal — not exported from `src/index.ts`.
4
+ */
5
+ /**
6
+ * True when there is no browser behind the current code path.
7
+ *
8
+ * Two things depend on this. Cookies: Node holds no jar, so a request that
9
+ * relies on one comes back refused and says nothing about the real state.
10
+ * Timers: one armed on the Nitro server outlives the response it belongs to
11
+ * and fires against a request nobody is waiting for.
12
+ *
13
+ * `import.meta.server` is the Nuxt-side answer; the `document` check keeps the
14
+ * guard honest anywhere the flag is not injected, and makes it testable.
15
+ */
16
+ export declare function isServerSide(): boolean;
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Base URLs the application declares to the library.
3
+ *
4
+ * `baseUrl` is what {@link useHttp} uses when the caller names no target.
5
+ * `targets` holds the other origins the app talks to, addressed by name.
6
+ */
7
+ export interface HttpConfig {
8
+ /** Base URL used by `useHttp()`. May carry a path prefix. */
9
+ baseUrl: string;
10
+ /** Extra origins, addressed by name: `useHttp('happy')`. */
11
+ targets?: Record<string, string>;
12
+ }
13
+ /**
14
+ * Declares the base URLs the library must use.
15
+ *
16
+ * The app owns its configuration. It reads its own keys — from
17
+ * `runtimeConfig`, from the environment, from anywhere — and it hands the
18
+ * result to the library. The library never reads the configuration of the app,
19
+ * so it imposes no key name and it needs no knowledge of the host framework.
20
+ *
21
+ * Call this once, as early as the app can: a Nuxt plugin, or the entry point of
22
+ * a non-Nuxt host.
23
+ *
24
+ * The key names below belong to the app, and to the app alone. This library
25
+ * names none of them, which is the whole point of the arrangement.
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * // app/plugins/00.http.ts
30
+ * const config = useRuntimeConfig()
31
+ *
32
+ * configureHttp({
33
+ * baseUrl: config.public.apiBaseUrl as string,
34
+ * targets: { reporting: config.public.reportingApiUrl as string },
35
+ * })
36
+ * ```
37
+ */
38
+ export declare function configureHttp(config: HttpConfig): void;
39
+ /**
40
+ * Returns the base URL for a target, or the default base URL when `target` is
41
+ * absent.
42
+ *
43
+ * Throws instead of returning `undefined`. A base URL that is missing builds
44
+ * request URLs such as `"undefined/api/v2/…"`, which fail far from their cause
45
+ * and read as a network problem once they do.
46
+ *
47
+ * Internal: the public surface is {@link configureHttp} and {@link useHttp}.
48
+ */
49
+ export declare function resolveBaseUrl(target?: string): string;
50
+ /**
51
+ * Test seam: drops the declaration so a suite can declare again between cases.
52
+ * Not part of the public API.
53
+ */
54
+ export declare function resetHttpConfig(): void;
@@ -1,22 +1,35 @@
1
1
  import { MandeInstance } from 'mande';
2
2
  /**
3
- * Returns a `mande` instance pre-configured against the CMC API base URL,
4
- * along with two helpers to attach/detach the `Authorization` bearer token.
3
+ * Returns a `mande` instance bound to one of the base URLs the app declared
4
+ * through `configureHttp`, along with two helpers to attach/detach the
5
+ * `Authorization` bearer token.
5
6
  *
6
7
  * The returned `http` instance exposes the standard `mande` verbs
7
- * (`get`, `post`, `put`, `patch`, `delete`) and is meant to be the only
8
- * way the lib (and downstream apps) talk to the CMC backend.
8
+ * (`get`, `post`, `put`, `patch`, `delete`) and is meant to be the only way the
9
+ * lib (and downstream apps) talk to an HTTP backend.
10
+ *
11
+ * Every instance renews the session on its own — see {@link createAuthFetch}.
12
+ *
13
+ * @param target - Name of a declared target. Omit it for the default base URL,
14
+ * which is what almost every caller wants. Name one to reach
15
+ * another origin the app declared — the call site then holds no
16
+ * URL of its own, and no second HTTP client has to exist.
9
17
  *
10
18
  * @example
11
19
  * ```ts
12
- * const { http, setToken, clearToken } = useHttp()
20
+ * const { http } = useHttp()
13
21
  *
14
- * setToken(accessToken)
15
22
  * const { item } = await http.get<RetrieveResponse<User>>('/me')
16
- * clearToken() // on logout
23
+ * ```
24
+ *
25
+ * @example Another declared origin, authenticated by hand
26
+ * ```ts
27
+ * const { http, setToken } = useHttp('happy')
28
+ *
29
+ * setToken(tokenForThatOrigin)
17
30
  * ```
18
31
  */
19
- export declare function useHttp(): {
32
+ export declare function useHttp(target?: string): {
20
33
  http: MandeInstance;
21
34
  setToken: (token: string) => void;
22
35
  clearToken: () => void;
@@ -1,10 +1,10 @@
1
1
  /**
2
- * Public i18n types shared by every composable in this folder. Reflect the
3
- * languages actually supported by ChooseMyCompany apps as of today; add a new
4
- * locale here and downstream code (translations maps, country dictionaries,
5
- * etc.) will get a compile-time error to keep them in sync.
2
+ * Public i18n types shared by every composable in this folder. Reflect the set
3
+ * of languages the library supports; add a new locale here and downstream code
4
+ * (translations maps, country dictionaries, etc.) will get a compile-time error
5
+ * to keep them in sync.
6
6
  */
7
- /** Languages currently shipped by ChooseMyCompany apps (ISO 639-1 codes). */
7
+ /** Languages the library ships translations for (ISO 639-1 codes). */
8
8
  export type Language = 'en' | 'fr' | 'de' | 'es' | 'it' | 'da' | 'pt';
9
9
  /**
10
10
  * A translation bundle: a partial map from `Language` to its translated string.
package/dist/index.d.ts CHANGED
@@ -5,19 +5,23 @@
5
5
  * re-exported here is considered internal and may change without notice.
6
6
  *
7
7
  * Grouped by concern:
8
- * - **HTTP** — {@link useHttp}: thin `mande` wrapper bound to the CMC API base URL.
8
+ * - **HTTP** — {@link configureHttp}: the app declares its base URLs;
9
+ * {@link useHttp}: thin `mande` wrapper bound to one of them.
9
10
  * - **Store** — {@link useStore}, {@link getViewKey}: typed cache for `retrieve` /
10
11
  * `list` workflows with single-flight, per-key errors, and CRUD mutations.
11
12
  * - **i18n** — locale-aware translators for plain strings, country names,
12
13
  * region resolution, and rich tagged messages.
13
14
  * - **UI** — small DOM / window-aware helpers: outside-click detection, responsive
14
15
  * sizing, image-cache watcher.
16
+ * - **Auth** — {@link useAuthSession}: shared session store (open/expired state, single-flight refresh).
15
17
  * - **Errors** — {@link showAndThrowError}: Nuxt error trigger shorthand.
16
18
  * - **Analytics** — gtag conversion + Hubspot contact URL helpers.
17
19
  *
18
20
  * @packageDocumentation
19
21
  */
20
22
  export { useHttp } from './http/useHttp';
23
+ export { configureHttp, type HttpConfig } from './http/config';
24
+ export { useAuthSession } from './auth/useAuthSession';
21
25
  export { useStore, getViewKey, CREATE_PENDING_KEY, type Store } from './store/useStore';
22
26
  export { useClickOutside } from './ui/useClickOutside';
23
27
  export { useCountriesTranslation, type CountryCodes } from './i18n/useCountriesTranslation';
@@ -31,4 +35,5 @@ export { useResponsiveSize } from './ui/useResponsiveSize';
31
35
  export { useTranslate } from './i18n/useTranslate';
32
36
  export type { StoreOptions, RetrieveOptions, ListOptions, ViewKeyParams, View, ViewOptions, } from './store/types';
33
37
  export type { PaginatedQuery, Pagination, ListResponse, RetrieveResponse, HttpResponse, RequestOptions, ErrorItem, MandeError, MandeErrorBody, } from './http/types';
38
+ export type { SessionExpiryReason } from './auth/types';
34
39
  export type { Language, Translation, InternationalizedRoute, } from './i18n/types';
package/dist/index.js CHANGED
@@ -1,176 +1,280 @@
1
- import { mande as D } from "mande";
2
- import { useRuntimeConfig as L, showError as K, useState as H } from "nuxt/app";
3
- import { ref as M, onMounted as z, onBeforeUnmount as F, computed as N, onUnmounted as O } from "vue";
1
+ import { mande as N } from "mande";
2
+ import { ref as w, computed as E, onMounted as z, onBeforeUnmount as K, onUnmounted as H } from "vue";
3
+ import { defineStore as F } from "pinia";
4
4
  import { useI18n as k } from "vue-i18n";
5
- import { createError as q } from "h3";
6
- let w;
7
- function Z() {
8
- return w || (w = L().public.cmcApiUrl, w);
5
+ import { createError as O } from "h3";
6
+ import { showError as x, useRuntimeConfig as q, useState as Z } from "nuxt/app";
7
+ let I;
8
+ function le(e) {
9
+ if (!e.baseUrl)
10
+ throw new Error("@choosemycompany/lib: configureHttp() needs a non-empty baseUrl");
11
+ I = e;
9
12
  }
10
- function ea() {
11
- const a = Z(), i = D(a, {
13
+ function D(e) {
14
+ if (!I)
15
+ throw new Error(
16
+ "@choosemycompany/lib: useHttp() was called before configureHttp(). Declare the base URLs from an app plugin."
17
+ );
18
+ if (e === void 0) return I.baseUrl;
19
+ const a = I.targets ?? {}, n = Object.hasOwn(a, e) ? a[e] : void 0;
20
+ if (typeof n != "string" || !n) {
21
+ const t = Object.keys(a), i = t.length > 0 ? t.join(", ") : "none";
22
+ throw new Error(
23
+ `@choosemycompany/lib: no HTTP target named "${e}". Declared targets: ${i}.`
24
+ );
25
+ }
26
+ return n;
27
+ }
28
+ const V = "/auth/api/v2/login/token/refresh", J = "/auth/api/v2/", j = "cmc-auth-session-refresh", _ = F("cmc-auth-session", () => {
29
+ const e = w(!1), a = w(!1), n = w(void 0);
30
+ let t, i = 0;
31
+ const s = E(() => e.value && !a.value);
32
+ function d() {
33
+ e.value = !0, a.value = !1, n.value = void 0;
34
+ }
35
+ function l() {
36
+ i += 1, e.value = !1, a.value = !1, n.value = void 0;
37
+ }
38
+ function p() {
39
+ i += 1, e.value = !1, a.value = !0, n.value = "logout";
40
+ }
41
+ function c(h) {
42
+ i += 1, e.value = !1, a.value = !0, n.value = h;
43
+ }
44
+ async function m() {
45
+ if (a.value)
46
+ throw new Error("Session is expired: no refresh will be attempted");
47
+ return t ??= v(g).finally(() => {
48
+ t = void 0;
49
+ }), t;
50
+ }
51
+ async function v(h) {
52
+ const b = globalThis.navigator?.locks;
53
+ if (!b) return h();
54
+ await b.request(j, h);
55
+ }
56
+ async function g() {
57
+ const h = i, b = () => h !== i, r = new URL(V, D()).href;
58
+ let u;
59
+ try {
60
+ u = await fetch(r, {
61
+ method: "POST",
62
+ credentials: "include"
63
+ });
64
+ } catch (o) {
65
+ throw b() || C(), o;
66
+ }
67
+ if (!u.ok)
68
+ throw b() || (u.status === 401 ? c(e.value ? "refresh-rejected" : "no-session") : C()), new Error(`Token refresh failed with status ${u.status}`);
69
+ if (b())
70
+ throw new Error("Session was dropped while the refresh was in flight");
71
+ d();
72
+ }
73
+ function C() {
74
+ n.value = "refresh-unreachable";
75
+ }
76
+ return {
77
+ isOpen: e,
78
+ isExpired: a,
79
+ expiryReason: n,
80
+ isAuthenticated: s,
81
+ open: d,
82
+ expire: c,
83
+ clear: l,
84
+ logout: p,
85
+ refresh: m
86
+ };
87
+ });
88
+ function $() {
89
+ return import.meta.server || typeof document > "u";
90
+ }
91
+ function W(e) {
92
+ return (typeof e == "string" ? e : e instanceof URL ? e.href : e.url).includes(J);
93
+ }
94
+ function Q() {
95
+ return async (e, a) => {
96
+ if ($()) return fetch(e, a);
97
+ const n = await fetch(e, a);
98
+ if (n.status !== 401 || W(e) || new Headers(a?.headers).has("Authorization")) return n;
99
+ let t;
100
+ try {
101
+ t = _();
102
+ } catch {
103
+ return n;
104
+ }
105
+ if (t.isExpired) return n;
106
+ try {
107
+ await t.refresh();
108
+ } catch (i) {
109
+ return t.isExpired || console.warn("[cmc-lib] token refresh failed, returning the original 401", i), n;
110
+ }
111
+ return fetch(e, a);
112
+ };
113
+ }
114
+ function ce(e) {
115
+ const a = N(D(e), {
12
116
  headers: {}
13
- });
14
- function t(e) {
15
- i.options.headers = {
16
- ...i.options.headers ?? {},
17
- Authorization: `Bearer ${e}`
117
+ }, Q());
118
+ function n(i) {
119
+ a.options.headers = {
120
+ ...a.options.headers ?? {},
121
+ Authorization: `Bearer ${i}`
18
122
  };
19
123
  }
20
- function n() {
21
- i.options.headers && delete i.options.headers.Authorization;
124
+ function t() {
125
+ a.options.headers && delete a.options.headers.Authorization;
22
126
  }
23
- return { http: i, setToken: t, clearToken: n };
127
+ return { http: a, setToken: n, clearToken: t };
24
128
  }
25
- function T(a) {
26
- return Object.entries(a).sort(([i], [t]) => i.localeCompare(t)).map(([i, t]) => `${i}=${t}`).join("|");
129
+ function U(e) {
130
+ return Object.entries(e).sort(([a], [n]) => a.localeCompare(n)).map(([a, n]) => `${a}=${n}`).join("|");
27
131
  }
28
- const x = "create";
29
- function na(a) {
30
- const i = M({}), t = M({}), n = M({}), e = M({}), s = a.getItemId ?? ((r) => {
31
- const d = r.id;
32
- if (d === void 0)
132
+ const Y = "create";
133
+ function fe(e) {
134
+ const a = w({}), n = w({}), t = w({}), i = w({}), s = e.getItemId ?? ((r) => {
135
+ const u = r.id;
136
+ if (u === void 0)
33
137
  throw new Error(
34
138
  "useStore: no `getItemId` option provided and item has no `id` property. Either pass `getItemId` in the store options, or expose an `id` field on your items."
35
139
  );
36
- return d;
140
+ return u;
37
141
  });
38
- function c(r) {
39
- return !!e.value[r];
142
+ function d(r) {
143
+ return !!i.value[r];
40
144
  }
41
- async function l(r, d) {
42
- e.value[r] = d;
145
+ async function l(r, u) {
146
+ i.value[r] = u;
43
147
  try {
44
- const o = await d;
45
- return delete n.value[r], o;
148
+ const o = await u;
149
+ return delete t.value[r], o;
46
150
  } catch (o) {
47
- throw n.value[r] = o, o;
151
+ throw t.value[r] = o, o;
48
152
  } finally {
49
- e.value[r] === d && delete e.value[r];
153
+ i.value[r] === u && delete i.value[r];
50
154
  }
51
155
  }
52
- async function g(r, d = {}) {
53
- if (!a.fetchOne)
156
+ async function p(r, u = {}) {
157
+ if (!e.fetchOne)
54
158
  throw new Error("useStore.retrieve called but fetchOne is not defined in store options");
55
- const { force: o = !1 } = d;
56
- if (i.value[r] && !o)
57
- return i.value[r];
58
- const u = e.value[r];
59
- if (u)
60
- return u;
61
- const f = a.fetchOne, C = (async () => {
159
+ const { force: o = !1 } = u;
160
+ if (a.value[r] && !o)
161
+ return a.value[r];
162
+ const f = i.value[r];
163
+ if (f)
164
+ return f;
165
+ const B = e.fetchOne, S = (async () => {
62
166
  try {
63
- const A = await f(r), h = a.enrichItem ? a.enrichItem(A) : A;
64
- return i.value[r] = h, delete n.value[r], i.value[r];
65
- } catch (A) {
66
- n.value[r] = A;
167
+ const M = await B(r), A = e.enrichItem ? e.enrichItem(M) : M;
168
+ return a.value[r] = A, delete t.value[r], a.value[r];
169
+ } catch (M) {
170
+ t.value[r] = M;
67
171
  return;
68
172
  } finally {
69
- delete e.value[r];
173
+ delete i.value[r];
70
174
  }
71
175
  })();
72
- return e.value[r] = C, C;
176
+ return i.value[r] = S, S;
73
177
  }
74
- function p(r) {
75
- const d = T(r), o = t.value[d];
178
+ function c(r) {
179
+ const u = U(r), o = n.value[u];
76
180
  if (o)
77
181
  return {
78
- items: o.itemIds.map((u) => i.value[u]).filter((u) => u !== void 0),
182
+ items: o.itemIds.map((f) => a.value[f]).filter((f) => f !== void 0),
79
183
  total: o.total,
80
184
  hasMore: o.hasMore,
81
185
  page: o.page,
82
186
  limit: o.limit
83
187
  };
84
188
  }
85
- async function b(r, d = {}) {
86
- if (!a.fetchPage)
189
+ async function m(r, u = {}) {
190
+ if (!e.fetchPage)
87
191
  throw new Error("useStore.list called but fetchPage is not defined in store options");
88
- const o = T(r), { force: u = !1 } = d;
89
- if (t.value[o] && !u)
90
- return p(r);
91
- const f = e.value[o];
92
- if (f)
93
- return await f, p(r);
94
- const C = a.fetchPage, A = (async () => {
192
+ const o = U(r), { force: f = !1 } = u;
193
+ if (n.value[o] && !f)
194
+ return c(r);
195
+ const B = i.value[o];
196
+ if (B)
197
+ return await B, c(r);
198
+ const S = e.fetchPage, M = (async () => {
95
199
  try {
96
- const h = await C(r), R = [];
97
- for (const E of h.items) {
98
- const y = a.enrichItem ? a.enrichItem(E) : E, P = s(y);
99
- i.value[P] = y, R.push(P);
200
+ const A = await S(r), R = [];
201
+ for (const y of A.items) {
202
+ const P = e.enrichItem ? e.enrichItem(y) : y, T = s(P);
203
+ a.value[T] = P, R.push(T);
100
204
  }
101
- t.value[o] = {
205
+ n.value[o] = {
102
206
  itemIds: R,
103
- total: h.total,
104
- hasMore: h.hasMore,
105
- page: h.page,
106
- limit: h.limit
107
- }, delete n.value[o];
108
- } catch (h) {
109
- n.value[o] = h;
207
+ total: A.total,
208
+ hasMore: A.hasMore,
209
+ page: A.page,
210
+ limit: A.limit
211
+ }, delete t.value[o];
212
+ } catch (A) {
213
+ t.value[o] = A;
110
214
  } finally {
111
- delete e.value[o];
215
+ delete i.value[o];
112
216
  }
113
217
  })();
114
- return e.value[o] = A, await A, p(r);
218
+ return i.value[o] = M, await M, c(r);
115
219
  }
116
- async function B(r, d = x) {
117
- if (!a.createMutation)
220
+ async function v(r, u = Y) {
221
+ if (!e.createMutation)
118
222
  throw new Error("useStore.create called but createMutation is not defined in store options");
119
- const o = a.createMutation, u = await l(d, (async () => o(r))()), f = a.enrichItem ? a.enrichItem(u) : u, C = s(f);
120
- return i.value[C] = f, t.value = {}, f;
223
+ const o = e.createMutation, f = await l(u, (async () => o(r))()), B = e.enrichItem ? e.enrichItem(f) : f, S = s(B);
224
+ return a.value[S] = B, n.value = {}, B;
121
225
  }
122
- async function m(r, d) {
123
- if (!a.updateMutation)
226
+ async function g(r, u) {
227
+ if (!e.updateMutation)
124
228
  throw new Error("useStore.update called but updateMutation is not defined in store options");
125
- const o = a.updateMutation, u = await l(r, (async () => o(r, d))()), f = a.enrichItem ? a.enrichItem(u) : u;
126
- return i.value[r] = f, f;
229
+ const o = e.updateMutation, f = await l(r, (async () => o(r, u))()), B = e.enrichItem ? e.enrichItem(f) : f;
230
+ return a.value[r] = B, B;
127
231
  }
128
- async function v(r) {
129
- if (!a.removeMutation)
232
+ async function C(r) {
233
+ if (!e.removeMutation)
130
234
  throw new Error("useStore.remove called but removeMutation is not defined in store options");
131
- const d = a.removeMutation;
132
- await l(r, (async () => d(r))()), delete i.value[r];
133
- for (const o of Object.values(t.value)) {
134
- const u = o.itemIds.indexOf(r);
135
- u !== -1 && (o.itemIds.splice(u, 1), o.total = Math.max(0, o.total - 1));
235
+ const u = e.removeMutation;
236
+ await l(r, (async () => u(r))()), delete a.value[r];
237
+ for (const o of Object.values(n.value)) {
238
+ const f = o.itemIds.indexOf(r);
239
+ f !== -1 && (o.itemIds.splice(f, 1), o.total = Math.max(0, o.total - 1));
136
240
  }
137
241
  }
138
- function I() {
139
- n.value = {};
242
+ function h() {
243
+ t.value = {};
140
244
  }
141
- function S() {
142
- i.value = {}, t.value = {}, n.value = {}, e.value = {};
245
+ function b() {
246
+ a.value = {}, n.value = {}, t.value = {}, i.value = {};
143
247
  }
144
- return { items: i, views: t, errors: n, isPending: c, list: b, reset: S, retrieve: g, getView: p, withPending: l, create: B, update: m, remove: v, clearErrors: I };
248
+ return { items: a, views: n, errors: t, isPending: d, list: m, reset: b, retrieve: p, getView: c, withPending: l, create: v, update: g, remove: C, clearErrors: h };
145
249
  }
146
- function ia(a, i) {
147
- const t = (n) => {
148
- const e = a.value, s = n.target;
149
- !e || !s || e.contains(s) || i();
250
+ function pe(e, a) {
251
+ const n = (t) => {
252
+ const i = e.value, s = t.target;
253
+ !i || !s || i.contains(s) || a();
150
254
  };
151
255
  z(() => {
152
- document.addEventListener("click", t);
153
- }), F(() => {
154
- document.removeEventListener("click", t);
256
+ document.addEventListener("click", n);
257
+ }), K(() => {
258
+ document.removeEventListener("click", n);
155
259
  });
156
260
  }
157
- function ta() {
158
- const { locale: a } = k();
159
- function i(t, n = null) {
160
- const e = V[t.trim().toUpperCase()];
161
- if (!e)
162
- throw new Error(`Unknown country code: ${t}`);
163
- if (n && e[n])
164
- return e[n];
165
- if (e[a.value])
166
- return e[a.value];
167
- if (a.value !== "en" && e.en)
168
- return e.en;
169
- throw new Error(`Unknown country code: ${t}`);
261
+ function ge() {
262
+ const { locale: e } = k();
263
+ function a(n, t = null) {
264
+ const i = X[n.trim().toUpperCase()];
265
+ if (!i)
266
+ throw new Error(`Unknown country code: ${n}`);
267
+ if (t && i[t])
268
+ return i[t];
269
+ if (i[e.value])
270
+ return i[e.value];
271
+ if (e.value !== "en" && i.en)
272
+ return i.en;
273
+ throw new Error(`Unknown country code: ${n}`);
170
274
  }
171
- return i;
275
+ return a;
172
276
  }
173
- const V = {
277
+ const X = {
174
278
  AD: { en: "Andorra", fr: "Andorre", es: "Andorra", de: "Andorra", it: "Andorra", pt: "Andorra", da: "Andorra" },
175
279
  AE: { en: "United Arab Emirates", fr: "Émirats arabes unis", es: "Emiratos Árabes Unidos", de: "Vereinigte Arabische Emirate", it: "Emirati Arabi Uniti", pt: "Emirados Árabes Unidos", da: "De Forenede Arabiske Emirater" },
176
280
  AF: { en: "Afghanistan", fr: "Afghanistan", es: "Afganistán", de: "Afghanistan", it: "Afghanistan", pt: "Afeganistão", da: "Afghanistan" },
@@ -308,150 +412,152 @@ const V = {
308
412
  ZA: { en: "South Africa", fr: "Afrique Du Sud", es: "Sudáfrica", de: "Südafrika", it: "Sudafrica", pt: "África Do Sul", da: "Sydafrika" },
309
413
  ZM: { en: "Zambia", fr: "Zambie", es: "Zambia", de: "Sambia", it: "Zambia", pt: "Zâmbia", da: "Zambia" },
310
414
  ZW: { en: "Zimbabwe", fr: "Zimbabwe", es: "Zimbabue", de: "Simbabwe", it: "Zimbabwe", pt: "Zimbábue", da: "Zimbabwe" }
311
- }, ra = ({ code: a, message: i, data: t }) => {
312
- const n = i || "An unexpected error occurred", e = q({
313
- statusCode: a,
314
- statusMessage: n,
315
- message: n,
316
- data: t
415
+ }, me = ({ code: e, message: a, data: n }) => {
416
+ const t = a || "An unexpected error occurred", i = O({
417
+ statusCode: e,
418
+ statusMessage: t,
419
+ message: t,
420
+ data: n
317
421
  });
318
- throw K(e), e;
319
- }, J = "ilcJCL_lmpwcEJfSkKND";
320
- function oa() {
321
- const { gtagId: a } = L().public;
422
+ throw x(i), i;
423
+ }, ee = "ilcJCL_lmpwcEJfSkKND";
424
+ function he() {
425
+ const { gtagId: e } = q().public;
322
426
  return { reportConversion: () => {
323
- if (typeof window > "u" || typeof window.gtag > "u" || !a)
427
+ if (typeof window > "u" || typeof window.gtag > "u" || !e)
324
428
  return;
325
- const t = `${a}/${J}`;
429
+ const n = `${e}/${ee}`;
326
430
  window.gtag("event", "conversion", {
327
- send_to: t
431
+ send_to: n
328
432
  });
329
433
  } };
330
434
  }
331
- const U = "https://5509641.hs-sites-eu1.com";
332
- function sa() {
333
- const { locale: a } = k();
334
- return { contactUrl: N(() => a.value === "fr" ? `${U}/contact` : `${U}/${a.value}/contact`) };
435
+ const L = "https://5509641.hs-sites-eu1.com";
436
+ function be() {
437
+ const { locale: e } = k();
438
+ return { contactUrl: E(() => e.value === "fr" ? `${L}/contact` : `${L}/${e.value}/contact`) };
335
439
  }
336
- function da() {
337
- async function a(n) {
440
+ function Be() {
441
+ async function e(t) {
338
442
  await Promise.all(
339
- n.map(
340
- (e) => new Promise((s) => {
341
- if (!e) return s(null);
342
- const c = new Image();
343
- c.onload = () => s(null), c.onerror = () => s(null), c.src = e;
443
+ t.map(
444
+ (i) => new Promise((s) => {
445
+ if (!i) return s(null);
446
+ const d = new Image();
447
+ d.onload = () => s(null), d.onerror = () => s(null), d.src = i;
344
448
  })
345
449
  )
346
450
  );
347
451
  }
348
- function i(n, e) {
349
- return e.split(".").reduce((s, c) => s && typeof s == "object" && c in s ? s[c] : "", n) ?? "";
452
+ function a(t, i) {
453
+ return i.split(".").reduce((s, d) => s && typeof s == "object" && d in s ? s[d] : "", t) ?? "";
350
454
  }
351
- function t(n, e, s) {
455
+ function n(t, i, s) {
352
456
  if (import.meta.server)
353
457
  return async (l) => {
354
- n.value = !0;
458
+ t.value = !0;
355
459
  };
356
- const c = H(
357
- `${e}LoadedImageCache`,
460
+ const d = Z(
461
+ `${i}LoadedImageCache`,
358
462
  () => ({})
359
463
  );
360
464
  return async (l) => {
361
465
  if (!l) {
362
- n.value = !1;
466
+ t.value = !1;
363
467
  return;
364
468
  }
365
- const g = s.map((B) => i(l, B)), p = `${e}|${g.join("|")}`;
366
- if (c.value[p]) {
367
- n.value = !0;
469
+ const p = s.map((v) => a(l, v)), c = `${i}|${p.join("|")}`;
470
+ if (d.value[c]) {
471
+ t.value = !0;
368
472
  return;
369
473
  }
370
- n.value = !1;
371
- const b = g.filter(Boolean).map(String);
372
- await a(b), c.value[p] = !0, n.value = !0;
474
+ t.value = !1;
475
+ const m = p.filter(Boolean).map(String);
476
+ await e(m), d.value[c] = !0, t.value = !0;
373
477
  };
374
478
  }
375
- return t;
479
+ return n;
376
480
  }
377
- const j = {
481
+ const ae = {
378
482
  en: ["US", "UK"]
379
- }, $ = "FR";
380
- function _(a) {
381
- const i = a.trim().replace("_", "-"), [t, n] = i.split("-");
483
+ }, ne = "FR";
484
+ function ie(e) {
485
+ const a = e.trim().replace("_", "-"), [n, t] = a.split("-");
382
486
  return {
383
- language: t?.toLowerCase() ?? "",
384
- region: n?.toUpperCase() ?? ""
487
+ language: n?.toLowerCase() ?? "",
488
+ region: t?.toUpperCase() ?? ""
385
489
  };
386
490
  }
387
- function G(a) {
388
- return a.toString().trim().toUpperCase();
491
+ function G(e) {
492
+ return e.toString().trim().toUpperCase();
389
493
  }
390
- function ua() {
391
- function a(i, t) {
392
- if (!t.length) return;
393
- const n = t.map(G), e = new Set(n), { language: s, region: c } = _(i), l = [];
394
- c && l.push(c);
395
- const g = j[s];
396
- g?.length && l.push(...g.map(G)), s && l.push(s.toUpperCase()), l.push($);
397
- for (const p of l)
398
- if (e.has(p))
399
- return p;
400
- return n[0];
494
+ function ve() {
495
+ function e(a, n) {
496
+ if (!n.length) return;
497
+ const t = n.map(G), i = new Set(t), { language: s, region: d } = ie(a), l = [];
498
+ d && l.push(d);
499
+ const p = ae[s];
500
+ p?.length && l.push(...p.map(G)), s && l.push(s.toUpperCase()), l.push(ne);
501
+ for (const c of l)
502
+ if (i.has(c))
503
+ return c;
504
+ return t[0];
401
505
  }
402
- return { getRegionFromLocale: a };
506
+ return { getRegionFromLocale: e };
403
507
  }
404
- function la() {
405
- const { t: a } = k();
406
- function i(t, n) {
407
- const e = a(t), s = [], l = n.map((m) => m.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|"), g = new RegExp(`\\[(${l})\\]([\\s\\S]*?)\\[\\/\\1\\]`, "g"), p = n.reduce((m, v) => (m[v] = !1, m), {});
408
- let b = 0, B = g.exec(e);
409
- for (; B; ) {
410
- const { index: m, 0: v, 1: I, 2: S } = B;
411
- m > b && s.push({ text: e.slice(b, m), ...p }), S && I && s.push({ text: S, ...p, [I]: !0 }), b = m + v.length, B = g.exec(e);
508
+ function Ae() {
509
+ const { t: e } = k();
510
+ function a(n, t) {
511
+ const i = e(n), s = [], l = t.map((g) => g.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|"), p = new RegExp(`\\[(${l})\\]([\\s\\S]*?)\\[\\/\\1\\]`, "g"), c = t.reduce((g, C) => (g[C] = !1, g), {});
512
+ let m = 0, v = p.exec(i);
513
+ for (; v; ) {
514
+ const { index: g, 0: C, 1: h, 2: b } = v;
515
+ g > m && s.push({ text: i.slice(m, g), ...c }), b && h && s.push({ text: b, ...c, [h]: !0 }), m = g + C.length, v = p.exec(i);
412
516
  }
413
- return b < e.length && s.push({ text: e.slice(b), ...p }), s;
517
+ return m < i.length && s.push({ text: i.slice(m), ...c }), s;
414
518
  }
415
- return { parse: i };
519
+ return { parse: a };
416
520
  }
417
- function ca(a, i, t = 768) {
418
- const n = M(t - 1), e = N(
419
- () => n.value >= t ? i : a
521
+ function Ce(e, a, n = 768) {
522
+ const t = w(n - 1), i = E(
523
+ () => t.value >= n ? a : e
420
524
  );
421
525
  if (import.meta.client) {
422
526
  const s = () => {
423
- n.value = window.innerWidth;
527
+ t.value = window.innerWidth;
424
528
  };
425
529
  z(() => {
426
530
  s(), window.addEventListener("resize", s);
427
- }), O(() => {
531
+ }), H(() => {
428
532
  window.removeEventListener("resize", s);
429
533
  });
430
534
  }
431
- return { size: e, windowWidth: n };
535
+ return { size: i, windowWidth: t };
432
536
  }
433
- function pa() {
434
- const { locale: a } = k();
435
- function i(t, n = "fr") {
436
- if (!t) return "";
437
- const e = a.value;
438
- return t[e] ?? t[n] ?? "";
537
+ function we() {
538
+ const { locale: e } = k();
539
+ function a(n, t = "fr") {
540
+ if (!n) return "";
541
+ const i = e.value;
542
+ return n[i] ?? n[t] ?? "";
439
543
  }
440
- return i;
544
+ return a;
441
545
  }
442
546
  export {
443
- x as CREATE_PENDING_KEY,
444
- T as getViewKey,
445
- ra as showAndThrowError,
446
- ia as useClickOutside,
447
- ta as useCountriesTranslation,
448
- oa as useGtagConversion,
449
- ea as useHttp,
450
- sa as useHubspotContactUrl,
451
- da as useImageCacheWatcherCallback,
452
- ua as useLocaleHelpers,
453
- la as useParseTranslation,
454
- ca as useResponsiveSize,
455
- na as useStore,
456
- pa as useTranslate
547
+ Y as CREATE_PENDING_KEY,
548
+ le as configureHttp,
549
+ U as getViewKey,
550
+ me as showAndThrowError,
551
+ _ as useAuthSession,
552
+ pe as useClickOutside,
553
+ ge as useCountriesTranslation,
554
+ he as useGtagConversion,
555
+ ce as useHttp,
556
+ be as useHubspotContactUrl,
557
+ Be as useImageCacheWatcherCallback,
558
+ ve as useLocaleHelpers,
559
+ Ae as useParseTranslation,
560
+ Ce as useResponsiveSize,
561
+ fe as useStore,
562
+ we as useTranslate
457
563
  };
@@ -26,8 +26,8 @@ export type View<Item> = ViewKeyParams & {
26
26
  hasMore: boolean;
27
27
  };
28
28
  /**
29
- * Reserved for future "infinite scroll vs. paginated" switching. Currently
30
- * unused by the implementation — declared here to lock the public surface.
29
+ * Reserved for "infinite scroll vs. paginated" switching. Not read by the
30
+ * implementation — declared here to lock the public surface.
31
31
  */
32
32
  export type ViewOptions = {
33
33
  infinite?: boolean;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@choosemycompany/lib",
3
3
  "description": "Shared composables, stores and types for ChooseMyCompany front apps",
4
- "version": "0.6.0",
4
+ "version": "0.8.0",
5
5
  "private": false,
6
6
  "type": "module",
7
7
  "packageManager": "pnpm@10.17.0",
@@ -31,7 +31,7 @@
31
31
  "peerDependencies": {
32
32
  "@nuxtjs/i18n": "^10.0.0",
33
33
  "h3": "^1.0.0",
34
- "mande": "^2.0.0",
34
+ "mande": "^2.0.10",
35
35
  "nuxt": "^4.0.0",
36
36
  "pinia": "^3.0.0",
37
37
  "ufo": "^1.0.0",
@@ -49,7 +49,7 @@
49
49
  "h3": "^1.13.0",
50
50
  "happy-dom": "^18.0.1",
51
51
  "jiti": "^2.6.0",
52
- "mande": "^2.0.9",
52
+ "mande": "^2.0.10",
53
53
  "pinia": "^3.0.3",
54
54
  "typescript": "^5.9.2",
55
55
  "typescript-eslint": "^8.44.1",