@commercengine/storefront-sdk-nextjs 0.1.0-alpha.0 → 1.0.0-alpha.2

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/dist/index.d.ts CHANGED
@@ -1,116 +1,41 @@
1
- import { TokenStorage, StorefrontSDK, StorefrontSDKOptions } from '@commercengine/storefront-sdk';
2
- export { Environment, StorefrontSDK, StorefrontSDKOptions } from '@commercengine/storefront-sdk';
1
+ import { StorefrontSDK } from '@commercengine/storefront-sdk';
2
+ export { StorefrontSDK } from '@commercengine/storefront-sdk';
3
+ import { S as StorefrontRuntimeConfig } from './server-CwxgXezP.js';
3
4
 
4
- /**
5
- * Configuration options for NextJSTokenStorage
6
- */
7
- interface NextJSTokenStorageOptions {
8
- /**
9
- * Prefix for cookie names (default: "ce_")
10
- */
11
- prefix?: string;
12
- /**
13
- * Maximum age of cookies in seconds (default: 30 days)
14
- */
15
- maxAge?: number;
16
- /**
17
- * Cookie path (default: "/")
18
- */
19
- path?: string;
20
- /**
21
- * Cookie domain (default: current domain)
22
- */
23
- domain?: string;
24
- /**
25
- * Whether cookies should be secure (default: auto-detect based on environment)
26
- */
27
- secure?: boolean;
28
- /**
29
- * SameSite cookie attribute (default: "Lax")
30
- */
31
- sameSite?: "Strict" | "Lax" | "None";
32
- }
33
- /**
34
- * Client-side token storage that uses document.cookie
35
- */
36
- declare class ClientTokenStorage implements TokenStorage {
37
- private accessTokenKey;
38
- private refreshTokenKey;
39
- private options;
40
- constructor(options?: NextJSTokenStorageOptions);
41
- getAccessToken(): Promise<string | null>;
42
- setAccessToken(token: string): Promise<void>;
43
- getRefreshToken(): Promise<string | null>;
44
- setRefreshToken(token: string): Promise<void>;
45
- clearTokens(): Promise<void>;
46
- private getCookie;
47
- private setCookie;
48
- private deleteCookie;
49
- }
50
- type NextCookieStore$1 = {
51
- get: (name: string) => {
52
- value: string;
53
- } | undefined;
54
- set: (name: string, value: string, options?: any) => void;
55
- delete: (name: string) => void;
56
- };
57
- /**
58
- * Server-side token storage that uses Next.js cookies API
59
- */
60
- declare class ServerTokenStorage implements TokenStorage {
61
- private accessTokenKey;
62
- private refreshTokenKey;
63
- private options;
64
- private cookieStore;
65
- constructor(cookieStore: NextCookieStore$1, options?: NextJSTokenStorageOptions);
66
- getAccessToken(): Promise<string | null>;
67
- setAccessToken(token: string): Promise<void>;
68
- getRefreshToken(): Promise<string | null>;
69
- setRefreshToken(token: string): Promise<void>;
70
- clearTokens(): Promise<void>;
71
- }
72
-
73
- /**
74
- * Configuration for the NextJS SDK wrapper
75
- */
76
- interface NextJSSDKConfig extends Omit<StorefrontSDKOptions, "tokenStorage"> {
77
- /**
78
- * Token storage configuration options
79
- */
80
- tokenStorageOptions?: NextJSTokenStorageOptions;
81
- }
82
5
  type NextCookieStore = {
83
6
  get: (name: string) => {
7
+ name: string;
84
8
  value: string;
85
9
  } | undefined;
86
- set: (name: string, value: string, options?: any) => void;
10
+ set: (name: string, value: string, opts?: Record<string, unknown>) => void;
87
11
  delete: (name: string) => void;
88
12
  };
