@fajarmaulana/komerce-lp-helper 0.1.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.
@@ -0,0 +1,503 @@
1
+ var __extends = (this && this.__extends) || (function () {
2
+ var extendStatics = function (d, b) {
3
+ extendStatics = Object.setPrototypeOf ||
4
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
5
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
6
+ return extendStatics(d, b);
7
+ };
8
+ return function (d, b) {
9
+ if (typeof b !== "function" && b !== null)
10
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
11
+ extendStatics(d, b);
12
+ function __() { this.constructor = d; }
13
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14
+ };
15
+ })();
16
+ var __assign = (this && this.__assign) || function () {
17
+ __assign = Object.assign || function(t) {
18
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
19
+ s = arguments[i];
20
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
21
+ t[p] = s[p];
22
+ }
23
+ return t;
24
+ };
25
+ return __assign.apply(this, arguments);
26
+ };
27
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
28
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
29
+ return new (P || (P = Promise))(function (resolve, reject) {
30
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
31
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
32
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
33
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
34
+ });
35
+ };
36
+ var __generator = (this && this.__generator) || function (thisArg, body) {
37
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
38
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
39
+ function verb(n) { return function (v) { return step([n, v]); }; }
40
+ function step(op) {
41
+ if (f) throw new TypeError("Generator is already executing.");
42
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
43
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
44
+ if (y = 0, t) op = [op[0] & 2, t.value];
45
+ switch (op[0]) {
46
+ case 0: case 1: t = op; break;
47
+ case 4: _.label++; return { value: op[1], done: false };
48
+ case 5: _.label++; y = op[1]; op = [0]; continue;
49
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
50
+ default:
51
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
52
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
53
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
54
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
55
+ if (t[2]) _.ops.pop();
56
+ _.trys.pop(); continue;
57
+ }
58
+ op = body.call(thisArg, _);
59
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
60
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
61
+ }
62
+ };
63
+ var __read = (this && this.__read) || function (o, n) {
64
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
65
+ if (!m) return o;
66
+ var i = m.call(o), r, ar = [], e;
67
+ try {
68
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
69
+ }
70
+ catch (error) { e = { error: error }; }
71
+ finally {
72
+ try {
73
+ if (r && !r.done && (m = i["return"])) m.call(i);
74
+ }
75
+ finally { if (e) throw e.error; }
76
+ }
77
+ return ar;
78
+ };
79
+ export var buildURL = function (url, params) {
80
+ if (!params)
81
+ return url;
82
+ var queryString = Object.entries(params)
83
+ .map(function (_a) {
84
+ var _b = __read(_a, 2), key = _b[0], value = _b[1];
85
+ if (Array.isArray(value)) {
86
+ var joined = value.map(function (v) { return encodeURIComponent(v); }).join(",");
87
+ return "".concat(encodeURIComponent(key), "=").concat(joined);
88
+ }
89
+ return "".concat(encodeURIComponent(key), "=").concat(encodeURIComponent(value));
90
+ })
91
+ .join("&");
92
+ return url.includes("?") ? "".concat(url, "&").concat(queryString) : "".concat(url, "?").concat(queryString);
93
+ };
94
+ var ApiMeta = /** @class */ (function (_super) {
95
+ __extends(ApiMeta, _super);
96
+ function ApiMeta(code, message, status) {
97
+ var _this = _super.call(this, message) || this;
98
+ _this.code = code;
99
+ _this.status = status;
100
+ return _this;
101
+ }
102
+ return ApiMeta;
103
+ }(Error));
104
+ export { ApiMeta };
105
+ var ApiInstance = /** @class */ (function () {
106
+ function ApiInstance(options) {
107
+ if (options === void 0) { options = {}; }
108
+ this.interceptors = {};
109
+ this.baseURL = options.baseURL || "";
110
+ this.defaultHeaders = options.headers || {};
111
+ this.source = "komcards-".concat(options.source || "default");
112
+ this.cache = new Map();
113
+ this.maxCacheSize = options.maxCacheSize || 100;
114
+ this.cacheAccessOrder = [];
115
+ }
116
+ ApiInstance.prototype.setInterceptors = function (interceptors) {
117
+ this.interceptors = interceptors;
118
+ };
119
+ ApiInstance.prototype.hash = function (str) {
120
+ var hash = 0;
121
+ for (var i = 0; i < str.length; i++) {
122
+ var char = str.charCodeAt(i);
123
+ hash = (hash << 5) - hash + char;
124
+ hash = hash & hash;
125
+ }
126
+ return hash.toString(36);
127
+ };
128
+ ApiInstance.prototype.buildcacheKey = function (config) {
129
+ var keyObj = {
130
+ url: config.url,
131
+ params: config.params,
132
+ };
133
+ var keyString = JSON.stringify(keyObj);
134
+ if (keyString.length > 200) {
135
+ return "".concat(this.source, ":").concat(this.hash(keyString));
136
+ }
137
+ return "".concat(this.source, ":").concat(keyString);
138
+ };
139
+ ApiInstance.prototype.fetchWithXHR = function (input, init, onUpload, onDownload) {
140
+ return __awaiter(this, void 0, void 0, function () {
141
+ return __generator(this, function (_a) {
142
+ return [2 /*return*/, new Promise(function (resolve, reject) {
143
+ var xhr = new XMLHttpRequest();
144
+ var method = (init.method || "GET").toUpperCase();
145
+ xhr.open(method, input);
146
+ if (init.headers) {
147
+ var headers = new Headers(init.headers);
148
+ headers.forEach(function (value, key) {
149
+ xhr.setRequestHeader(key, value);
150
+ });
151
+ }
152
+ if (onUpload && xhr.upload) {
153
+ xhr.upload.addEventListener("progress", function (e) {
154
+ var total = e.lengthComputable ? e.total : 0;
155
+ var percentage = e.lengthComputable ? Math.round((e.loaded / e.total) * 100) : 0;
156
+ onUpload({
157
+ loaded: e.loaded,
158
+ total: total,
159
+ percentage: percentage,
160
+ });
161
+ });
162
+ }
163
+ if (onDownload) {
164
+ xhr.responseType = "blob";
165
+ xhr.addEventListener("progress", function (e) {
166
+ var total = e.lengthComputable ? e.total : 0;
167
+ var percentage = e.lengthComputable ? Math.round((e.loaded / e.total) * 100) : 0;
168
+ onDownload({
169
+ loaded: e.loaded,
170
+ total: total,
171
+ percentage: percentage,
172
+ });
173
+ });
174
+ }
175
+ if (init.signal) {
176
+ init.signal.addEventListener("abort", function () {
177
+ xhr.abort();
178
+ reject(new DOMException("The operation was aborted.", "AbortError"));
179
+ });
180
+ }
181
+ xhr.onload = function () {
182
+ var headers = new Headers();
183
+ xhr
184
+ .getAllResponseHeaders()
185
+ .split("\r\n")
186
+ .forEach(function (line) {
187
+ var parts = line.split(": ");
188
+ if (parts.length === 2) {
189
+ headers.append(parts[0], parts[1]);
190
+ }
191
+ });
192
+ var response = new Response(xhr.response, {
193
+ status: xhr.status,
194
+ statusText: xhr.statusText,
195
+ headers: headers,
196
+ });
197
+ resolve(response);
198
+ };
199
+ xhr.onerror = function () { return reject(new TypeError("Network request failed")); };
200
+ xhr.ontimeout = function () { return reject(new TypeError("Network request timeout")); };
201
+ xhr.send(init.body);
202
+ })];
203
+ });
204
+ });
205
+ };
206
+ ApiInstance.prototype.fetchWithRetry = function (input, init, retry, signal, onUpload, onDownload) {
207
+ return __awaiter(this, void 0, void 0, function () {
208
+ var attempt, lastErr, _loop_1, this_1, state_1;
209
+ return __generator(this, function (_a) {
210
+ switch (_a.label) {
211
+ case 0:
212
+ attempt = 0;
213
+ _loop_1 = function () {
214
+ var res, clonedRes, error, code, message, status_1, err_1, delay_1;
215
+ return __generator(this, function (_b) {
216
+ switch (_b.label) {
217
+ case 0:
218
+ _b.trys.push([0, 7, , 9]);
219
+ res = void 0;
220
+ if (!(onUpload || onDownload)) return [3 /*break*/, 2];
221
+ return [4 /*yield*/, this_1.fetchWithXHR(input, __assign(__assign({}, init), { signal: signal }), onUpload, onDownload)];
222
+ case 1:
223
+ res = _b.sent();
224
+ return [3 /*break*/, 4];
225
+ case 2: return [4 /*yield*/, fetch(input, __assign(__assign({}, init), { signal: signal }))];
226
+ case 3:
227
+ res = _b.sent();
228
+ _b.label = 4;
229
+ case 4:
230
+ if (!!res.ok) return [3 /*break*/, 6];
231
+ clonedRes = res.clone();
232
+ return [4 /*yield*/, clonedRes.json()];
233
+ case 5:
234
+ error = _b.sent();
235
+ if (error.meta || error.status) {
236
+ code = error.code || error.meta.code || res.status;
237
+ message = error.message || error.meta.message || JSON.stringify(error);
238
+ status_1 = error.status || error.meta.status || res.statusText;
239
+ throw new ApiMeta(code, message, status_1);
240
+ }
241
+ throw error;
242
+ case 6: return [2 /*return*/, { value: res }];
243
+ case 7:
244
+ err_1 = _b.sent();
245
+ if (err_1 instanceof Error && err_1.name === "AbortError") {
246
+ throw err_1;
247
+ }
248
+ lastErr = err_1;
249
+ if (attempt === retry)
250
+ throw lastErr;
251
+ delay_1 = Math.pow(2, attempt) * 200;
252
+ return [4 /*yield*/, new Promise(function (r) { return setTimeout(r, delay_1); })];
253
+ case 8:
254
+ _b.sent();
255
+ attempt++;
256
+ return [3 /*break*/, 9];
257
+ case 9: return [2 /*return*/];
258
+ }
259
+ });
260
+ };
261
+ this_1 = this;
262
+ _a.label = 1;
263
+ case 1:
264
+ if (!(attempt <= retry)) return [3 /*break*/, 3];
265
+ return [5 /*yield**/, _loop_1()];
266
+ case 2:
267
+ state_1 = _a.sent();
268
+ if (typeof state_1 === "object")
269
+ return [2 /*return*/, state_1.value];
270
+ return [3 /*break*/, 1];
271
+ case 3: throw lastErr;
272
+ }
273
+ });
274
+ });
275
+ };
276
+ ApiInstance.prototype.handleInterceptors = function (config) {
277
+ return __awaiter(this, void 0, void 0, function () {
278
+ return __generator(this, function (_a) {
279
+ switch (_a.label) {
280
+ case 0:
281
+ if (!this.interceptors.request) return [3 /*break*/, 2];
282
+ return [4 /*yield*/, this.interceptors.request(config)];
283
+ case 1: return [2 /*return*/, _a.sent()];
284
+ case 2: return [2 /*return*/, config];
285
+ }
286
+ });
287
+ });
288
+ };
289
+ ApiInstance.prototype.handleResponse = function (response) {
290
+ return __awaiter(this, void 0, void 0, function () {
291
+ return __generator(this, function (_a) {
292
+ switch (_a.label) {
293
+ case 0:
294
+ if (!this.interceptors.response) return [3 /*break*/, 2];
295
+ return [4 /*yield*/, this.interceptors.response(response)];
296
+ case 1: return [2 /*return*/, _a.sent()];
297
+ case 2: return [2 /*return*/, response];
298
+ }
299
+ });
300
+ });
301
+ };
302
+ ApiInstance.prototype.handleError = function (error) {
303
+ return __awaiter(this, void 0, void 0, function () {
304
+ return __generator(this, function (_a) {
305
+ switch (_a.label) {
306
+ case 0:
307
+ if (!this.interceptors.error) return [3 /*break*/, 2];
308
+ return [4 /*yield*/, this.interceptors.error(error)];
309
+ case 1: return [2 /*return*/, _a.sent()];
310
+ case 2: throw error;
311
+ }
312
+ });
313
+ });
314
+ };
315
+ ApiInstance.prototype.getCacheEntry = function (key) {
316
+ var entry = this.cache.get(key);
317
+ if (entry) {
318
+ var index = this.cacheAccessOrder.indexOf(key);
319
+ if (index > -1) {
320
+ this.cacheAccessOrder.splice(index, 1);
321
+ }
322
+ this.cacheAccessOrder.push(key);
323
+ }
324
+ return entry;
325
+ };
326
+ ApiInstance.prototype.setCacheEntry = function (key, entry) {
327
+ if (this.cache.size >= this.maxCacheSize && !this.cache.has(key)) {
328
+ var oldestKey = this.cacheAccessOrder.shift();
329
+ if (oldestKey) {
330
+ this.cache.delete(oldestKey);
331
+ }
332
+ }
333
+ this.cache.set(key, entry);
334
+ var index = this.cacheAccessOrder.indexOf(key);
335
+ if (index > -1) {
336
+ this.cacheAccessOrder.splice(index, 1);
337
+ }
338
+ this.cacheAccessOrder.push(key);
339
+ };
340
+ ApiInstance.prototype.removeCacheEntry = function (key) {
341
+ this.cache.delete(key);
342
+ var index = this.cacheAccessOrder.indexOf(key);
343
+ if (index > -1) {
344
+ this.cacheAccessOrder.splice(index, 1);
345
+ }
346
+ };
347
+ ApiInstance.prototype.request = function (config) {
348
+ return __awaiter(this, void 0, void 0, function () {
349
+ var finalConfig, cacheKey, cached, expired, url, finalURL, isFormData, response, finalResponse, error, code, message, status_2, _a, errorText, contentType, data, error_1;
350
+ var _b, _c;
351
+ return __generator(this, function (_d) {
352
+ switch (_d.label) {
353
+ case 0:
354
+ _d.trys.push([0, 15, , 16]);
355
+ return [4 /*yield*/, this.handleInterceptors(config)];
356
+ case 1:
357
+ finalConfig = _d.sent();
358
+ cacheKey = this.buildcacheKey(finalConfig);
359
+ if (finalConfig.cache && finalConfig.cache.enabled && finalConfig.method === "GET") {
360
+ cached = this.getCacheEntry(cacheKey);
361
+ if (cached) {
362
+ expired = cached.ttl && Date.now() - cached.timestamp > cached.ttl;
363
+ if (!expired) {
364
+ return [2 /*return*/, { data: cached.data, cacheKey: cacheKey, fromCache: true }];
365
+ }
366
+ this.removeCacheEntry(cacheKey);
367
+ }
368
+ }
369
+ url = this.baseURL ? "".concat(this.baseURL).concat(finalConfig.url) : finalConfig.url;
370
+ finalURL = buildURL(url, finalConfig.params);
371
+ isFormData = finalConfig.body instanceof FormData;
372
+ return [4 /*yield*/, this.fetchWithRetry(finalURL, {
373
+ method: finalConfig.method || "GET",
374
+ headers: __assign(__assign(__assign({}, (isFormData ? {} : { "Content-Type": "application/json" })), this.defaultHeaders), finalConfig.headers),
375
+ body: isFormData
376
+ ? finalConfig.body
377
+ : finalConfig.body
378
+ ? JSON.stringify(finalConfig.body)
379
+ : undefined,
380
+ }, (_b = finalConfig.retry) !== null && _b !== void 0 ? _b : 0, finalConfig.signal, finalConfig.onUpload, finalConfig.onDownload)];
381
+ case 2:
382
+ response = _d.sent();
383
+ return [4 /*yield*/, this.handleResponse(response)];
384
+ case 3:
385
+ finalResponse = _d.sent();
386
+ if (!!finalResponse.ok) return [3 /*break*/, 8];
387
+ _d.label = 4;
388
+ case 4:
389
+ _d.trys.push([4, 6, , 8]);
390
+ return [4 /*yield*/, finalResponse.clone().json()];
391
+ case 5:
392
+ error = _d.sent();
393
+ if (error.meta || error.status) {
394
+ code = error.code || error.meta.code || finalResponse.status;
395
+ message = error.message || error.meta.message || JSON.stringify(error);
396
+ status_2 = error.status || error.meta.status || finalResponse.statusText;
397
+ throw new ApiMeta(code, message, status_2);
398
+ }
399
+ throw error;
400
+ case 6:
401
+ _a = _d.sent();
402
+ return [4 /*yield*/, finalResponse.text()];
403
+ case 7:
404
+ errorText = _d.sent();
405
+ throw new Error(errorText || finalResponse.statusText);
406
+ case 8:
407
+ contentType = finalResponse.headers.get("content-type") || "";
408
+ data = void 0;
409
+ if (!contentType.includes("application/json")) return [3 /*break*/, 10];
410
+ return [4 /*yield*/, finalResponse.json()];
411
+ case 9:
412
+ data = (_d.sent());
413
+ return [3 /*break*/, 14];
414
+ case 10:
415
+ if (!contentType.includes("text/")) return [3 /*break*/, 12];
416
+ return [4 /*yield*/, finalResponse.text()];
417
+ case 11:
418
+ data = (_d.sent());
419
+ return [3 /*break*/, 14];
420
+ case 12: return [4 /*yield*/, finalResponse.blob()];
421
+ case 13:
422
+ data = (_d.sent());
423
+ _d.label = 14;
424
+ case 14:
425
+ if (finalConfig.cache && finalConfig.cache.enabled && finalConfig.method === "GET") {
426
+ this.setCacheEntry(cacheKey, {
427
+ data: data,
428
+ timestamp: Date.now(),
429
+ ttl: (_c = finalConfig.cache) === null || _c === void 0 ? void 0 : _c.revalidate,
430
+ });
431
+ }
432
+ return [2 /*return*/, { data: data, cacheKey: cacheKey, fromCache: false }];
433
+ case 15:
434
+ error_1 = _d.sent();
435
+ return [2 /*return*/, this.handleError(error_1)];
436
+ case 16: return [2 /*return*/];
437
+ }
438
+ });
439
+ });
440
+ };
441
+ ApiInstance.prototype.get = function (url, config) {
442
+ if (config === void 0) { config = {}; }
443
+ return this.request(__assign(__assign({}, config), { url: url, method: "GET" }));
444
+ };
445
+ ApiInstance.prototype.post = function (url, body, config) {
446
+ if (config === void 0) { config = {}; }
447
+ return this.request(__assign(__assign({}, config), { url: url, method: "POST", body: body }));
448
+ };
449
+ ApiInstance.prototype.put = function (url, body, config) {
450
+ if (config === void 0) { config = {}; }
451
+ return this.request(__assign(__assign({}, config), { url: url, method: "PUT", body: body }));
452
+ };
453
+ ApiInstance.prototype.patch = function (url, body, config) {
454
+ if (config === void 0) { config = {}; }
455
+ return this.request(__assign(__assign({}, config), { url: url, method: "PATCH", body: body }));
456
+ };
457
+ ApiInstance.prototype.delete = function (url, body, config) {
458
+ if (config === void 0) { config = {}; }
459
+ return this.request(__assign(__assign({}, config), { url: url, method: "DELETE", body: body }));
460
+ };
461
+ ApiInstance.prototype.getCache = function (key) {
462
+ var entry = this.getCacheEntry(key);
463
+ return entry === null || entry === void 0 ? void 0 : entry.data;
464
+ };
465
+ ApiInstance.prototype.setCache = function (key, data, ttl) {
466
+ this.setCacheEntry(key, { data: data, timestamp: Date.now(), ttl: ttl });
467
+ };
468
+ ApiInstance.prototype.removeCache = function (key) {
469
+ this.removeCacheEntry(key);
470
+ };
471
+ ApiInstance.prototype.clearCache = function () {
472
+ this.cache.clear();
473
+ this.cacheAccessOrder = [];
474
+ };
475
+ return ApiInstance;
476
+ }());
477
+ export { ApiInstance };
478
+ var instance = new ApiInstance();
479
+ var http = {
480
+ get: function (url, config) { return instance.get(url, config); },
481
+ post: function (url, body, config) {
482
+ return instance.post(url, body, config);
483
+ },
484
+ put: function (url, body, config) {
485
+ return instance.put(url, body, config);
486
+ },
487
+ patch: function (url, body, config) {
488
+ return instance.patch(url, body, config);
489
+ },
490
+ delete: function (url, body, config) {
491
+ return instance.delete(url, body, config);
492
+ },
493
+ getCache: function (key) { return instance.getCache(key); },
494
+ setCache: function (key, data, ttl) { return instance.setCache(key, data, ttl); },
495
+ removeCache: function (key) { return instance.removeCache(key); },
496
+ clearCache: function () { return instance.clearCache(); },
497
+ request: function (config) { return instance.request(config); },
498
+ create: function (options) {
499
+ if (options === void 0) { options = {}; }
500
+ return new ApiInstance(options);
501
+ },
502
+ };
503
+ export default http;
@@ -0,0 +1,50 @@
1
+ type TCookie<T> = {
2
+ key: string;
3
+ value: T;
4
+ maxAge?: number;
5
+ };
6
+ /**
7
+ * Sets a cookie with the specified key, value, and optional max age.
8
+ *
9
+ * @param key - The cookie key.
10
+ * @param value - The cookie value (will be JSON-stringified).
11
+ * @param maxAge - Optional max age of the cookie in seconds.
12
+ */
13
+ export declare const setCookie: <T>({ key, value, maxAge }: TCookie<T>) => void;
14
+ /**
15
+ * Sets multiple cookies from an array of cookie objects.
16
+ *
17
+ * @param items - Array of cookies to set.
18
+ */
19
+ export declare const setCookies: (items: TCookie<unknown>[]) => void;
20
+ /**
21
+ * Gets the value of a cookie by key and parses it from JSON.
22
+ *
23
+ * @param key - The key of the cookie to get.
24
+ * @returns The parsed cookie value, or null if not found.
25
+ */
26
+ export declare const getCookie: <T>(key: string) => T | null;
27
+ /**
28
+ * Retrieves multiple cookies by keys.
29
+ *
30
+ * @param keys - Array of keys to retrieve.
31
+ * @returns Object with keys and their corresponding parsed values.
32
+ */
33
+ export declare const getCookies: <T extends Record<string, unknown>, K extends keyof T = keyof T>(keys: readonly K[]) => { [P in K]: T[P] | null; };
34
+ /**
35
+ * Removes a cookie by key by setting its max age to 0.
36
+ *
37
+ * @param key - The key of the cookie to remove.
38
+ */
39
+ export declare const removeCookie: (key: string) => void;
40
+ /**
41
+ * Removes multiple cookies by keys.
42
+ *
43
+ * @param keys - Array of keys to remove.
44
+ */
45
+ export declare const removeCookies: (keys: string[]) => void;
46
+ /**
47
+ * Clears all cookies by setting their max age to 0.
48
+ */
49
+ export declare const clearCookies: () => void;
50
+ export {};
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Sets a cookie with the specified key, value, and optional max age.
3
+ *
4
+ * @param key - The cookie key.
5
+ * @param value - The cookie value (will be JSON-stringified).
6
+ * @param maxAge - Optional max age of the cookie in seconds.
7
+ */
8
+ export var setCookie = function (_a) {
9
+ var key = _a.key, value = _a.value, maxAge = _a.maxAge;
10
+ var serializedValue = JSON.stringify(value);
11
+ document.cookie = "".concat(key, "=").concat(serializedValue).concat(maxAge ? "; Max-Age=".concat(maxAge) : '', "; Secure; SameSite=Strict; path=/");
12
+ };
13
+ /**
14
+ * Sets multiple cookies from an array of cookie objects.
15
+ *
16
+ * @param items - Array of cookies to set.
17
+ */
18
+ export var setCookies = function (items) {
19
+ items.forEach(function (item) { return setCookie(item); });
20
+ };
21
+ /**
22
+ * Gets the value of a cookie by key and parses it from JSON.
23
+ *
24
+ * @param key - The key of the cookie to get.
25
+ * @returns The parsed cookie value, or null if not found.
26
+ */
27
+ export var getCookie = function (key) {
28
+ var match = document.cookie.match(new RegExp('(^| )' + key + '=([^;]+)'));
29
+ if (!match)
30
+ return null;
31
+ try {
32
+ return JSON.parse(decodeURIComponent(match[2]));
33
+ }
34
+ catch (_a) {
35
+ return decodeURIComponent(match[2]);
36
+ }
37
+ };
38
+ /**
39
+ * Retrieves multiple cookies by keys.
40
+ *
41
+ * @param keys - Array of keys to retrieve.
42
+ * @returns Object with keys and their corresponding parsed values.
43
+ */
44
+ export var getCookies = function (keys) {
45
+ return keys.reduce(function (acc, key) {
46
+ acc[key] = getCookie(key);
47
+ return acc;
48
+ }, {});
49
+ };
50
+ /**
51
+ * Removes a cookie by key by setting its max age to 0.
52
+ *
53
+ * @param key - The key of the cookie to remove.
54
+ */
55
+ export var removeCookie = function (key) {
56
+ document.cookie = "".concat(key, "=; Max-Age=0; Secure; SameSite=Strict; path=/");
57
+ };
58
+ /**
59
+ * Removes multiple cookies by keys.
60
+ *
61
+ * @param keys - Array of keys to remove.
62
+ */
63
+ export var removeCookies = function (keys) {
64
+ keys.forEach(function (key) { return removeCookie(key); });
65
+ };
66
+ /**
67
+ * Clears all cookies by setting their max age to 0.
68
+ */
69
+ export var clearCookies = function () {
70
+ document.cookie.split('; ').forEach(function (cookie) {
71
+ var eqPos = cookie.indexOf('=');
72
+ var key = eqPos > -1 ? cookie.substring(0, eqPos) : cookie;
73
+ removeCookie(key);
74
+ });
75
+ };