@akinon/next 2.0.137-rc.0 → 2.0.137

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.
@@ -86,9 +86,7 @@ const withPrettyUrl =
86
86
  const matchedLanguagePrefix = url.pathname.match(
87
87
  urlLocaleMatcherRegex
88
88
  )?.[0];
89
- const prettyUrlPathname = matchedLanguagePrefix
90
- ? url.pathname.replace(matchedLanguagePrefix, '')
91
- : url.pathname;
89
+ const prettyUrlPathname = url.pathname.replace(matchedLanguagePrefix, '');
92
90
  const isValidPrettyUrlPath = (pathname: string) => {
93
91
  return (
94
92
  new RegExp(/^\/[a-zA-Z0-9/]+(?:-[a-zA-Z0-9/]+)*$/).test(pathname) &&
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@akinon/next",
3
3
  "description": "Core package for Project Zero Next",
4
- "version": "2.0.137-rc.0",
4
+ "version": "2.0.137",
5
5
  "private": false,
6
6
  "license": "MIT",
7
7
  "bin": {
@@ -36,7 +36,7 @@
36
36
  "set-cookie-parser": "2.6.0"
37
37
  },
38
38
  "devDependencies": {
39
- "@akinon/eslint-plugin-projectzero": "2.0.137-rc.0",
39
+ "@akinon/eslint-plugin-projectzero": "2.0.137",
40
40
  "@babel/core": "7.26.10",
41
41
  "@babel/preset-env": "7.26.9",
42
42
  "@babel/preset-typescript": "7.27.0",
package/plugins.d.ts CHANGED
@@ -37,16 +37,6 @@ declare module '@akinon/pz-cybersource-uc/src/redux/middleware' {
37
37
  export default middleware as any;
38
38
  }
39
39
 
40
- declare module '@akinon/pz-apple-pay' {}
41
-
42
- declare module '@akinon/pz-similar-products' {
43
- export const SimilarProductsModal: any;
44
- export const SimilarProductsFilterSidebar: any;
45
- export const SimilarProductsResultsGrid: any;
46
- export const SimilarProductsPlugin: any;
47
- export const SimilarProductsButtonPlugin: any;
48
- }
49
-
50
40
  declare module '@akinon/pz-cybersource-uc/src/redux/reducer' {
51
41
  export default reducer as any;
52
42
  }
package/plugins.js CHANGED
@@ -16,7 +16,6 @@ module.exports = [
16
16
  'pz-tabby-extension',
17
17
  'pz-apple-pay',
18
18
  'pz-tamara-extension',
19
- 'pz-similar-products',
20
19
  'pz-cybersource-uc',
21
20
  'pz-hepsipay',
22
21
  'pz-flow-payment',
@@ -25,29 +25,17 @@ import {
25
25
  setUnavailablePaymentOptions
26
26
  } from '../../redux/reducers/checkout';
27
27
  import { RootState, TypedDispatch } from 'redux/store';
28
- import { checkoutApi } from '../../data/client/checkout';
29
- import { CheckoutContext, MiddlewareAction, PreOrder } from '../../types';
28
+ import {
29
+ checkoutApi,
30
+ setAttributeBasedShippingPageName
31
+ } from '../../data/client/checkout';
32
+ import { CheckoutContext, PreOrder } from '../../types';
30
33
  import { getCookie } from '../../utils';
31
34
  import settings from 'settings';
32
35
  import { LocaleUrlStrategy } from '../../localization';
33
36
  import { showMobile3dIframe } from '../../utils/mobile-3d-iframe';
34
37
  import { showRedirectionIframe } from '../../utils/redirection-iframe';
35
38
 
36
- const IFRAME_REDIRECTION_KEY = 'pz-iframe-redirection-active';
37
-
38
- const isIframeRedirectionActive = () =>
39
- typeof window !== 'undefined' &&
40
- sessionStorage.getItem(IFRAME_REDIRECTION_KEY) === 'true';
41
-
42
- const setIframeRedirectionActive = (active: boolean) => {
43
- if (typeof window === 'undefined') return;
44
- if (active) {
45
- sessionStorage.setItem(IFRAME_REDIRECTION_KEY, 'true');
46
- } else {
47
- sessionStorage.removeItem(IFRAME_REDIRECTION_KEY);
48
- }
49
- };
50
-
51
39
  interface CheckoutResult {
52
40
  payload: {
53
41
  errors?: Record<string, string[]>;
@@ -84,7 +72,7 @@ export const redirectUrlMiddleware: Middleware = () => {
84
72
  const result = next(action) as CheckoutResult;
85
73
  const redirectUrl = result?.payload?.redirect_url;
86
74
 
87
- if (redirectUrl && !isIframeRedirectionActive()) {
75
+ if (redirectUrl) {
88
76
  const currentLocale = getCookie('pz-locale');
89
77
 
90
78
  let url = redirectUrl;
@@ -114,15 +102,8 @@ export const contextListMiddleware: Middleware = ({
114
102
  const { isMobileApp, userPhoneNumber } = getState().root;
115
103
  const result = next(action) as CheckoutResult;
116
104
  const preOrder = result?.payload?.pre_order;
117
- const act = action as MiddlewareAction;
118
105
 
119
106
  if (result?.payload?.context_list) {
120
- const endpointName = act.meta?.arg?.endpointName;
121
- const isBinNumberResponse = endpointName === 'setBinNumber';
122
- const hasCardTypeInContextList = result.payload.context_list.some(
123
- (ctx) => ctx.page_context.card_type
124
- );
125
-
126
107
  result.payload.context_list.forEach((context) => {
127
108
  const redirectUrl = context.page_context.redirect_url;
128
109
  const isIframe = context.page_context.is_iframe ?? false;
@@ -156,7 +137,6 @@ export const contextListMiddleware: Middleware = ({
156
137
  if (isMobileDevice && isIframePaymentOptionIncluded) {
157
138
  showMobile3dIframe(urlObj.toString());
158
139
  } else if (isIframe) {
159
- setIframeRedirectionActive(true);
160
140
  showRedirectionIframe(urlObj.toString());
161
141
  } else {
162
142
  window.location.href = urlObj.toString();
@@ -194,6 +174,7 @@ export const contextListMiddleware: Middleware = ({
194
174
  }
195
175
 
196
176
  if (context.page_context.attribute_based_shipping_options) {
177
+ setAttributeBasedShippingPageName(context.page_name);
197
178
  dispatch(
198
179
  setAttributeBasedShippingOptions(
199
180
  context.page_context.attribute_based_shipping_options
@@ -232,34 +213,15 @@ export const contextListMiddleware: Middleware = ({
232
213
  (ctx) => ctx.page_name === 'DeliveryOptionSelectionPage'
233
214
  )
234
215
  ) {
235
- const isCreditCardPayment =
236
- preOrder?.payment_option?.payment_type === 'credit_card' ||
237
- preOrder?.payment_option?.payment_type === 'masterpass';
238
-
239
216
  if (context.page_context.card_type) {
240
217
  dispatch(setCardType(context.page_context.card_type));
241
- } else if (
242
- isCreditCardPayment &&
243
- isBinNumberResponse &&
244
- !hasCardTypeInContextList
245
- ) {
246
- dispatch(setCardType(null));
247
- dispatch(setInstallmentOptions([]));
248
218
  }
249
219
 
250
220
  if (
251
221
  context.page_context.installments &&
252
222
  preOrder?.payment_option?.payment_type !== 'masterpass_rest'
253
223
  ) {
254
- if (
255
- !isCreditCardPayment ||
256
- context.page_context.card_type ||
257
- hasCardTypeInContextList
258
- ) {
259
- dispatch(
260
- setInstallmentOptions(context.page_context.installments)
261
- );
262
- }
224
+ dispatch(setInstallmentOptions(context.page_context.installments));
263
225
  }
264
226
  }
265
227
 
@@ -21,12 +21,28 @@ export const attributeBasedShippingOptionMiddleware: Middleware = ({
21
21
  Object.keys(attributeBasedShippingOptions).length > 0 &&
22
22
  !preOrder.attribute_based_shipping_options
23
23
  ) {
24
- const initialSelectedOptions: Record<string, number> = Object.fromEntries(
25
- Object.entries(attributeBasedShippingOptions).map(([key, options]) => [
26
- key,
27
- options.attribute_based_shipping_options[0].pk
28
- ])
29
- );
24
+ // A group can come back without any option: the service logs it and still
25
+ // reports the group with an empty list, so indexing into it would throw
26
+ // inside the middleware chain and drop the whole checkout response.
27
+ const initialSelectedOptions: Record<string, number> = {};
28
+
29
+ Object.entries(attributeBasedShippingOptions).forEach(([key, group]) => {
30
+ const pk = group?.attribute_based_shipping_options?.[0]?.pk;
31
+
32
+ if (typeof pk === 'number') {
33
+ initialSelectedOptions[key] = pk;
34
+ }
35
+ });
36
+
37
+ // The backend rejects a selection that does not cover every group it
38
+ // reported, and the rejection leaves pre_order empty, which brings us
39
+ // straight back here. Post nothing rather than start that loop.
40
+ if (
41
+ Object.keys(initialSelectedOptions).length !==
42
+ Object.keys(attributeBasedShippingOptions).length
43
+ ) {
44
+ return result;
45
+ }
30
46
 
31
47
  dispatch(
32
48
  apiEndpoints.setAttributeBasedShippingOptions.initiate(
@@ -14,17 +14,9 @@ export const installmentOptionMiddleware: Middleware = ({
14
14
  return result;
15
15
  }
16
16
 
17
- const { installmentOptions, cardType } = getState().checkout;
17
+ const { installmentOptions } = getState().checkout;
18
18
  const { endpoints: apiEndpoints } = checkoutApi;
19
19
 
20
- const isCreditCardPayment =
21
- preOrder?.payment_option?.payment_type === 'credit_card' ||
22
- preOrder?.payment_option?.payment_type === 'masterpass';
23
-
24
- if (isCreditCardPayment && !cardType) {
25
- return result;
26
- }
27
-
28
20
  if (
29
21
  !preOrder?.installment &&
30
22
  preOrder?.payment_option?.payment_type !== 'saved_card' &&
package/types/index.ts CHANGED
@@ -85,12 +85,6 @@ export interface Settings {
85
85
  };
86
86
  usePrettyUrlRoute?: boolean;
87
87
  commerceUrl: string;
88
- /**
89
- * This option allows you to track Sentry events on the client side, in addition to server and edge environments.
90
- *
91
- * It overrides process.env.NEXT_PUBLIC_SENTRY_DSN and process.env.SENTRY_DSN.
92
- */
93
- sentryDsn?: string;
94
88
  /**
95
89
  * CSRF cookie hardening settings.
96
90
  *
@@ -242,7 +236,6 @@ export interface Settings {
242
236
  separator?: string;
243
237
  segments: PzSegmentDefinition[];
244
238
  };
245
- payloadOptimization?: import('../utils/payload-optimizer').PayloadOptimizationConfig;
246
239
  }
247
240
 
248
241
  export interface CacheOptions {
@@ -302,9 +295,7 @@ export interface PzSegmentsConfig {
302
295
  }
303
296
 
304
297
  // Search params type compatible with both Next.js resolved searchParams and URLSearchParams
305
- export type SearchParams =
306
- | Record<string, string | string[] | undefined>
307
- | URLSearchParams;
298
+ export type SearchParams = Record<string, string | string[] | undefined> | URLSearchParams;
308
299
 
309
300
  // Raw Next 16 server prop shape, used at the middleware/HOC boundary before normalization
310
301
  export type RawSearchParams = Record<string, string | string[] | undefined>;
@@ -337,16 +328,14 @@ export interface RootLayoutProps<T = any> extends LayoutProps<T> {
337
328
 
338
329
  // Async versions for Next.js 16 generateMetadata and internal use
339
330
  export interface AsyncPageProps<T = any> {
340
- params: Promise<
341
- T & {
342
- pz?: string;
343
- commerce?: string;
344
- locale?: string;
345
- currency?: string;
346
- url?: string;
347
- [key: string]: any;
348
- }
349
- >;
331
+ params: Promise<T & {
332
+ pz?: string;
333
+ commerce?: string;
334
+ locale?: string;
335
+ currency?: string;
336
+ url?: string;
337
+ [key: string]: any;
338
+ }>;
350
339
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
351
340
  }
352
341
 
package/utils/csrf.ts CHANGED
@@ -46,7 +46,7 @@ export function getCsrfCookieFlags(): CsrfCookieFlags {
46
46
 
47
47
  return {
48
48
  httpOnly,
49
- secure: process.env.NODE_ENV === 'production',
49
+ secure: httpOnly && process.env.NODE_ENV === 'production',
50
50
  sameSite: 'lax'
51
51
  };
52
52
  }
package/with-pz-config.js CHANGED
@@ -30,10 +30,6 @@ const defaultConfig = {
30
30
  {
31
31
  protocol: 'https',
32
32
  hostname: '**.akinoncdn.com'
33
- },
34
- {
35
- protocol: 'https',
36
- hostname: '**.akinoncloudcdn.com'
37
33
  }
38
34
  ]
39
35
  },
@@ -78,8 +74,7 @@ const defaultConfig = {
78
74
  acc[`@akinon/${plugin}`] = false;
79
75
  return acc;
80
76
  }, {}),
81
- translations: false,
82
- '@opentelemetry/exporter-jaeger': false
77
+ translations: false
83
78
  };
84
79
  // Ensure webpack can resolve deps from the app's node_modules when
85
80
  // compiling transpiled packages (e.g. @akinon/next) whose imports
package/api/client-env.ts DELETED
@@ -1,78 +0,0 @@
1
- import { NextRequest, NextResponse } from 'next/server';
2
-
3
- /**
4
- * Runtime access to public (`NEXT_PUBLIC_*`) environment variables.
5
- *
6
- * Next.js inlines `process.env.NEXT_PUBLIC_*` into the bundle at *build* time.
7
- * On hosting platforms where the build has no access to the environment (e.g.
8
- * Akinon Cloud Commerce), those references resolve to `undefined` in the
9
- * browser. This route reads the variables from the *server runtime* instead —
10
- * `process.env[name]` is a computed lookup, so webpack never statically inlines
11
- * it — and hands them back to the client.
12
- *
13
- * Only `NEXT_PUBLIC_`-prefixed names are resolvable. These values are public by
14
- * design (they are shipped to the browser anyway), so nothing secret can leak
15
- * through here; the prefix check is what keeps server-only secrets unreadable.
16
- *
17
- * Query: one or more `env` params, repeated (`?env=A&env=B`) and/or comma
18
- * separated (`?env=A,B`). Names must include the full prefix. Responds with a
19
- * `{ [name]: value | null }` map (`null` when the variable is not set).
20
- *
21
- * The consuming route file must set `export const dynamic = 'force-dynamic'` so
22
- * Next never statically caches a build-time (empty) response.
23
- *
24
- * @see `@akinon/next/hooks` — `useClientEnv` / `getClientEnv` read from here.
25
- */
26
-
27
- const CLIENT_ENV_NAME = /^NEXT_PUBLIC_[A-Za-z0-9_]+$/;
28
-
29
- export async function GET(request: NextRequest) {
30
- try {
31
- const { searchParams } = new URL(request.url);
32
-
33
- const names = Array.from(
34
- new Set(
35
- searchParams
36
- .getAll('env')
37
- .flatMap((value) => value.split(','))
38
- .map((value) => value.trim())
39
- .filter(Boolean)
40
- )
41
- );
42
-
43
- if (names.length === 0) {
44
- return NextResponse.json(
45
- { message: 'At least one `env` query parameter is required.' },
46
- { status: 400 }
47
- );
48
- }
49
-
50
- const invalid = names.filter((name) => !CLIENT_ENV_NAME.test(name));
51
-
52
- if (invalid.length > 0) {
53
- return NextResponse.json(
54
- {
55
- message:
56
- 'Only NEXT_PUBLIC_-prefixed environment variables can be read.',
57
- invalid
58
- },
59
- { status: 400 }
60
- );
61
- }
62
-
63
- const values = names.reduce<Record<string, string | null>>((acc, name) => {
64
- acc[name] = process.env[name] ?? null;
65
- return acc;
66
- }, {});
67
-
68
- return NextResponse.json(values, {
69
- headers: { 'Cache-Control': 'no-store' }
70
- });
71
- } catch (error) {
72
- console.error('Error in client-env API:', error);
73
- return NextResponse.json(
74
- { message: 'Internal server error' },
75
- { status: 500 }
76
- );
77
- }
78
- }
@@ -1,265 +0,0 @@
1
- 'use client';
2
-
3
- import { useEffect, useState } from 'react';
4
-
5
- /**
6
- * Runtime access to public (`NEXT_PUBLIC_*`) environment variables from Client
7
- * Components.
8
- *
9
- * `process.env.NEXT_PUBLIC_*` is inlined at *build* time, so on platforms where
10
- * the build has no environment (e.g. Akinon Cloud Commerce) it resolves to
11
- * `undefined` in the browser. These helpers read the value from the server
12
- * runtime through the `/api/client-env` route handler instead
13
- * (`@akinon/next/api/client-env`).
14
- *
15
- * Always pass the full variable name, including the `NEXT_PUBLIC_` prefix:
16
- *
17
- * ```tsx
18
- * // inside a Client Component
19
- * const { value, isLoading } = useClientEnv('NEXT_PUBLIC_MAP_API_KEY');
20
- *
21
- * // imperative (event handlers, third-party init, ...)
22
- * const key = await getClientEnv('NEXT_PUBLIC_MAP_API_KEY');
23
- * ```
24
- *
25
- * Server Components do not need this — read the value with computed access
26
- * (`process.env['NEXT_PUBLIC_MAP_API_KEY']`) so it is not build-time inlined.
27
- */
28
-
29
- const ENDPOINT = '/api/client-env';
30
-
31
- // Shared across every caller so each variable is fetched at most once per page
32
- // load, no matter how many components ask for it.
33
- const cache = new Map<string, string | null>();
34
- const inflight = new Map<string, Promise<string | null>>();
35
-
36
- function request(names: string[]): void {
37
- const pending = names.filter(
38
- (name) => !cache.has(name) && !inflight.has(name)
39
- );
40
-
41
- if (pending.length === 0) return;
42
-
43
- const query = pending
44
- .map((name) => `env=${encodeURIComponent(name)}`)
45
- .join('&');
46
-
47
- const response = fetch(`${ENDPOINT}?${query}`, {
48
- headers: { Accept: 'application/json' }
49
- })
50
- .then((res) => {
51
- if (!res.ok) {
52
- throw new Error(`Failed to load client env (status ${res.status}).`);
53
- }
54
- return res.json() as Promise<Record<string, string | null>>;
55
- })
56
- .then((data) => {
57
- pending.forEach((name) => cache.set(name, data?.[name] ?? null));
58
- });
59
-
60
- // One in-flight entry per name so concurrent callers dedupe. On failure the
61
- // entry is cleared (not cached) so a later render can retry.
62
- pending.forEach((name) => {
63
- inflight.set(
64
- name,
65
- response
66
- .then(() => cache.get(name) ?? null)
67
- .finally(() => inflight.delete(name))
68
- );
69
- });
70
- }
71
-
72
- function resolve(name: string): Promise<string | null> {
73
- if (cache.has(name)) return Promise.resolve(cache.get(name) ?? null);
74
- return inflight.get(name) ?? Promise.resolve(null);
75
- }
76
-
77
- /**
78
- * Read a single public (`NEXT_PUBLIC_*`) environment variable at runtime,
79
- * outside React (event handlers, third-party SDK init, …). Cached and
80
- * deduplicated across callers.
81
- *
82
- * @param name - Full variable name, including the `NEXT_PUBLIC_` prefix.
83
- * @returns The runtime value, or `null` when the variable is unset. Rejects if
84
- * the request fails, so wrap direct calls in `try`/`catch`. A failed request is
85
- * not cached — a later call retries.
86
- *
87
- * @example
88
- * ```tsx
89
- * import { getClientEnv } from '@akinon/next/hooks'
90
- *
91
- * const handleShare = async () => {
92
- * const baseUrl = await getClientEnv('NEXT_PUBLIC_URL')
93
- * navigator.clipboard.writeText(`${baseUrl}/product/123`)
94
- * }
95
- * ```
96
- */
97
- export async function getClientEnv(name: string): Promise<string | null> {
98
- request([name]);
99
- return resolve(name);
100
- }
101
-
102
- /**
103
- * Read several public (`NEXT_PUBLIC_*`) environment variables at runtime in a
104
- * single request, outside React.
105
- *
106
- * @param names - Full variable names, each including the `NEXT_PUBLIC_` prefix.
107
- * @returns A `{ [name]: value | null }` map. Rejects if the request fails.
108
- *
109
- * @example
110
- * ```ts
111
- * import { getClientEnvs } from '@akinon/next/hooks'
112
- *
113
- * const env = await getClientEnvs(['NEXT_PUBLIC_GTM_KEY', 'NEXT_PUBLIC_URL'])
114
- * // env['NEXT_PUBLIC_URL']
115
- * ```
116
- */
117
- export async function getClientEnvs(
118
- names: string[]
119
- ): Promise<Record<string, string | null>> {
120
- request(names);
121
- const values = await Promise.all(names.map((name) => resolve(name)));
122
- return names.reduce<Record<string, string | null>>((acc, name, index) => {
123
- acc[name] = values[index];
124
- return acc;
125
- }, {});
126
- }
127
-
128
- /**
129
- * Read a single public (`NEXT_PUBLIC_*`) environment variable at runtime from a
130
- * Client Component.
131
- *
132
- * @param name - Full variable name, including the `NEXT_PUBLIC_` prefix.
133
- * @returns `{ value, isLoading, error }`. `value` is `null` while loading, when
134
- * the variable is unset, or on failure.
135
- *
136
- * @example
137
- * ```tsx
138
- * 'use client'
139
- * import { useClientEnv } from '@akinon/next/hooks'
140
- *
141
- * export const StoreMap = () => {
142
- * const { value: mapApiKey, isLoading } = useClientEnv('NEXT_PUBLIC_MAP_API_KEY')
143
- *
144
- * if (isLoading) return <Spinner />
145
- * if (!mapApiKey) return null
146
- *
147
- * return <GoogleMap apiKey={mapApiKey} />
148
- * }
149
- * ```
150
- */
151
- export function useClientEnv(name: string) {
152
- const [value, setValue] = useState<string | null>(
153
- () => cache.get(name) ?? null
154
- );
155
- const [isLoading, setIsLoading] = useState(() => !cache.has(name));
156
- const [error, setError] = useState<Error | null>(null);
157
-
158
- useEffect(() => {
159
- let active = true;
160
-
161
- if (cache.has(name)) {
162
- setValue(cache.get(name) ?? null);
163
- setIsLoading(false);
164
- setError(null);
165
- return;
166
- }
167
-
168
- setIsLoading(true);
169
- setError(null);
170
-
171
- getClientEnv(name)
172
- .then((resolved) => {
173
- if (!active) return;
174
- setValue(resolved);
175
- setIsLoading(false);
176
- })
177
- .catch((err) => {
178
- if (!active) return;
179
- setError(err instanceof Error ? err : new Error(String(err)));
180
- setIsLoading(false);
181
- });
182
-
183
- return () => {
184
- active = false;
185
- };
186
- }, [name]);
187
-
188
- return { value, isLoading, error };
189
- }
190
-
191
- /**
192
- * Read several public (`NEXT_PUBLIC_*`) environment variables at runtime in a
193
- * single request from a Client Component.
194
- *
195
- * @param names - Full variable names, each including the `NEXT_PUBLIC_` prefix.
196
- * @returns `{ values, isLoading, error }` where `values` is a
197
- * `{ [name]: value | null }` map.
198
- *
199
- * @example
200
- * ```tsx
201
- * 'use client'
202
- * import { useClientEnvs } from '@akinon/next/hooks'
203
- *
204
- * const { values, isLoading } = useClientEnvs([
205
- * 'NEXT_PUBLIC_GTM_KEY',
206
- * 'NEXT_PUBLIC_URL'
207
- * ])
208
- *
209
- * const gtmKey = values['NEXT_PUBLIC_GTM_KEY']
210
- * ```
211
- */
212
- export function useClientEnvs(names: string[]) {
213
- // Stable serialization so the effect re-runs only when the set changes, not
214
- // on every render (a new array identity would otherwise loop it forever).
215
- const key = names.join(',');
216
-
217
- const [values, setValues] = useState<Record<string, string | null>>(() => {
218
- const initial: Record<string, string | null> = {};
219
- names.forEach((name) => {
220
- if (cache.has(name)) initial[name] = cache.get(name) ?? null;
221
- });
222
- return initial;
223
- });
224
- const [isLoading, setIsLoading] = useState(
225
- () => !names.every((name) => cache.has(name))
226
- );
227
- const [error, setError] = useState<Error | null>(null);
228
-
229
- useEffect(() => {
230
- let active = true;
231
- const list = key ? key.split(',') : [];
232
-
233
- if (list.every((name) => cache.has(name))) {
234
- const resolved: Record<string, string | null> = {};
235
- list.forEach((name) => (resolved[name] = cache.get(name) ?? null));
236
- setValues(resolved);
237
- setIsLoading(false);
238
- setError(null);
239
- return;
240
- }
241
-
242
- setIsLoading(true);
243
- setError(null);
244
-
245
- getClientEnvs(list)
246
- .then((resolved) => {
247
- if (!active) return;
248
- setValues(resolved);
249
- setIsLoading(false);
250
- })
251
- .catch((err) => {
252
- if (!active) return;
253
- setError(err instanceof Error ? err : new Error(String(err)));
254
- setIsLoading(false);
255
- });
256
-
257
- return () => {
258
- active = false;
259
- };
260
- // `key` is the stable serialization of `names`.
261
- // eslint-disable-next-line react-hooks/exhaustive-deps
262
- }, [key]);
263
-
264
- return { values, isLoading, error };
265
- }