89
13
  /**
90
- * Smart SDK getter that automatically detects environment
14
+ * Creates a configured storefront function that works universally across all Next.js contexts
91
15
  *
92
16
  * Usage:
93
- * - Client-side: getStorefrontSDK()
94
- * - Server-side: getStorefrontSDK(await cookies())
95
- */
96
- declare function getStorefrontSDK(): StorefrontSDK;
97
- declare function getStorefrontSDK(cookieStore: NextCookieStore): StorefrontSDK;
98
-
99
- interface StorefrontSDKInitializerProps {
100
- config: NextJSSDKConfig;
101
- }
102
- /**
103
- * Client-side initialization component
104
- * Use this in your root layout to initialize the SDK once
17
+ * ```typescript
18
+ * // lib/storefront.ts
19
+ * import { createStorefront } from "@commercengine/storefront-sdk-nextjs";
105
20
  *
106
- * The core SDK middleware now automatically handles everything:
107
- * - Creates anonymous tokens automatically on first API request (if no tokens exist)
108
- * - Token state assessment and cleanup on first request per page load
109
- * - Expired token refresh with automatic anonymous fallback
110
- * - Graceful handling of partial token states
21
+ * export const storefront = createStorefront({
22
+ * debug: true,
23
+ * logger: (msg, ...args) => console.log('[DEBUG]', msg, ...args)
24
+ * });
25
+ * ```
111
26
  *
112
- * No manual token creation needed - just make API calls and everything works!
27
+ * @param config Optional configuration for advanced options (defaults to empty if not provided)
28
+ * @returns A storefront function that works in all Next.js contexts
113
29
  */
114
- declare function StorefrontSDKInitializer({ config, }: StorefrontSDKInitializerProps): null;
30
+ declare function createStorefront(config?: StorefrontRuntimeConfig): {
31
+ (): StorefrontSDK;
32
+ (cookieStore: NextCookieStore): StorefrontSDK;
33
+ (options: {
34
+ isRootLayout: true;
35
+ }): StorefrontSDK;
36
+ (cookieStore: NextCookieStore, options: {
37
+ isRootLayout?: boolean;
38
+ }): StorefrontSDK;
39
+ };
115
40
 
116
- export { ClientTokenStorage, type NextJSSDKConfig, type NextJSTokenStorageOptions, ServerTokenStorage, StorefrontSDKInitializer, getStorefrontSDK };
41
+ export { StorefrontRuntimeConfig, createStorefront };
package/dist/index.js CHANGED
@@ -1,13 +1,9 @@
1
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
- }) : x)(function(x) {
4
- if (typeof require !== "undefined") return require.apply(this, arguments);
5
- throw Error('Dynamic require of "' + x + '" is not supported');
6
- });
7
-
8
1
  // src/sdk-manager.ts
2
+ import { cache } from "react";
9
3
  import {
10
- StorefrontSDK
4
+ StorefrontSDK,
5
+ MemoryTokenStorage,
6
+ Environment
11
7
  } from "@commercengine/storefront-sdk";
12
8
 
13
9
  // src/token-storage.ts
@@ -116,7 +112,7 @@ var ServerTokenStorage = class {
116
112
  secure: this.options.secure,
117
113
  sameSite: this.options.sameSite?.toLowerCase(),
118
114
  httpOnly: false
119
- // Must be false for client-side access
115
+ // Allow client-side access for SDK flexibility
120
116
  });
121
117
  } catch (error) {
122
118
  console.warn(`Could not set access token on server:`, error);
@@ -139,7 +135,7 @@ var ServerTokenStorage = class {
139
135
  secure: this.options.secure,
140
136
  sameSite: this.options.sameSite?.toLowerCase(),
141
137
  httpOnly: false
142
- // Must be false for client-side access
138
+ // Allow client-side access for SDK flexibility
143
139
  });
144
140
  } catch (error) {
145
141
  console.warn(`Could not set refresh token on server:`, error);
@@ -155,151 +151,253 @@ var ServerTokenStorage = class {
155
151
  }
156
152
  };
157
153
 
