cookie-es 1.2.2 → 3.0.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/dist/index.mjs CHANGED
@@ -1,262 +1,407 @@
1
+ //#region src/_utils.ts
2
+ /**
3
+ * RFC 6265bis cookie-age-limit: 400 days in seconds.
4
+ */
5
+ const COOKIE_MAX_AGE_LIMIT = 400 * 24 * 60 * 60;
6
+ /**
7
+ * Find the `;` character between `min` and `len` in str.
8
+ */
9
+ function endIndex(str, min, len) {
10
+ const index = str.indexOf(";", min);
11
+ return index === -1 ? len : index;
12
+ }
13
+ /**
14
+ * Find the `=` character between `min` and `max` in str.
15
+ */
16
+ function eqIndex(str, min, max) {
17
+ const index = str.indexOf("=", min);
18
+ return index < max ? index : -1;
19
+ }
20
+ /**
21
+ * Slice out a value between start to max.
22
+ */
23
+ function valueSlice(str, min, max) {
24
+ if (min === max) return "";
25
+ let start = min;
26
+ let end = max;
27
+ do {
28
+ const code = str.charCodeAt(start);
29
+ if (code !== 32 && code !== 9) break;
30
+ } while (++start < end);
31
+ while (end > start) {
32
+ const code = str.charCodeAt(end - 1);
33
+ if (code !== 32 && code !== 9) break;
34
+ end--;
35
+ }
36
+ return str.slice(start, end);
37
+ }
38
+ //#endregion
39
+ //#region src/cookie/parse.ts
40
+ const NullObject = /* @__PURE__ */ (() => {
41
+ const C = function() {};
42
+ C.prototype = Object.create(null);
43
+ return C;
44
+ })();
1
45
  function parse(str, options) {
2
- if (typeof str !== "string") {
3
- throw new TypeError("argument str must be a string");
4
- }
5
- const obj = {};
6
- const opt = options || {};
7
- const dec = opt.decode || decode;
8
- let index = 0;
9
- while (index < str.length) {
10
- const eqIdx = str.indexOf("=", index);
11
- if (eqIdx === -1) {
12
- break;
13
- }
14
- let endIdx = str.indexOf(";", index);
15
- if (endIdx === -1) {
16
- endIdx = str.length;
17
- } else if (endIdx < eqIdx) {
18
- index = str.lastIndexOf(";", eqIdx - 1) + 1;
19
- continue;
20
- }
21
- const key = str.slice(index, eqIdx).trim();
22
- if (opt?.filter && !opt?.filter(key)) {
23
- index = endIdx + 1;
24
- continue;
25
- }
26
- if (void 0 === obj[key]) {
27
- let val = str.slice(eqIdx + 1, endIdx).trim();
28
- if (val.codePointAt(0) === 34) {
29
- val = val.slice(1, -1);
30
- }
31
- obj[key] = tryDecode(val, dec);
32
- }
33
- index = endIdx + 1;
34
- }
35
- return obj;
46
+ const obj = new NullObject();
47
+ const len = str.length;
48
+ if (len < 2) return obj;
49
+ const dec = options?.decode || decode;
50
+ const allowMultiple = options?.allowMultiple || false;
51
+ let index = 0;
52
+ do {
53
+ const eqIdx = eqIndex(str, index, len);
54
+ if (eqIdx === -1) break;
55
+ const endIdx = endIndex(str, index, len);
56
+ if (eqIdx > endIdx) {
57
+ index = str.lastIndexOf(";", eqIdx - 1) + 1;
58
+ continue;
59
+ }
60
+ const key = valueSlice(str, index, eqIdx);
61
+ if (options?.filter && !options.filter(key)) {
62
+ index = endIdx + 1;
63
+ continue;
64
+ }
65
+ const val = dec(valueSlice(str, eqIdx + 1, endIdx));
66
+ if (allowMultiple) {
67
+ const existing = obj[key];
68
+ if (existing === void 0) obj[key] = val;
69
+ else if (Array.isArray(existing)) existing.push(val);
70
+ else obj[key] = [existing, val];
71
+ } else if (obj[key] === void 0) obj[key] = val;
72
+ index = endIdx + 1;
73
+ } while (index < len);
74
+ return obj;
36
75
  }
