cookie-es 2.0.0 → 3.0.1

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.
Files changed (4) hide show
  1. package/README.md +118 -10
  2. package/dist/index.d.mts +205 -195
  3. package/dist/index.mjs +296 -250
  4. package/package.json +26 -23
package/README.md CHANGED
@@ -10,26 +10,25 @@
10
10
 
11
11
  <!-- /automd -->
12
12
 
13
- ESM ready [`Cookie`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cookie) and [`Set-Cookie`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie) parser and serializer based on [cookie](https://github.com/jshttp/cookie) and [set-cookie-parser](https://github.com/nfriedly/set-cookie-parser) with built-in types.
13
+ ESM-ready [`Cookie`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cookie) and [`Set-Cookie`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie) parser and serializer based on [cookie](https://github.com/jshttp/cookie) and [set-cookie-parser](https://github.com/nfriedly/set-cookie-parser) with built-in TypeScript types. Compliant with [RFC 6265bis](https://httpwg.org/http-extensions/draft-ietf-httpbis-rfc6265bis.html).
14
14
 
15
- ## Usage
16
-
17
- Install:
15
+ ## Install
18
16
 
19
17
  ```sh
20
18
  # ✨ Auto-detect (npm, yarn, pnpm, bun, deno)
21
19
  npx nypm install cookie-es
22
20
  ```
23
21
 
24
- Import:
22
+ ## Import
25
23
 
26
24
  **ESM** (Node.js, Bun, Deno)
27
25
 
28
26
  ```js
29
27
  import {
30
- parse,
31
- serialize,
28
+ parseCookie,
32
29
  parseSetCookie,
30
+ serializeCookie,
31
+ stringifyCookie,
33
32
  splitSetCookieString,
34
33
  } from "cookie-es";
35
34
  ```
@@ -38,15 +37,124 @@ import {
38
37
 
39
38
  ```js
40
39
  import {
41
- parse,
42
- serialize,
40
+ parseCookie,
43
41
  parseSetCookie,
42
+ serializeCookie,
43
+ stringifyCookie,
44
44
  splitSetCookieString,
45
45
  } from "https://esm.sh/cookie-es";
46
46
  ```
47
47
 
48
+ ## API
49
+
50
+ ### `parseCookie(str, options?)`
51
+
52
+ Parse a `Cookie` header string into an object. First occurrence wins for duplicate names.
53
+
54
+ ```js
55
+ parseCookie("foo=bar; equation=E%3Dmc%5E2");
56
+ // { foo: "bar", equation: "E=mc^2" }
57
+
58
+ // Custom decoder
59
+ parseCookie("foo=bar", { decode: (v) => v });
60
+
61
+ // Only parse specific keys
62
+ parseCookie("a=1; b=2; c=3", { filter: (key) => key !== "b" });
63
+ // { a: "1", c: "3" }
64
+ ```
65
+
66
+ ### `parseSetCookie(str, options?)`
67
+
68
+ Parse a `Set-Cookie` header string into an object with all cookie attributes.
69
+
70
+ ```js
71
+ parseSetCookie(
72
+ "id=abc; Domain=example.com; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=3600; Partitioned; Priority=High",
73
+ );
74
+ // {
75
+ // name: "id",
76
+ // value: "abc",
77
+ // domain: "example.com",
78
+ // path: "/",
79
+ // httpOnly: true,
80
+ // secure: true,
81
+ // sameSite: "lax",
82
+ // maxAge: 3600,
83
+ // partitioned: true,
84
+ // priority: "high",
85
+ // }
86
+ ```
87
+
88
+ Supports `decode` option (custom function or `false` to skip decoding). Returns `undefined` for cookies with forbidden names (prototype pollution protection) or when both name and value are empty ([RFC 6265bis](https://httpwg.org/http-extensions/draft-ietf-httpbis-rfc6265bis.html) sec 5.7).
89
+
90
+ ### `serializeCookie(name, value, options?)`
91
+
92
+ Serialize a cookie name-value pair into a `Set-Cookie` header string.
93
+
94
+ ```js
95
+ serializeCookie("foo", "bar", { httpOnly: true, secure: true, maxAge: 3600 });
96
+ // "foo=bar; Max-Age=3600; HttpOnly; Secure"
97
+
98
+ // Also accepts a cookie object
99
+ serializeCookie({
100
+ name: "foo",
101
+ value: "bar",
102
+ domain: "example.com",
103
+ path: "/",
104
+ sameSite: "lax",
105
+ });
106
+ // "foo=bar; Domain=example.com; Path=/; SameSite=Lax"
107
+ ```
108
+
109
+ Supported attributes: `maxAge`, `expires`, `domain`, `path`, `httpOnly`, `secure`, `sameSite`, `priority`, `partitioned`. Use `encode` option for custom value encoding (default: `encodeURIComponent`).
110
+
111
+ > [!NOTE]
112
+ > `parse` and `serialize` are available as shorter aliases for `parseCookie` and `serializeCookie`.
113
+
114
+ ### `stringifyCookie(cookies, options?)`
115
+
116
+ Stringify a cookies object into an HTTP `Cookie` header string.
117
+
118
+ ```js
119
+ stringifyCookie({ foo: "bar", baz: "qux" });
120
+ // "foo=bar; baz=qux"
121
+ ```
122
+
123
+ ### `splitSetCookieString(input)`
124
+
125
+ Split comma-joined `Set-Cookie` headers into individual strings. Correctly handles commas within cookie attributes like `Expires` dates.
126
+
127
+ ```js
128
+ splitSetCookieString(
129
+ "foo=bar; Expires=Thu, 01 Jan 2026 00:00:00 GMT, baz=qux",
130
+ );
131
+ // ["foo=bar; Expires=Thu, 01 Jan 2026 00:00:00 GMT", "baz=qux"]
132
+
133
+ // Also accepts an array
134
+ splitSetCookieString(["a=1, b=2", "c=3"]);
135
+ // ["a=1", "b=2", "c=3"]
136
+ ```
137
+
138
+ ## Parsing Options
139
+
140
+ ### `allowMultiple`
141
+
142
+ By default, when a cookie name appears more than once, only the first value is kept. Set `allowMultiple: true` to collect all values into an array:
143
+
144
+ ```js
145
+ import { parseCookie } from "cookie-es";
146
+
147
+ // Default: first value wins
148
+ parseCookie("foo=a;bar=b;foo=c");
149
+ // => { foo: "a", bar: "b" }
150
+
151
+ // With allowMultiple: duplicates return arrays
152
+ parseCookie("foo=a;bar=b;foo=c", { allowMultiple: true });
153
+ // => { foo: ["a", "c"], bar: "b" }
154
+ ```
155
+
48
156
  ## License
49
157
 
50
158
  [MIT](./LICENSE)
51
159
 
52
- Based on [jshttp/cookie](https://github.com/jshttp/cookie) (Roman Shtylman and hristopher Wilson) and [nfriedly/set-cookie-parser](https://github.com/nfriedly/set-cookie-parser) (Nathan Friedly).
160
+ Based on [jshttp/cookie](https://github.com/jshttp/cookie) (Roman Shtylman and Douglas Christopher Wilson) and [nfriedly/set-cookie-parser](https://github.com/nfriedly/set-cookie-parser) (Nathan Friedly).
package/dist/index.d.mts CHANGED
@@ -1,216 +1,227 @@
1
1
  /**
2
- * Basic HTTP cookie parser and serializer for HTTP servers.
2
+ * Parse options.
3
3
  */
4
+ interface CookieParseOptions {
5
+ /**
6
+ * Specifies a function that will be used to decode a [cookie-value](https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1).
7
+ * Since the value of a cookie has a limited character set (and must be a simple string), this function can be used to decode
8
+ * a previously-encoded cookie value into a JavaScript string.
9
+ *
10
+ * The default function is the global `decodeURIComponent`, wrapped in a `try..catch`. If an error
11
+ * is thrown it will return the cookie's original value. If you provide your own encode/decode
12
+ * scheme you must ensure errors are appropriately handled.
13
+ *
14
+ * @default decode
15
+ */
16
+ decode?: (str: string) => string | undefined;
17
+ /**
18
+ * Custom function to filter parsing specific keys.
19
+ */
20
+ filter?(key: string): boolean;
21
+ /**
22
+ * When enabled, duplicate cookie names will return an array of values
23
+ * instead of only the first value.
24
+ */
25
+ allowMultiple?: boolean;
26
+ }
27
+ /**
28
+ * Cookies object.
29
+ */
30
+ type Cookies = Record<string, string | undefined>;
4
31
  /**
5
- * Additional serialization options
32
+ * Cookies object when `allowMultiple` is enabled.
6
33
  */
7
- interface CookieSerializeOptions {
8
- /**
9
- * Specifies the value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.3|Domain Set-Cookie attribute}. By default, no
10
- * domain is set, and most clients will consider the cookie to apply to only
11
- * the current domain.
12
- */
13
- domain?: string | undefined;
14
- /**
15
- * Specifies a function that will be used to encode a cookie's value. Since
16
- * value of a cookie has a limited character set (and must be a simple
17
- * string), this function can be used to encode a value into a string suited
18
- * for a cookie's value.
19
- *
20
- * The default function is the global `encodeURIComponent`, which will
21
- * encode a JavaScript string into UTF-8 byte sequences and then URL-encode
22
- * any that fall outside of the cookie range.
23
- */
24
- encode?(value: string): string;
25
- /**
26
- * Specifies the `Date` object to be the value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.1|`Expires` `Set-Cookie` attribute}. By default,
27
- * no expiration is set, and most clients will consider this a "non-persistent cookie" and will delete
28
- * it on a condition like exiting a web browser application.
29
- *
30
- * *Note* the {@link https://tools.ietf.org/html/rfc6265#section-5.3|cookie storage model specification}
31
- * states that if both `expires` and `maxAge` are set, then `maxAge` takes precedence, but it is
32
- * possible not all clients by obey this, so if both are set, they should
33
- * point to the same date and time.
34
- */
35
- expires?: Date | undefined;
36
- /**
37
- * Specifies the boolean value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.6|`HttpOnly` `Set-Cookie` attribute}.
38
- * When truthy, the `HttpOnly` attribute is set, otherwise it is not. By
39
- * default, the `HttpOnly` attribute is not set.
40
- *
41
- * *Note* be careful when setting this to true, as compliant clients will
42
- * not allow client-side JavaScript to see the cookie in `document.cookie`.
43
- */
44
- httpOnly?: boolean | undefined;
45
- /**
46
- * Specifies the number (in seconds) to be the value for the `Max-Age`
47
- * `Set-Cookie` attribute. The given number will be converted to an integer
48
- * by rounding down. By default, no maximum age is set.
49
- *
50
- * *Note* the {@link https://tools.ietf.org/html/rfc6265#section-5.3|cookie storage model specification}
51
- * states that if both `expires` and `maxAge` are set, then `maxAge` takes precedence, but it is
52
- * possible not all clients by obey this, so if both are set, they should
53
- * point to the same date and time.
54
- */
55
- maxAge?: number | undefined;
56
- /**
57
- * Specifies the value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.4|`Path` `Set-Cookie` attribute}.
58
- * By default, the path is considered the "default path".
59
- */
60
- path?: string | undefined;
61
- /**
62
- * Specifies the `string` to be the value for the [`Priority` `Set-Cookie` attribute][rfc-west-cookie-priority-00-4.1].
63
- *
64
- * - `'low'` will set the `Priority` attribute to `Low`.
65
- * - `'medium'` will set the `Priority` attribute to `Medium`, the default priority when not set.
66
- * - `'high'` will set the `Priority` attribute to `High`.
67
- *
68
- * More information about the different priority levels can be found in
69
- * [the specification][rfc-west-cookie-priority-00-4.1].
70
- *
71
- * **note** This is an attribute that has not yet been fully standardized, and may change in the future.
72
- * This also means many clients may ignore this attribute until they understand it.
73
- */
74
- priority?: "low" | "medium" | "high" | undefined;
75
- /**
76
- * Specifies the boolean or string to be the value for the {@link https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7|`SameSite` `Set-Cookie` attribute}.
77
- *
78
- * - `true` will set the `SameSite` attribute to `Strict` for strict same
79
- * site enforcement.
80
- * - `false` will not set the `SameSite` attribute.
81
- * - `'lax'` will set the `SameSite` attribute to Lax for lax same site
82
- * enforcement.
83
- * - `'strict'` will set the `SameSite` attribute to Strict for strict same
84
- * site enforcement.
85
- * - `'none'` will set the SameSite attribute to None for an explicit
86
- * cross-site cookie.
87
- *
88
- * More information about the different enforcement levels can be found in {@link https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7|the specification}.
89
- *
90
- * *note* This is an attribute that has not yet been fully standardized, and may change in the future. This also means many clients may ignore this attribute until they understand it.
91
- */
92
- sameSite?: true | false | "lax" | "strict" | "none" | undefined;
93
- /**
94
- * Specifies the boolean value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.5|`Secure` `Set-Cookie` attribute}. When truthy, the
95
- * `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set.
96
- *
97
- * *Note* be careful when setting this to `true`, as compliant clients will
98
- * not send the cookie back to the server in the future if the browser does
99
- * not have an HTTPS connection.
100
- */
101
- secure?: boolean | undefined;
102
- /**
103
- * Specifies the `boolean` value for the [`Partitioned` `Set-Cookie`](https://datatracker.ietf.org/doc/html/draft-cutler-httpbis-partitioned-cookies#section-2.1)
104
- * attribute. When truthy, the `Partitioned` attribute is set, otherwise it is not. By default, the
105
- * `Partitioned` attribute is not set.
106
- *
107
- * **note** This is an attribute that has not yet been fully standardized, and may change in the future.
108
- * This also means many clients may ignore this attribute until they understand it.
109
- *
110
- * More information can be found in the [proposal](https://github.com/privacycg/CHIPS).
111
- */
112
- partitioned?: boolean;
34
+ type MultiCookies = Record<string, string | string[] | undefined>;
35
+ /**
36
+ * Stringify options.
37
+ */
38
+ interface CookieStringifyOptions {
39
+ /**
40
+ * Specifies a function that will be used to encode a [cookie-value](https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1).
41
+ * Since value of a cookie has a limited character set (and must be a simple string), this function can be used to encode
42
+ * a value into a string suited for a cookie's value, and should mirror `decode` when parsing.
43
+ *
44
+ * @default encodeURIComponent
45
+ */
46
+ encode?: (str: string) => string;
113
47
  }
114
48
  /**
115
- * Additional parsing options
49
+ * Set-Cookie object.
116
50
  */
117
- interface CookieParseOptions {
118
- /**
119
- * Specifies a function that will be used to decode a cookie's value. Since
120
- * the value of a cookie has a limited character set (and must be a simple
121
- * string), this function can be used to decode a previously-encoded cookie
122
- * value into a JavaScript string or other object.
123
- *
124
- * The default function is the global `decodeURIComponent`, which will decode
125
- * any URL-encoded sequences into their byte representations.
126
- *
127
- * *Note* if an error is thrown from this function, the original, non-decoded
128
- * cookie value will be returned as the cookie's value.
129
- */
130
- decode?(value: string): string;
131
- /**
132
- * Custom function to filter parsing specific keys.
133
- */
134
- filter?(key: string): boolean;
51
+ interface SetCookie {
52
+ /**
53
+ * Specifies the name of the cookie.
54
+ */
55
+ name: string;
56
+ /**
57
+ * Specifies the string to be the value for the cookie.
58
+ */
59
+ value: string | undefined;
60
+ /**
61
+ * Specifies the `number` (in seconds) to be the value for the [`Max-Age` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.2).
62
+ *
63
+ * The [cookie storage model specification](https://tools.ietf.org/html/rfc6265#section-5.3) states that if both `expires` and
64
+ * `maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this,
65
+ * so if both are set, they should point to the same date and time.
66
+ */
67
+ maxAge?: number;
68
+ /**
69
+ * Specifies the `Date` object to be the value for the [`Expires` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.1).
70
+ * When no expiration is set, clients consider this a "non-persistent cookie" and delete it when the current session is over.
71
+ *
72
+ * The [cookie storage model specification](https://tools.ietf.org/html/rfc6265#section-5.3) states that if both `expires` and
73
+ * `maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this,
74
+ * so if both are set, they should point to the same date and time.
75
+ */
76
+ expires?: Date;
77
+ /**
78
+ * Specifies the value for the [`Domain` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.3).
79
+ * When no domain is set, clients consider the cookie to apply to the current domain only.
80
+ */
81
+ domain?: string;
82
+ /**
83
+ * Specifies the value for the [`Path` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.4).
84
+ * When no path is set, the path is considered the ["default path"](https://tools.ietf.org/html/rfc6265#section-5.1.4).
85
+ */
86
+ path?: string;
87
+ /**
88
+ * Enables the [`HttpOnly` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.6).
89
+ * When enabled, clients will not allow client-side JavaScript to see the cookie in `document.cookie`.
90
+ */
91
+ httpOnly?: boolean;
92
+ /**
93
+ * Enables the [`Secure` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.5).
94
+ * When enabled, clients will only send the cookie back if the browser has an HTTPS connection.
95
+ */
96
+ secure?: boolean;
97
+ /**
98
+ * Enables the [`Partitioned` `Set-Cookie` attribute](https://tools.ietf.org/html/draft-cutler-httpbis-partitioned-cookies/).
99
+ * When enabled, clients will only send the cookie back when the current domain _and_ top-level domain matches.
100
+ *
101
+ * This is an attribute that has not yet been fully standardized, and may change in the future.
102
+ * This also means clients may ignore this attribute until they understand it. More information
103
+ * about can be found in [the proposal](https://github.com/privacycg/CHIPS).
104
+ */
105
+ partitioned?: boolean;
106
+ /**
107
+ * Specifies the value for the [`Priority` `Set-Cookie` attribute](https://tools.ietf.org/html/draft-west-cookie-priority-00#section-4.1).
108
+ *
109
+ * - `'low'` will set the `Priority` attribute to `Low`.
110
+ * - `'medium'` will set the `Priority` attribute to `Medium`, the default priority when not set.
111
+ * - `'high'` will set the `Priority` attribute to `High`.
112
+ *
113
+ * More information about priority levels can be found in [the specification](https://tools.ietf.org/html/draft-west-cookie-priority-00#section-4.1).
114
+ */
115
+ priority?: "low" | "medium" | "high";
116
+ /**
117
+ * Specifies the value for the [`SameSite` `Set-Cookie` attribute](https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-09#section-5.4.7).
118
+ *
119
+ * - `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement.
120
+ * - `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement.
121
+ * - `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie.
122
+ * - `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement.
123
+ *
124
+ * More information about enforcement levels can be found in [the specification](https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-09#section-5.4.7).
125
+ */
126
+ sameSite?: boolean | "lax" | "strict" | "none";
135
127
  }
136
-
137
128
  /**
138
- * Parse an HTTP Cookie header string and returning an object of all cookie
139
- * name-value pairs.
129
+ * Backward compatibility serialize options.
130
+ */
131
+ type CookieSerializeOptions = CookieStringifyOptions & Omit<SetCookie, "name" | "value">;
132
+ /**
133
+ * Parse a `Cookie` header.
140
134
  *
141
- * @param str the string representing a `Cookie` header value
142
- * @param [options] object containing parsing options
135
+ * Parse the given cookie header string into an object
136
+ * The object has the various cookies as keys(names) => values
143
137
  */
144
- declare function parse(str: string, options?: CookieParseOptions): Record<string, string>;
145
-
138
+ declare function parse(str: string, options: CookieParseOptions & {
139
+ allowMultiple: true;
140
+ }): MultiCookies;
141
+ declare function parse(str: string, options?: CookieParseOptions): Cookies;
146
142
  /**
147
- * Serialize a cookie name-value pair into a `Set-Cookie` header string.
143
+ * Stringifies an object into an HTTP `Cookie` header.
144
+ */
145
+ declare function stringifyCookie(cookie: Cookies, options?: CookieStringifyOptions): string;
146
+ /**
147
+ * Serialize data into a cookie header.
148
+ *
149
+ * Serialize a name value pair into a cookie string suitable for
150
+ * http headers. An optional options object specifies cookie parameters.
148
151
  *
149
- * @param name the name for the cookie
150
- * @param value value to set the cookie to
151
- * @param [options] object containing serialization options
152
- * @throws {TypeError} when `maxAge` options is invalid
152
+ * serialize('foo', 'bar', { httpOnly: true })
153
+ * => "foo=bar; httpOnly"
153
154
  */
154
- declare function serialize(name: string, value: string, options?: CookieSerializeOptions): string;
155
-
155
+ declare function serialize(cookie: SetCookie, options?: CookieStringifyOptions): string;
156
+ declare function serialize(name: string, val: string, options?: CookieSerializeOptions): string;
156
157
  interface SetCookieParseOptions {
157
- /**
158
- * Custom decode function to use on cookie values.
159
- *
160
- * By default, `decodeURIComponent` is used.
161
- *
162
- * **Note:** If decoding fails, the original (undecoded) value will be used
163
- */
164
- decode?: false | ((value: string) => string);
158
+ /**
159
+ * Custom decode function to use on cookie values.
160
+ *
161
+ * By default, `decodeURIComponent` is used.
162
+ *
163
+ * **Note:** If decoding fails, the original (undecoded) value will be used
164
+ */
165
+ decode?: false | ((value: string) => string);
165
166
  }
166
- interface SetCookie {
167
- /**
168
- * Cookie name
169
- */
170
- name: string;
171
- /**
172
- * Cookie value
173
- */
174
- value: string;
175
- /**
176
- * Cookie path
177
- */
178
- path?: string | undefined;
179
- /**
180
- * Absolute expiration date for the cookie
181
- */
182
- expires?: Date | undefined;
183
- /**
184
- * Relative max age of the cookie in seconds from when the client receives it (integer or undefined)
185
- *
186
- * Note: when using with express's res.cookie() method, multiply maxAge by 1000 to convert to milliseconds
187
- */
188
- maxAge?: number | undefined;
189
- /**
190
- * Domain for the cookie,
191
- * May begin with "." to indicate the named domain or any subdomain of it
192
- */
193
- domain?: string | undefined;
194
- /**
195
- * Indicates that this cookie should only be sent over HTTPs
196
- */
197
- secure?: boolean | undefined;
198
- /**
199
- * Indicates that this cookie should not be accessible to client-side JavaScript
200
- */
201
- httpOnly?: boolean | undefined;
202
- /**
203
- * Indicates a cookie ought not to be sent along with cross-site requests
204
- */
205
- sameSite?: true | false | "lax" | "strict" | "none" | undefined;
206
- [key: string]: unknown;
167
+ interface SetCookie$1 {
168
+ /**
169
+ * Cookie name
170
+ */
171
+ name: string;
172
+ /**
173
+ * Cookie value
174
+ */
175
+ value: string;
176
+ /**
177
+ * Cookie path
178
+ */
179
+ path?: string | undefined;
180
+ /**
181
+ * Absolute expiration date for the cookie
182
+ */
183
+ expires?: Date | undefined;
184
+ /**
185
+ * Relative max age of the cookie in seconds from when the client receives it (integer or undefined)
186
+ *
187
+ * Note: when using with express's res.cookie() method, multiply maxAge by 1000 to convert to milliseconds
188
+ */
189
+ maxAge?: number | undefined;
190
+ /**
191
+ * Domain for the cookie,
192
+ * May begin with "." to indicate the named domain or any subdomain of it
193
+ */
194
+ domain?: string | undefined;
195
+ /**
196
+ * Indicates that this cookie should only be sent over HTTPs
197
+ */
198
+ secure?: boolean | undefined;
199
+ /**
200
+ * Indicates that this cookie should not be accessible to client-side JavaScript
201
+ */
202
+ httpOnly?: boolean | undefined;
203
+ /**
204
+ * Indicates a cookie ought not to be sent along with cross-site requests
205
+ */
206
+ sameSite?: true | false | "lax" | "strict" | "none" | undefined;
207
+ /**
208
+ * Indicates that the cookie should be stored using partitioned storage
209
+ *
210
+ * See https://developer.mozilla.org/en-US/docs/Web/Privacy/Privacy_sandbox/Partitioned_cookies
211
+ */
212
+ partitioned?: boolean | undefined;
213
+ /**
214
+ * Indicates the priority of the cookie
215
+ *
216
+ * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#prioritylow_medium_high
217
+ */
218
+ priority?: "low" | "medium" | "high" | undefined;
219
+ [key: string]: unknown;
207
220
  }
208
-
209
221
  /**
210
222
  * Parse a [Set-Cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie) header string into an object.
211
223
  */
212
- declare function parseSetCookie(setCookieValue: string, options?: SetCookieParseOptions): SetCookie;
213
-
224
+ declare function parseSetCookie(str: string, options?: SetCookieParseOptions): SetCookie$1 | undefined;
214
225
  /**
215
226
  * Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas
216
227
  * that are within a single set-cookie field-value, such as in the Expires portion.
@@ -218,5 +229,4 @@ declare function parseSetCookie(setCookieValue: string, options?: SetCookieParse
218
229
  * See https://tools.ietf.org/html/rfc2616#section-4.2
219
230
  */
220
231
  declare function splitSetCookieString(cookiesString: string | string[]): string[];
221
-
222
- export { type CookieParseOptions, type CookieSerializeOptions, type SetCookie, type SetCookieParseOptions, parse, parseSetCookie, serialize, splitSetCookieString };
232
+ export { type CookieParseOptions, type CookieSerializeOptions, type CookieStringifyOptions, type Cookies, type MultiCookies, type SetCookie, type SetCookieParseOptions, parse, parse as parseCookie, parseSetCookie, serialize, serialize as serializeCookie, splitSetCookieString, stringifyCookie };
package/dist/index.mjs CHANGED
@@ -1,262 +1,308 @@
1
+ const COOKIE_MAX_AGE_LIMIT = 400 * 24 * 60 * 60;
2
+ function endIndex(str, min, len) {
3
+ const index = str.indexOf(";", min);
4
+ return index === -1 ? len : index;
5
+ }
6
+ function eqIndex(str, min, max) {
7
+ const index = str.indexOf("=", min);
8
+ return index < max ? index : -1;
9
+ }
10
+ function valueSlice(str, min, max) {
11
+ if (min === max) return "";
12
+ let start = min;
13
+ let end = max;
14
+ do {
15
+ const code = str.charCodeAt(start);
16
+ if (code !== 32 && code !== 9) break;
17
+ } while (++start < end);
18
+ while (end > start) {
19
+ const code = str.charCodeAt(end - 1);
20
+ if (code !== 32 && code !== 9) break;
21
+ end--;
22
+ }
23
+ return str.slice(start, end);
24
+ }
25
+ const NullObject = /* @__PURE__ */ (() => {
26
+ const C = function() {};
27
+ C.prototype = Object.create(null);
28
+ return C;
29
+ })();
1
30
  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;
31
+ const obj = new NullObject();
32
+ const len = str.length;
33
+ if (len < 2) return obj;
34
+ const dec = options?.decode || decode;
35
+ const allowMultiple = options?.allowMultiple || false;
36
+ let index = 0;
37
+ do {
38
+ const eqIdx = eqIndex(str, index, len);
39
+ if (eqIdx === -1) break;
40
+ const endIdx = endIndex(str, index, len);
41
+ if (eqIdx > endIdx) {
42
+ index = str.lastIndexOf(";", eqIdx - 1) + 1;
43
+ continue;
44
+ }
45
+ const key = valueSlice(str, index, eqIdx);
46
+ if (options?.filter && !options.filter(key)) {
47
+ index = endIdx + 1;
48
+ continue;
49
+ }
50
+ const val = dec(valueSlice(str, eqIdx + 1, endIdx));
51
+ if (allowMultiple) {
52
+ const existing = obj[key];
53
+ if (existing === void 0) obj[key] = val;
54
+ else if (Array.isArray(existing)) existing.push(val);
55
+ else obj[key] = [existing, val];
56
+ } else if (obj[key] === void 0) obj[key] = val;
57
+ index = endIdx + 1;
58
+ } while (index < len);
59
+ return obj;
36
60
  }
37
61
  function decode(str) {
38
- return str.includes("%") ? decodeURIComponent(str) : str;
62
+ if (!str.includes("%")) return str;
63
+ try {
64
+ return decodeURIComponent(str);
65
+ } catch {
66
+ return str;
67
+ }
39
68
  }
40
- function tryDecode(str, decode2) {
41
- try {
42
- return decode2(str);
43
- } catch {
44
- return str;
45
- }
69
+ const cookieNameRegExp = /^[\u0021-\u003A\u003C\u003E-\u007E]+$/;
70
+ const cookieValueRegExp = /^[\u0021-\u003A\u003C-\u007E]*$/;
71
+ 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;
72
+ const pathValueRegExp = /^[\u0020-\u003A\u003C-\u007E]*$/;
73
+ const __toString = Object.prototype.toString;
74
+ function stringifyCookie(cookie, options) {
75
+ const enc = options?.encode || encodeURIComponent;
76
+ const keys = Object.keys(cookie);
77
+ let str = "";
78
+ for (const [i, name] of keys.entries()) {
79
+ const val = cookie[name];
80
+ if (val === void 0) continue;
81
+ if (!cookieNameRegExp.test(name)) throw new TypeError(`cookie name is invalid: ${name}`);
82
+ const value = enc(val);
83
+ if (!cookieValueRegExp.test(value)) throw new TypeError(`cookie val is invalid: ${val}`);
84
+ if (i > 0) str += "; ";
85
+ str += name + "=" + value;
86
+ }
87
+ return str;
46
88
  }
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;
89
+ function serialize(_name, _val, _opts) {
90
+ const cookie = typeof _name === "object" ? _name : {
91
+ ..._opts,
92
+ name: _name,
93
+ value: String(_val)
94
+ };
95
+ const enc = (typeof _val === "object" ? _val : _opts)?.encode || encodeURIComponent;
96
+ if (!cookieNameRegExp.test(cookie.name)) throw new TypeError(`argument name is invalid: ${cookie.name}`);
97
+ const value = cookie.value ? enc(cookie.value) : "";
98
+ if (!cookieValueRegExp.test(value)) throw new TypeError(`argument val is invalid: ${cookie.value}`);
99
+ if (!cookie.secure) {
100
+ if (cookie.partitioned) throw new TypeError(`Partitioned cookies must have the Secure attribute`);
101
+ if (cookie.sameSite && String(cookie.sameSite).toLowerCase() === "none") throw new TypeError(`SameSite=None cookies must have the Secure attribute`);
102
+ if (cookie.name.length > 9 && cookie.name.charCodeAt(0) === 95 && cookie.name.charCodeAt(1) === 95) {
103
+ const nameLower = cookie.name.toLowerCase();
104
+ if (nameLower.startsWith("__secure-") || nameLower.startsWith("__host-")) throw new TypeError(`${cookie.name} cookies must have the Secure attribute`);
105
+ }
106
+ }
107
+ if (cookie.name.length > 7 && cookie.name.charCodeAt(0) === 95 && cookie.name.charCodeAt(1) === 95 && cookie.name.toLowerCase().startsWith("__host-")) {
108
+ if (cookie.path !== "/") throw new TypeError(`__Host- cookies must have Path=/`);
109
+ if (cookie.domain) throw new TypeError(`__Host- cookies must not have a Domain attribute`);
110
+ }
111
+ let str = cookie.name + "=" + value;
112
+ if (cookie.maxAge !== void 0) {
113
+ if (!Number.isInteger(cookie.maxAge)) throw new TypeError(`option maxAge is invalid: ${cookie.maxAge}`);
114
+ str += "; Max-Age=" + Math.max(0, Math.min(cookie.maxAge, COOKIE_MAX_AGE_LIMIT));
115
+ }
116
+ if (cookie.domain) {
117
+ if (!domainValueRegExp.test(cookie.domain)) throw new TypeError(`option domain is invalid: ${cookie.domain}`);
118
+ str += "; Domain=" + cookie.domain;
119
+ }
120
+ if (cookie.path) {
121
+ if (!pathValueRegExp.test(cookie.path)) throw new TypeError(`option path is invalid: ${cookie.path}`);
122
+ str += "; Path=" + cookie.path;
123
+ }
124
+ if (cookie.expires) {
125
+ if (!isDate(cookie.expires) || !Number.isFinite(cookie.expires.valueOf())) throw new TypeError(`option expires is invalid: ${cookie.expires}`);
126
+ str += "; Expires=" + cookie.expires.toUTCString();
127
+ }
128
+ if (cookie.httpOnly) str += "; HttpOnly";
129
+ if (cookie.secure) str += "; Secure";
130
+ if (cookie.partitioned) str += "; Partitioned";
131
+ if (cookie.priority) switch (typeof cookie.priority === "string" ? cookie.priority.toLowerCase() : void 0) {
132
+ case "low":
133
+ str += "; Priority=Low";
134
+ break;
135
+ case "medium":
136
+ str += "; Priority=Medium";
137
+ break;
138
+ case "high":
139
+ str += "; Priority=High";
140
+ break;
141
+ default: throw new TypeError(`option priority is invalid: ${cookie.priority}`);
142
+ }
143
+ if (cookie.sameSite) switch (typeof cookie.sameSite === "string" ? cookie.sameSite.toLowerCase() : cookie.sameSite) {
144
+ case true:
145
+ case "strict":
146
+ str += "; SameSite=Strict";
147
+ break;
148
+ case "lax":
149
+ str += "; SameSite=Lax";
150
+ break;
151
+ case "none":
152
+ str += "; SameSite=None";
153
+ break;
154
+ default: throw new TypeError(`option sameSite is invalid: ${cookie.sameSite}`);
155
+ }
156
+ return str;
142
157
  }
143
158
  function isDate(val) {
144
- return Object.prototype.toString.call(val) === "[object Date]" || val instanceof Date;
159
+ return __toString.call(val) === "[object Date]";
160
+ }
161
+ const maxAgeRegExp = /^-?\d+$/;
162
+ const _nullProto = Object.getPrototypeOf({});
163
+ function parseSetCookie(str, options) {
164
+ const len = str.length;
165
+ let _endIdx = len;
166
+ let eqIdx = -1;
167
+ for (let i = 0; i < len; i++) {
168
+ const c = str.charCodeAt(i);
169
+ if (c === 59) {
170
+ _endIdx = i;
171
+ break;
172
+ }
173
+ if (c === 61 && eqIdx === -1) eqIdx = i;
174
+ }
175
+ if (eqIdx >= _endIdx) eqIdx = -1;
176
+ const name = eqIdx === -1 ? "" : _trim(str, 0, eqIdx);
177
+ if (name && name in _nullProto) return void 0;
178
+ let value = eqIdx === -1 ? _trim(str, 0, _endIdx) : _trim(str, eqIdx + 1, _endIdx);
179
+ if (!name && !value) return void 0;
180
+ if (name.length + value.length > 4096) return void 0;
181
+ if (options?.decode !== false) value = _decode(value, options?.decode);
182
+ const setCookie = {
183
+ name,
184
+ value
185
+ };
186
+ let index = _endIdx + 1;
187
+ while (index < len) {
188
+ let endIdx = len;
189
+ let attrEqIdx = -1;
190
+ for (let i = index; i < len; i++) {
191
+ const c = str.charCodeAt(i);
192
+ if (c === 59) {
193
+ endIdx = i;
194
+ break;
195
+ }
196
+ if (c === 61 && attrEqIdx === -1) attrEqIdx = i;
197
+ }
198
+ if (attrEqIdx >= endIdx) attrEqIdx = -1;
199
+ const attr = attrEqIdx === -1 ? _trim(str, index, endIdx) : _trim(str, index, attrEqIdx);
200
+ const val = attrEqIdx === -1 ? void 0 : _trim(str, attrEqIdx + 1, endIdx);
201
+ if (val === void 0 || val.length <= 1024) switch (attr.toLowerCase()) {
202
+ case "httponly":
203
+ setCookie.httpOnly = true;
204
+ break;
205
+ case "secure":
206
+ setCookie.secure = true;
207
+ break;
208
+ case "partitioned":
209
+ setCookie.partitioned = true;
210
+ break;
211
+ case "domain":
212
+ if (val) setCookie.domain = (val.charCodeAt(0) === 46 ? val.slice(1) : val).toLowerCase();
213
+ break;
214
+ case "path":
215
+ setCookie.path = val;
216
+ break;
217
+ case "max-age":
218
+ if (val && maxAgeRegExp.test(val)) setCookie.maxAge = Math.min(Number(val), COOKIE_MAX_AGE_LIMIT);
219
+ break;
220
+ case "expires": {
221
+ if (!val) break;
222
+ const date = new Date(val);
223
+ if (Number.isFinite(date.valueOf())) {
224
+ const maxDate = new Date(Date.now() + COOKIE_MAX_AGE_LIMIT * 1e3);
225
+ setCookie.expires = date > maxDate ? maxDate : date;
226
+ }
227
+ break;
228
+ }
229
+ case "priority": {
230
+ if (!val) break;
231
+ const priority = val.toLowerCase();
232
+ if (priority === "low" || priority === "medium" || priority === "high") setCookie.priority = priority;
233
+ break;
234
+ }
235
+ case "samesite": {
236
+ if (!val) break;
237
+ const sameSite = val.toLowerCase();
238
+ if (sameSite === "lax" || sameSite === "strict" || sameSite === "none") setCookie.sameSite = sameSite;
239
+ else setCookie.sameSite = "lax";
240
+ break;
241
+ }
242
+ default: {
243
+ const attrLower = attr.toLowerCase();
244
+ if (attrLower && !(attrLower in _nullProto)) setCookie[attrLower] = val;
245
+ }
246
+ }
247
+ index = endIdx + 1;
248
+ }
249
+ return setCookie;
145
250
  }
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;
251
+ function _trim(str, start, end) {
252
+ if (start === end) return "";
253
+ let s = start;
254
+ let e = end;
255
+ while (s < e && (str.charCodeAt(s) === 32 || str.charCodeAt(s) === 9)) s++;
256
+ while (e > s && (str.charCodeAt(e - 1) === 32 || str.charCodeAt(e - 1) === 9)) e--;
257
+ return str.slice(s, e);
192
258
  }
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 };
259
+ function _decode(value, decode) {
260
+ if (!decode && !value.includes("%")) return value;
261
+ try {
262
+ return (decode || decodeURIComponent)(value);
263
+ } catch {
264
+ return value;
265
+ }
204
266
  }
205
-
206
267
  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));
257
- }
258
- }
259
- return cookiesStrings;
268
+ if (Array.isArray(cookiesString)) return cookiesString.flatMap((c) => splitSetCookieString(c));
269
+ if (typeof cookiesString !== "string") return [];
270
+ const cookiesStrings = [];
271
+ let pos = 0;
272
+ let start;
273
+ let ch;
274
+ let lastComma;
275
+ let nextStart;
276
+ let cookiesSeparatorFound;
277
+ const skipWhitespace = () => {
278
+ while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) pos += 1;
279
+ return pos < cookiesString.length;
280
+ };
281
+ const notSpecialChar = () => {
282
+ ch = cookiesString.charAt(pos);
283
+ return ch !== "=" && ch !== ";" && ch !== ",";
284
+ };
285
+ while (pos < cookiesString.length) {
286
+ start = pos;
287
+ cookiesSeparatorFound = false;
288
+ while (skipWhitespace()) {
289
+ ch = cookiesString.charAt(pos);
290
+ if (ch === ",") {
291
+ lastComma = pos;
292
+ pos += 1;
293
+ skipWhitespace();
294
+ nextStart = pos;
295
+ while (pos < cookiesString.length && notSpecialChar()) pos += 1;
296
+ if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
297
+ cookiesSeparatorFound = true;
298
+ pos = nextStart;
299
+ cookiesStrings.push(cookiesString.slice(start, lastComma));
300
+ start = pos;
301
+ } else pos = lastComma + 1;
302
+ } else pos += 1;
303
+ }
304
+ if (!cookiesSeparatorFound || pos >= cookiesString.length) cookiesStrings.push(cookiesString.slice(start));
305
+ }
306
+ return cookiesStrings;
260
307
  }
261
-
262
- export { parse, parseSetCookie, serialize, splitSetCookieString };
308
+ export { parse, parse as parseCookie, parseSetCookie, serialize, serialize as serializeCookie, splitSetCookieString, stringifyCookie };
package/package.json CHANGED
@@ -1,37 +1,40 @@
1
1
  {
2
2
  "name": "cookie-es",
3
- "version": "2.0.0",
4
- "repository": "unjs/cookie-es",
3
+ "version": "3.0.1",
5
4
  "license": "MIT",
6
- "sideEffects": false,
7
- "type": "module",
8
- "exports": {
9
- "types": "./dist/index.d.mts",
10
- "default": "./dist/index.mjs"
11
- },
12
- "types": "./dist/index.d.mts",
5
+ "repository": "unjs/cookie-es",
13
6
  "files": [
14
7
  "dist"
15
8
  ],
9
+ "type": "module",
10
+ "sideEffects": false,
11
+ "types": "./dist/index.d.mts",
12
+ "exports": {
13
+ ".": "./dist/index.mjs"
14
+ },
16
15
  "scripts": {
17
- "build": "unbuild",
16
+ "build": "obuild",
18
17
  "dev": "vitest --coverage",
19
- "lint": "eslint --cache . && prettier -c src test",
20
- "lint:fix": "automd && eslint --cache . --fix && prettier -c src test -w",
18
+ "lint": "oxlint . && oxfmt --check src test",
19
+ "fmt": "automd && oxlint . --fix && oxfmt src test",
21
20
  "release": "pnpm test && pnpm build && changelogen --release --push && npm publish",
22
21
  "test": "pnpm lint && vitest run --coverage"
23
22
  },
24
23
  "devDependencies": {
25
- "@types/node": "^22.13.5",
26
- "@vitest/coverage-v8": "^3.0.7",
27
- "automd": "^0.4.0",
28
- "changelogen": "^0.6.0",
29
- "eslint": "^9.21.0",
30
- "eslint-config-unjs": "^0.4.2",
31
- "prettier": "^3.5.2",
32
- "typescript": "^5.7.3",
33
- "unbuild": "^3.5.0",
34
- "vitest": "^3.0.7"
24
+ "@types/node": "^25.5.0",
25
+ "@vitest/coverage-v8": "^4.1.1",
26
+ "automd": "^0.4.3",
27
+ "changelogen": "^0.6.2",
28
+ "cookie": "^1.1.1",
29
+ "eslint-config-unjs": "^0.6.2",
30
+ "magic-string": "^0.30.21",
31
+ "mitata": "^1.0.34",
32
+ "obuild": "^0.4.32",
33
+ "oxfmt": "^0.41.0",
34
+ "oxlint": "^1.56.0",
35
+ "rolldown": "1.0.0-rc.11",
36
+ "typescript": "^6.0.2",
37
+ "vitest": "^4.1.1"
35
38
  },
36
- "packageManager": "pnpm@10.5.2"
39
+ "packageManager": "pnpm@10.32.1"
37
40
  }