158
- // src/sdk-manager.ts
159
- var NextJSSDKManager = class _NextJSSDKManager {
160
- constructor() {
161
- this.clientSDK = null;
162
- this.config = null;
163
- }
164
- static getInstance() {
165
- if (!_NextJSSDKManager.instance) {
166
- _NextJSSDKManager.instance = new _NextJSSDKManager();
167
- }
168
- return _NextJSSDKManager.instance;
169
- }
170
- /**
171
- * Initialize the SDK with configuration (should be called once)
172
- */
173
- initialize(config) {
174
- this.config = config;
175
- if (typeof window !== "undefined" && !this.clientSDK) {
176
- this.clientSDK = this.createClientSDK();
177
- }
154
+ // src/build-token-cache.ts
155
+ var store = /* @__PURE__ */ new Map();
156
+ function isExpired(token) {
157
+ if (!token) return true;
158
+ if (!token.expiresAt) return false;
159
+ return Date.now() > token.expiresAt - 3e4;
160
+ }
161
+ function getCachedToken(key) {
162
+ const token = store.get(key);
163
+ return isExpired(token) ? null : token;
164
+ }
165
+ function setCachedToken(key, token) {
166
+ const expiresAt = token.ttlSeconds != null ? Date.now() + token.ttlSeconds * 1e3 : void 0;
167
+ store.set(key, {
168
+ accessToken: token.accessToken,
169
+ refreshToken: token.refreshToken ?? null,
170
+ expiresAt
171
+ });
172
+ }
173
+ function clearCachedToken(key) {
174
+ store.delete(key);
175
+ }
176
+
177
+ // src/build-caching-memory-storage.ts
178
+ var DEFAULT_TTL_SECONDS = 5 * 60;
179
+ var BuildCachingMemoryTokenStorage = class {
180
+ constructor(cacheKey, ttlSeconds = DEFAULT_TTL_SECONDS) {
181
+ this.cacheKey = cacheKey;
182
+ this.ttlSeconds = ttlSeconds;
183
+ this.access = null;
184
+ this.refresh = null;
178
185
  }
179
- /**
180
- * Get SDK instance for client-side usage
181
- */
182
- getClientSDK() {
183
- if (!this.config) {
184
- throw new Error("SDK not initialized. Call initialize() first.");
186
+ async getAccessToken() {
187
+ if (this.access) {
188
+ return this.access;
185
189
  }
186
- if (!this.clientSDK) {
187
- this.clientSDK = this.createClientSDK();
190
+ const cached = getCachedToken(this.cacheKey);
191
+ if (cached?.accessToken) {
192
+ this.access = cached.accessToken;
193
+ this.refresh = cached.refreshToken ?? null;
194
+ return this.access;
188
195
  }
189
- return this.clientSDK;
196
+ return null;
190
197
  }
191
- /**
192
- * Get SDK instance for server-side usage
193
- */
194
- getServerSDK(cookieStore) {
195
- if (!this.config) {
196
- throw new Error("SDK not initialized. Call initialize() first.");
197
- }
198
- return new StorefrontSDK({
199
- ...this.config,
200
- tokenStorage: new ServerTokenStorage(
201
- cookieStore,
202
- this.config.tokenStorageOptions
203
- )
198
+ async setAccessToken(token) {
199
+ this.access = token;
200
+ setCachedToken(this.cacheKey, {
201
+ accessToken: token,
202
+ refreshToken: this.refresh,
203
+ ttlSeconds: this.ttlSeconds
204
204
  });
205
205
  }
206
- createClientSDK() {
207
- if (!this.config) {
208
- throw new Error("SDK not initialized. Call initialize() first.");
209
- }
210
- return new StorefrontSDK({
211
- ...this.config,
212
- tokenStorage: new ClientTokenStorage(this.config.tokenStorageOptions)
213
- });
206
+ async getRefreshToken() {
207
+ return this.refresh;
214
208
  }
215
- /**
216
- * Check if SDK is initialized
217
- */
218
- isInitialized() {
219
- return this.config !== null;
209
+ async setRefreshToken(token) {
210
+ this.refresh = token;
211
+ setCachedToken(this.cacheKey, {
212
+ accessToken: this.access ?? "",
213
+ refreshToken: token,
214
+ ttlSeconds: this.ttlSeconds
215
+ });
220
216
  }
221
- /**
222
- * Reset the SDK (useful for testing)
223
- */
224
- reset() {
225
- this.clientSDK = null;
226
- this.config = null;
217
+ async clearTokens() {
218
+ this.access = null;
219
+ this.refresh = null;
220
+ clearCachedToken(this.cacheKey);
227
221
  }
228
222
  };
223
+
224
+ // src/sdk-manager.ts
225
+ function getConfig() {
226
+ const envStoreId = process.env.NEXT_PUBLIC_STORE_ID;
227
+ const envApiKey = process.env.NEXT_PUBLIC_API_KEY;
228
+ const envEnvironment = process.env.NEXT_PUBLIC_ENVIRONMENT;
229
+ const envBaseUrl = process.env.NEXT_PUBLIC_API_BASE_URL;
230
+ const envTimeout = process.env.NEXT_PUBLIC_API_TIMEOUT ? parseInt(process.env.NEXT_PUBLIC_API_TIMEOUT, 10) : void 0;
231
+ const envDebug = process.env.NEXT_PUBLIC_DEBUG_MODE === "true";
232
+ const envDefaultHeaders = {};
233
+ if (process.env.NEXT_PUBLIC_DEFAULT_CUSTOMER_GROUP_ID) {
234
+ envDefaultHeaders.customer_group_id = process.env.NEXT_PUBLIC_DEFAULT_CUSTOMER_GROUP_ID;
235
+ }
236
+ const storeId = globalStorefrontConfig?.storeId || envStoreId;
237
+ const apiKey = globalStorefrontConfig?.apiKey || envApiKey;
238
+ const environment = globalStorefrontConfig?.environment || (envEnvironment === "production" ? Environment.Production : Environment.Staging);
239
+ const baseUrl = globalStorefrontConfig?.baseUrl || envBaseUrl;
240
+ const timeout = globalStorefrontConfig?.timeout || envTimeout;
241
+ const debug = globalStorefrontConfig?.debug !== void 0 ? globalStorefrontConfig.debug : envDebug;
242
+ const defaultHeaders = {
243
+ ...envDefaultHeaders,
244
+ ...globalStorefrontConfig?.defaultHeaders
245
+ };
246
+ if (!storeId || !apiKey) {
247
+ throw new Error(
248
+ `StorefrontSDK configuration missing! Please set the following environment variables:
249
+
250
+ NEXT_PUBLIC_STORE_ID=your-store-id
251
+ NEXT_PUBLIC_API_KEY=your-api-key
252
+ NEXT_PUBLIC_ENVIRONMENT=staging (or production)
253
+
254
+ These variables are required for both client and server contexts to work.`
255
+ );
256
+ }
257
+ const config = {
258
+ storeId,
259
+ apiKey,
260
+ environment
261
+ };
262
+ if (baseUrl) config.baseUrl = baseUrl;
263
+ if (timeout) config.timeout = timeout;
264
+ if (debug) config.debug = debug;
265
+ const logger = globalStorefrontConfig?.logger;
266
+ const accessToken = globalStorefrontConfig?.accessToken;
267
+ const refreshToken = globalStorefrontConfig?.refreshToken;
268
+ const onTokensUpdated = globalStorefrontConfig?.onTokensUpdated;
269
+ const onTokensCleared = globalStorefrontConfig?.onTokensCleared;
270
+ const tokenStorageOptions = globalStorefrontConfig?.tokenStorageOptions;
271
+ if (logger) config.logger = logger;
272
+ if (accessToken) config.accessToken = accessToken;
273
+ if (refreshToken) config.refreshToken = refreshToken;
274
+ if (onTokensUpdated) config.onTokensUpdated = onTokensUpdated;
275
+ if (onTokensCleared) config.onTokensCleared = onTokensCleared;
276
+ if (Object.keys(defaultHeaders).length > 0) config.defaultHeaders = defaultHeaders;
277
+ if (tokenStorageOptions) config.tokenStorageOptions = tokenStorageOptions;
278
+ return config;
279
+ }
280
+ var globalStorefrontConfig = null;
281
+ var clientSDK = null;
282
+ function createTokenStorage(cookieStore, options, config) {
283
+ if (typeof window !== "undefined") {
284
+ return new ClientTokenStorage(options);
285
+ }
286
+ if (cookieStore) {
287
+ return new ServerTokenStorage(cookieStore, options);
288
+ }
289
+ const shouldCache = process.env.NEXT_BUILD_CACHE_TOKENS === "true";
290
+ if (shouldCache && config) {
291
+ const cacheKey = `${config.storeId}:${config.environment || "production"}`;
292
+ return new BuildCachingMemoryTokenStorage(cacheKey);
293
+ }
294
+ return new MemoryTokenStorage();
295
+ }
296
+ var getServerSDKCached = cache((cookieStore) => {
297
+ const config = getConfig();
298
+ return new StorefrontSDK({
299
+ ...config,
300
+ tokenStorage: createTokenStorage(
301
+ cookieStore,
302
+ config.tokenStorageOptions,
303
+ config
304
+ )
305
+ });
306
+ });
307
+ var buildTimeSDK = null;
308
+ function getBuildTimeSDK() {
309
+ const config = getConfig();
310
+ if (!buildTimeSDK) {
311
+ buildTimeSDK = new StorefrontSDK({
312
+ ...config,
313
+ tokenStorage: createTokenStorage(
314
+ void 0,
315
+ config.tokenStorageOptions,
316
+ config
317
+ )
318
+ });
319
+ }
320
+ return buildTimeSDK;
321
+ }
229
322
  function getStorefrontSDK(cookieStore) {
230
- const manager = NextJSSDKManager.getInstance();
231
323
  if (typeof window !== "undefined") {
232
324
  if (cookieStore) {
233
325
  console.warn(
234
326
  "Cookie store passed in client environment - this will be ignored"
235
327
  );
236
328
  }
237
- return manager.getClientSDK();
329
+ const config = getConfig();
330
+ if (!clientSDK) {
331
+ clientSDK = new StorefrontSDK({
332
+ ...config,
333
+ tokenStorage: createTokenStorage(
334
+ void 0,
335
+ config.tokenStorageOptions,
336
+ config
337
+ )
338
+ });
339
+ }
340
+ return clientSDK;
238
341
  }
239
- if (!cookieStore) {
240
- let autoDetectMessage = "";
241
- try {
242
- __require.resolve("next/headers");
243
- autoDetectMessage = `
244
-
245
- \u{1F50D} Auto-detection attempted but failed. You may be in:
246
- - Server Action (use: const sdk = getStorefrontSDK(await cookies()))
247
- - API Route (use: const sdk = getStorefrontSDK(cookies()))
248
- - Middleware (token access limited)
249
- `;
250
- } catch {
251
- autoDetectMessage = `
342
+ if (cookieStore) {
343
+ return getServerSDKCached(cookieStore);
344
+ }
345
+ return getBuildTimeSDK();
346
+ }
347
+ function setGlobalStorefrontConfig(config) {
348
+ globalStorefrontConfig = config;
349
+ clientSDK = null;
350
+ buildTimeSDK = null;
351
+ }
252
352
 
253
- \u{1F4A1} Make sure you have Next.js installed and are in a server context.
254
- `;
353
+ // src/create-storefront.ts
354
+ function createStorefront(config) {
355
+ if (config) {
356
+ setGlobalStorefrontConfig(config);
357
+ }
358
+ function storefront(cookieStoreOrOptions, options) {
359
+ if (typeof window !== "undefined") {
360
+ return getStorefrontSDK();
361
+ }
362
+ let cookieStore;
363
+ let isRootLayout = false;
364
+ if (cookieStoreOrOptions) {
365
+ if ("isRootLayout" in cookieStoreOrOptions) {
366
+ isRootLayout = cookieStoreOrOptions.isRootLayout;
367
+ } else {
368
+ cookieStore = cookieStoreOrOptions;
369
+ isRootLayout = options?.isRootLayout || false;
370
+ }
371
+ }
372
+ if (cookieStore) {
373
+ return getStorefrontSDK(cookieStore);
374
+ }
375
+ if (process.env.NEXT_IS_BUILD === "true" || process.env.NEXT_BUILD_CACHE_TOKENS === "true") {
376
+ return getStorefrontSDK();
377
+ }
378
+ if (isRootLayout) {
379
+ return getStorefrontSDK();
255
380
  }
256
381
  throw new Error(
257
- `
258
- \u{1F6A8} Server Environment Detected!
259
-
260
- You're calling getStorefrontSDK() on the server without cookies.
261
- Please pass the Next.js cookie store:
262
-
263
- \u2705 Correct usage:
264
- import { cookies } from 'next/headers';
265
-
266
- // Server Actions & Route Handlers
267
- const sdk = getStorefrontSDK(await cookies());
268
-
269
- // API Routes (Next.js 12)
270
- const sdk = getStorefrontSDK(cookies());
271
-
272
- \u274C Your current usage:
273
- const sdk = getStorefrontSDK(); // Missing cookies!
274
- ${autoDetectMessage}
275
- This is required for server-side token access.
276
- `.trim()
382
+ [
383
+ "\u{1F6A8} Server context requires cookies for user continuity!",
384
+ "",
385
+ "You're calling storefront() on the server without cookies.",
386
+ "This breaks user session continuity and analytics tracking.",
387
+ "",
388
+ "\u2705 Correct usage:",
389
+ " import { cookies } from 'next/headers'",
390
+ " const sdk = storefront(cookies())",
391
+ "",
392
+ "\u{1F4CD} Root Layout exception:",
393
+ " const sdk = storefront({ isRootLayout: true })",
394
+ "",
395
+ "This is required to maintain consistent user identity across requests."
396
+ ].join("\n")
277
397
  );
278
398
  }
279
- return manager.getServerSDK(cookieStore);
399
+ return storefront;
280
400
  }
281
- function initializeStorefrontSDK(config) {
282
- const manager = NextJSSDKManager.getInstance();
283
- manager.initialize(config);
284
- }
285
-
286
- // src/init-client.ts
287
- import { useEffect } from "react";
288
- function StorefrontSDKInitializer({
289
- config
290
- }) {
291
- useEffect(() => {
292
- initializeStorefrontSDK(config);
293
- }, [config]);
294
- return null;
295
- }
296
-
297
- // src/index.ts
298
- import { Environment } from "@commercengine/storefront-sdk";
299
401
  export {
300
- ClientTokenStorage,
301
- Environment,
302
- ServerTokenStorage,
303
- StorefrontSDKInitializer,
304
- getStorefrontSDK
402
+ createStorefront
305
403
  };
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/middleware.ts
21
+ var middleware_exports = {};
22
+ __export(middleware_exports, {
23
+ ensureStorefrontTokens: () => ensureStorefrontTokens
24
+ });
25
+ module.exports = __toCommonJS(middleware_exports);
26
+
27
+ // src/middleware-helper.ts
28
+ async function ensureStorefrontTokens(reqCookies, resCookies, opts) {
29
+ const prefix = opts.cookiePrefix ?? "ce_";
30
+ const ACCESS = `${prefix}access_token`;
31
+ const existingAccess = reqCookies.get(ACCESS)?.value;
32
+ if (existingAccess) {
33
+ return false;
34
+ }
35
+ try {
36
+ const resp = await fetch(`${opts.baseUrl}/auth/anonymous`, {
37
+ method: "POST",
38
+ headers: {
39
+ "Content-Type": "application/json",
40
+ ...opts.apiKey ? { "X-Api-Key": opts.apiKey } : {}
41
+ }
42
+ });
43
+ if (!resp.ok) return false;
44
+ const data = await resp.json();
45
+ const content = data?.content;
46
+ if (!content?.access_token || !content?.refresh_token) return false;
47
+ const cookieDefaults = {
48
+ path: "/",
49
+ httpOnly: false,
50
+ sameSite: "lax",
51
+ secure: opts.cookieOptions?.secure ?? false,
52
+ maxAge: 30 * 24 * 60 * 60
53
+ // 30 days
54
+ };
55
+ const finalOpts = { ...cookieDefaults, ...opts.cookieOptions || {} };
56
+ resCookies.set(ACCESS, content.access_token, finalOpts);
57
+ resCookies.set(`${prefix}refresh_token`, content.refresh_token, finalOpts);
58
+ return true;
59
+ } catch {
60
+ return false;
61
+ }
62
+ }
63
+ // Annotate the CommonJS export names for ESM import in node:
64
+ 0 && (module.exports = {
65
+ ensureStorefrontTokens
66
+ });
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Minimal cookie interface compatible with Next.js middleware cookies API.
3
+ */
4
+ interface NextCookiesLike {
5
+ get: (name: string) => {
6
+ value: string;
7
+ } | undefined;
8
+ set: (name: string, value: string, options?: {
9
+ maxAge?: number;
10
+ path?: string;
11
+ domain?: string;
12
+ secure?: boolean;
13
+ sameSite?: "strict" | "lax" | "none" | (string & {});
14
+ httpOnly?: boolean;
15
+ }) => any;
16
+ }
17
+ interface EnsureTokensOptions {
18
+ baseUrl: string;
19
+ apiKey?: string;
20
+ cookiePrefix?: string;
21
+ cookieOptions?: {
22
+ maxAge?: number;
23
+ path?: string;
24
+ domain?: string;
25
+ secure?: boolean;
26
+ sameSite?: "strict" | "lax" | "none";
27
+ httpOnly?: boolean;
28
+ };
29
+ }
30
+ /**
31
+ * Pre-seed anonymous tokens in Next.js middleware when missing.
32
+ * Call this early to ensure SSR and client share the same session.
33
+ *
34
+ * Returns true if tokens were set on the response, false otherwise.
35
+ */
36
+ declare function ensureStorefrontTokens(reqCookies: NextCookiesLike, resCookies: NextCookiesLike, opts: EnsureTokensOptions): Promise<boolean>;
37
+
38
+ export { type EnsureTokensOptions, type NextCookiesLike, ensureStorefrontTokens };