76
+ /**
77
+ * URL-decode string value. Optimized to skip native call when no %.
78
+ */
37
79
  function decode(str) {
38
- return str.includes("%") ? decodeURIComponent(str) : str;
80
+ if (!str.includes("%")) return str;
81
+ try {
82
+ return decodeURIComponent(str);
83
+ } catch {
84
+ return str;
85
+ }
39
86
  }
40
- function tryDecode(str, decode2) {
41
- try {
42
- return decode2(str);
43
- } catch {
44
- return str;
45
- }
87
+ //#endregion
88
+ //#region src/cookie/serialize.ts
89
+ /**
90
+ * RegExp to match cookie-name in RFC 6265bis sec 4.1.1
91
+ * This refers out to the obsoleted definition of token in RFC 2616 sec 2.2
92
+ * which has been replaced by the token definition in RFC 7230 appendix B.
93
+ *
94
+ * cookie-name = token
95
+ * token = 1*tchar
96
+ * tchar = "!" / "#" / "$" / "%" / "&" / "'" /
97
+ * "*" / "+" / "-" / "." / "^" / "_" /
98
+ * "`" / "|" / "~" / DIGIT / ALPHA
99
+ *
100
+ * Note: Allowing more characters - https://github.com/jshttp/cookie/issues/191
101
+ * Allow same range as cookie value, except `=`, which delimits end of name.
102
+ */
103
+ const cookieNameRegExp = /^[\u0021-\u003A\u003C\u003E-\u007E]+$/;
104
+ /**
105
+ * RegExp to match cookie-value in RFC 6265bis sec 4.1.1
106
+ *
107
+ * cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
108
+ * cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
109
+ * ; US-ASCII characters excluding CTLs,
110
+ * ; whitespace DQUOTE, comma, semicolon,
111
+ * ; and backslash
112
+ *
113
+ * Allowing more characters: https://github.com/jshttp/cookie/issues/191
114
+ * Comma, backslash, and DQUOTE are not part of the parsing algorithm.
115
+ */
116
+ const cookieValueRegExp = /^[\u0021-\u003A\u003C-\u007E]*$/;
117
+ /**
118
+ * RegExp to match domain-value in RFC 6265bis sec 4.1.1
119
+ *
120
+ * domain-value = <subdomain>
121
+ * ; defined in [RFC1034], Section 3.5, as
122
+ * ; enhanced by [RFC1123], Section 2.1
123
+ * <subdomain> = <label> | <subdomain> "." <label>
124
+ * <label> = <let-dig> [ [ <ldh-str> ] <let-dig> ]
125
+ * Labels must be 63 characters or less.
126
+ * 'let-dig' not 'letter' in the first char, per RFC1123
127
+ * <ldh-str> = <let-dig-hyp> | <let-dig-hyp> <ldh-str>
128
+ * <let-dig-hyp> = <let-dig> | "-"
129
+ * <let-dig> = <letter> | <digit>
130
+ * <letter> = any one of the 52 alphabetic characters A through Z in
131
+ * upper case and a through z in lower case
132
+ * <digit> = any one of the ten digits 0 through 9
133
+ *
134
+ * Keep support for leading dot: https://github.com/jshttp/cookie/issues/173
135
+ *
136
+ * > (Note that a leading %x2E ("."), if present, is ignored even though that
137
+ * character is not permitted, but a trailing %x2E ("."), if present, will
138
+ * cause the user agent to ignore the attribute.)
139
+ */
140
+ const domainValueRegExp = /^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i;
141
+ /**
142
+ * RegExp to match path-value in RFC 6265bis sec 4.1.1
143
+ *
144
+ * path-value = <any CHAR except CTLs or ";">
145
+ * CHAR = %x01-7F
146
+ * ; defined in RFC 5234 appendix B.1
147
+ */
148
+ const pathValueRegExp = /^[\u0020-\u003A\u003C-\u007E]*$/;
149
+ const __toString = Object.prototype.toString;
150
+ /**
151
+ * Stringifies an object into an HTTP `Cookie` header.
152
+ */
153
+ function stringifyCookie(cookie, options) {
154
+ const enc = options?.encode || encodeURIComponent;
155
+ const keys = Object.keys(cookie);
156
+ let str = "";
157
+ for (const [i, name] of keys.entries()) {
158
+ const val = cookie[name];
159
+ if (val === void 0) continue;
160
+ if (!cookieNameRegExp.test(name)) throw new TypeError(`cookie name is invalid: ${name}`);
161
+ const value = enc(val);
162
+ if (!cookieValueRegExp.test(value)) throw new TypeError(`cookie val is invalid: ${val}`);
163
+ if (i > 0) str += "; ";
164
+ str += name + "=" + value;
165
+ }
166
+ return str;
46
167
  }
47
-
48
- const fieldContentRegExp = /^[\u0009\u0020-\u007E\u0080-\u00FF]+$/;
49
- function serialize(name, value, options) {
50
- const opt = options || {};
51
- const enc = opt.encode || encodeURIComponent;
52
- if (typeof enc !== "function") {
53
- throw new TypeError("option encode is invalid");
54
- }
55
- if (!fieldContentRegExp.test(name)) {
56
- throw new TypeError("argument name is invalid");
57
- }
58
- const encodedValue = enc(value);
59
- if (encodedValue && !fieldContentRegExp.test(encodedValue)) {
60
- throw new TypeError("argument val is invalid");
61
- }
62
- let str = name + "=" + encodedValue;
63
- if (void 0 !== opt.maxAge && opt.maxAge !== null) {
64
- const maxAge = opt.maxAge - 0;
65
- if (Number.isNaN(maxAge) || !Number.isFinite(maxAge)) {
66
- throw new TypeError("option maxAge is invalid");
67
- }
68
- str += "; Max-Age=" + Math.floor(maxAge);
69
- }
70
- if (opt.domain) {
71
- if (!fieldContentRegExp.test(opt.domain)) {
72
- throw new TypeError("option domain is invalid");
73
- }
74
- str += "; Domain=" + opt.domain;
75
- }
76
- if (opt.path) {
77
- if (!fieldContentRegExp.test(opt.path)) {
78
- throw new TypeError("option path is invalid");
79
- }
80
- str += "; Path=" + opt.path;
81
- }
82
- if (opt.expires) {
83
- if (!isDate(opt.expires) || Number.isNaN(opt.expires.valueOf())) {
84
- throw new TypeError("option expires is invalid");
85
- }
86
- str += "; Expires=" + opt.expires.toUTCString();
87
- }
88
- if (opt.httpOnly) {
89
- str += "; HttpOnly";
90
- }
91
- if (opt.secure) {
92
- str += "; Secure";
93
- }
94
- if (opt.priority) {
95
- const priority = typeof opt.priority === "string" ? opt.priority.toLowerCase() : opt.priority;
96
- switch (priority) {
97
- case "low": {
98
- str += "; Priority=Low";
99
- break;
100
- }
101
- case "medium": {
102
- str += "; Priority=Medium";
103
- break;
104
- }
105
- case "high": {
106
- str += "; Priority=High";
107
- break;
108
- }
109
- default: {
110
- throw new TypeError("option priority is invalid");
111
- }
112
- }
113
- }
114
- if (opt.sameSite) {
115
- const sameSite = typeof opt.sameSite === "string" ? opt.sameSite.toLowerCase() : opt.sameSite;
116
- switch (sameSite) {
117
- case true: {
118
- str += "; SameSite=Strict";
119
- break;
120
- }
121
- case "lax": {
122
- str += "; SameSite=Lax";
123
- break;
124
- }
125
- case "strict": {
126
- str += "; SameSite=Strict";
127
- break;
128
- }
129
- case "none": {
130
- str += "; SameSite=None";
131
- break;
132
- }
133
- default: {
134
- throw new TypeError("option sameSite is invalid");
135
- }
136
- }
137
- }
138
- if (opt.partitioned) {
139
- str += "; Partitioned";
140
- }
141
- return str;
168
+ function serialize(_name, _val, _opts) {
169
+ const cookie = typeof _name === "object" ? _name : {
170
+ ..._opts,
171
+ name: _name,
172
+ value: String(_val)
173
+ };
174
+ const enc = (typeof _val === "object" ? _val : _opts)?.encode || encodeURIComponent;
175
+ if (!cookieNameRegExp.test(cookie.name)) throw new TypeError(`argument name is invalid: ${cookie.name}`);
176
+ const value = cookie.value ? enc(cookie.value) : "";
177
+ if (!cookieValueRegExp.test(value)) throw new TypeError(`argument val is invalid: ${cookie.value}`);
178
+ if (!cookie.secure) {
179
+ if (cookie.partitioned) throw new TypeError(`Partitioned cookies must have the Secure attribute`);
180
+ if (cookie.sameSite && String(cookie.sameSite).toLowerCase() === "none") throw new TypeError(`SameSite=None cookies must have the Secure attribute`);
181
+ if (cookie.name.length > 9 && cookie.name.charCodeAt(0) === 95 && cookie.name.charCodeAt(1) === 95) {
182
+ const nameLower = cookie.name.toLowerCase();
183
+ if (nameLower.startsWith("__secure-") || nameLower.startsWith("__host-")) throw new TypeError(`${cookie.name} cookies must have the Secure attribute`);
184
+ }
185
+ }
186
+ if (cookie.name.length > 7 && cookie.name.charCodeAt(0) === 95 && cookie.name.charCodeAt(1) === 95 && cookie.name.toLowerCase().startsWith("__host-")) {
187
+ if (cookie.path !== "/") throw new TypeError(`__Host- cookies must have Path=/`);
188
+ if (cookie.domain) throw new TypeError(`__Host- cookies must not have a Domain attribute`);
189
+ }
190
+ let str = cookie.name + "=" + value;
191
+ if (cookie.maxAge !== void 0) {
192
+ if (!Number.isInteger(cookie.maxAge)) throw new TypeError(`option maxAge is invalid: ${cookie.maxAge}`);
193
+ str += "; Max-Age=" + Math.max(0, Math.min(cookie.maxAge, COOKIE_MAX_AGE_LIMIT));
194
+ }
195
+ if (cookie.domain) {
196
+ if (!domainValueRegExp.test(cookie.domain)) throw new TypeError(`option domain is invalid: ${cookie.domain}`);
197
+ str += "; Domain=" + cookie.domain;
198
+ }
199
+ if (cookie.path) {
200
+ if (!pathValueRegExp.test(cookie.path)) throw new TypeError(`option path is invalid: ${cookie.path}`);
201
+ str += "; Path=" + cookie.path;
202
+ }
203
+ if (cookie.expires) {
204
+ if (!isDate(cookie.expires) || !Number.isFinite(cookie.expires.valueOf())) throw new TypeError(`option expires is invalid: ${cookie.expires}`);
205
+ str += "; Expires=" + cookie.expires.toUTCString();
206
+ }
207
+ if (cookie.httpOnly) str += "; HttpOnly";
208
+ if (cookie.secure) str += "; Secure";
209
+ if (cookie.partitioned) str += "; Partitioned";
210
+ if (cookie.priority) switch (typeof cookie.priority === "string" ? cookie.priority.toLowerCase() : void 0) {
211
+ case "low":
212
+ str += "; Priority=Low";
213
+ break;
214
+ case "medium":
215
+ str += "; Priority=Medium";
216
+ break;
217
+ case "high":
218
+ str += "; Priority=High";
219
+ break;
220
+ default: throw new TypeError(`option priority is invalid: ${cookie.priority}`);
221
+ }
222
+ if (cookie.sameSite) switch (typeof cookie.sameSite === "string" ? cookie.sameSite.toLowerCase() : cookie.sameSite) {
223
+ case true:
224
+ case "strict":
225
+ str += "; SameSite=Strict";
226
+ break;
227
+ case "lax":
228
+ str += "; SameSite=Lax";
229
+ break;
230
+ case "none":
231
+ str += "; SameSite=None";
232
+ break;
233
+ default: throw new TypeError(`option sameSite is invalid: ${cookie.sameSite}`);
234
+ }
235
+ return str;
142
236
  }
237
+ /**
238
+ * Determine if value is a Date.
239
+ */
143
240
  function isDate(val) {
144
- return Object.prototype.toString.call(val) === "[object Date]" || val instanceof Date;
241
+ return __toString.call(val) === "[object Date]";
242
+ }
243
+ //#endregion
244
+ //#region src/set-cookie/parse.ts
245
+ /**
246
+ * RegExp to match max-age-value in RFC 6265 sec 5.6.2
247
+ */
248
+ const maxAgeRegExp = /^-?\d+$/;
249
+ const _nullProto = Object.getPrototypeOf({});
250
+ /**
251
+ * Parse a [Set-Cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie) header string into an object.
252
+ */
253
+ function parseSetCookie(str, options) {
254
+ const len = str.length;
255
+ let _endIdx = len;
256
+ let eqIdx = -1;
257
+ for (let i = 0; i < len; i++) {
258
+ const c = str.charCodeAt(i);
259
+ if (c === 59) {
260
+ _endIdx = i;
261
+ break;
262
+ }
263
+ if (c === 61 && eqIdx === -1) eqIdx = i;
264
+ }
265
+ if (eqIdx >= _endIdx) eqIdx = -1;
266
+ const name = eqIdx === -1 ? "" : _trim(str, 0, eqIdx);
267
+ if (name && name in _nullProto) return void 0;
268
+ let value = eqIdx === -1 ? _trim(str, 0, _endIdx) : _trim(str, eqIdx + 1, _endIdx);
269
+ if (!name && !value) return void 0;
270
+ if (name.length + value.length > 4096) return void 0;
271
+ if (options?.decode !== false) value = _decode(value, options?.decode);
272
+ const setCookie = {
273
+ name,
274
+ value
275
+ };
276
+ let index = _endIdx + 1;
277
+ while (index < len) {
278
+ let endIdx = len;
279
+ let attrEqIdx = -1;
280
+ for (let i = index; i < len; i++) {
281
+ const c = str.charCodeAt(i);
282
+ if (c === 59) {
283
+ endIdx = i;
284
+ break;
285
+ }
286
+ if (c === 61 && attrEqIdx === -1) attrEqIdx = i;
287
+ }
288
+ if (attrEqIdx >= endIdx) attrEqIdx = -1;
289
+ const attr = attrEqIdx === -1 ? _trim(str, index, endIdx) : _trim(str, index, attrEqIdx);
290
+ const val = attrEqIdx === -1 ? void 0 : _trim(str, attrEqIdx + 1, endIdx);
291
+ if (val === void 0 || val.length <= 1024) switch (attr.toLowerCase()) {
292
+ case "httponly":
293
+ setCookie.httpOnly = true;
294
+ break;
295
+ case "secure":
296
+ setCookie.secure = true;
297
+ break;
298
+ case "partitioned":
299
+ setCookie.partitioned = true;
300
+ break;
301
+ case "domain":
302
+ if (val) setCookie.domain = (val.charCodeAt(0) === 46 ? val.slice(1) : val).toLowerCase();
303
+ break;
304
+ case "path":
305
+ setCookie.path = val;
306
+ break;
307
+ case "max-age":
308
+ if (val && maxAgeRegExp.test(val)) setCookie.maxAge = Math.min(Number(val), COOKIE_MAX_AGE_LIMIT);
309
+ break;
310
+ case "expires": {
311
+ if (!val) break;
312
+ const date = new Date(val);
313
+ if (Number.isFinite(date.valueOf())) {
314
+ const maxDate = new Date(Date.now() + COOKIE_MAX_AGE_LIMIT * 1e3);
315
+ setCookie.expires = date > maxDate ? maxDate : date;
316
+ }
317
+ break;
318
+ }
319
+ case "priority": {
320
+ if (!val) break;
321
+ const priority = val.toLowerCase();
322
+ if (priority === "low" || priority === "medium" || priority === "high") setCookie.priority = priority;
323
+ break;
324
+ }
325
+ case "samesite": {
326
+ if (!val) break;
327
+ const sameSite = val.toLowerCase();
328
+ if (sameSite === "lax" || sameSite === "strict" || sameSite === "none") setCookie.sameSite = sameSite;
329
+ else setCookie.sameSite = "lax";
330
+ break;
331
+ }
332
+ default: {
333
+ const attrLower = attr.toLowerCase();
334
+ if (attrLower && !(attrLower in _nullProto)) setCookie[attrLower] = val;
335
+ }
336
+ }
337
+ index = endIdx + 1;
338
+ }
339
+ return setCookie;
145
340
  }
146
-
147
- function parseSetCookie(setCookieValue, options) {
148
- const parts = (setCookieValue || "").split(";").filter((str) => typeof str === "string" && !!str.trim());
149
- const nameValuePairStr = parts.shift() || "";
150
- const parsed = _parseNameValuePair(nameValuePairStr);
151
- const name = parsed.name;
152
- let value = parsed.value;
153
- try {
154
- value = options?.decode === false ? value : (options?.decode || decodeURIComponent)(value);
155
- } catch {
156
- }
157
- const cookie = {
158
- name,
159
- value
160
- };
161
- for (const part of parts) {
162
- const sides = part.split("=");
163
- const partKey = (sides.shift() || "").trimStart().toLowerCase();
164
- const partValue = sides.join("=");
165
- switch (partKey) {
166
- case "expires": {
167
- cookie.expires = new Date(partValue);
168
- break;
169
- }
170
- case "max-age": {
171
- cookie.maxAge = Number.parseInt(partValue, 10);
172
- break;
173
- }
174
- case "secure": {
175
- cookie.secure = true;
176
- break;
177
- }
178
- case "httponly": {
179
- cookie.httpOnly = true;
180
- break;
181
- }
182
- case "samesite": {
183
- cookie.sameSite = partValue;
184
- break;
185
- }
186
- default: {
187
- cookie[partKey] = partValue;
188
- }
189
- }
190
- }
191
- return cookie;
341
+ function _trim(str, start, end) {
342
+ if (start === end) return "";
343
+ let s = start;
344
+ let e = end;
345
+ while (s < e && (str.charCodeAt(s) === 32 || str.charCodeAt(s) === 9)) s++;
346
+ while (e > s && (str.charCodeAt(e - 1) === 32 || str.charCodeAt(e - 1) === 9)) e--;
347
+ return str.slice(s, e);
192
348
  }
193
- function _parseNameValuePair(nameValuePairStr) {
194
- let name = "";
195
- let value = "";
196
- const nameValueArr = nameValuePairStr.split("=");
197
- if (nameValueArr.length > 1) {
198
- name = nameValueArr.shift();
199
- value = nameValueArr.join("=");
200
- } else {
201
- value = nameValuePairStr;
202
- }
203
- return { name, value };
349
+ function _decode(value, decode) {
350
+ if (!decode && !value.includes("%")) return value;
351
+ try {
352
+ return (decode || decodeURIComponent)(value);
353
+ } catch {
354
+ return value;
355
+ }
204
356
  }
205
-
357
+ //#endregion
358
+ //#region src/set-cookie/split.ts
359
+ /**
360
+ * Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas
361
+ * that are within a single set-cookie field-value, such as in the Expires portion.
362
+ *
363
+ * See https://tools.ietf.org/html/rfc2616#section-4.2
364
+ */
206
365
  function splitSetCookieString(cookiesString) {
207
- if (Array.isArray(cookiesString)) {
208
- return cookiesString.flatMap((c) => splitSetCookieString(c));
209
- }
210
- if (typeof cookiesString !== "string") {
211
- return [];
212
- }
213
- const cookiesStrings = [];
214
- let pos = 0;
215
- let start;
216
- let ch;
217
- let lastComma;
218
- let nextStart;
219
- let cookiesSeparatorFound;
220
- const skipWhitespace = () => {
221
- while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
222
- pos += 1;
223
- }
224
- return pos < cookiesString.length;
225
- };
226
- const notSpecialChar = () => {
227
- ch = cookiesString.charAt(pos);
228
- return ch !== "=" && ch !== ";" && ch !== ",";
229
- };
230
- while (pos < cookiesString.length) {
231
- start = pos;
232
- cookiesSeparatorFound = false;
233
- while (skipWhitespace()) {
234
- ch = cookiesString.charAt(pos);
235
- if (ch === ",") {
236
- lastComma = pos;
237
- pos += 1;
238
- skipWhitespace();
239
- nextStart = pos;
240
- while (pos < cookiesString.length && notSpecialChar()) {
241
- pos += 1;
242
- }
243
- if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
244
- cookiesSeparatorFound = true;
245
- pos = nextStart;
246
- cookiesStrings.push(cookiesString.slice(start, lastComma));
247
- start = pos;
248
- } else {
249
- pos = lastComma + 1;
250
- }
251
- } else {
252
- pos += 1;
253
- }
254
- }
255
- if (!cookiesSeparatorFound || pos >= cookiesString.length) {
256
- cookiesStrings.push(cookiesString.slice(start, cookiesString.length));
257
- }
258
- }
259
- return cookiesStrings;
366
+ if (Array.isArray(cookiesString)) return cookiesString.flatMap((c) => splitSetCookieString(c));
367
+ if (typeof cookiesString !== "string") return [];
368
+ const cookiesStrings = [];
369
+ let pos = 0;
370
+ let start;
371
+ let ch;
372
+ let lastComma;
373
+ let nextStart;
374
+ let cookiesSeparatorFound;
375
+ const skipWhitespace = () => {
376
+ while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) pos += 1;
377
+ return pos < cookiesString.length;
378
+ };
379
+ const notSpecialChar = () => {
380
+ ch = cookiesString.charAt(pos);
381
+ return ch !== "=" && ch !== ";" && ch !== ",";
382
+ };
383
+ while (pos < cookiesString.length) {
384
+ start = pos;
385
+ cookiesSeparatorFound = false;
386
+ while (skipWhitespace()) {
387
+ ch = cookiesString.charAt(pos);
388
+ if (ch === ",") {
389
+ lastComma = pos;
390
+ pos += 1;
391
+ skipWhitespace();
392
+ nextStart = pos;
393
+ while (pos < cookiesString.length && notSpecialChar()) pos += 1;
394
+ if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
395
+ cookiesSeparatorFound = true;
396
+ pos = nextStart;
397
+ cookiesStrings.push(cookiesString.slice(start, lastComma));
398
+ start = pos;
399
+ } else pos = lastComma + 1;
400
+ } else pos += 1;
401
+ }
402
+ if (!cookiesSeparatorFound || pos >= cookiesString.length) cookiesStrings.push(cookiesString.slice(start));
403
+ }
404
+ return cookiesStrings;
260
405
  }
261
-
262
- export { parse, parseSetCookie, serialize, splitSetCookieString };
406
+ //#endregion
407
+ export { parse, parse as parseCookie, parseSetCookie, serialize, serialize as serializeCookie, splitSetCookieString, stringifyCookie };