@akinon/next 2.0.38 → 2.0.39-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/api/client-env.ts +78 -0
- package/bin/pz-generate-routes.js +4 -1
- package/components/plugin-module.tsx +0 -1
- package/data/client/checkout.ts +0 -1
- package/data/server/category.ts +13 -1
- package/data/server/list.ts +12 -0
- package/data/server/product.ts +10 -0
- package/data/server/special-page.ts +13 -0
- package/data/server/widget.ts +14 -1
- package/data/urls.ts +9 -4
- package/hooks/index.ts +1 -0
- package/hooks/use-captcha.tsx +1 -1
- package/hooks/use-client-env.ts +265 -0
- package/middlewares/default.ts +252 -205
- package/package.json +2 -2
- package/plugins.d.ts +10 -0
- package/plugins.js +1 -0
- package/redux/middlewares/checkout.ts +45 -3
- package/redux/middlewares/pre-order/installment-option.ts +9 -1
- package/types/index.ts +20 -9
- package/utils/csrf.ts +1 -1
- package/utils/payload-optimizer.ts +481 -0
- package/with-pz-config.js +7 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,35 @@
|
|
|
1
1
|
# @akinon/next
|
|
2
2
|
|
|
3
|
+
## 2.0.39-rc.0
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 0cf9ea23: BRDG-16491: Prevent redirect when iframe payment is active
|
|
8
|
+
- 324f97d5: ZERO-4219: replace masterpass-rest-complete with masterpass-rest-callback
|
|
9
|
+
- 51ea0688: ZERO-4377: Fix checkout card type state being cleared after valid bin number responses.
|
|
10
|
+
- ZERO-4160: Enhance oauth-login middleware with improved request handling and logging
|
|
11
|
+
- 2fea4143: ZERO-4620: Add runtime access to `NEXT_PUBLIC_*` environment variables from Client Components
|
|
12
|
+
- b55acb768: ZERO-2577: Fix pagination bug and update usePagination hook and ensure pagination controls rendering correctly
|
|
13
|
+
- 760258c1: ZERO-4160: Enhance oauth-login middleware to handle fetch errors and improve response handling
|
|
14
|
+
- 143be2b9d: ZERO-3457: Crop styles are customizable and logic improved for rendering similar products modal
|
|
15
|
+
- 7889b08f: ZERO-4276: Enhance route generation by adding .env loading and custom skip segments support
|
|
16
|
+
- 9f8cd3bc5: ZERO-3449: AI Search Active Filters & Crop Style changes have been implemented
|
|
17
|
+
- bfafa3f4: ZERO-4160: Refactor oauth-login middleware to use fetchCommerce for API calls and improve cookie handling
|
|
18
|
+
- 57d7eb30: ZERO-4276: Refactor route generation logic by removing environment loading and simplifying skip segments handling
|
|
19
|
+
- d99a6a7d5: ZERO-3457_1: Fixed the settings prop and made sure everything is customizable.
|
|
20
|
+
- 9db81a71: ZERO-4365: Remove brand `@theme/*` alias imports from library packages
|
|
21
|
+
- 591e345e1: ZERO-3855: Enhance credit card payment handling in checkout middlewares
|
|
22
|
+
- 4de5303c5: ZERO-2504: add cookie filter to api client request
|
|
23
|
+
- 95b139dc1: ZERO-3795: Remove duplicate entry for SavedCard in PluginComponents map
|
|
24
|
+
- 1d00f2d0: BRDG-16664: Set secure flag for CSRF token cookies in useCaptcha and default middleware
|
|
25
|
+
- 4ac7b2a1: ZERO-4219: fix masterpass-rest callback route format and double-encoded error cookie
|
|
26
|
+
- e9598c71: ZERO-4622: Images remotePatterns for improved readability
|
|
27
|
+
- 4998a963: ZERO-4168: Add server-side payload optimization
|
|
28
|
+
- 804d2bd6: ZERO-4536: Add akinon.net domain to CSP frame-ancestors directive
|
|
29
|
+
- 3909d3224: Edit the duplicate Plugin.SimilarProducts in the plugin-module.
|
|
30
|
+
- 6a3d8a63: ZERO-4541: Fix URL query string formatting in getOrders and getOldOrders functions
|
|
31
|
+
- e18836b2: ZERO-4160: Restore scope in Sentry addon configuration in akinon.json
|
|
32
|
+
|
|
3
33
|
## 2.0.38
|
|
4
34
|
|
|
5
35
|
## 2.0.37
|
|
@@ -0,0 +1,78 @@
|
|
|
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
|
+
}
|
|
@@ -6,6 +6,7 @@ const findBaseDir = require('../utils/find-base-dir');
|
|
|
6
6
|
|
|
7
7
|
const generateRoutes = () => {
|
|
8
8
|
const baseDir = findBaseDir();
|
|
9
|
+
|
|
9
10
|
const srcDir = path.join(baseDir, 'src');
|
|
10
11
|
const appDir = path.join(srcDir, 'app');
|
|
11
12
|
|
|
@@ -34,8 +35,10 @@ const generateRoutes = () => {
|
|
|
34
35
|
'[segment]',
|
|
35
36
|
'[url]',
|
|
36
37
|
'[theme]',
|
|
37
|
-
'[member_type]'
|
|
38
|
+
'[member_type]',
|
|
39
|
+
'[clienttype]'
|
|
38
40
|
];
|
|
41
|
+
|
|
39
42
|
const skipCatchAllRoutes = ['[...prettyurl]', '[...not_found]'];
|
|
40
43
|
|
|
41
44
|
const walkDirectory = (dir, basePath = '') => {
|
package/data/client/checkout.ts
CHANGED
|
@@ -738,7 +738,6 @@ export const checkoutApi = api.injectEndpoints({
|
|
|
738
738
|
},
|
|
739
739
|
async onQueryStarted(arg, { dispatch, queryFulfilled }) {
|
|
740
740
|
dispatch(setPaymentStepBusy(true));
|
|
741
|
-
dispatch(setCardType(arg));
|
|
742
741
|
await queryFulfilled;
|
|
743
742
|
dispatch(setPaymentStepBusy(false));
|
|
744
743
|
}
|
package/data/server/category.ts
CHANGED
|
@@ -8,6 +8,8 @@ import { parse } from 'lossless-json';
|
|
|
8
8
|
import logger from '../../utils/log';
|
|
9
9
|
import { headers as nHeaders } from 'next/headers';
|
|
10
10
|
import { ServerVariables } from '../../utils/server-variables';
|
|
11
|
+
import { optimizeCategoryResponse } from '../../utils/payload-optimizer';
|
|
12
|
+
import settings from 'settings';
|
|
11
13
|
|
|
12
14
|
function getCategoryDataHandler(
|
|
13
15
|
pk: number,
|
|
@@ -81,7 +83,7 @@ function getCategoryDataHandler(
|
|
|
81
83
|
};
|
|
82
84
|
}
|
|
83
85
|
|
|
84
|
-
export const getCategoryData = ({
|
|
86
|
+
export const getCategoryData = async ({
|
|
85
87
|
pk,
|
|
86
88
|
searchParams,
|
|
87
89
|
headers,
|
|
@@ -105,6 +107,16 @@ export const getCategoryData = ({
|
|
|
105
107
|
compressed: true
|
|
106
108
|
}
|
|
107
109
|
);
|
|
110
|
+
|
|
111
|
+
if (settings.payloadOptimization?.enabled && result?.data) {
|
|
112
|
+
try {
|
|
113
|
+
return { ...result, data: optimizeCategoryResponse(result.data, settings.payloadOptimization) };
|
|
114
|
+
} catch (e) {
|
|
115
|
+
logger.error('Payload optimization failed for category', { pk, error: (e as Error).message });
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
return result;
|
|
108
120
|
};
|
|
109
121
|
|
|
110
122
|
function getCategoryBySlugDataHandler(
|
package/data/server/list.ts
CHANGED
|
@@ -7,6 +7,8 @@ import appFetch, { FetchResponseType } from '../../utils/app-fetch';
|
|
|
7
7
|
import { parse } from 'lossless-json';
|
|
8
8
|
import logger from '../../utils/log';
|
|
9
9
|
import { ServerVariables } from '../../utils/server-variables';
|
|
10
|
+
import { optimizeCategoryResponse } from '../../utils/payload-optimizer';
|
|
11
|
+
import settings from 'settings';
|
|
10
12
|
|
|
11
13
|
const getListDataHandler = (
|
|
12
14
|
locale,
|
|
@@ -78,4 +80,14 @@ export const getListData = async ({
|
|
|
78
80
|
compressed: true
|
|
79
81
|
}
|
|
80
82
|
);
|
|
83
|
+
|
|
84
|
+
if (settings.payloadOptimization?.enabled && result) {
|
|
85
|
+
try {
|
|
86
|
+
return optimizeCategoryResponse(result, settings.payloadOptimization);
|
|
87
|
+
} catch (e) {
|
|
88
|
+
logger.error('Payload optimization failed for list', { error: (e as Error).message });
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
return result;
|
|
81
93
|
};
|
package/data/server/product.ts
CHANGED
|
@@ -5,6 +5,8 @@ import appFetch from '../../utils/app-fetch';
|
|
|
5
5
|
import { normalizeSearchParams } from '../../utils/normalize-search-params';
|
|
6
6
|
import { ServerVariables } from '../../utils/server-variables';
|
|
7
7
|
import logger from '../../utils/log';
|
|
8
|
+
import { optimizeProductResponse } from '../../utils/payload-optimizer';
|
|
9
|
+
import settings from 'settings';
|
|
8
10
|
|
|
9
11
|
type GetProduct = {
|
|
10
12
|
pk: number | string;
|
|
@@ -166,5 +168,13 @@ export const getProductData = async ({
|
|
|
166
168
|
throw error;
|
|
167
169
|
}
|
|
168
170
|
|
|
171
|
+
if (settings.payloadOptimization?.enabled && result?.data) {
|
|
172
|
+
try {
|
|
173
|
+
return { ...result, data: optimizeProductResponse(result.data, settings.payloadOptimization) };
|
|
174
|
+
} catch (e) {
|
|
175
|
+
logger.error('Payload optimization failed for product', { pk, error: (e as Error).message });
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
169
179
|
return result;
|
|
170
180
|
};
|
|
@@ -5,6 +5,9 @@ import { generateCommerceSearchParams } from '../../utils';
|
|
|
5
5
|
import { normalizeSearchParams } from '../../utils/normalize-search-params';
|
|
6
6
|
import appFetch from '../../utils/app-fetch';
|
|
7
7
|
import { ServerVariables } from '../../utils/server-variables';
|
|
8
|
+
import { optimizeCategoryResponse } from '../../utils/payload-optimizer';
|
|
9
|
+
import logger from '../../utils/log';
|
|
10
|
+
import settings from 'settings';
|
|
8
11
|
|
|
9
12
|
const getSpecialPageDataHandler = (
|
|
10
13
|
pk: number,
|
|
@@ -57,4 +60,14 @@ export const getSpecialPageData = async ({
|
|
|
57
60
|
compressed: true
|
|
58
61
|
}
|
|
59
62
|
);
|
|
63
|
+
|
|
64
|
+
if (settings.payloadOptimization?.enabled && result) {
|
|
65
|
+
try {
|
|
66
|
+
return optimizeCategoryResponse(result, settings.payloadOptimization);
|
|
67
|
+
} catch (e) {
|
|
68
|
+
logger.error('Payload optimization failed for special-page', { pk, error: (e as Error).message });
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
return result;
|
|
60
73
|
};
|
package/data/server/widget.ts
CHANGED
|
@@ -4,6 +4,9 @@ import { CacheOptions, WidgetResultType, WidgetSchemaType } from '../../types';
|
|
|
4
4
|
import appFetch from '../../utils/app-fetch';
|
|
5
5
|
import { widgets } from '../urls';
|
|
6
6
|
import { ServerVariables } from '../../utils/server-variables';
|
|
7
|
+
import { optimizeWidgetResponse } from '../../utils/payload-optimizer';
|
|
8
|
+
import logger from '../../utils/log';
|
|
9
|
+
import settings from 'settings';
|
|
7
10
|
|
|
8
11
|
const getWidgetDataHandler =
|
|
9
12
|
(
|
|
@@ -53,7 +56,7 @@ export const getWidgetData = async <T>({
|
|
|
53
56
|
cacheOptions?: CacheOptions;
|
|
54
57
|
headers?: Record<string, string>;
|
|
55
58
|
}): Promise<WidgetResultType<T>> => {
|
|
56
|
-
|
|
59
|
+
const result = await Cache.wrap(
|
|
57
60
|
CacheKey.Widget(slug),
|
|
58
61
|
locale,
|
|
59
62
|
getWidgetDataHandler(slug, locale, currency, headers),
|
|
@@ -62,6 +65,16 @@ export const getWidgetData = async <T>({
|
|
|
62
65
|
...cacheOptions
|
|
63
66
|
}
|
|
64
67
|
);
|
|
68
|
+
|
|
69
|
+
if (settings.payloadOptimization?.enabled && result) {
|
|
70
|
+
try {
|
|
71
|
+
return optimizeWidgetResponse(result, settings.payloadOptimization) as WidgetResultType<T>;
|
|
72
|
+
} catch (e) {
|
|
73
|
+
logger.error('Payload optimization failed for widget', { slug, error: (e as Error).message });
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return result as WidgetResultType<T>;
|
|
65
78
|
};
|
|
66
79
|
|
|
67
80
|
const getCollectionWidgetDataHandler =
|
package/data/urls.ts
CHANGED
|
@@ -40,10 +40,11 @@ export const account = {
|
|
|
40
40
|
shipping_option_slug
|
|
41
41
|
? `&shipping_option_slug${shipping_option_operator}${shipping_option_slug}`
|
|
42
42
|
: ''
|
|
43
|
-
}${currency ? `¤cy=${currency}` : ''}
|
|
44
|
-
|
|
43
|
+
}${currency ? `¤cy=${currency}` : ''}${
|
|
44
|
+
filterType && filterValue ? `&${filterType}=${filterValue}` : ''
|
|
45
|
+
}`,
|
|
45
46
|
getOldOrders: ({ page, limit }: { page?: number; limit?: number }) =>
|
|
46
|
-
`/users/old-orders/?page=${page || 1}&limit=${limit || 12}
|
|
47
|
+
`/users/old-orders/?page=${page || 1}&limit=${limit || 12}`,
|
|
47
48
|
getQuotations: (page?: number, status?: string, limit?: number) =>
|
|
48
49
|
`/b2b/my-quotations/?page=${page || 1}` +
|
|
49
50
|
(status ? `&status=${status}` : '') +
|
|
@@ -183,7 +184,11 @@ export const product = {
|
|
|
183
184
|
breadcrumbUrl: (menuitemmodel: string) =>
|
|
184
185
|
`/menus/generate_breadcrumb/?item=${menuitemmodel}&generator_name=menu_item`,
|
|
185
186
|
bundleProduct: (productPk: string, queryString: string) =>
|
|
186
|
-
`/bundle-product/${productPk}/?${queryString}
|
|
187
|
+
`/bundle-product/${productPk}/?${queryString}`,
|
|
188
|
+
similarProducts: (params?: string) =>
|
|
189
|
+
`/similar-products${params ? `?${params}` : ''}`,
|
|
190
|
+
similarProductsList: (params?: string) =>
|
|
191
|
+
`/similar-product-list${params ? `?${params}` : ''}`
|
|
187
192
|
};
|
|
188
193
|
|
|
189
194
|
export const wishlist = {
|
package/hooks/index.ts
CHANGED
package/hooks/use-captcha.tsx
CHANGED
|
@@ -0,0 +1,265 @@
|
|
|
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
|
+
}
|