arky-sdk 0.7.104 → 0.7.106

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/admin.cjs CHANGED
@@ -164,37 +164,8 @@ function buildQueryString(params) {
164
164
  }
165
165
 
166
166
  // src/services/createHttpClient.ts
167
- var TOKEN_KEY = "arky_token";
168
- var LEGACY_KEYS = ["arky_refresh", "arky_expires_at"];
169
- function defaultGetToken() {
170
- if (typeof window === "undefined") return { access_token: "" };
171
- return {
172
- access_token: localStorage.getItem(TOKEN_KEY) || ""
173
- };
174
- }
175
- function defaultSetToken(tokens) {
176
- if (typeof window === "undefined") return;
177
- if (tokens.access_token) {
178
- localStorage.setItem(TOKEN_KEY, tokens.access_token);
179
- } else {
180
- localStorage.removeItem(TOKEN_KEY);
181
- }
182
- LEGACY_KEYS.forEach((key) => localStorage.removeItem(key));
183
- }
184
- function defaultLogout() {
185
- if (typeof window === "undefined") return;
186
- localStorage.removeItem(TOKEN_KEY);
187
- LEGACY_KEYS.forEach((key) => localStorage.removeItem(key));
188
- }
189
- function defaultIsAuthenticated() {
190
- if (typeof window === "undefined") return false;
191
- const token = localStorage.getItem(TOKEN_KEY) || "";
192
- return token.startsWith("customer_") || token.startsWith("account_");
193
- }
194
167
  function createHttpClient(cfg) {
195
- const getToken = cfg.getToken || defaultGetToken;
196
- const setToken = cfg.setToken || defaultSetToken;
197
- const logout = cfg.logout || defaultLogout;
168
+ const { authStorage } = cfg;
198
169
  let refreshPromise = null;
199
170
  function getRefreshEndpoint() {
200
171
  const refreshPath = typeof cfg.refreshPath === "function" ? cfg.refreshPath() : cfg.refreshPath || "/v1/auth/refresh";
@@ -205,9 +176,10 @@ function createHttpClient(cfg) {
205
176
  return refreshPromise;
206
177
  }
207
178
  refreshPromise = (async () => {
208
- const { refresh_token } = await getToken();
179
+ const tokens = authStorage.getTokens();
180
+ const refresh_token = tokens?.refresh_token;
209
181
  if (!refresh_token) {
210
- logout();
182
+ authStorage.onForcedLogout();
211
183
  const err = new Error("No refresh token available");
212
184
  err.name = "ApiError";
213
185
  err.statusCode = 401;
@@ -219,14 +191,14 @@ function createHttpClient(cfg) {
219
191
  body: JSON.stringify({ refresh_token })
220
192
  });
221
193
  if (!refRes.ok) {
222
- logout();
194
+ authStorage.onForcedLogout();
223
195
  const err = new Error("Token refresh failed");
224
196
  err.name = "ApiError";
225
197
  err.statusCode = 401;
226
198
  throw err;
227
199
  }
228
200
  const data = await refRes.json();
229
- setToken(data);
201
+ authStorage.onTokensRefreshed(data);
230
202
  })().finally(() => {
231
203
  refreshPromise = null;
232
204
  });
@@ -241,15 +213,14 @@ function createHttpClient(cfg) {
241
213
  "Content-Type": "application/json",
242
214
  ...options?.headers || {}
243
215
  };
244
- let { access_token, access_expires_at } = await getToken();
216
+ let tokens = authStorage.getTokens();
245
217
  const nowSec = Date.now() / 1e3;
246
- if (access_expires_at && nowSec > access_expires_at) {
218
+ if (tokens?.access_expires_at && nowSec > tokens.access_expires_at) {
247
219
  await ensureFreshToken();
248
- const tokens = await getToken();
249
- access_token = tokens.access_token;
220
+ tokens = authStorage.getTokens();
250
221
  }
251
- if (access_token) {
252
- headers["Authorization"] = `Bearer ${access_token}`;
222
+ if (tokens?.access_token) {
223
+ headers["Authorization"] = `Bearer ${tokens.access_token}`;
253
224
  }
254
225
  const finalPath = options?.params ? path + buildQueryString(options.params) : path;
255
226
  const fetchOpts = { method, headers };
@@ -278,9 +249,11 @@ function createHttpClient(cfg) {
278
249
  if (res.status === 401 && !options?.["_retried"]) {
279
250
  try {
280
251
  await ensureFreshToken();
281
- const tokens = await getToken();
282
- headers["Authorization"] = `Bearer ${tokens.access_token}`;
283
- fetchOpts.headers = headers;
252
+ const refreshed = authStorage.getTokens();
253
+ if (refreshed?.access_token) {
254
+ headers["Authorization"] = `Bearer ${refreshed.access_token}`;
255
+ fetchOpts.headers = headers;
256
+ }
284
257
  return request(method, path, body, { ...options, _retried: true });
285
258
  } catch (refreshError) {
286
259
  throw refreshError;
@@ -389,7 +362,16 @@ var createAccountApi = (apiConfig) => {
389
362
  };
390
363
 
391
364
  // src/api/auth.ts
392
- var createAuthApi = (apiConfig) => {
365
+ var createAuthApi = (apiConfig, updateSession) => {
366
+ function applyAuthToken(result, email) {
367
+ const next = {
368
+ access_token: result.access_token,
369
+ refresh_token: result.refresh_token,
370
+ access_expires_at: result.access_expires_at,
371
+ email
372
+ };
373
+ updateSession(() => next);
374
+ }
393
375
  return {
394
376
  async code(params, options) {
395
377
  return apiConfig.httpClient.post("/v1/auth/code", params, options);
@@ -401,7 +383,7 @@ var createAuthApi = (apiConfig) => {
401
383
  options
402
384
  );
403
385
  if (result?.access_token) {
404
- apiConfig.setToken({ access_token: result.access_token, refresh_token: result.refresh_token });
386
+ applyAuthToken(result, params.email);
405
387
  }
406
388
  return result;
407
389
  },
@@ -418,7 +400,7 @@ var createAuthApi = (apiConfig) => {
418
400
  options
419
401
  );
420
402
  if (result?.access_token) {
421
- apiConfig.setToken({ access_token: result.access_token, refresh_token: result.refresh_token });
403
+ applyAuthToken(result, params.email);
422
404
  }
423
405
  return result;
424
406
  },
@@ -429,7 +411,7 @@ var createAuthApi = (apiConfig) => {
429
411
  };
430
412
 
431
413
  // src/api/store.ts
432
- var createStoreApi = (apiConfig) => {
414
+ var createStoreApi = (apiConfig, updateSession) => {
433
415
  return {
434
416
  async createStore(params, options) {
435
417
  return apiConfig.httpClient.post(`/v1/stores`, params, options);
@@ -494,11 +476,19 @@ var createStoreApi = (apiConfig) => {
494
476
  },
495
477
  async handleInvitation(params, options) {
496
478
  const { store_id, ...payload } = params;
497
- return apiConfig.httpClient.put(
479
+ const result = await apiConfig.httpClient.put(
498
480
  `/v1/stores/${store_id || apiConfig.storeId}/invitation`,
499
481
  payload,
500
482
  options
501
483
  );
484
+ if (params.action === "accept" && result?.access_token) {
485
+ updateSession(() => ({
486
+ access_token: result.access_token,
487
+ refresh_token: result.refresh_token,
488
+ access_expires_at: result.access_expires_at
489
+ }));
490
+ }
491
+ return result;
502
492
  },
503
493
  async testWebhook(params, options) {
504
494
  return apiConfig.httpClient.post(
@@ -618,12 +608,12 @@ var createMediaApi = (apiConfig) => {
618
608
  const formData = new FormData();
619
609
  files.forEach((file) => formData.append("files", file));
620
610
  urls.forEach((url2) => formData.append("urls", url2));
621
- const tokens = await apiConfig.getToken();
611
+ const tokens = apiConfig.authStorage.getTokens();
622
612
  const response = await fetch(url, {
623
613
  method: "POST",
624
614
  body: formData,
625
615
  headers: {
626
- Authorization: `Bearer ${tokens.access_token}`
616
+ Authorization: `Bearer ${tokens?.access_token || ""}`
627
617
  }
628
618
  });
629
619
  if (!response.ok) {
@@ -650,10 +640,10 @@ var createMediaApi = (apiConfig) => {
650
640
  if (sort_field) queryParams.sort_field = sort_field;
651
641
  if (sort_direction) queryParams.sort_direction = sort_direction;
652
642
  const queryString = new URLSearchParams(queryParams).toString();
653
- const tokens = await apiConfig.getToken();
643
+ const tokens = apiConfig.authStorage.getTokens();
654
644
  const response = await fetch(`${url}?${queryString}`, {
655
645
  headers: {
656
- Authorization: `Bearer ${tokens.access_token}`
646
+ Authorization: `Bearer ${tokens?.access_token || ""}`
657
647
  }
658
648
  });
659
649
  if (!response.ok) {
@@ -1257,6 +1247,20 @@ var createActivityAdminApi = (apiConfig) => ({
1257
1247
  `/v1/stores/${store_id}/activities/timeline`,
1258
1248
  { ...options, params: queryParams }
1259
1249
  );
1250
+ },
1251
+ async find(params, options) {
1252
+ const store_id = apiConfig.storeId;
1253
+ const queryParams = {};
1254
+ if (params.customer_id) queryParams.customer_id = params.customer_id;
1255
+ if (params.types && params.types.length > 0) queryParams.types = params.types;
1256
+ if (params.from !== void 0) queryParams.from = params.from;
1257
+ if (params.to !== void 0) queryParams.to = params.to;
1258
+ if (params.limit !== void 0) queryParams.limit = params.limit;
1259
+ if (params.cursor) queryParams.cursor = params.cursor;
1260
+ return apiConfig.httpClient.get(
1261
+ `/v1/stores/${store_id}/activities`,
1262
+ { ...options, params: queryParams }
1263
+ );
1260
1264
  }
1261
1265
  });
1262
1266
  var createCustomerApi = (apiConfig) => {
@@ -1462,6 +1466,26 @@ var createPlatformApi = (apiConfig) => {
1462
1466
  },
1463
1467
  async getWebhookEvents(options) {
1464
1468
  return apiConfig.httpClient.get("/v1/platform/events", options);
1469
+ },
1470
+ data: {
1471
+ async scan(params, options) {
1472
+ return apiConfig.httpClient.get("/v1/platform/data", {
1473
+ ...options,
1474
+ params: { key: params.key, limit: params.limit ?? 200 }
1475
+ });
1476
+ },
1477
+ async put(params, options) {
1478
+ return apiConfig.httpClient.post("/v1/platform/data", params, options);
1479
+ },
1480
+ async delete(params, options) {
1481
+ return apiConfig.httpClient.delete("/v1/platform/data", {
1482
+ ...options,
1483
+ params: { key: params.key }
1484
+ });
1485
+ }
1486
+ },
1487
+ async runScript(params, options) {
1488
+ return apiConfig.httpClient.post("/v1/platform/scripts", params, options);
1465
1489
  }
1466
1490
  };
1467
1491
  };
@@ -1724,14 +1748,11 @@ var createFormApi = (apiConfig) => {
1724
1748
  );
1725
1749
  },
1726
1750
  async getSubmissions(params, options) {
1727
- const { store_id, form_id, ...queryParams } = params;
1751
+ const { store_id, ...queryParams } = params;
1728
1752
  const target_store_id = store_id || apiConfig.storeId;
1729
1753
  return apiConfig.httpClient.get(
1730
- `/v1/stores/${target_store_id}/forms/${form_id}/submissions`,
1731
- {
1732
- ...options,
1733
- params: { ...queryParams, form_id, store_id: target_store_id }
1734
- }
1754
+ `/v1/stores/${target_store_id}/forms/submissions`,
1755
+ { ...options, params: queryParams }
1735
1756
  );
1736
1757
  },
1737
1758
  async getSubmission(params, options) {
@@ -2121,25 +2142,86 @@ function createUtilitySurface(apiConfig) {
2121
2142
  getFirstAvailableFCId
2122
2143
  };
2123
2144
  }
2145
+ var ADMIN_STORAGE_KEY = "arky_admin_session";
2146
+ function readAdminSession() {
2147
+ if (typeof window === "undefined") return null;
2148
+ try {
2149
+ const raw = localStorage.getItem(ADMIN_STORAGE_KEY);
2150
+ return raw ? JSON.parse(raw) : null;
2151
+ } catch {
2152
+ return null;
2153
+ }
2154
+ }
2155
+ function writeAdminSession(s) {
2156
+ if (typeof window === "undefined") return;
2157
+ if (s) {
2158
+ localStorage.setItem(ADMIN_STORAGE_KEY, JSON.stringify(s));
2159
+ } else {
2160
+ localStorage.removeItem(ADMIN_STORAGE_KEY);
2161
+ }
2162
+ }
2124
2163
  function createAdmin(config) {
2125
2164
  const locale = config.locale || "en";
2126
- const getToken = config.getToken || defaultGetToken;
2127
- const setToken = config.setToken || defaultSetToken;
2128
- const logout = config.logout || defaultLogout;
2129
- const isAuthenticated = config.isAuthenticated || defaultIsAuthenticated;
2130
- const httpClient = createHttpClient({ ...config, getToken, setToken, logout });
2165
+ const listeners = /* @__PURE__ */ new Set();
2166
+ function toPublic(s) {
2167
+ return s ? { email: s.email } : null;
2168
+ }
2169
+ function emit() {
2170
+ const pub = toPublic(readAdminSession());
2171
+ for (const l of listeners) {
2172
+ Promise.resolve().then(() => l(pub)).catch(() => {
2173
+ });
2174
+ }
2175
+ }
2176
+ const updateSession = (updater) => {
2177
+ const prev = readAdminSession();
2178
+ const next = updater(prev);
2179
+ writeAdminSession(next);
2180
+ emit();
2181
+ };
2182
+ const authStorage = {
2183
+ getTokens() {
2184
+ const s = readAdminSession();
2185
+ if (!s) return null;
2186
+ return {
2187
+ access_token: s.access_token,
2188
+ refresh_token: s.refresh_token,
2189
+ access_expires_at: s.access_expires_at
2190
+ };
2191
+ },
2192
+ onTokensRefreshed(tokens) {
2193
+ updateSession(
2194
+ (prev) => prev ? {
2195
+ ...prev,
2196
+ access_token: tokens.access_token,
2197
+ refresh_token: tokens.refresh_token ?? prev.refresh_token,
2198
+ access_expires_at: tokens.access_expires_at ?? prev.access_expires_at
2199
+ } : null
2200
+ );
2201
+ },
2202
+ onForcedLogout() {
2203
+ updateSession(() => null);
2204
+ }
2205
+ };
2206
+ const httpClient = createHttpClient({
2207
+ baseUrl: config.baseUrl,
2208
+ storeId: config.storeId,
2209
+ refreshPath: config.refreshPath,
2210
+ navigate: config.navigate,
2211
+ loginFallbackPath: config.loginFallbackPath,
2212
+ authStorage
2213
+ });
2131
2214
  const apiConfig = {
2132
2215
  httpClient,
2133
2216
  storeId: config.storeId,
2134
2217
  baseUrl: config.baseUrl,
2135
2218
  market: config.market,
2136
2219
  locale,
2137
- setToken,
2138
- getToken
2220
+ authStorage
2139
2221
  };
2140
2222
  const accountApi = createAccountApi(apiConfig);
2141
- const authApi = createAuthApi(apiConfig);
2142
- const storeApi = createStoreApi(apiConfig);
2223
+ const authApi = createAuthApi(apiConfig, updateSession);
2224
+ const storeApi = createStoreApi(apiConfig, updateSession);
2143
2225
  const platformApi = createPlatformApi(apiConfig);
2144
2226
  const cmsApi = createCmsApi(apiConfig);
2145
2227
  const eshopApi = createEshopApi(apiConfig);
@@ -2313,9 +2395,26 @@ function createAdmin(config) {
2313
2395
  apiConfig.locale = locale2;
2314
2396
  },
2315
2397
  getLocale: () => apiConfig.locale,
2316
- isAuthenticated,
2317
- logout,
2318
- setToken,
2398
+ get currentSession() {
2399
+ return toPublic(readAdminSession());
2400
+ },
2401
+ get isAuthenticated() {
2402
+ return readAdminSession() !== null;
2403
+ },
2404
+ onAuthStateChanged(listener) {
2405
+ listeners.add(listener);
2406
+ const current = toPublic(readAdminSession());
2407
+ if (current) {
2408
+ Promise.resolve().then(() => listener(current)).catch(() => {
2409
+ });
2410
+ }
2411
+ return () => {
2412
+ listeners.delete(listener);
2413
+ };
2414
+ },
2415
+ async logout() {
2416
+ updateSession(() => null);
2417
+ },
2319
2418
  extractBlockValues,
2320
2419
  utils: createUtilitySurface(apiConfig)
2321
2420
  };