@akinon/next 2.0.39-rc.0 → 2.0.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1 -29
- package/bin/pz-generate-routes.js +1 -4
- package/components/plugin-module.tsx +1 -0
- package/data/client/checkout.ts +1 -0
- package/data/server/category.ts +1 -13
- package/data/server/list.ts +0 -12
- package/data/server/product.ts +0 -10
- package/data/server/special-page.ts +0 -13
- package/data/server/widget.ts +1 -14
- package/data/urls.ts +4 -9
- package/hooks/index.ts +0 -1
- package/hooks/use-captcha.tsx +1 -1
- package/middlewares/default.ts +205 -252
- package/package.json +2 -2
- package/plugins.d.ts +0 -10
- package/plugins.js +0 -1
- package/redux/middlewares/checkout.ts +3 -45
- package/redux/middlewares/pre-order/installment-option.ts +1 -9
- package/types/index.ts +9 -20
- package/utils/csrf.ts +1 -1
- package/with-pz-config.js +2 -7
- package/api/client-env.ts +0 -78
- package/hooks/use-client-env.ts +0 -265
- package/utils/payload-optimizer.ts +0 -481
|
@@ -26,28 +26,13 @@ import {
|
|
|
26
26
|
} from '../../redux/reducers/checkout';
|
|
27
27
|
import { RootState, TypedDispatch } from 'redux/store';
|
|
28
28
|
import { checkoutApi } from '../../data/client/checkout';
|
|
29
|
-
import { CheckoutContext,
|
|
29
|
+
import { CheckoutContext, PreOrder } from '../../types';
|
|
30
30
|
import { getCookie } from '../../utils';
|
|
31
31
|
import settings from 'settings';
|
|
32
32
|
import { LocaleUrlStrategy } from '../../localization';
|
|
33
33
|
import { showMobile3dIframe } from '../../utils/mobile-3d-iframe';
|
|
34
34
|
import { showRedirectionIframe } from '../../utils/redirection-iframe';
|
|
35
35
|
|
|
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
36
|
interface CheckoutResult {
|
|
52
37
|
payload: {
|
|
53
38
|
errors?: Record<string, string[]>;
|
|
@@ -84,7 +69,7 @@ export const redirectUrlMiddleware: Middleware = () => {
|
|
|
84
69
|
const result = next(action) as CheckoutResult;
|
|
85
70
|
const redirectUrl = result?.payload?.redirect_url;
|
|
86
71
|
|
|
87
|
-
if (redirectUrl
|
|
72
|
+
if (redirectUrl) {
|
|
88
73
|
const currentLocale = getCookie('pz-locale');
|
|
89
74
|
|
|
90
75
|
let url = redirectUrl;
|
|
@@ -114,15 +99,8 @@ export const contextListMiddleware: Middleware = ({
|
|
|
114
99
|
const { isMobileApp, userPhoneNumber } = getState().root;
|
|
115
100
|
const result = next(action) as CheckoutResult;
|
|
116
101
|
const preOrder = result?.payload?.pre_order;
|
|
117
|
-
const act = action as MiddlewareAction;
|
|
118
102
|
|
|
119
103
|
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
104
|
result.payload.context_list.forEach((context) => {
|
|
127
105
|
const redirectUrl = context.page_context.redirect_url;
|
|
128
106
|
const isIframe = context.page_context.is_iframe ?? false;
|
|
@@ -156,7 +134,6 @@ export const contextListMiddleware: Middleware = ({
|
|
|
156
134
|
if (isMobileDevice && isIframePaymentOptionIncluded) {
|
|
157
135
|
showMobile3dIframe(urlObj.toString());
|
|
158
136
|
} else if (isIframe) {
|
|
159
|
-
setIframeRedirectionActive(true);
|
|
160
137
|
showRedirectionIframe(urlObj.toString());
|
|
161
138
|
} else {
|
|
162
139
|
window.location.href = urlObj.toString();
|
|
@@ -232,34 +209,15 @@ export const contextListMiddleware: Middleware = ({
|
|
|
232
209
|
(ctx) => ctx.page_name === 'DeliveryOptionSelectionPage'
|
|
233
210
|
)
|
|
234
211
|
) {
|
|
235
|
-
const isCreditCardPayment =
|
|
236
|
-
preOrder?.payment_option?.payment_type === 'credit_card' ||
|
|
237
|
-
preOrder?.payment_option?.payment_type === 'masterpass';
|
|
238
|
-
|
|
239
212
|
if (context.page_context.card_type) {
|
|
240
213
|
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
214
|
}
|
|
249
215
|
|
|
250
216
|
if (
|
|
251
217
|
context.page_context.installments &&
|
|
252
218
|
preOrder?.payment_option?.payment_type !== 'masterpass_rest'
|
|
253
219
|
) {
|
|
254
|
-
|
|
255
|
-
!isCreditCardPayment ||
|
|
256
|
-
context.page_context.card_type ||
|
|
257
|
-
hasCardTypeInContextList
|
|
258
|
-
) {
|
|
259
|
-
dispatch(
|
|
260
|
-
setInstallmentOptions(context.page_context.installments)
|
|
261
|
-
);
|
|
262
|
-
}
|
|
220
|
+
dispatch(setInstallmentOptions(context.page_context.installments));
|
|
263
221
|
}
|
|
264
222
|
}
|
|
265
223
|
|
|
@@ -14,17 +14,9 @@ export const installmentOptionMiddleware: Middleware = ({
|
|
|
14
14
|
return result;
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
-
const { installmentOptions
|
|
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
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
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
|
@@ -31,7 +31,7 @@ export function getCsrfCookieFlags(): CsrfCookieFlags {
|
|
|
31
31
|
const httpOnly = isCsrfHttpOnly();
|
|
32
32
|
return {
|
|
33
33
|
httpOnly,
|
|
34
|
-
secure: process.env.NODE_ENV === 'production',
|
|
34
|
+
secure: httpOnly && process.env.NODE_ENV === 'production',
|
|
35
35
|
sameSite: 'lax'
|
|
36
36
|
};
|
|
37
37
|
}
|
package/with-pz-config.js
CHANGED
|
@@ -25,10 +25,6 @@ const defaultConfig = {
|
|
|
25
25
|
{
|
|
26
26
|
protocol: 'https',
|
|
27
27
|
hostname: '**.akinoncdn.com'
|
|
28
|
-
},
|
|
29
|
-
{
|
|
30
|
-
protocol: 'https',
|
|
31
|
-
hostname: '**.akinoncloudcdn.com'
|
|
32
28
|
}
|
|
33
29
|
]
|
|
34
30
|
},
|
|
@@ -54,7 +50,7 @@ const defaultConfig = {
|
|
|
54
50
|
{
|
|
55
51
|
key: 'Content-Security-Policy',
|
|
56
52
|
value:
|
|
57
|
-
"frame-ancestors 'self' https://*.akifast.com akifast.com https://*.akinoncloud.com akinoncloud.com
|
|
53
|
+
"frame-ancestors 'self' https://*.akifast.com akifast.com https://*.akinoncloud.com akinoncloud.com http://localhost:5174 localhost:5174"
|
|
58
54
|
}
|
|
59
55
|
]
|
|
60
56
|
}
|
|
@@ -73,8 +69,7 @@ const defaultConfig = {
|
|
|
73
69
|
acc[`@akinon/${plugin}`] = false;
|
|
74
70
|
return acc;
|
|
75
71
|
}, {}),
|
|
76
|
-
translations: false
|
|
77
|
-
'@opentelemetry/exporter-jaeger': false
|
|
72
|
+
translations: false
|
|
78
73
|
};
|
|
79
74
|
// Ensure webpack can resolve deps from the app's node_modules when
|
|
80
75
|
// 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
|
-
}
|
package/hooks/use-client-env.ts
DELETED
|
@@ -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
|
-
}
|